text:
Q: Website compilation fails in MSBuild but works in Visual Studio I am experiencing weird behavior of MSBuild tasks when I try to use it to build my VS2010 solution, which includes Web Site project. If I open that solution in Visual Studio 2010 and try to compile it, it works. However if I try to compile it from my MSBuild script, it fails with error.
I have tracked it down to the fact, that there is a User Control in the WebSite directory, which does not use code behind.
Steps to reproduce:
1.) Imagine you have simple solution. Just with a web site and two user controls:
web\Controls\HelpButton.ascx:
<%@ Control Language="C#" ClassName="HelpButton" %>

<script runat="server">
    private string _helpUrl;
    public string HelpUrl
    {
        get { return _helpUrl; }
        set { _helpUrl = value; }
    }

</script>

web\AnotherFolder\TestUserControl.ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="TestUserControl.ascx.cs" Inherits="AnotherFolder_TestUserControl" %>
<%@ Register Src="~/Controls/HelpButton.ascx" TagPrefix="myCtrl" TagName="HelpButton" %>

 <myCtrl:HelpButton runat="server" ID="HelpButton" />

web\AnotherFolder\TestUserControl.ascx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class AnotherFolder_TestUserControl : System.Web.UI.UserControl
{
    protected override void OnLoad(EventArgs e)
    {
        this.HelpButton.HelpUrl = "trada";

        base.OnLoad(e);
    }

}

VS2010 can build this website without a problem.
2.) Use following MSBuild:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
DefaultTargets="Build">

<PropertyGroup>
<SolutionProperties>Configuration=Release</SolutionProperties>
</PropertyGroup>

<Target Name="Build" DependsOnTargets="">

 <MSBuild Projects="BuildTest.sln" Targets="Build" Properties="$(SolutionProperties)" RebaseOutputs="true">
  </MSBuild>
    </Target>
</Project>

3.) Run the MSBuild script: msbuild build.msbuild
Following error is displayed:
Microsoft (R) Build Engine Version 4.0.30319.1
[Microsoft .NET Framework, Version 4.0.30319.235]
Copyright (C) Microsoft Corporation 2007. All rights reserved.

Build started 9/9/2011 2:21:50 PM.
Project "d:\Src\MSBuildIssue\build.msbuild" on node 1 (default targets).
Project "d:\Src\MSBuildIssue\build.msbuild" (1) is building "d:\Src\MSBuildIssue\BuildTest.sln" (2) on node 1 (Build target(s)).
ValidateSolutionConfiguration:
  Building solution configuration "Release|Any CPU".
Project "d:\Src\MSBuildIssue\BuildTest.sln" (2) is building "d:\Src\MSBuildIssue\WebSite.metaproj" (3) on node 1 (default targets).
Build:
  C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler.exe -v /WebSite -p WebSite\ -u -f PrecompiledWeb\WebSite\
d:\Src\MSBuildIssue\WebSite\AnotherFolder\TestUserControl.ascx.cs(12): error CS1061: 'System.Web.UI.UserControl' does not contain a definition for 'HelpUrl' and no extension method 'HelpUrl' accepting a first argument of type 'System.Web.UI.UserControl' could be found (are you missing a using directive or an assembly reference?) [d:\Src\MSBuildIssue\WebSite.metaproj]
Done Building Project "d:\Src\MSBuildIssue\WebSite.metaproj" (default targets) -- FAILED.
Done Building Project "d:\Src\MSBuildIssue\BuildTest.sln" (Build target(s)) -- FAILED.
Done Building Project "d:\Src\MSBuildIssue\build.msbuild" (default targets) -- FAILED.

Build FAILED.

"d:\Src\MSBuildIssue\build.msbuild" (default target) (1) ->
"d:\Src\MSBuildIssue\BuildTest.sln" (Build target) (2) ->
"d:\Src\MSBuildIssue\WebSite.metaproj" (default target) (3) ->
(Build target) ->
  d:\Src\MSBuildIssue\WebSite\AnotherFolder\TestUserControl.ascx.cs(12): error CS1061: 'System.Web.UI.UserControl' does not contain a definition for 'HelpUrl' and no extension method 'HelpUrl' accepting a first argument of type 'System.Web.UI.UserControl' could be found (are you missing a using directive or an assembly reference?) [d:\Src\MSBuildIssue\WebSite.metaproj]

    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:02.66

It looks to me like if it compiled user controls in wrong order 'HelpButton' is placed on 'TestUserControl' and 'TestUserControl' assigns a value to property of 'HelpButton' object.
Is this known issue? Any suggestions how to workaround this?
One workaround that didn't work for me was to execute devenv.exe from MSBuild script and let devenv.exe build solution. It compiles it sucessfully, but problem is that I can't send additional MSBuild properties this way.
Thank you
Edit: Output of msbuild command when executed directly against solution file:
c:\Tmp\MSBuildIssue>msbuild.exe BuildTest.sln /target:Build /p:Configuration="Debug",Platform="Any CPU"

Microsoft (R) Build Engine Version 4.0.30319.1
[Microsoft .NET Framework, Version 4.0.30319.235]
Copyright (C) Microsoft Corporation 2007. All rights reserved.

Build started 9/12/2011 12:05:38 PM.
Project "c:\Tmp\MSBuildIssue\BuildTest.sln" on node 1 (Build target(s)).
ValidateSolutionConfiguration:
  Building solution configuration "Debug|Any CPU".
Project "c:\Tmp\MSBuildIssue\BuildTest.sln" (1) is building "c:\Tmp\MSBuildIssue\WebSite.metaproj" (2) on node 1 (default targets).
Build:
  C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_compiler.exe -v /WebSite -p WebSite\ -u -f -d PrecompiledWeb\WebSite\
c:\Tmp\MSBuildIssue\WebSite\AnotherFolder\TestUserControl.ascx.cs(12): error CS1061: 'System.Web.UI.UserControl' does not contain a definition for 'HelpUrl' and no extension method 'HelpUrl' accepting a first argument of type 'System.Web.UI.UserControl' could be found (are you missing a using directive or an assembly reference?) [c:\Tmp\MSBuildIssue\WebSite.metaproj]
Done Building Project "c:\Tmp\MSBuildIssue\WebSite.metaproj" (default targets) -- FAILED.
Done Building Project "c:\Tmp\MSBuildIssue\BuildTest.sln" (Build target(s)) -- FAILED.

Build FAILED.

"c:\Tmp\MSBuildIssue\BuildTest.sln" (Build target) (1) ->
"c:\Tmp\MSBuildIssue\WebSite.metaproj" (default target) (2) ->
(Build target) ->
  c:\Tmp\MSBuildIssue\WebSite\AnotherFolder\TestUserControl.ascx.cs(12): error CS1061: 'System.Web.UI.UserControl' does not contain a definition for 'HelpUrl' and no extension method 'HelpUrl' accepting a first argument of type 'System.Web.UI.UserControl' could be found (are you missing a using directive or an assembly reference?) [c:\Tmp\MSBuildIssue\WebSite.metaproj]

    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:01.77

A: In the end I have end up using AspNetCompiler tasks instead of MSBuild. Surprisingly AspNetCompiler works in situation when MSBuild tasks fails.
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <Target Name="PrecompileWeb">
        <AspNetCompiler
            VirtualPath="/MyWebSite"
            PhysicalPath="c:\inetpub\wwwroot\MyWebSite\"
            TargetPath="c:\precompiledweb\MyWebSite\"
            Force="true"
            Debug="true"
        />
    </Target>

The only problem I had to resolve with our real production solution was, that our solution contains many other projects (assemblies, executables), not just the website. For that reason I had to split build of the solution to two steps - at first only compile assemblies (using MSBuild tasks) and as second step call AspNetCompiler to compile the website.
Thanks for help

A: What about this line <%@ Register Src="~/Controls/HelpButton.ascx" ... ? Your button seems to be located in a different directory.


text:
Q: Cassandra store data in BLOB We are using Cassandra 3 and have come up with a modelling based on the initial requirements. Since there have been very frequent requirements changes, this model has subsequently changed many times as well. Hence considering these requirements and model changes, there has been no major improvement in terms of development. The team have decided to go with the BLOB data type and store the entire data in the BLOB. Can you please share the drawback to use BLOB such a  scenario. Thanks in Advance.

A: We migrated from Astyanax Cassandra 1.1 to CQL Cassandra 3.0 directly, so we still have a lot of column families which have value as BLOB.
Major issues we face right now are:
1) Difficult to visualize data directly from database: Biggest advantage of CQL is it supports SQL like queries, hence logging into cql terminal and getting results directly from there is saves a lot of time normally. If you use BLOB you will not be able to do all such things.
2) CQL performs better when your table has a well defined schema instead of using blob to store big chunk of data together.
If you are creating a new table, I will suggest to use Collections for your use case. You will be able to store different type of data and performance will also be good.
Nice slides comparing performance of schemaless tables and tables with scehma and collections. You can skip to slide 26 if you just want the summary.
https://www.slideshare.net/DataStax/migration-from-thrift-to-cql-brij-bhushan-ravat-ericsson-cassandra-summit-2016

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is a table prefix? What is a table prefix, and what are their advantages and disadvantages? This is in relation to MySQL.

A: Tables do not require prefixes.
This is purely up to you.
However, we prefix tables with relation to the MODULES in the application they belong to, just to group the tables more easily.

A: Some people advocate tbl or tbl_ (e.g. tbl_MyTable or tblMyTable) whilst others go with a suffix such as MyTable_T.
Personally I avoid the prefixes/suffixes. I may substitute in a View in place of a Table if a schema is changing over time so I don't really distinguish between the two types of object.
The most important thing is that you have your naming guidelines documented within your team and you all stick to the same set of guidelines for consistency.

A: This is often used to distinguish different installations of the same script from each other.
For example let´s say you have two Joomla Installations with different content on your server, but only one MySQL Database.
Now, for obvious reasons both Joomla installations can´t share the same database tables, as that would result in both installations displaying the same contents. And that is where the prefix kicks in.
By using different table prefixes you can let Joomla Installation #1 know that it is supposed to use all the table with Prefix JOS_ and Joomla Installation #2 has to use all the tables with the prefix JOS2_

A: In a small amount of cases, such as those where malware scripts have been created to target specific types of sites such as WordPress etc., changing the table prefixes has been useful as an extra security measure.
For example, adding table prefixes obscures common table names making it harder for hackers to access data in your database through SQL injection or other security holes because they will first need to discover what your table names are.
Be sure, however, to look at table prefixes as only a very minor layer of security. It should NOT be your main security method. You should still be taking other more important security measures to prevent SQL injection and other similar threats. For example, depending on how your code is set up it may still be possible for a hacker to run a "show tables" command through SQL injection to get the names of your database tables.

A: Strange no one mentioned that you also can use table prefixes to use normally reserved keywords as tablenames.
E.g. t_user or t_order are now possible.

A: If you have a complicated website and database structure, table prefixes may help prevent naming conflicts in the database.
You often see table prefixes in situations where:

*

*Multiple scripts are being integrated together into one website, and the finished website needs to share data, but the table names would conflict without a prefix unique to each script.

*You are adding functionality to a script you acquired, and you want to distinguish between tables native to that script and new tables you are manually creating. That way if you create a new table, it won't conflict with any future updates to the base script, since it has a different table prefix.

*You have a hosting plan that only gives you one database and you want to use that database to service multiple scripts. (This isn't recommended for a variety of reasons, but I've seen users do this.)
When you are writing a script from scratch, table prefixes usually aren't necessary since you control all aspects of the database structure. It's when you start integrating multiple scripts together that it becomes useful and sometimes even necessary. It allows you to create unique data views, and join tables, and such between multiple scripts without worrying about naming conflicts in the database.

A: It may help to distinguish between tables and views depending on what your naming convention is.
The disadvantage is that you may be limited as far as the name of a table is concerned. Oracle has a limit of 30 characters for this. If you use "Tbl_" as the prefix, you automatically lose 4 characters. That may be a problem.


text:
Q: Scientific Problems for Python Coding Dojos We are organizing a Coding Dojo of scientific applications in the Brazilian Python Community, the main goals are: improve our skills in Numpy (and some others scientific libs); improve the use of TDD in this kind of applications; and better understand of limitations of these APIs.
I'm looking for problems that fit these goals (mainly using Numpy). Any suggestions?
Update 1:
It's a randori coding dojo.
We don't have preferences for a specific area (mostly work in different areas), and since this is ours first "scientific dojo" we don't know exactly what is the best kind of problems for a sci-dojo.
Anyway, the problems must be small, probably we will need to explain the theory behind the problem, so, they also can't be complex (unless in special occasions). An example: implement a multivariate normal function
Summary for the future generation:

*

*Principal component analysis (PCA) for projecting a set of data on a 2D plan.

*Implementing a part of speech tagger using Vitterbi algorithm.

*Picture color quantification using a mixture of gaussian, and the EM algorithm (Using scikit?)

*Simulating stochastic partial differential equation.

*Implement a Multivariate Normal Function.

*... What else? ...

A: Software Carpentry, a set of educational materials for scientific computing, is mostly in Python and has a number of well thought out example problems.

A: You sold take a look on this lecture of the MIT. Back in the days I learned some new stuff and also learned how to deal with python. They have some simple examples of different things and present the basic idea of computations.
My Point of view is that you should implement some examples of SciPy cookbook and also some Numpy examples. Doing some scientific stuff without NumPy/SciPy would be impossible. Also the implementations of methods which are already available with NumPy like multivariate normal distribution is a waste of time and inefficient. I would say, use some calculations like Newton-Iterations or something equal which is easy to program and looks good in python. There is also a small book which is perfect for your course. It's about using python for science. This book deals with Numpy/Scipy, Matplotlib and other examples which are important for scientist. The things presented there are useful, but I didn't find it via Google. I will search for you in my small library but it may take some time (it's somewhere there - I know it).
Hope this helps you.

A: You don't mention what code kata resources you're using and why they're not suitable.
Many code kata postings are just fine for this kind of thing.
To create a new code kata for scientists, you need to brainstorm the kinds of things that are common data processing tasks.  You need a bunch of user stories from which you can derive a good code kata.
Working with actuaries, for example, I spend a lot of time reading raw source data, filtering, cleansing, organizing and summarizing.  Often, in a single, short Python application that uses CSV a few if-statements, a few dictionaries and a final print-loop.
Often, I can bang one of these out in an hour or two, depending on the complexity and the number of tests I have to write to be sure anything good will happen.

A: How long do you need these to be?

*

*PCA for projecting a set of data on a 2D plan

*Implementing a part of speech tagger using Vitterbi algorithm.

*Picture color quantification using a mixture of gaussian, and the EM algorithm

*Simulating stochastic partial differential equation.


text:
Q: How to delete system property in glassfish I have created a system property using this command:
asadmin create-system-properties --target test-backend-inst-config warning.enable.for.Institution.value=false

I want to delete this system property so when i try to use this command:
asadmin delete-system-properties warning.enable.for.Institution.value

getting following message on console:
Command delete-system-properties not found.
Check the entry of command name. This command may be provided by a package that is not installed.
Closest matching local and remote command(s):
delete-system-property

seems to be that delete command not present in asadmin in glassfish Is there any other way to delete this system property in glassfish ?

A: The command is delete-system-property, not delete-system-properties:

Use the delete-system-property subcommand in remote mode to delete
  system properties.
Ensure that the server is running. Remote subcommands require a
  running server.
List the existing system properties by using the
  list-system-properties(1) subcommand. Delete the system property by
  using the delete-system-property(1) subcommand. If necessary, notify
  users that the system property has been deleted.
Example 2-12 Deleting a System Property
This example deletes a system property named http-listener-port from
  localhost.
asadmin> delete-system-property http-listener-port Command
delete-system-property executed successfully.

https://docs.oracle.com/cd/E18930_01/html/821-2416/ghcjc.html#ggonc


text:
Q: Como llamar un registro tipo clob desde php Estoy llamando a un registro y lo estoy almacenando en un array asociativo, y al momento de ejecutar la pagina NO ME APARECE EL RESULTADO, es más, YA NO CARGA EL RESTO DE LA PAGINA, es como si hubiera puesto un die(). AQUÍ MI CODIGO:
BASE DE DATOS
CREATE TABLE TBLPRUEBA
(
ID_ACORDEON NUMBER PRIMARY KEY,
DESCRIP_ACORDEON CLOB
);

EL REGISTRO QUE TIENE LA TABLA
    DECLARE
    str_html CLOB := '

                                                <?php echo $cabecera[0]["NOMBRE_CABECERA"]; ?>

                                                    <?php echo $cabecera[1]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_valoracion_de_gestion_educativa_1.php"; ?>

                                                    <?php echo $cabecera[2]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_valoracion_de_gestion_educativa_2.php"; ?>

                                                    <?php echo $cabecera[3]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_valoracion_de_gestion_educativa_3.php"; ?>

                                                    <?php echo $cabecera[4]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_valoracion_de_gestion_educativa_4.php"; ?>

                                                    <?php echo $cabecera[5]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_valoracion_de_gestion_educativa_5.php"; ?>

                                                <?php echo $cabecera[6]["NOMBRE_CABECERA"]; ?>

                                                    <?php echo $cabecera[7]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_de_promocion_educativa_zonales_1.php"; ?>

                                                    <?php echo $cabecera[8]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_de_promocion_educativa_zonales_2.php"; ?>

                                                    <?php echo $cabecera[9]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_de_promocion_educativa_zonales_3.php"; ?>

                                                    <?php echo $cabecera[10]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_de_promocion_educativa_zonales_4.php"; ?>

                                                    <?php echo $cabecera[11]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_de_promocion_educativa_zonales_5.php"; ?>

                                                <?php echo $cabecera[12]["NOMBRE_CABECERA"]; ?>

                                                    <?php echo $cabecera[13]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_de_coordinacion_educativa_zonales_1.php"; ?>

                                                    <?php echo $cabecera[14]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_de_coordinacion_educativa_zonales_2.php"; ?>

                                                    <?php echo $cabecera[15]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_de_coordinacion_educativa_zonales_3.php"; ?>

                                                    <?php echo $cabecera[16]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_de_coordinacion_educativa_zonales_4.php"; ?>

                                                    <?php echo $cabecera[17]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_de_coordinacion_educativa_zonales_5.php"; ?>

                                                <?php echo $cabecera[18]["NOMBRE_CABECERA"]; ?>

                                                    <?php echo $cabecera[19]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_valoracion_de_coordinacion_academica_est_1.php"; ?>

                                                    <?php echo $cabecera[20]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_valoracion_de_coordinacion_academica_est_2.php"; ?>

                                                    <?php echo $cabecera[21]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_valoracion_de_coordinacion_academica_est_3.php"; ?>

                                                    <?php echo $cabecera[22]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_valoracion_de_coordinacion_academica_est_4.php"; ?>

                                                    <?php echo $cabecera[23]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_valoracion_de_coordinacion_academica_est_5.php"; ?>

                                                <?php echo $cabecera[24]["NOMBRE_CABECERA"]; ?>

                                                    <?php echo $cabecera[25]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_del_desempeno_docente_1.php"; ?>

                                                    <?php echo $cabecera[26]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_del_desempeno_docente_2.php"; ?>

                                                    <?php echo $cabecera[27]["NOMBRE_CABECERA"]; ?>

                                                    <?php require_once "include/ficha_de_evaluacion_del_desempeno_docente_3.php"; ?>

';
BEGIN
    INSERT INTO TBLPRUEBA VALUES(1, str_html);
    COMMIT;
END;

CODIGO PHP PARA OBTENER EL REGISTRO
<?php
class Contenido
{

    private $arreglo = array();

    public function listarAcordeon()
    {
        $sql = 'SELECT * FROM TBLPRUEBA';
        $stid = oci_parse(conex::con(), $sql);
        oci_execute($stid);
        while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false) {
            $this->arreglo[] = $row;
        }
        return $this->arreglo;
        oci_free_statement($stid);
        oci_close(conex::con());
    }
}
?>

<?php
include '../class/class_acordeon.php';
$prueba = new Contenido();
$tabla = $prueba->listarAcordeon();
?>

<?php
....CODIGO
<?=$tabla[0]["DESCRIP_ACORDEON"]?>//ACÁ DEBERIA APARECERME TODO EL SCRIPT QUE ESTABA DENTRO DEL CLOB, PERO NO ME CARGA.
....CODIGO
?>

A: Puedes hacerlo de esta forma.
select ID_ACORDEON, DBMS_LOB.substr(DESCRIP_ACORDEON, 4000) DESCRIP_ACORDEON from TBLPRUEBA;

ahora solo seria hacer un:
echo $tabla[0]["DESCRIP_ACORDEON"];

nota: el codigo php saldra comentado como si fuera html ya que el interprete lo tomara como texto plano!


text:
Q: How to concat javascript array let A = ["u23", "c35",-----so on];

let B = ["123", "234", ---- so on];

both a and b indexes count are 100 and same
Expected output C = ["u23,123", "c35,234", ---- so on];
I need to achieve output in very few steps without using complex steps of for loop.
ECMAScript 6 and above also will be fine.

A: You have to loop at least once - no other option. This is one of the possible solutions:

let A = ["u23", "c35", "d34"];
let B = ["123", "234", "345"];

let C = A.map((el, i) => el + "," + B[i]);
console.log(C);

The above solution may be improved by using a standard for-loop:
let C = [];
for (let i = 0; i < 1e6; i++){
  C.push(A[i] + "," + B[i]);
}

and you can improve it further by modifying one of the input arrays instead of creating a new array:
for (let i = 0; i < 1e6; i++){
  A[i] += "," + B[i];
}

You can compare the performance of each of the three above in the repl I've created here.
After a few runs, you'll notice that the last method is the fastest. It's because in the second example there's a new array C created and it has length of 0. With every .push(), the array has to be stretched which takes time. In the third example, you already have an array with the right size and you only modify its entries.
The thing which will always steal time is the string concatenation. You can play with my solutions by replacing the string concatenation with simple addition (as numbers) and you'll see that it makes the operation much faster. I hope it sheds some light on your problem.

A: let newArr =[];
A.forEach((el, index)=> {
  newArr.push(el);
  newArr.push(B[index]);
}

The newArr is now in your required format.


text:
Q: System.getproperty("spring.profiles.active") always getting Null in JPA Entity Listeners I am trying to get Spring active profile in JPA Entity Listener using System.getproperty("spring.profiles.active"). But it is always returning Null profile. However I have checked on server and profile is correctly configured.
I have tried to get Spring active profile using Environment but in the listener, I am unable to @Autowired Environment also.
    @PostUpdate

    public void methodInvoked afterUpdate(Example example){

    String activeProfile = System.getproperty("spring.profiles.active");

    }

Any guidance please !

A: You should use Environment bean while injecting it as described in this answer. SpringBeanAutowiringSupport will work if you are building a web application:
@Autowired
private Environment env;

@PostUpdate
public void methodInvoked afterUpdate(Example example) {
  SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
  String[] activeProfile = env.getActiveProfiles();

}

A: Inject the Environment into your code and then call the getActiveProfiles() method on Environment. This returns an array of Strings of all the active profiles.
See
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html#getActiveProfiles--
Don't rely on the "spring.profiles.active" as this may not be set - this property is used to set values via a property, and it's value does not reflect which profiles are active, as these may have been set programmatically.

A: Use boolean Environment.acceptsProfiles(String ...profiles) instead.
Javadoc:

Return whether one or more of the given profiles is active or, in the case of no explicit active profiles, whether one or more of the given profiles is included in the set of default profiles. If a profile begins with '!' the logic is inverted, i.e. the method will return true if the given profile is not active. For example,
env.acceptsProfiles("p1", "!p2")

will return true if profile 'p1' is active or 'p2' is not active.

It rationalizes the spring.profiles.active and spring.profiles.default lists.  This means that if my-profile is in the default list but !my-profile is in the active list when you ask if it accepts my-profile it will return false.
This is done mostly through the protected AbstractEnvironment.isProfileActive(profile) method which you can use if you make a custom Environment.

A: I found a solution because I needed to know the currently active profile in my entities and it is bad practice to inject bean Environment there, so i registered event listener:
public class PropertySettingListener {

    private final Environment environment;

    @Autowired
    public PropertySettingListener(Environment environment) {
        this.environment = environment;
    }

    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {

        String[] profiles = environment.getActiveProfiles();
        for (String profile : profiles) {
            if ("springldaptest".equals(profile)) {
                System.setProperty("ldap.profiles.active", profile);
            }
        }
    }
}

It will set property regarding the current profile and you can just use System.getProperty() wherever you want.

A: That's how I got it:
  @Autowired
  private Environment environment;

  public void getActiveProfiles() {
    getActiveProfiles();
    System.out.println((isProfileActive("test-dev-std")));
  }

  private void getActiveProfiles() {

    for (String profileName : environment.getActiveProfiles()) {
      System.out.println("Currently active profile - " + profileName);
    }
  }

  private boolean isProfileActive(String profile) {

    final String[] profiles = environment.getActiveProfiles();

    return Arrays.stream(profiles).anyMatch(str -> str.equals(profile));

  }

The log is:

Currently active profile - test-dev-std
Currently active profile - log
Currently active profile - dev-standalone
true


text:
Q: How do I convert text to datetime in SQL Server? I want to convert text to datetime in SQL Server.
I have text which in the format dd/mm/yyyy, but I want to convert this text format to datetime yyyymmdd.
I am using this method.
Convert(varchar(8), Right(text, 4) + Substring(text, 4, 2) + Left(text, 2), 112)

BUT I need a simpler query.

A: Answer:
SELECT FORMAT(CONVERT(date, '30/01/2018', 103), 'yyyyMMdd')

Explanation:
So this one is a little trickier because you've got DD/MM/YYYY, so you need to CONVERT first:
SELECT CONVERT(date, '30/01/2018', 103)

Result: 2018-01-30
Then if you are using SQL Server 2012+ use FORMAT()
SELECT FORMAT(CONVERT(date, '30/01/2018', 103), 'yyyyMMdd')

Result: 20180130


text:
Q: Where does this resistor appear in my nodal analysis? [BJT small signal analysis] Here is my small signal circuit of a PNP common base amplifier with a resistor Rin at the emitter, Rl at the collector and a voltage source Vb at the base. Here is my large signal circuit:

simulate this circuit – Schematic created using CircuitLab
Here is my small signal equivalent.

simulate this circuit
Normally, this is an easy nodal analysis without the emitter resistance but i'm lost with it. Since it is connected to both nodes Vx and Vy, how would that even go? I think one of the currents leaving node Vx would both go through rpi and Re is that right? So that means rpi and Re would add up? But how about for Vy? Does Re matter for Vy or its just gmVx?


text:
Q: How to invoke the appium server via python I am trying to start an appium server via a call to a python function at the start of my script.
I found the line I used to type into the windows command prompt was:
appium --base-path /wd/hub --default-capabilities "{\"app\": \"myapp.app\"}"
This worked fine.
Therefore, I tried the following in python:
import subprocess

subprocess.Popen("""start appium --base-path /wd/hub --default-capabilities "{\"app\": \"myapp.app\"}"
""",shell=True)

This gives the following error:
C:\Users\jainv\AppData\Roaming\npm\node_modules\appium\build\lib\main.js: error: argument -dc/--default-capabilities: invalid parseDefaultCaps value: '{app: myapp.app}'
It appears to be removing the "" around the capabilities dict and replacing them with single quotes instead. Why is this happening?

A: Try the following code
# --base-path has to give which is used to slove https://github.com/appium/appium/issues/15813
# [HTTP] no route found for /wd/hub/session
from appium.webdriver.appium_service import AppiumService
appium_service = AppiumService()
appium_service.start(args=["--base-path", "/wd/hub"])

A: Long keys did not work for me. What worked for me is
appium_service.start(args=['-pa', '/wd/hub'])


text:
Q: Dictionary object is shown as HashTable during runtime DataColumnCollection class has a columnFromName field that is defined as Dictionary of string and DataColumn as shown below
public sealed class DataColumnCollection : InternalDataCollectionBase {

        private readonly DataTable table;
        private readonly ArrayList _list = new ArrayList();
        private int defaultNameIndex = 1;
        private DataColumn[] delayedAddRangeColumns;

        private readonly Dictionary<string, DataColumn> columnFromName;
....

When I see this object in memory, its shown as a Hashtable (image below).

I have used Dictionary object in many applications that are shown as Dictionary in Windbg/Sos also. How come this Dictionary is getting translated into a Hashtable?


text:
Q: how to make different values of rows into columns in presto sql I was wondering if it is possible to make each distinct values of rows into different columns in presto
For example, what I want to get results like below form
message_varation_id / first_cv / second_cv / third_cv / fourth_cv

however what I end up getting is like below image

which is full of blank values I don't want, and I am getting four rows (for distinct values, I want rows to be unique by message_variation_id)
for example, what I want to get as output in this case is
message_variation_id | first_cv | second_cv | third_cv | fourth_cv
-------------------------------------------------------------------
9617b279~            | {custom~}| {window=~}|{custom~} | {custom ~}

I used the code like below
select distinct message_variation_id, first_cv, second_cv, third_cv, fourth_cv
from (
select distinct message_variation_id
    , if(bcc.conversion_behavior_index = 0, bcc.conversion_behavior) first_cv
    , if(bcc.conversion_behavior_index = 1, bcc.conversion_behavior) second_cv
    , if(bcc.conversion_behavior_index = 2, bcc.conversion_behavior) third_cv
    , if(bcc.conversion_behavior_index = 3, bcc.conversion_behavior) fourth_cv
from braze_currents.campaigns_conversion_partitioned bcc
where message_variation_id = '9617b279-f5bd-452d-abca-3263cf7e4651'
)

and the table I used, braze_currents.campaigns_conversion_partitioned looks like below

select message_variation_id, conversion_behavior_index, conversion_behavior
from braze_currents.campaigns_conversion_partitioned
limit 10

I think it is because of the null value, but sometimes third_cv or fourth_cv don't have values so I made a query like above. I was thinking of using join query, but I am thinking there might an efficient way. any suggestion would be great, thanks! :)

A: I think you are looking for a conditional max() (your images are hard to read):
select message_variation_id,
       max(case when bcc.conversion_behavior_index = 0 then  bcc.conversion_behavior end) as first_cv,
       max(case when bcc.conversion_behavior_index = 1 then bcc.conversion_behavior end) second_cv,
       max(case when bcc.conversion_behavior_index = 2 then bcc.conversion_behavior end) as third_cv,
       max(case when bcc.conversion_behavior_index = 3 then bcc.conversion_behavior end) as fourth_cv
from braze_currents.campaigns_conversion_partitioned bcc
where message_variation_id = '9617b279-f5bd-452d-abca-3263cf7e4651'
group by message_variation_id

A: I think sql below should work.
select message_variation_id,
       GROUP_CONCAT(DISTINCT first_cv SEPARATOR '') as first_cv,
       GROUP_CONCAT(DISTINCT second_cv SEPARATOR '') as second_cv,
       GROUP_CONCAT(DISTINCT third_cv SEPARATOR '') as third_cv,
       GROUP_CONCAT(DISTINCT fourth_cv SEPARATOR '') as fourth_cv
from braze_currents.campaigns_conversion_partitioned
group by message_variation_id;


text:
Q: Inequação em linguagem C Dados: Brutus tem 1,84m e pesa 122kg e Olívia tem 1,76m e pesa 45kg.
IMC = peso/(altura*altura);

IMC: 18,5 a 25 -----> Saudável

Quero criar um algoritmo que imprima qual é a quantidade MÍNIMA de
quilos que Brutus e Olívia devem perder/ganhar para atingirem um peso saudável segundo a classificação do IMC.
Pensei em usar uma inequação, como no exemplo abaixo para o Brutus:
peso_a_perder = peso - x / (altura * altura) <= 25;

Fiz uma rápida pesquisa e não achei uma função de inequação na biblioteca math.h. Segue abaixo parte do código.
float imc_Brutus, imc_Olivia, peso_Brutus = 122, altura_Brutus = 1.84, peso_Olivia = 45, altura_Olivia = 1.76;
/*
O calculo do IMC dos dois esta aqui (omisso)
*/

float x, peso_a_perder_Brutus, peso_a_perder_Olivia;
peso_a_perder_Brutus = peso_Brutus - x / (altura_Brutus * altura_Brutus) <= 25;
printf("Brutus deve perder %0.2f kg para atingir um peso saudavel\n", peso_a_perder_Brutus);
printf("Olivia deve ganhar %0.2f kg para atingir um peso saudavel\n", peso_a_perder_Olivia);

OBS: Devo criar o algoritmo usando conhecimentos bem básicos de C (não incluir comandos condicionais, comandos de repetição, vetor, matriz, etc...)
OBS2: Saídas:

*

*Brutus precisa perder no mínimo 37.36 quilos.

*Olivia precisa ganhar no mínimo 12.31 quilos.

Pergunta extra: Qual seria o método mais eficiente de resolver esse cálculo? Inequação mesmo, ou outra coisa?

A: Pela definição do IMC, saudável seria de 18,5 até 25.
Primeiro, vamos criar uma função para calcular o IMC:
float imc(float peso, float altura) {
    return peso / (altura * altura);
}

Poderíamos também criar uma função que diga se o IMC é saudável ou não (mas nem vamos precisar aqui):
int imc_saudavel(float imc) {
    return imc >= 18.5 && imc <= 25;
}

Se fulano tem um IMC baixo, quanto peso ele precisa ganhar para chegar em 18,5?

Vamos resolver a equação:

imc(peso_atual + peso_a_ganhar, altura) = 18,5
(peso_atual + peso_a_ganhar) / (altura * altura) = 18,5
peso_atual + peso_a_ganhar = 18,5 * altura * altura
peso_a_ganhar = 18,5 * altura * altura - peso_atual

E se for acima de 25, quanto ele tem que perder?

imc(peso_atual - peso_a_perder, altura) = 25
(peso_atual - peso_a_perder) / (altura * altura) = 25
peso_atual - peso_a_perder = 25 * altura * altura
-peso_a_perder = 25 * altura * altura - peso_atual

Considerando que peso_a_perder = -peso_a_ganhar, então:
peso_a_ganhar = 25 * altura * altura - peso_atual

Em ambos os casos, temos isso:
peso_a_ganhar = imc_ideal * altura * altura - peso_atual

Então, podemos fazer uma função que diz quanto peso uma pessoa deve ganhar ou perder:
float peso_a_variar(float peso, float altura) {
    float valorImc = imc(peso, altura);
    if (valorImc >= 18.5 && valorImc <= 25) return 0; // A pessoa já tem o IMC saudável.
    float fator = valorImc < 18.5 ? 18.5 : 25;
    return fator * altura * altura - peso;
}

Observe as inequações nestes ifs e no uso do operador ternário. O resto se baseia em equações.

Posso eliminar esse if?

Se a pessoa já tiver um peso ideal, poderíamos eliminar o if ao usar como fator, o próprio valorImc. Uma vez que nesse caso:
valorImc = peso / (altura * altura)

Então o return iria produzir isso:
(peso / (altura * altura)) * altura * altura - peso

Observe que peso é dividido por altura * altura e depois multiplicado por esse mesmo termo. Essas duas operações se anulam, de forma que isso resulta em:
peso - peso

O que obviamente é sempre zero. Logo, se a pessoa já tiver peso ideal, podemos usar o valorImc no lugar do fator. Isso deixa o código um pouco mais simples:
float peso_a_variar(float peso, float altura) {
    float valorImc = imc(peso, altura);
    float fator = valorImc < 18.5 ? 18.5 : valorImc > 25 ? 25 : valorImc;
    return fator * altura * altura - peso;
}

Posso eliminar esses operadores ternários?

A função desses operadores ternários é garantir que o fator esteja dentro da faixa saudável de 18,5 até 25. Logo, você pode substituí-los ao usar o fminf e o fmaxf (não esqueça o #include <math.h>):
float peso_a_variar(float peso, float altura) {
    float valorImc = imc(peso, altura);
    float fator = fmaxf(18.5, fminf(valorImc, 25.0));
    return fator * altura * altura - peso;
}

Se não quiser usar funções que já não estejam prontas na biblioteca padrão também:
float peso_fulano = ...;
float altura_fulano = ...;
float imc_fulano = peso_fulano / (altura_fulano * altura_fulano);
float fator_fulano = fmaxf(18.5, fminf(imc_fulano, 25.0));
float peso_a_ganhar_fulano = fator_fulano * altura_fulano * altura_fulano - peso_fulano;

E você tem como resultado um código que usa apenas conhecimentos bem básicos em C.


text:
Q: Pogoplug not mounting on MacOS High Sierra I have attached drives on Pogoplug. I tried installing their Pogoplug drive software but it does nothing. Totally nothing. I tried emailing the company and nobody responds.
I want to mount my hard drives on my Mac whether I am connected to internet or not.
I can access the server address and Pogoplug id. How do I mount the drives on my Mac. Is there any way to contact the company and tell them to at least make working software. I bought it for 100$ in the beginning.
Is there a way to install alternate software on Pogoplug to make it work faster better and simpler?
Is there an alternate service that can extend my Mac storage easily.

A: Pogoplug has shut down their services. There is no solution for people who have bought products from them.


text:
Q: How to create candidate key in cakephp 3? I want to create candidate key (as primary key ) using program_id, location_id, course_id

A: Updated per comment - originally thought this was a 2.0 question.
CakePHP 3 does support for composite keys:
class YourTable extends Table {
    public function initialize(array $config)
    {
        $this->table('table_name');
        $this->primaryKey(['program_id', 'location_id', 'course_id']);
    }
}

As well as composite relationships:
$this->belongsTo('Students', [
    'foreignKey' => ['program_id', 'location_id', 'course_id'],
]);

Previous Answer:
CakePHP 2.0 was designed to work with singular primary keys, per their docs on Conventions:

CakePHP does not support composite primary keys. If you want to directly manipulate your join table data, use direct query calls or add a primary key to act on it as a normal model.

You could instead specify the combo as a UNIQUE field in MySQL, but CakePHP will expect a single field for it's key, by default "id".


text:
Q: Need help in creating API level Shopify Webhooks - Its driving me crazy I am new to Shopify, and working on a shop right now. I am developing an app (shopify_app example using RoR) where I need to use the API level Webhooks.
I have read the Shopify Webhook documents, But I am completely dont understand it.
can some one write/help me on how to create for one 'orders/create' topic
few question that I have
In which controller I have to create the webhooks, How can I confirm that Webhook is created, how can i delete it
I have tried few examples and ended up with frustation. I just need complete example for topic 'orders/create' so that I can explore.
I have tried the following code, But I completely dont understand what is happening
webhook = ShopifyAPI::Webhook.new(:format => "json", :topic => "products/update", :address => "http://xx.xx.xx.xx/webhooks/api.php")
raise "Webhook invalid: #{webhook.errors}" unless webhook.valid?
puts webhook # printing # which I dont understand what is happening
Please some one help me.
Thanks in advance.

A: I would first try using the Ruby based Shopify console:
http://docs.shopify.com/api/introduction/using-the-api-console
Once you're comfortable with the API mechanics of registering a webhook, then start coding again.
Next, I would use a tool like Requestb.in (http://requestb.in) or Runscope Request Capture (https://www.runscope.com/docs/request-capture) as my testing hook URLs, because you'll be confident that those services will capture any incoming data, eliminating any doubt that the hook was properly registered and/or an event fired.


text:
Q: How do I get R to ignore N/A values without having it delete the whole row? I am working on a big dataset (around 40 column) and I need to aggregate the values of different column by months, averaging the values inside the month.
The dataset looks something like this.
dd <-
mo  yr Na   NH4 NO2
1 2009 0.4  N/A N/A
1 2009 0.2  0.1 N/A
2 2009 0.5  0.6 0.4
2 2009 0.7  0.2 0.1

I've used
dd.agg=aggregate(.~mo+yr, dd, FUN=mean)

to create a new dataset, but since I have some N/A datas (and I can't remove them or change them into 0s because they are due to some problem in the sampling procedure) in the NO2 column, the whole month of January is removed from the dd.agg dataset. I've tried to add na.rm=TRUE, but it doesn't seem to help.
What I need is, essentially, for R to just ignore the presence of the N/A data. Not to treat them like 0s (it would affect the average) but to obtain from that dataset something like this
dd.agg <-
mo  yr Na   NH4 NO2
1 2009 0.3  0.1 N/A
2 2009 0.6  0.4 0.25

Where if a whole month is comprised of N/As the average is just a N/A value (or an empty cell, it doesn't really matter to me since I don't need them in the plots) and when a month has just a couple of N/As, to average the non N/As value.
I could do row by row the same aggregate procedure and then put everything inside a new dataset manually, but for 40 column is a bit of a pain...
Any ideas?

A: We can use na.action = na.pass
aggregate(.~mo+yr, dd, FUN=mean, na.rm = TRUE, na.action = na.pass)
#   mo   yr  Na NH4  NO2
#1  1 2009 0.3 0.1  NaN
#2  2 2009 0.6 0.4 0.25

With tidyverse, this can be done with
library(tidyverse)
dd %>%
    group_by(mo, yr) %>%
    summarise_all(mean, na.rm = TRUE)

NOTE: N/A is not regarded as NA in R.  It should be first converted to NA before attempting this
While reading the data with read.table/read.csv, specify the elements that are going to be NA with na.strings
dd <- read.csv('file.csv', na.strings = "N/A")

data
dd <- structure(list(mo = c(1L, 1L, 2L, 2L), yr = c(2009L, 2009L, 2009L,
 2009L), Na = c(0.4, 0.2, 0.5, 0.7), NH4 = c(NA, 0.1, 0.6, 0.2
 ), NO2 = c(NA, NA, 0.4, 0.1)), class = "data.frame", row.names = c(NA,
 -4L))

Here, we specify as NA because N/A is a string and this can change the column type of character or factor depending on the way it was read (stringsAsFactors - option)


text:
Q: Ruby - Forbid constants redefinition redefining some constant in Ruby (ex. FOO = 'bar') generates the warning already initialized constant.
I'm trying to write a sort of ReallyConstants module, where this code should have this behaviour:
ReallyConstants.define_constant(:FOO, 'bar') #=> sets the constant ReallyConstants::FOO to 'bar'
ReallyConstants::FOO #=> 'bar'
ReallyConstants::FOO = 'foobar' #=> this should raise an Exception

that is, constant redefinition should generate an exception.
Is that possible?

A: Just scope your constant within a module and then use Module#freeze to prohibit further modification of the module.
E.g.
module Really
  CONSTANT = :foo
  freeze
end

Really::CONSTANT = :bar
-> RuntimeError: can't modify frozen Module

Note that this doesn't speak to the mutability of the value assigned to the constant.  For that, use Object#freeze.
This approach will bite you hard in environments where your code is reloaded, like in a Rails application.  There, you'll have to jump through an additional hoop, checking whether the module has been defined yet before defining it.
Generally, defensive programming in Ruby is more trouble than it's worth. What's your concern?


text:
Q: ASP Classic, Looping through query and sending emails I am trying to loop through a database query and send emails to the email addresses I get from the query.
Here is my piece of code.
do until rs.EOF
    Set myMail = CreateObject("CDO.Message")
    myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") ="relay-hosting.secureserver.net"
    myMail.Configuration.Fields.Update
    myMail.Subject= subject
    myMail.From="something@Something.Something"
    myMail.To = rs("Email")
    myMail.HTMLBody = strMessage & "Some Message"
    myMail.Send
    Set myMail = Nothing
    rs.MoveNext
loop

I have searched and tried different solution without any luck.
Following line of the code seems to have an issue, but i could not find what
myMail.To = rs("Email")

Before giving any answer or suggestion please keep in mind,

*

*This code works fine when I use any static email address in "TO" attribute of CDO Message object

*The query is giving accurate results

*I receive 500 Internal server error when i use dynamic email (email from the query) in the "TO" attribute of CDO Message object. I don't have the access to the IIS to enable detailed error messages.

A: Well, as others observed in the comments, without the actual error message it`s hard to tell. There are many possible sources:

*

*the recordset is closed at this point for some reason

*there is no "Email" field in the recordset

*E-Mail address invalid

*...

The good thing is, you can use classic ASP error handling to find the error like this:
on error resume next

do until rs.EOF
    Set myMail = CreateObject("CDO.Message")
    myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") ="relay-hosting.secureserver.net"
    myMail.Configuration.Fields.Update
    myMail.Subject= subject
    myMail.From="something@Something.Something"
    myMail.To = rs("Email")
    myMail.HTMLBody = strMessage & "Some Message"
    myMail.Send

    if err then
        Response.write "<code>" & err.Source & " - " & err.Description & "</code>"
    end if

    Set myMail = Nothing
    rs.MoveNext
loop

on error goto 0

There are of course better ways to handle these errors, even in classic ASP (search SO or see this solution). This is only to help you find the error when you don't have access to the IIS settings.

A: I once had a similar problem and found that it was caused by bad email addresses where their server responded with an error. That error broke the loop. It is impossible to keep unused email addresses out of a database, so to solve the problem I simply added On Error Resume Next
ObjSendMail.To = "Me <my@example.com>"
ObjSendMail.Subject = strSubject
ObjSendMail.From = strFromName & " <no-reply@example.com>"
ObjSendMail.ReplyTo = strFromName & " <" & strFromEmail & ">"
ObjSendMail.BodyPart.Charset = "UTF-8"
ObjSendMail.TextBody = strEmailBody
ObjSendMail.TextBodyPart.Charset = "UTF-8"
On Error Resume Next
ObjSendMail.Send
Set ObjSendMail = Nothing

Then it won't matter if the routine trips on any more failed emails because it will ignore them and move onto the next email.


text:
Q: Entity Framework 5.0 (C#): Seed method only run if Update-Database is run twice I have the following model:
public class User
{
    public int UserId { get; set; }
    public string EmailAddress { get; set; }
    public byte[] PasswordHash { get; set; }
    public byte[] PasswordSalt { get; set; }

    public virtual List<Role> Roles { get; set; }
    public virtual List<Job> Jobs { get; set; }
    public virtual List<Project> Projects { get; set; }
    public virtual List<Submission> Submissions { get; set; }
    public virtual List<PROMembership> PROMemberships { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string ZipCode { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public string Phone { get; set; }
    public string Notes { get; set; }
    public Guid? PasswordRetrievalToken { get; set; }

    [NotMapped]
    [Display(Name = "Full name")]
    public string FullName
    {
        get
        {
            if ((FirstName != null && FirstName.Length > 0) || (LastName != null && LastName.Length > 0))
            {
                return (FirstName + " " + LastName).Trim();
            }
            else
            {
                return EmailAddress;
            }
        }
    }
}

With the following fluent configuration class:
public class UserConfiguration : EntityTypeConfiguration<User>
{
    public const int EmailAddressMinLength = 3;
    public const int EmailAddressMaxLength = 62;
    public const int FirstNameMaxLength = 50;
    public const int LastNameMaxLength = 50;
    public const int AddressMaxLength = 100;
    public const int ZipCodeMaxLength = 20;
    public const int CityMaxLength = 50;
    public const int CountryMaxLength = 50;
    public const int PhoneMaxLength = 50;
    public const int NotesMaxLength = 1000;

    public UserConfiguration()
    {
        ToTable("Users");
        HasKey(u => u.UserId).Property(u => u.UserId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(u => u.EmailAddress).IsRequired();
        Property(u => u.EmailAddress).HasMaxLength(EmailAddressMaxLength);
        Property(u => u.PasswordHash).IsRequired();
        Property(u => u.PasswordSalt).IsRequired();
        Property(u => u.FirstName).HasMaxLength(FirstNameMaxLength);
        Property(u => u.LastName).HasMaxLength(LastNameMaxLength);
        Property(u => u.Address).HasMaxLength(AddressMaxLength);
        Property(u => u.ZipCode).HasMaxLength(ZipCodeMaxLength);
        Property(u => u.City).HasMaxLength(CityMaxLength);
        Property(u => u.Country).HasMaxLength(CountryMaxLength);
        Property(u => u.Phone).HasMaxLength(PhoneMaxLength);
        Property(u => u.Notes).HasMaxLength(NotesMaxLength);
        Property(u => u.PasswordRetrievalToken).IsOptional(); // somehow the DB is generated with this field required if this is ommited
        HasMany(u => u.Roles).WithMany(r => r.Users).Map(m => { m.MapLeftKey("UserId"); m.MapRightKey("RoleId"); m.ToTable("UsersInRoles"); });
        HasMany(u => u.Jobs).WithMany(j => j.Composers).Map(m => { m.MapLeftKey("UserId"); m.MapRightKey("JobId"); m.ToTable("ComposersInJobs"); });
    }
}

And with this context configuration class:
internal sealed class Configuration : DbMigrationsConfiguration<WebProject.DataAccess.WebProjectContext>
{
    private readonly bool _pendingMigrations;

    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        AutomaticMigrationDataLossAllowed = true;
        var migrator = new DbMigrator(this);
        _pendingMigrations = migrator.GetPendingMigrations().Any();
    }

    protected override void Seed(WebProject.DataAccess.WebProjectContext context)
    {
        if (!_pendingMigrations)
            return;
        // imagine seeding code here

So far, so good. When I execute Update-Database, everything works as expected and the Database is created/updated correctly and in the end, the seed method in my Context-Configuration class is executed.
Now I had to add some fields to the model. Using Add-Migration Command:
public partial class AddClientRepresentation : DbMigration
{
    public override void Up()
    {
        AddColumn("dbo.Users", "MiddleName", c => c.String(maxLength: 50));
        AddColumn("dbo.Users", "Company", c => c.String(maxLength: 50));
        AddColumn("dbo.Users", "State", c => c.String(maxLength: 50));
        AddColumn("dbo.Users", "SecondaryPhone", c => c.String(maxLength: 50));
        AddColumn("dbo.Users", "SecondaryEmailAddress", c => c.String(maxLength: 62));
    }

    public override void Down()
    {
        DropColumn("dbo.Users", "SecondaryEmailAddress");
        DropColumn("dbo.Users", "SecondaryPhone");
        DropColumn("dbo.Users", "State");
        DropColumn("dbo.Users", "Company");
        DropColumn("dbo.Users", "MiddleName");
    }
}

And so I have the following classes:
public class User
{
    public int UserId { get; set; }
    public string EmailAddress { get; set; }
    public byte[] PasswordHash { get; set; }
    public byte[] PasswordSalt { get; set; }

    public virtual List<Role> Roles { get; set; }
    public virtual List<Job> Jobs { get; set; }
    public virtual List<Project> Projects { get; set; }
    public virtual List<Submission> Submissions { get; set; }
    public virtual List<PROMembership> PROMemberships { get; set; }

    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string Company { get; set; }
    public string Address { get; set; }
    public string ZipCode { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
    public string Phone { get; set; }
    public string SecondaryPhone { get; set; }
    public string SecondaryEmailAddress { get; set; }
    public string Notes { get; set; }
    public Guid? PasswordRetrievalToken { get; set; }

    [NotMapped]
    [Display(Name = "Full name")]
    public string FullName
    {
        get
        {
            if ((FirstName != null && FirstName.Length > 0) || (LastName != null && LastName.Length > 0))
            {
                return (FirstName + " " + LastName).Trim();
            }
            else
            {
                return EmailAddress;
            }
        }
    }
}

public class UserConfiguration : EntityTypeConfiguration<User>
{
    public const int EmailAddressMinLength = 3;
    public const int EmailAddressMaxLength = 62;
    public const int FirstNameMaxLength = 50;
    public const int MiddleNameMaxLength = 50;
    public const int LastNameMaxLength = 50;
    public const int CompanyMaxLength = 50;
    public const int AddressMaxLength = 100;
    public const int ZipCodeMaxLength = 20;
    public const int CityMaxLength = 50;
    public const int StateMaxLength = 50;
    public const int CountryMaxLength = 50;
    public const int PhoneMaxLength = 50;
    public const int NotesMaxLength = 1000;

    public UserConfiguration()
    {
        ToTable("Users");
        HasKey(u => u.UserId).Property(u => u.UserId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(u => u.EmailAddress).IsRequired();
        Property(u => u.EmailAddress).HasMaxLength(EmailAddressMaxLength);
        Property(u => u.PasswordHash).IsRequired();
        Property(u => u.PasswordSalt).IsRequired();
        Property(u => u.FirstName).HasMaxLength(FirstNameMaxLength);
        Property(u => u.MiddleName).HasMaxLength(MiddleNameMaxLength);
        Property(u => u.LastName).HasMaxLength(LastNameMaxLength);
        Property(u => u.Company).HasMaxLength(CompanyMaxLength);
        Property(u => u.Address).HasMaxLength(AddressMaxLength);
        Property(u => u.ZipCode).HasMaxLength(ZipCodeMaxLength);
        Property(u => u.City).HasMaxLength(CityMaxLength);
        Property(u => u.State).HasMaxLength(StateMaxLength);
        Property(u => u.Country).HasMaxLength(CountryMaxLength);
        Property(u => u.Phone).HasMaxLength(PhoneMaxLength);
        Property(u => u.SecondaryPhone).HasMaxLength(PhoneMaxLength);
        Property(u => u.SecondaryEmailAddress).HasMaxLength(EmailAddressMaxLength);
        Property(u => u.Notes).HasMaxLength(NotesMaxLength);
        Property(u => u.PasswordRetrievalToken).IsOptional(); // somehow the DB is generated with this field required if this is ommited
        HasMany(u => u.Roles).WithMany(r => r.Users).Map(m => { m.MapLeftKey("UserId"); m.MapRightKey("RoleId"); m.ToTable("UsersInRoles"); });
        HasMany(u => u.Jobs).WithMany(j => j.Composers).Map(m => { m.MapLeftKey("UserId"); m.MapRightKey("JobId"); m.ToTable("ComposersInJobs"); });
    }
}

When I NOW run Update-Database, the migrations run fine, but the Seed method is NOT executed (no matter whether I use -Force).
If I run the Update-Database command a second time, the seed method is executed, but returns immediately because there are no pending migrations.
I digged into it step by step and found out, that if I comment out all the new fields (MiddleName, Company, State, SecondaryPhone, SecondaryEmailAddress) in the EntityTypeConfiguration, the seed method is executed the first time I run the Update command without any problems.
Did anyone experience the same issue? What can be the reason?

A: I'm guessing this code is the culprit:
if (!_pendingMigrations)
    return;

which makes sense why it would only run the 2nd time since you don't have any pending migrations at that point.


text:
Q: Solving a set of two coupled nonlinear ODE's The equations are: $\ddot{r} - r \ddot{\varphi}^2=0$ and $\ddot{\varphi} + \frac{2}{r}\dot{r}\dot{\varphi}=0$. I unfortunately have no clue how to go about solving this.

A: $\ddot{\varphi}+\frac{2}{r}\dot{r}\dot{\varphi}=0 \; \Rightarrow \;  \dot{(r^2\dot{\varphi})}=0 \; \Rightarrow \; \dot{\varphi}= \frac{c}{r^2}$, where $c$ is a constant.
Then the other given equation becomes,
$ \ddot{r} = r \left(\frac{4}{r^2}\dot{r}^2\dot{\varphi}^2 \right) = \frac{4 c^2 \dot{r}^2}{r^5}$
First solve $ \ddot{r} = \frac{4 c^2 \dot{r}^2}{r^5} $  for $v = \dot{r}$ in the following way,
$ \ddot{r}=\dot{v} = v \frac{dv}{dr}$ and then solve for $ v \frac{dv}{dr}= \frac{4 c^2 v^2}{r^5} $


text:
Q: Проблема с использованием шаблона класса в C++ Возникла проблема при написании шаблонного класса, в его методе test вызывается метод другого класса, при компиляции получаю ошибку

undefined reference to `bar::printHello()'

В чем может быть проблема?
main.cpp
#include<main.h>
#include <foo.h>

int main(){
    foo<int> _fo ;
    _fo.test();
    return 0;
}

main.h
#pragma once
#include <bar.h>

foo.h
#pragma once
#include<bar.h>
template<class T>
class foo{
public:
    foo(){
    }

   void  test(){
      bar b;
      b.printHello();
    }
};

foo.cpp
#include "foo.h"

bar.h
#pragma once
class bar
{
public:
    bar();
    void printHello();
};

bar.cpp
#include "bar.h"
#include <iostream>
bar::bar()
{
}

void printHello(){
    std::cout<<"Hello";
}

A: Вы не пробовали переписать
void printHello(){
    std::cout<<"Hello";
}

как
void bar::printHello(){
    std::cout<<"Hello";
}

?
Т.е. пояснить, что это не просто свободная функция printHello, а член класса bar?


text:
Q: How to use Google Analytics Android SDK Custom Metrics I try to collect a custom metric from an Android application using Google Analytics SDK v3.
The doc says to do it like this :
// May return null if EasyTracker has not yet been initialized with a
// property ID.
EasyTracker easyTracker = EasyTracker.getInstance();

// Set the custom metric to be incremented by 5 using its index.
easyTracker.set(Fields.customMetric(1), 5);

// Custom metric value sent is with this screen view.
easyTracker.send(MapBuilder
    .createAppView("Home screen")
    .build()
);

https://developers.google.com/analytics/devguides/collection/android/v3/customdimsmets
However set(Fields.customMetric(1), 5); is undefined because only EasyTracker.set(String,String) exists. The documentation seems not up to date with the v3 SDK.
So here is what I tried instead :
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onStart() {
        super.onStart();
        EasyTracker.getInstance(this).activityStart(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EasyTracker.getInstance(this).activityStop(this);
    }

    public void onDetected()
    {
        EasyTracker easyTracker = EasyTracker.getInstance(this);
        easyTracker.set(Fields.customMetric(1), "1"); //not working
        easyTracker.send(MapBuilder
                .createEvent("cat", "detected", "beacon", (long) 1) // also tried with createAppView
                .set(Fields.customMetric(1), "1") // not working
                .set("&cm1", "1") // not working
                .build());
    }

But none of this actually works. How can I collect custom metrics using Google Analytics Android SDK ?

A: Have you looked at using the method:
Tracker.setCustomMetric(int, long)

I have done something similar with a custom dimension and it worked for me (tracker.setCustomDimension(String, string)).  Another gotcha that I ran into is that I had to make sure that the dimension was defined in the admin panel before GA would accept it.


text:
Q: Receiving all values in JSON php I have the following JSON:
{

"thirdPartyForms": [
    {
        "driverAddress": "Adress",
        "PolicyOwner": "nimo",
        "driverInsCompany": "lkjlkj",
        "driverName": "drvivcer name",
        "agentPhone": "kj",
        "carLicensing": "lkjkl",
        "driverId": "0980980980",
        "driverPhone": "098908098",
        "agentName": "j"
    },
    {
        "driverAddress": "",
        "PolicyOwner": "",
        "driverInsCompany": "",
        "driverName": "driver 5",
        "agentPhone": "",
        "carLicensing": "",
        "driverId": "",
        "driverPhone": "",
        "agentName": ""
    }
],
"personalForm": {
    "insDriverName": "",
    "insCarLicensing": "",
    "insId": "039956974",
    "insName": "bnrus",
    "insDriverId": "",
    "insPhone": ""
}
}

I tried to save all fields using this function I wrote:
    function JSONForm()
    {
        if(get_magic_quotes_gpc()){
            $d = stripslashes($_POST['formJSON']);
        }else{
            $d = $_POST['formJSON'];
        }
        $d = json_decode($d,true);

    $myArray = array();

    foreach($d as $item)
    {

        foreach($item as $key => $value)
        {
            $myArray[$key] = $value."\n";
        }
    }

 }

I'm not getting all the fields (i'm getting 'array' instead the fields). This is my output:
0 => Array
1 => Array
insDriverName =>
insCarLicensing =>
insId => 039956974
insName => bnrus
insDriverId =>
insPhone =>

How can I improve my function so that it will work?
That means -> i'm not able to save all the values inside the JSONArray (output line 1 & 2).

A: The Solution
Moved to the top for clarity.
Try this to recursively flatten the array
$d = json_decode($json, true);

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($d));
foreach($it as $k => $v) {
  echo $k . " is " . $v . "\n";
}

ORIGINAL ANSWER
Your code is working as expected, you cannot echo or print an array, the data is there. Instead do this;
function JSONForm()
{
   if(get_magic_quotes_gpc()){
       $d = stripslashes($_POST['formJSON']);
   }else{
       $d = $_POST['formJSON'];
   }
   $d = json_decode($d,true);

   // A var_dump here will show you the true values of all of the
   // decoded array
   var_dump($d);

   // In fact you do not need to iterate over the array, at all
   // because the variable $d already contains all the json data

   $myArray = array();

   foreach($d as $item)
   {
    foreach($item as $key => $value)
    {
        // This will output all the array using print_r, setting the 2nd
        // parameter to be true will return the output, rather than print it
        $myArray[$key] = print_r($value, true)."\n";
    }
   }
 }

EDIT
This is your data;
// thirdPartyForms is an array, it has no keys so the array will be
// zero indexed
"thirdPartyForms": [
    { // this is position zero
        "driverAddress": "Adress",
        "PolicyOwner": "nimo",
        "driverInsCompany": "lkjlkj",
        "driverName": "drvivcer name",
        "agentPhone": "kj",
        "carLicensing": "lkjkl",
        "driverId": "0980980980",
        "driverPhone": "098908098",
        "agentName": "j"
    },
    { // this is position one
        "driverAddress": "",
        "PolicyOwner": "",
        "driverInsCompany": "",
        "driverName": "driver 5",
        "agentPhone": "",
        "carLicensing": "",
        "driverId": "",
        "driverPhone": "",
        "agentName": ""
    }
],
"personalForm": {
    "insDriverName": "",
    "insCarLicensing": "",
    "insId": "039956974",
    "insName": "bnrus",
    "insDriverId": "",
    "insPhone": ""
}

So you can then access the array using numbered indices;
// This will give you 'Adress'
echo $d["thirdPartyForms"][0]["driverAddress"]

// This will give you 'bnrus'
echo $d["personalForm"]["insName"];

Using var_dump($d) will make this much easier as you can see the make up of the array more clearly.
Using a loop;
foreach($d as $key => $data)
{
   // This will output the data for a key, note that var_dump will
   // output an array just fine
   var_dump($data);

   // The issue you have is that $data could be a string or another array,
   // Because your first element "thirdPartyForms" is an array of arrays
   // The second element "personalForm" is an array of strings

   // Check if its an array and if so iterate again
   if(is_array($data))
   {
      echo $key . " is an array\n";

      // Here we loop over the array again, note that if you have arrays in a
      // array then you will need a recursive function
      foreach($data as $k => $value)
      {
         echo $k . " within an array is " . $value . "\n";
      }
   }
   else
   {
      echo $key . " is not an array, it is " . $data . "\n";
   }
}


text:
Q: state gets updated before setState is called lifeParser is a method called to process and update boardData. The problem is boardData gets updated while the loop is still processing.
lifeParser(){
    var parseArray = this.state.boardData.slice(0);

    for(var i=0;i<30;i++){
        for(var j=0;j<30;j++){
            parseArray[i][j] = 5; // boardData gets updated here before setState is even called
        }
    }
    this.setState({boardData : parseArray});
}

A: This is because your boardData is multi-dimensional and you can't clone it only with slice method. Use it with map like this.
var parseArray = this.state.boardData.map(function(arr) {
    return arr.slice();
});

or with arrow syntax
var parseArray = this.state.boardData.map(a => a.slice());

A: Because it's a nested array. You are only copying the first level (shallow clone). The inner arrays are still the same references. Consider the follow example:
var nestedArray = [
 [1, 2, 3],
 [6, 6, 6, 6, 7, 8],
 [0, 3, 5, 6, 5]
];

// This only does a shallow clone
var copy = nestedArray.slice(0);

// When you do this
copy[0][0] = 100;

// `nestedArray` will also be mutated,
// you get 100 here
console.log(nestedArray[0][0]);

In your case, you can do a deep clone or simply use something like map() to get a fresh new array:
lifeParser(){
    var parseArray = this.state.boardData.slice(0);

    for (var i = 0; i < 30; i++) {
      parseArray[i] = parseArray[i].map(() => 5);
    }
    this.setState({boardData : parseArray});
}

Doing a deep clone in this example is more expensive because you need 1 more loop. The benefit of using map() here is that you compute and clone your data at the same time.
You can also use two map()s in this example:
lifeParser(){
    var parseArray = this.state.boardData.map(innerArray => innerArray.map(() => 5));
    this.setState({boardData : parseArray});
}

// Or this might be more readable:
var parseArray = this.state.boardData.map(innerArray => {
  return innerArray.map(() => 5);
});


text:
Q: two divs side by side, one 100% width others width depended on content I want to place two DIV tags side by side without using fixed width.
The first div expands to its content  and the second div should fill the remaining space. Also the div must NOT sit on top of the other div, because they have a transparent background image so if they intersect it's noticeable. I tried all possibilities that i could think off but couldn't find a solution using DIV tags.
I can do this using a TABLE, but is it possible to do it using DIV's? Or is this one more thing DIV's can't do?
Here's the code:
            #right{
              background: green;
              width: 100%;
            }
            #left {
              margin-top: 5px; /* to test if they intersect*/
              background: red;
            }
            #container {
               width: 800px;
            }

 This div is as big as it's content

 rest of space

Thanks for the replies!

A: See: http://jsfiddle.net/kGpdM/
#left {
    background: #aaa;
    float: left
}
#right {
    background: cyan;
    overflow: hidden
}

This works in all modern browsers and IE7+.
The left column will be exactly as wide as the content inside it. The right column will take the remaining space.
The overflow: hidden "trick" behind this answer is explained here.


text:
Q: Segmentation Fault & printing an array without loops I'm Just trying to run a simple program to count the number of spaces, digits and other characters using arrays. Below is my program:
void main(){

    int digit_holders[10]={0};
    int ch;
    int i, white_space=0,other=0;

    while((ch=getchar())!=EOF){

            if(isspace(ch))
                    white_space++;
            else if(isdigit(ch))
                    digit_holders[ch-'0']++;
            else
                    other++;
    }
    digit_holders[12]=20;
    printf("\n White spaces=%d\n Other=%d\n",white_space,other);
    for(i=0;i<=9;i++)
            printf("\ndigit_holders[%d]=%d\n",i,digit_holders[i]);
    printf("\n digit_holder[12]=%d\n",digit_holders[12]);
}

2 Questions:

*

*Why does digit_holders[12] still manage to print the assigned vale despite it being outside the range? Why doesn't it display a segmentation fault ?The same happens when I change the for loop check to i<=11 it manages to print digit_holders[11]=0 ( which it shouldn't) .. however when I replace 11/10 with 1100 i.e digit_holders[1100] in either of the case, the program crashes ( segmentation fault).  Why so ?

*Is there an easier way to print the elements of this array without using for loop ?

-Thanks!

A: There is no range checking in C so it gives it is best shot (I.e enough rope to hang yourself and the rest of the family).
Segmentation fault occurs from the OS. i.e. trying to access memory not assigned to the process.

A: As I wrote in the comment:
You will need a loop of some kind to print the content of your array in C.
You are assigning the 13th element of an array with only 10 elements declared, its risky to do and will be unstable, but wont necessarily result in a seg fault because if the OS hasnt modified it in the time between write and read, your pointer will resolve the value without error.  But again, risky.
If you had declared an array with 13 elements, all 13 will be reserved in memory and there will be no chance of a seg fault.  You are likely to get a seg fault if you interrogate an array outside of its declared limits, more so the further you go away from the range you defined.

A: It's possible to print "out-of-range" array indices in C because digit_holders[12] is handled as though digit_holders were a pointer with an offset of 12 * sizeof(int) added on to it.
This won't necessarily cause a segmentation fault, since the memory address being read might still be earmarked as being "available" to the program. A good example of this is a struct containing an array:
typedef struct {
    int some_array[12];
    int another_int;
} my_struct;

If you were to read the value of some_array[12], you'd get the contents of another_int instead, since it's stored directly after the last "valid" index of some_array.
As for the printing out of arrays: I'm not aware of any way to print out an array without using a loop in C, though it is possible in some other languages. For example, you could easily print out a list of strings in Python using print(", ".join(["This", "That", "The other"]))


text:
Q: Trying to improve my search bar using Flutter Im trying to improve my search bar using flutter but it doesnt seem to work. I want it so that the user can find the note title without to write the whole note title. I works but i want to improve it. Any help is greatly apprieciated
Original code:
Expanded(
  child: StreamBuilder<QuerySnapshot>(
    stream: _searchController.text.isEmpty
        ? FirebaseFirestore.instance.collection('notes').snapshots()
        : FirebaseFirestore.instance
            .collection('notes')
            .where('note_title', isEqualTo: _searchController.text)
            .snapshots(),
    builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      if (snapshot.hasData) {
        final List<DocumentSnapshot> notes = snapshot.data!.docs;
        final List<DocumentSnapshot> matchingNotes = notes
            .where((note) => note['note_title']
                .toString()
                .toLowerCase()
                .contains(_searchController.text.toLowerCase()))
            .toList();
        return GridView.count(
          crossAxisCount: 2,
          children: snapshot.data!.docs
              .map((note) => noteCard(() {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                NoteReaderScreen(note)));
                  }, note))
              .toList(),
        );
      }
      return Container();
    },
  ),
)

Modified code:
Expanded(
  child: StreamBuilder<QuerySnapshot>(
    stream: _searchController.text.isEmpty
        ? FirebaseFirestore.instance.collection('notes').snapshots()
        : FirebaseFirestore.instance
            .collection('notes')
            .where('note_title',
                isGreaterThanOrEqualTo:
                    _searchController.text.toLowerCase())
            .where('note_title',
                isLessThanOrEqualTo:
                    '${_searchController.text.toLowerCase()}\uf8ff')
            .snapshots(),
    builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      }
      if (snapshot.hasData) {
        final List<DocumentSnapshot> notes = snapshot.data!.docs;
        final List<DocumentSnapshot> matchingNotes = notes
            .where((note) => note['note_title']
                .toString()
                .toLowerCase()
                .contains(_searchController.text.toLowerCase()))
            .toList();
        return GridView.count(
          crossAxisCount: 2,
          children: snapshot.data!.docs
              .map((note) => noteCard(() {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                NoteReaderScreen(note)));
                  }, note))
              .toList(),
        );
      }
      return Container();
    },
  ),
)

I tried adding:
.where('note_title', isGreaterThanOrEqualTo: _searchController.text.toLowerCase())
  .where('note_title', isLessThanOrEqualTo: _searchController.text.toLowerCase() + '\uf8ff')

and it doesnt have an effect.


text:
Q: unable to open '/boot/vmlinuz-5.8.0-43-generic.dpkg-new': Operation not permitted I can't apt upgrade anymore after the dpkg broken installing linux-image-5.8.0-43-generic . I tried to remove the entries in /var/lib/dpkg/status . The /boot is not in a different partition. Thanks in advance. Information:
$ sudo apt upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 linux-image-generic : Depends: linux-image-5.8.0-43-generic but it is not installed
 linux-image-generic-hwe-20.04 : Depends: linux-image-5.8.0-43-generic but it is not installed
 linux-modules-extra-5.8.0-43-generic : Depends: linux-image-5.8.0-43-generic but it is not installed or
                                                 linux-image-unsigned-5.8.0-43-generic but it is not installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

sudo apt --purge autoremove
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies:
 linux-image-generic : Depends: linux-image-5.8.0-43-generic but it is not installed
 linux-image-generic-hwe-20.04 : Depends: linux-image-5.8.0-43-generic but it is not installed
 linux-modules-extra-5.8.0-43-generic : Depends: linux-image-5.8.0-43-generic but it is not installed or
                                                 linux-image-unsigned-5.8.0-43-generic but it is not installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

sudo apt --fix-broken install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following additional packages will be installed:
  linux-image-5.8.0-43-generic
Suggested packages:
  fdutils linux-doc | linux-source-5.8.0 linux-tools
The following NEW packages will be installed:
  linux-image-5.8.0-43-generic
0 upgraded, 1 newly installed, 0 to remove and 9 not upgraded.
15 not fully installed or removed.
Need to get 0 B/10,7 MB of archives.
After this operation, 13,7 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
(Reading database ... 494609 files and directories currently installed.)
Preparing to unpack .../linux-image-5.8.0-43-generic_5.8.0-43.49_amd64.deb ...
Unpacking linux-image-5.8.0-43-generic (5.8.0-43.49) ...
dpkg: error processing archive /var/cache/apt/archives/linux-image-5.8.0-43-generic_5.8.0-43.49_amd64.deb (--unpack):
 unable to open '/boot/vmlinuz-5.8.0-43-generic.dpkg-new': Operation not permitted
Errors were encountered while processing:
 /var/cache/apt/archives/linux-image-5.8.0-43-generic_5.8.0-43.49_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

$ sudo df -H
Filesystem      Size  Used Avail Use% Mounted on
tmpfs           820M  2,2M  818M   1% /run
/dev/nvme0n1p2   83G   32G   47G  41% /
tmpfs           4,1G  376M  3,8G  10% /dev/shm
tmpfs           5,3M  4,1k  5,3M   1% /run/lock
tmpfs           4,2M     0  4,2M   0% /sys/fs/cgroup
/dev/nvme0n1p4  169G  9,3G  151G   6% /home
/dev/nvme0n1p1  207M  8,2M  199M   4% /boot/efi
/dev/sda1       492G  175G  292G  38% /data
tmpfs           820M  156k  820M   1% /run/user/1000
overlay          83G   32G   47G  41% /var/lib/docker/overlay2/71bb1c050c92e223f622374cc46ba7ebffeb699f43fab7b291c7c774a2e366a4/merged

$ sudo ls -la /boot
total 146345
drwxr-xr-x  4 root root     4096 fev 10 08:56 .
drwxr-xr-x 22 root root     4096 jan 28 17:55 ..
-rw-r--r--  1 root root   248258 jan 15 07:10 config-5.8.0-40-generic
-rw-r--r--  1 root root   248258 jan 18 13:01 config-5.8.0-41-generic
-rw-r--r--  1 root root   248258 fev  4 23:41 config-5.8.0-43-generic
drwx------  3 root root      512 dez 31  1969 efi
drwxr-xr-x  4 root root     4096 jan 27 20:06 grub
lrwxrwxrwx  1 root root       27 jan 27 20:06 initrd.img -> initrd.img-5.8.0-41-generic
-rw-r--r--  1 root root 52092341 jan 26 15:02 initrd.img-5.8.0-40-generic
-rw-r--r--  1 root root 52092440 jan 27 20:06 initrd.img-5.8.0-41-generic
lrwxrwxrwx  1 root root       27 jan 26 15:04 initrd.img.old -> initrd.img-5.8.0-40-generic
-rw-r--r--  1 root root   182704 ago 18 07:23 memtest86+.bin
-rw-r--r--  1 root root   184380 ago 18 07:23 memtest86+.elf
-rw-r--r--  1 root root   184884 ago 18 07:23 memtest86+_multiboot.bin
-rw-------  1 root root  5635676 jan 15 07:10 System.map-5.8.0-40-generic
-rw-------  1 root root  5635676 jan 18 13:01 System.map-5.8.0-41-generic
-rw-------  1 root root  5635676 fev  4 23:41 System.map-5.8.0-43-generic
lrwxrwxrwx  1 root root       24 jan 27 20:06 vmlinuz -> vmlinuz-5.8.0-41-generic
-rw-------  1 root root 13715232 jan 15 07:20 vmlinuz-5.8.0-40-generic
-rw-------  1 root root 13715296 jan 18 13:08 vmlinuz-5.8.0-41-generic
lrwxrwxrwx  1 root root       24 jan 26 15:04 vmlinuz.old -> vmlinuz-5.8.0-40-generic


text:
Q: Laravel how to create empty relationship? I have a condition inside a relationship where if the user is logged in it will return the relation and if not i want it to return empty relationship.
here is what i want :
public function dummy()
{
    return (auth()->user()) ? $this->hasOne(blah::class) : emptyrelationship();
}

A: You should check with DD() what is being returned as you like.
If there's no data for the relationship to show, it will just return no data.

A: To return an empty relationship instead of null, you can try this:
public function item()
{
    return $this->belongsTo(Item::class)
        ->withDefault(function () {
            return new Item();
        });
}

A: Try This example
public function shop(){
    if(true) {
        return $this->newQuery(); // or newQueryWithoutScopes()
    }
    return $this->belongsTo('App\Models\Shop');
}

A: If there is no user in the user table collection will return relationship as "relationship: user: []" as blank only  if you do dd($var) on your query,then you can check though conditions in your code;

A: Eloquent has a method for that newModelInstance
Best to keep the eloquent model standard relationship and move logic elsewhere
public function dummy()
{
    return $this->hasOne(blah::class);
}

$dummy = $model->dummy;
if (!$dummy) {
    $dummy = $model->dummy()->newModelInstance();
}


text:
Q: Lift Sails inside Docker container I know there are multiple examples (actually only a few) out there, and I've looked into some and tried to apply them to my case but then when I try to lift the container (docker-compose up) I end up with more or less the same error every time.
My folder structure is:
sails-project
--app
----api
----config
----node_modules
----.sailsrc
----app.js
----package.json

--docker-compose.yml
--Dockerfile

The docker-compose.yml file:
sails:
  build: .
  ports:
    - "8001:80"
  links:
    - postgres
  volumes:
    - ./app:/app
  environment:
    - NODE_ENV=development
  command: node app

postgres:
    image: postgres:latest
    ports:
      - "8002:5432"

And the Dockerfile:
FROM node:0.12.3

RUN mkdir /app

WORKDIR /app

# the dependencies are already installed in the local copy of the project, so
# they will be copied to the container
ADD app /app

CMD ["/app/app.js", "--no-daemon"]

RUN cd /app; npm i

I tried also having RUN npm i -g sails instead (in the Dockerfile) and command:sails lift, but I'm getting:

Naturally, I tried different configurations of the Dockerfile and then with different commands (node app, sails lift, npm start, etc...), but constantly ending up with the same error. Any ideas?

A: By using command: node app you are overriding the command CMD ["/app/app.js", "--no-daemon"] which as a consequence will have no effect. WORKDIR /app will create an app folder so you don't have to RUN mkdir /app. And most important you have to RUN cd /app; npm i before CMD ["/app/app.js", "--no-daemon"]. NPM dependencies have to be installed before you start your app.


text:
Q: Not allowed to load local resource: file:// in ASP.NET Core I have images saved on my C drive as follows:
C:\Users\Public\images\employees

I have a view model in my project that contains a property string ImageUrl. In my Controller, I am fetching the image according to the image name:
var model = new EmployeeViewModel
{
    FirstName = employeeDetails.FirstName,
    FullName = employeeDetails.FullName,
    LastName = employeeDetails.LastName,
    ImageUrl = new System.Uri(Path.Combine(@"C:\Users\Public\images\employees", "John.jpg")).AbsoluteUri
};

Then I am passing this model into the View. In my View, I want to display the image as follows:

But I am getting an exception

Not allowed to load local resource: file:// in ASP.NET Core

Can someone please help with this. Also, my application will de deployed to a domain. How can I ensure the image will still display?

A:
passing this model into the View. In my View, I want to display the image

If you'd like to display image(s) stored within a folder of C drive on your server in view page, you can refer to the following code snippet to serve files from expected location.
app.UseStaticFiles();

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
        Path.Combine(@"C:\Users\Public\images", "employees")),
    RequestPath = "/employees"
});

In controller action
var model = new EmployeeViewModel
{
    FirstName = employeeDetails.FirstName,
    FullName = employeeDetails.FullName,
    LastName = employeeDetails.LastName,
    ImageUrl = "/employees/John.jpg"
};

For more information about serving static files and PhysicalFileProvider, please check:

*

*https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

*https://learn.microsoft.com/en-us/aspnet/core/fundamentals/file-providers?view=aspnetcore-3.1#file-provider-implementations

A: put your images folder inside the wwwroot folder. That's where the static files should be. That worked for me.
<img src="/Imagens/conflito.png" alt="Sample Photo" height="300"  />

example

A: You can create virtual directory which will have this phisical location there "C:\Users\Public\images". It is not secure to use external files without add them to project resources. Or add this images to wwwroot which is by default used for project resources.
Virtual directory:
https://www.c-sharpcorner.com/article/virtual-directory-inside-of-asp-net-core-app-in-iis/

A: You have to create folder within the project because project can only access the local files which are within the current project.
You cannot access files out of the scope of the project.

A: I created a .Net Fiddle to help demonstrate what I believe you are experiencing, filling in some gaps. It can be found here.
https://dotnetfiddle.net/S6deCz
When tried using various browsers it highlights that the browsers are preventing remote code from accessing files from the local machine.
I would suggest the best way to solve this problem and allow everyone to access it, is to ensure that the employee images are stored on the web server (IIS from the questions and answers above).
I have added ServerImageUrl to the demonstrate how you'd achieve this using a web server located resource.
Hope this helps.


text:
Q: Is a foreach loop on $_GET a good way to apply htmlspecialchars? I'm wondering if there is a significant downside to using the following code:
if(isset($_GET)){
foreach($_GET as $v){
    $v = htmlspecialchars($v);
}
}

I realize that it probably isn't necessary to use htmlspecialchars on each variable. Anyone know offhand if this is good to do?
UPDATE:
Because I don't think my above code would work, I'm updating this with the code that I'm using (despite the negativity towards the suggestions). :)
if(isset($_GET)){
foreach($_GET as $k=>$v){
    $_GET[$k] = htmlspecialchars($v);
}
}

A: This totally depends on what you want to do.
In general, the answer is "no", and you should only escape data specifically for their intended purpose. Randomly escaping data without purpose isn't helping, and it just causes further confusion, as you have to keep track of what's been escaped and how.
In short, keep your data stored raw, and escape it specifically for its intended use when you use it:

*

*for HTML output, use htmlentities().

*for shell command names, use escapeshellcmd().

*for shell arguments, use escapeshellarg().

*for building a GET URL string, use urlencode() on the parameter values.

*for database queries, use the respective database escape mechanism (or prepared statements).

This reasoning applies recursively. So if you want to write a link to a GET URL to the HTML output, it'd be something like this:
echo "click";

It'd be terrible if at that point you'd have to remember if $var had already previously been escaped, and how.

A: Blanket escaping isn't necessary, and it's possibly harmful to the data. Don't do it.
Apply htmlspecialchars() only to data that you are about to output in a HTML page - ideally immediately before, or directly when you output it.

A: It won't affect numbers, but it can backfire for string parameters which are not intended to be put in HTML code.
You have to treat each key different depending on its meaning. Possibility of generalization also depends on your application.

A: The way you're doing it won't work. You need to make $v a reference, and it breaks for anything requiring recursion ($_GET['array'][0], for example).
if(isset($_GET)) {
  foreach($_GET as &$v) {
    $v = htmlspecialchars($v);
  }
}