text:
Q: JSONP Callback Function inside jQuery Plugin I'm writing my first jQuery plugin and looking for some help making a JSONP request inside it.
Normally I setup my JSON data inside of a callback function like so
saveDataCommunityPartners({
    "newsBlockItems": [
        {
            "title": "title title title",
            "img": "item-img.jpg"
        },
        {
            "title": "title title title",
            "img": "item-img.jpg"
        }
        ... and so on and so forth
    ]
})

Then on a page I call .getJSON() like so:
$.getJSON("http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-redesign-communitypartners.js?callback=?");

And set up the callback function
function saveDataCommunityPartners(data) {
    alert("got data");
}

And everything works fine. How would I get this to work inside my plugin? If I do it like it is below, I'm getting a "Uncaught ReferenceError: saveDataCommunityPartners is not defined" error.
(function($) {
    $.fn.createNewsBlock = function( options ) {
        // Establish defaults
        var settings = $.extend({
        thisData        : {},
        pageFilter      : "community"
    }, options);

    $.getJSON("http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-redesign-communitypartners.js?callback=?");

    function saveDataCommunityPartners(data) {
        alert("got data");
    }
}(jQuery));

I can either change the plugin, or how I set up the JSON file itself, whatever is recommended. Thanks!

A: The getJSON method has a callback feature that you can use.
$.getJSON("http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-redesign-communitypartners.js?callback=?",function(data){

saveDataCommunityPartners(data);

});

OR use the chained command
$.getJSON("http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-redesign-communitypartners.js?callback=?").done(function( data ) {

saveDataCommunityPartners(data);

})

You can also relocate the saveDataCommunityPartners function outside the JQuery container if the error still persists.

A: Got it working using this code from here:
$.ajax({
    type: 'GET',
    url: "http://i.cdn.turner.com/nba/nba/.element/media/2.0/teamsites/warriors/json/json-redesign-communitypartners.js?callback=?",
    async: false,
    jsonpCallback: 'saveDataCommunityPartners',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
        parseJSON(json); // pass to function to use for whatever
    },
    error: function(e) {
        console.log(e.message);
    }
});

Note that originally in the success function I tried to store the json in a variable called data like so: data = json;, but ran into problems as this does not ensure that the json will have returned by the time data could be accessed. See this question for more info on that end.


text:
Q: When do you need "...|while read..."? I saw a video tutorial for the paste command, in which three files foo,bar,baz were connected horizontally with a "+" sign between.
cat foo
51
33
67

cat bar
10
1
13

cat baz
7
100
15

So, he used a paste command to make each line a whole addition and piped this into a while-loop which iterates through each line and puts it into the bc calculator:
paste -d+ foo bar baz | while read bla;do echo $bla|bc;done

I was confused why he used the complicated while-loop since
paste -d+ foo bar baz|bc

worked as well,
however this made me thing "Are there situations in which piping into the while-loop makes sense or is even the only way to achieve something?"

A: In this case it was just for outputting what is progressed at the moment, and that line for line. Piping while loops is sometimes really useful e.g. displaying a progress bar.
Progress Bar Example:
for i in $(seq 1 100)
do
sleep 0.1
echo $i
done | whiptail --title 'Test script' --gauge 'Running...' 6 60 0

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spark NLP for Healthcare visualization library Am using Spark NLP for Healthcare(John Snow. In the below code, we are exporting one particular document(12) results into an HTML file.
Visualize results
from sparknlp_display import NerVisualizer

NerVisualizer().display(
    result = result.collect()[12],
    label_col = 'ner_chunk',
    document_col = 'document',
    save_path='./export.html'
)

How do export all the records(data frame) results into CSV/excel file?


text:
Q: Search for parentheses via ElasticSearch I have a requirement where i need to index some text that is prefixed with (std) which i should then be able to search for again.
Ie. a document (html) contains the following sentence

(std)Almindelige betingelser for misligholdelseserstatning

and i should be able to query for

(std)Almindelige betingelser

Now, i've read a whole lot in the documentations and have now a charfilter in place which replaces ( and ) with _, and i thought i would then be safe to just to a replace in the search-query as well, so it becomes

_std_Almindelige betingelser

but for some reason its simply not working AT ALL. No result at all is being returned when searching for _std_Almindelige betingelser even though i can see the term is there by browsing the document and return a list of facets.
This is my index settings and type mapping
var settings = new IndexSettings();

settings.Analysis.CharFilters.Add("parenthesis", new MappingCharFilter
{
    Mappings = new[] { "( => _", ") => _" }
});

settings.Analysis.TokenFilters.Add("snowball", new SnowballTokenFilter
{
    Language = "Danish"
});

settings.Analysis.Analyzers.Add("content", new CustomAnalyzer
{
    CharFilter = new List<string>() { "html_strip", "parenthesis" },
    Tokenizer = "whitespace",
    Filter = new List<string>() { "lowercase", "snowball" }
});

And the mapping
{"searchservicepages":{
    "_source":{
        "excludes" : ["content"]
    },
    "properties":{
        "content":{
            "type":"string",
            "index_analyzer"":"content"
        }
    }
}}

A: The problem is in the mapping.
You should change "index_analyzer": "content" into "analyzer":"your_analyzer_name"
While your mapping is giving me trouble, with same index settings following mapping worked fine.
  "testindex": {
        "testdoc": {
          "_source": {
            "excludes": [
              "content"
            ]
          },
          "properties": {
            "content": {
              "type": "string",
              "analyzer": "myAnalyzer"
            }
          }
        }

Btw I'm using ES 0.90.2


text:
Q: NAudio Peak Volume Meter I'm attempting to write a peak volume meter using NAudio. My code is very similar to http://channel9.msdn.com/coding4fun/articles/NET-Voice-Recorder, but both my code and the linked Voice Recorder project suffer from an issue.
When playing a sound of constant frequency and volume, the volume meter initially begins at a reasonable level, but then decays to a very small value. I'm not sure why this is the case, for the peak volume meter in the NAudioDemo does not do this. I attempted to replicate the code from NAudioDemo in my program, but I was unable to find the code file containing the peak volume meter code.
Can somebody guide me to an alternative solution for creating a peak volume meter or help me determine why my solution (and the one provided at the link) both don't work?
public MainWindow()
    {
        int waveInDevices = WaveIn.DeviceCount;
        for (int waveInDevice = 0; waveInDevice < waveInDevices; waveInDevice++)
        {
            WaveInCapabilities deviceInfo = WaveIn.GetCapabilities(waveInDevice);
            Console.WriteLine("Device {0}: {1}, {2} channels",
                waveInDevice, deviceInfo.ProductName, deviceInfo.Channels);

            WaveIn waveIn = new WaveIn();
            waveIn.DeviceNumber = 0; //TODO: Let the user choose which device, this comes from the device numbers above
            waveIn.DataAvailable += waveIn_DataAvailable;
            int sampleRate = SAMPLE_RATE; // 8 kHz
            int channels = 1; // mono
            waveIn.WaveFormat = new WaveFormat(sampleRate, channels);
            waveIn.StartRecording();
        }
    }

    void waveIn_DataAvailable(object sender, WaveInEventArgs e)
    {
        for (int index = 0; index < e.BytesRecorded; index += 2)
        {
            short sample = (short)((e.Buffer[index + 1] << 8) |
                                    e.Buffer[index + 0]);
            float sample32 = sample / 32768f;
            ProcessSample(sample32);
        }

    }

    void ProcessSample(float sample1)
    {
        samplenumber += 1;

        if (sample1 > maxval)
        {
            maxval = sample1;
        }

        if (sample1 < minval)
        {
            minval = sample1;
        }

        //Run updateView every few loops

        if (samplenumber > (double)SAMPLE_RATE / DISPLAY_UPDATE_RATE)
        {
            samplenumber = 0;
            updateView(); //needs to be fast!
        }
    }

    void updateView()
    {
        Console.WriteLine(maxval);
        Console.WriteLine(minval);
        progressBar1.Value = (maxval - minval)*50;

        maxval = 0;
        minval = 0;
    }

A: All that is happening in that article is that it is finding the maximum audio peak over a small interval (e.g. 20ms) and then plotting that on a decibel scale. To find the peak, examine the value of each sample in the interval and select the max value (It's what the SampleAggregator class is doing). To convert to decibels, take the log base 10 of the maximum value, and multiply by 10. So 0dB is the loudest, and anything below say -96dB is effectively silence. (actually, looking back at the article, I don't think I even bothered to convert to a decibel scale, which I probably should have done)

A: This was my little solution for getting peak from output device. I'm using NAudio version 1.7.0.15
 public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();

        MMDeviceEnumerator enumerator = new MMDeviceEnumerator();

        var devices = enumerator.EnumerateAudioEndPoints(DataFlow.All, DeviceState.Active);
        comboboxDevices.Items.AddRange(devices.ToArray());
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        if (comboboxDevices.SelectedItem != null)
        {
            var device = (MMDevice)comboboxDevices.SelectedItem;
            progressBar1.Value = (int)(Math.Round(device.AudioMeterInformation.MasterPeakValue * 100));
        }
    }
}

A: Trying to get the levels with MasterPeakValue appears to be more complicated than just calling the method, which defeats its simplicity.
I accidentally realized that you have to open the device for recording, even if you don't use with the incoming data. Since you are starting a WaveIn, MasterPeakValue should return a non-0 value.
A simple alternative, just for testing, is to open the properties of system's recording devices (right-click on system volume icon and choose "Recording devices").
(Tested on 2 different computers.)


text:
Q: How can i display the file name in the Edit View? File name is stored in the images Folder and also in database View is
@Html.TextBoxFor(model => model.ChooseFile, "", new { @class = "span12", placeholder = "Choose File",type="file"})
when i Edit it then i need the file name picked and stored in the database. also image is stored in the folder image.
I also need to give download option for the same.
Please help me.

A: You have few options

*

*If file size is small, read the bytes from db and send as file result from MBC controller

*If file is large, then try streaming.
You can try like this
  public FileContentResult GetFile(int id)
  {
     SqlDataReader rdr; byte[] fileContent = null;
     string mimeType = "";string fileName = "";
     const string connect = @"Server=.\SQLExpress;Database=FileTest;Trusted_Connection=True;";

     using (var conn = new SqlConnection(connect))
     {
        var qry = "SELECT FileContent, MimeType, FileName FROM FileStore WHERE ID = @ID";
        var cmd = new SqlCommand(qry, conn);
        cmd.Parameters.AddWithValue("@ID", id);
        conn.Open();
        rdr = cmd.ExecuteReader();
        if (rdr.HasRows)
          {
             rdr.Read();
             fileContent = (byte[])rdr["FileContent"];
             mimeType = rdr["MimeType"].ToString();
             fileName = rdr["FileName"].ToString();
          }
        }
        return File(fileContent, mimeType, fileName);
      }


text:
Q: converting parquet files in S3 to CSV and store back in S3 Information:
I have parquet files stored in S3 which I need to convert into CSV and store back into S3.
the way I have the parquet files structured in S3 is as so:
2019
2020
 |- 01
 ...
 |- 12
   |- 01
   ...
   |- 29
     |- part-0000.snappy.parquet
     |- part-0001.snappy.parquet
     ...
     |- part-1000.snappy.parquet
     ...

The solution required:

*

*Any AWS tooling (needs to use lambda, no EC2, ECS) (open to suggestions though)

*That the CSV files keep their headers during conversion (if they are split up)

*That the CSV retain are original information and have no added columns/information

*That the converted CSV file remain around 50-100MB

The solution I have already tried:
"entire folder method"
Using Athena CREATE EXTERNAL TABLE -> CREATE TABLE AS on the entire data folder (e.g: s3://2020/06/01/)
fig: #1
CREATE EXTERNAL TABLE IF NOT EXISTS database.table_name (
         value_0 bigint,
         value_1 string,
         value_2 string,
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe'
WITH SERDEPROPERTIES ( 'serialization.format' = '1' )
LOCATION 's3://2020/06/01' TBLPROPERTIES ('has_encrypted_data'='false')

fig: #2
CREATE TABLE database.different_table_name
WITH ( format='TEXTFILE', field_delimiter=',', external_location='s3://2020/06/01-output') AS
SELECT * FROM database.table_name

doing this "entire folder method" works at converting parquet to CSV but leaves the CSV files at around 1GB+ size which is way too large. I tried creating a solution to split up the CSV files (thanks to help from this guide) but it failed since lambda has a 15-minute limit & memory constraints which made it difficult to split about all these 1GB+ CSV files into about 50-100MB files.
"single file method"
using the same CREATE EXTERNAL TABLE (see fig: #1) and
fig: #3
CREATE TABLE database.different_table_name
WITH ( format = 'TEXTFILE', field_delimiter=',', external_location = 's3://2020/06/01-output') AS
SELECT *, "$path" FROM database.table_name
WHERE "$path" LIKE 's3://2020/06/01/part-0000.snappy.parquet';

doing this "single file method" required me to integrate AWS SQS to listen to events from S3 for objects created in the bucket which looked for .snappy.parquet. this solution converted the parquet to CSV and created CSVs which fit the size requirements. the only issue is that the CSVs were missing headers, and had additional fields which never existed in the parquet in the first place such as the entire bucket location.

A: You can use dask
import dask.dataframe as dd
df = dd.read_parquet(s3://bucket_path/*.parquet')
#converting dask df to pandas df
df = df.compute()
df.to_csv('out.csv')

A: While there's no way to configure the output file sizes, you can control the number out files in each output partition when using CTAS in Athena. The key is to use the bucket_count and bucketed_by configuration parameters, as described here: How can I set the number or size of files when I run a CTAS query in Athena?. Run a few conversions and record the sizes of the Parquet and CSV files, and use that as a heuristic for how many buckets to configure for each job, each bucket will become one file.
When working with Athena from Lambda you can use Step Functions to avoid the need for the Lambda function to run while Athena is executing. Use the Poll for Job Status tutorial as a starting point. It's especially useful when running CTAS jobs since these tend to take longer to run.


text:
Q: ¿Cómo obtener de una columna de una tabla solo los valores que se incrementan cada "n" valores en mysql? Por ejemplo si tengo una tabla con registros y uno de los campos tiene valores double como:

Y deseo por ejemplo presentar los registros cada 0.5 del valor. que el resultado sea algo como:

O si deseo que el valor sea cada 0.3, tenga como resultado algo como esto:

¿Cómo podría tener esta respuesta en un select o en un procedimiento almacenado?
ACTUALIZACIÓN:
Código para pruebas:
create table test.secuence(
 id_secuence int auto_increment,
 value text,
 primary key(id_secuence)
);

insert into test.secuence(value) values('1');
insert into test.secuence(value) values('1.1');
insert into test.secuence(value) values('1.5');
insert into test.secuence(value) values('1.7');
insert into test.secuence(value) values('1.9');
insert into test.secuence(value) values('2');
insert into test.secuence(value) values('2.0');
insert into test.secuence(value) values('2.2');
insert into test.secuence(value) values('2.9');
insert into test.secuence(value) values('3');
insert into test.secuence(value) values('3.1');
insert into test.secuence(value) values('3.2');
insert into test.secuence(value) values('3.3');
insert into test.secuence(value) values('3.8');
insert into test.secuence(value) values('3.9');
insert into test.secuence(value) values('4.0');

He intentado el escenario presentado en las respuestas pero no he obtenido una respuesta concreta.
La idea es que teniendo una secuencia de valores, expresada en la pregunta anteriormente, sea una secuencia ordenada o una secuencia con saltos (1.0, 1.1, 1.5, 1.6...), poder sacar los valores que deseo dependiendo de el numero de n saltos que necesite, en las respuestas la logica esta super bien explicada, y eso es lo que necesito por ejemplo si quiero los valores de 0.1 en 0.1, o cada valores de 2 en 2, etc.
Realice lo siguiente con el siguiente resultado:
El la primera respuesta funciono, pero en casos de haber saltos en los valores de la secuencia, lamentablemente se distorsiona el resultado, esto porque los valores los toma con respecto a los valores generados por @rownum

La actualización al aplicarla no logro tener los resultados deseados:

También intente hacerlo para los valores enteros, en el cual si funcionan, pero lo que necesito pues es que sean filtros tanto en valores decimales, como de valores enteros:

A: En Oracle existe la seudocolumna rownum la cual asigna un número a cada fila, pero en MySQL la cosa es distinta, aunque en MySQL esta característica se incorporó a partir de la versión 8.0, no obstante esta característica puede ser simulada de una manera fácil.
 select t.Values, t.Data from
 (
    select @rownum:= @rownum + 1 as rownum, tabla.*
    from (select @rownum:= -1) r, tabla
 ) t
 where rownum % x = 0

En la consulta interna declaramos la variable rownum y la inicializamos en -1. Esta variable rownum es la que nos va a servir para otorgarle un numero consecutivo y único a cada fila de la tabla y es esta variable rownum la que usaremos para filtrar por el criterio que deseas cada fila.
Sobre los resultados que arroja esta subconsulta hacemos entonces una consulta poniendo la condición
where rownum % x = 0

La x representa un numero cualquiera, por ejemplo si queremos obtener los valores 1, 1.3, 1.6, etc.. tienes que sustituir la x por 3, si quieres que sea 1, 1.5, 2, etc. la x tienes que sustituirla por 5. Y así sustituirías la x por cualquier numero que te construya la secuencia q deseas obtener.
Actualización:
select *
from tabla
where (value - 1) % x = 0

Aquí la x representa cualquier valor, por ejemplo si quieres obtener
la secuencia 1, 1.5, 2, 2.5... el valor de x sería 0.5.
Para la secuencia 1, 1.3, 1.6, 1.9 ... el valor de x sería 0.3.
Para la secuencia 1, 1.2, 1.4, 1.6, 1.8 ... el valor de x sería 0.2.


text:
Q: Vanilla Javascript - Adding class to element 1 and remove class from element 2 on click of element 1 I've been told I can no longer use jQuery on a project I'm building, so I'm forced to use vanilla Javascript which can sometimes be way over my head. I'm hoping to simply convert this jQuery to js. I've searched and searched on Stack Overflow to no avail, but I feel like it shouldn't be that difficult. Any help would be amazing!
$('.navbuttoncontainer a').on( 'click', function() {
$('.navbuttoncontainer .current').removeClass('current');
$(this).addClass('current');

A: You could attach a click event listener to the .navbuttoncontainer element.
Then determine whether the a element was clicked by checking the tag name of the target element (e.target). Use the .add()/.remove() methods on the classList property of the element in order to add/remove the class.

document.querySelector('.navbuttoncontainer').addEventListener('click', function (e) {
  var target = e.target;

  if (target.tagName === 'A') {
    e.currentTarget.querySelector('.current').classList.remove('current');
    target.classList.add('current');
  }
});
.current {
  color: #f00;
}

  Initially current item
  Second item
  Third item

A: All modern browsers have support for document.querySelector/document.querySelectorAll, which are essentially the same thing as the jQuery $ function.
(For supported browser info check out http://caniuse.com/#feat=queryselector.
Instead of calling addClass/removeClass on a jQuery object, the DOM API exposes a property of elements called className. This is same as the class attribute on an element:
this.className = 'current';
Lastly, event handlers are registered with the addEventListener function. The arguments are the event name and the event handler function.


text:
Q: Defining session level estimations for function In a function definition I can specify estimations for planner like ROWS 1000 and COST 100. But the function can return one row or a million rows depending on condition. Is there any "conditional way" to define estimations? Of course, this is not changing the function definition each time.

A: No, there is no conditional way.
The only exception I can think of are very simple SQL functions which can be "inlined" in the outer query (not possible for plpgsql functions). Then Postgres applies default estimates instead of the estimates declared for the black boxes that functions otherwise are to the query planner. (Inlining basically discards the function wrapper and incorporates the SQL in the body into the outer query.)
The settings for COST and ROWS don't matter much as long as the function isn't nested into a (complex) bigger query, and that's the case where you should rather avoid user-defined set-returning functions that cannot be inlined.  You can do it, but it may lead to sub-optimal query plans - where COST and ROWS settings are not the most important problem, either. The query planner cannot optimize the plan for the whole query, but has to do it for function and the rest of the query separately.
Related:

*

*PostgreSQL Stored Procedure Performance

*Difference between language sql and language plpgsql in PostgreSQL functions

*Function executes faster without STRICT modifier?

*Why is the planner coming up with different results for functions with different volatilities?

*SQL function very slow compared to query without function wrapper


text:
Q: How to avoid wrapping when using XmlSerializerFormat for WCF service? I'm using WCF to create a SOAP web service, with predefined XSD contract, and C# types auto-generated from that XSD.
 [ServiceContract]
 [XmlSerializerFormat]
 public interface IEBooking10
 {
       [OperationContract]
       [XmlSerializerFormat]
       OTA_CancelRS OTA_Cancel(OTA_CancelRQ rq);
 }

OTA_CancelRQ & OTA_CancelRS are auto-generated types, with corresponding XML serialization attributes.
The parameters get wrapped in OTA_Cancel and OTA_CancelResponse elements, like this:
<OTA_Cancel>
   <OTA_CancelRQ> ... </OTA_CancelRQ>
</OTA_Cancel>

and
<OTA_CancelResponse>
   <OTA_CancelRS> ... </OTA_CancelRS>
</OTA_CancelResponse>

How can I avoid wrapping that WCF does to input parameters of the OTA_Cancel operation?

A: That is not handled by serialization but by message definition. At the moment you are using defaults which says that serialized data must be wrapped but the operation element. If you want to overwrite this behavior you must use message contracts. Try something like this:
[MessageContract(IsWrapped = false)]
public class OTA_CancelRQMessage
{
    [MessageBodyMember]
    public void OTA_CancelRQ { get; set; }
}

[MessageContract(IsWrapped = false)]
public class OTA_CancelRSMessage
{
    [MessageBodyMember]
    public void OTA_CancelRS { get; set; }
}

[ServiceContract]
[XmlSerializerFormat]
public interface IEBooking10
{
   [OperationContract]
   [XmlSerializerFormat]
   OTA_CancelRSMessage OTA_Cancel(OTA_CancelRQMessage rq);
}


text:
Q: NHibernate.XmlSerializers - Não existe?
Não foi possível carregar arquivo ou assembly
  'NHibernate.XmlSerializers, Version=4.0.0.4000, Culture=neutral,
  PublicKeyToken=aa95f207798dfdb4' ou uma de suas dependências. O
  sistema não pode encontrar o arquivo especificado.

Minha aplicação começou a solicitar uma DLL que não existe, antes era minhaapp.dll.XmlSerializers então adicionei esse código ao projeto e o erro mudou de "endereço" e foi para a DLL do NHibernate
<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
    <!-- Delete the file because I can't figure out how to force the SGen task. -->
    <Delete
      Files="$(TargetDir)$(TargetName).XmlSerializers.dll"
      ContinueOnError="true" />
    <SGen
      BuildAssemblyName="$(TargetFileName)"
      BuildAssemblyPath="$(OutputPath)"
      References="@(ReferencePath)"
      ShouldGenerateSerializer="true"
      UseProxyTypes="false"
      KeyContainer="$(KeyContainerName)"
      KeyFile="$(KeyOriginatorFile)"
      DelaySign="$(DelaySign)"
      ToolPath="$(TargetFrameworkSDKToolsDirectory)"
      Platform="$(Platform)">
      <Output
       TaskParameter="SerializationAssembly"
       ItemName="SerializationAssembly" />
    </SGen>
  </Target>

Alguém tem alguma sugestão?


text:
Q: Webflux saving to repository without using .block() I have the following method in my service:
override fun enableDisable(id: String, active: Boolean) = tryCatch(
            repository.findById(id).let {
                it.map { p -> p.active = active }; repository.save(it)
            },
            DataNotFound("Data not found"))

I am having the following error:
Need: Product
Found: Mono<Product>

If i put:
repository.save(it.block()!!)

It works, but I read that it is not good practice to use .block(). Which alternative can I use here?

A: Use flatMap to chain your functions:
it.map { product -> product.active = active }.flatMap(repository::save)


text:
Q: Bridging two Ethernet networks /w DHCP over WiFi What I am looking for is a bridge. WiFi cannot handle normal bridging, so how can I route two IP Ethernet networks using WiFi? (Under Linux)
How do I set up IP routing under Linux? It must forward DHCP, that is, the router must forward broadcast packets.
NAT is not a solution.
UPDATE: The reason I am going WiFi is that our internet cable is badly grounded. Lightning recently traveled through our cables, destroying much of our equipment, including computers and routers. This is the most sure way to ensure it doesn't happen again.
SOLUTION: I have come up with 2 solutions thanks to the answers.

*

*Put NAT on the Ethernet side. Everything looks like it is coming from a single IP now. Shortcoming is that network access is difficult from the other side because of the NATing.

*Better solution is to run dhcrelay, parprouted, and set ip_forward=1. That allows true IP based routing to work and DHCP works because of dhcrelay. The shortcoming is that NetBIOS names (which relies on broadcast packets) are not relayed. So computers must be accessed by their UNC path IP address in Windows \\192.168.1.3\SharedDocuments instead of \\LaptopMain\SharedDocuments.

A: Can you clarify what you're looking to accomplish?  By definition, broadcast packets are not routed.  Routed connections and linked broadcast domains are mutually exclusive.  Setting up a DHCP helper is possible, but doesn't sound like what you're after.
There's nothing different between an IP network on Ethernet, and one on wi-fi, and they can share a broadcast domain easily if desired; plug them into each other.
If what you're really looking for is to route between your two networks, it's as simple as a change in /etc/sysctl.conf: net.ipv4.ip_forward=1.  And dhrelay provides a means to play DHCP helper.
Of course, then your router for the wireless network segment would be a client system, not accessible directly via the access point.  Not a good thing.

A: You're right wifi cannot handle normal bridging. It only works with certain hacks, which are very vendor specific.
Another hack (vendor independent) is http://freshmeat.net/projects/parprouted/. This can accomplish something like bridging. I used it but didn't like it. I would suggest a classic routing scheme: an additional subnet with it's own dhcpd or a relay.
You could also tunnel from the STA (the wifi bridge) to your router and then bridge through the tunnel.
http://lartc.org/howto/ gives a good overview on the possibilities linux has.
I use http://www.pcengines.ch/ to create linux based wifi-clients in order to be able to run dhcpd, dhcp relay, VPN or whatever I need.

A: If you want "normal" bridging, I'd suggest just plugging a wireless access point into your network instead of creating an overcomplicated setup using Linux and some wifi cards.
There are plenty of examples of "normal" bridging of interfaces under Linux kernels using brctl with a vast number of different wifi cards - projects like DD-WRT or OpenWRT are some of them - the only prerequisite is to have the wifi interface in acesspoint mode. But I suppose, since you were having problems with bridging, that you are using a wireless interface in client mode, where interface capabilities (unable to switch to promiscuous mode) or encryption may get in the way.
But if you still want to route your wireless traffic (there may be valid reasons to do so - network separation for security reasons being one of them), you would need to configure different IP addresses in different networks for your interfaces, enable IP forwarding as suggested by Shane and set up dhcrelay to act as a BOOTP/DHCP relay forwarding the client's DHCP requests to a predefined DHCP server - which in turn would need to have a scope defined for your wireless network.
If you have further questions on what to do at the specific steps, you would need to supply detailed information on what your config files / startup parameters look like, how your network interfaces are set up and what your DHCP server configuration looks like.

A: This may be a silly answer, but...
To ensure perfect electrical isolation simply connect your border machine to the rest of your network using optical fiber.
This avoids the potential security issues of wifi, keeps the latency down, and avoids unnecessary complexity.


text:
Q: Cannot start a simple TCP/IP client I'm trying to open a TCP/IP listener but when I run the code below, it crashes. It doesn't give me an error because when it crashes, it freezes and stops responding.
TcpListener server = new TcpListener(IPAddress.Any, 619);
TcpClient client;

private void button3_Click(object sender, EventArgs e)
{
    server.Start();
    client = server.AcceptTcpClient();

    if (client.Connected)
    {
        MessageBox.Show("connected");
    }
}

I know for a fact this port is free so that's not it. it crashes on this line:
client = server.acceptTcpClient();

A: This is expected behaviour. Your program hasn't crashed - the call to AccpetTcpClient() blocks waiting for an incoming connection:
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.accepttcpclient(v=vs.110).aspx
You need to also open a TCP connection to port 619 from another thread, then your program will continue to run.

A:
AcceptTcpClient is a blocking method

(https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.accepttcpclient%28v=vs.110%29.aspx).
When you call AcceptTcpClient, it will wait until a connection is made. Because it waits on the main thread (where also the GUI is running on), it will look like the program is frozen. Try using AcceptTcpClientAsync or putting the accepting part in a different thread. That should solve your problem.
Desirius

A: You're executing a blocking call on the UI thread which gives the appearance of a "Crashing" application.
You need to use another thread or do things asynchronously. Background worker might be a starting point.
private BackgroundWorker bgw = new BackgroundWorker();

public MainWindow()
{
    InitializeComponent();
    bgw.DoWork += Bgw_DoWork;
    bgw.RunWorkerCompleted += Bgw_RunWorkerCompleted;
    bgw.WorkerSupportsCancellation = true;
}

private void button3_Click(object sender, EventArgs e)
{
    if (!bgw.IsBusy)
    {
        bgw.RunWorkerAsync();
        ((Button)sender).Content = "Cancel";
    }
    else
    {
        bgw.CancelAsync();
    }
}

private void Bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    button.Content = "Start";
}

private void Bgw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    var server = new TcpListener(IPAddress.Any, 619);
    server.Start();
    while (true)
    {
        if (worker.CancellationPending)
        {
            e.Cancel = true;
            server.Stop();
            break;
        }
        else
        {
            if (server.Pending())
            {
                var client = listener.AcceptTcpClient();
                // handle client here or do something like below to return the client to the RunWorkerCompleted method in
                // e.result
                e.Result = client;
                break;
            }
        }
    }
}

There are other options such as using server.AcceptTcpClientAsync() instead of polling the server.Pending() property. Also, polling in this way without using Thread.Sleep in between may be overkill, i.e., you're checking the property very frequently and wasting cycles.
Following all of that, you need to figure out a way to deal with the client in a way that makes sense for your application. One click per client accepted? Handle new connections forever as they arrive until you cancel the listener? Etc. Good luck
BackgroundWorker tutorial
AcceptTcpClientAsync MSDN


text:
Q: How to create a CSS spinning loading animation? I want to create a css (or JS) loading animation depicted in this image:

There should be a container rectangle which has a class. Then some css should be applied to that rectangle so that there is some overlay. First it is all black with 50% transparency. Then over time, the black reduces as it spins clockwise, until there is no more black again. If I give it a value of 100, it should be all black, if I give it 0, it should have no black, and just show the underlying image completely.
Anyone know any tutorial or how to create this?

A: Undoubtedly difficult, but possible. After about an hour of grinding I came up with a lot of divs and some working code:

const inner = document.getElementById('inner');
const black = document.getElementById('black');
const cover = document.getElementById('cover');
const overlay = document.getElementById('overlay');
const block = document.getElementById('block');
inner.addEventListener('animationend', e => {
  inner.style.display = 'none';
  block.style.display = 'block';
});
cover.addEventListener('animationend', e => {
  alert('done!');
});
#wrapper {
  height: 100px;
  width: 100px;
  border: 5px solid black;
  position: relative;
  overflow: hidden;
}

#wrapper > div {
  position: absolute;
  height: 300%;
  width: 300%;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

#cover {
  background-color: white;
  animation: spin 5s linear 5s forwards;
}
#overlay {
  background-color: black;
  width: 50%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
}

#inner {
  animation: spin 5s linear forwards;
}
#black {
  background-color: black;
  width: 50%;
  height: 100%;
  position: absolute;
  right: 0;
  top: 0;
}

@keyframes spin {
  from {
    transform: translate(-50%, -50%) rotate(0);
  }
  to {
    transform: translate(-50%, -50%) rotate(180deg);
  }
}

#block {
  display: none;
  background-color: white;
  height: 100%!important;
  width: 50%!important;
  transform: translate(0, 0)!important;
  position: absolute;
  top: 0!important;
  right: 0!important;
  z-index: 10
}

/*Just for the demo*/
body, html {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}

How in the world does this work?
Consider this image (sorry for the terrible graphic):

The small square in the middle represents #wrapper. The larger square around it is its child #inner. On the right side of #inner (with the stripes) is #black, which takes up half of its parent. #inner spins 180 degrees, disappears, then #cover essentially does the same thing on the opposite side. #block keeps the black part of #cover from displaying on the other side. *Whew*, that was fun!

A: I figured it out using canvas.

var canvas = document.getElementById('loading_animation');
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#00000088';

var final = [];
var list1 = [
    [Math.floor(canvas.width / 2), 0],
    [Math.floor(canvas.width / 2), Math.floor(canvas.height / 2)]
];
var list2 = [
    [canvas.width - 1, 0],
    [canvas.width - 1, canvas.height - 1],
    [0, canvas.height - 1],
    [0, 0]
];
var last = [Math.floor(canvas.width / 2), 0];

for (var x = Math.floor(canvas.width / 2); x < canvas.width; x += 1) {
    var path = list1.concat([[x, 0]]).concat(list2).concat([last]);
    final.push(path);
}
list2.shift();
for (var y = 1; y < canvas.height; y += 1) {
    var path = list1.concat([[canvas.width - 1, y]]).concat(list2).concat([last]);
    final.push(path);
}
list2.shift();
for (var x = canvas.width - 2; x >= 0; x -= 1) {
    var path = list1.concat([[x, canvas.height - 1]]).concat(list2).concat([last]);
    final.push(path);
}
list2.shift();
for (var y = canvas.height - 2; y >= 0; y -= 1) {
    var path = list1.concat([[0, y]]).concat(list2).concat([last]);
    final.push(path);
}
list2.shift();
for (var x = 1; x < Math.floor(canvas.width / 2); x += 1) {
    var path = list1.concat([[x, 0]]).concat(list2).concat([last]);
    final.push(path);
}
function RenderAnimation() {
    var path = final.shift();
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.moveTo(path[0][0], path[0][1]);
    for (let i = 1; i < path.length; i++) {
        ctx.lineTo(path[i][0], path[i][1]);
    }
    ctx.closePath();
    ctx.fill();
    if (final.length > 0) {
        window.requestAnimationFrame(RenderAnimation);
    } else {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    }
}

RenderAnimation();
    <!DOCTYPE html>

        <title>Title of the document</title>

        <canvas id="loading_animation" width="300px" height="200px"></canvas>


text:
Q: Array of arrays accessing C# I have four arrays each of size two, and i want to put them all in one array, so the when it J is = 1, it should use the first array, if J = 2, it should access the second array and so on.
    char[] p1Arr = new char[2];
            char[] p2Arr = new char[2];
            char[] p3Arr = new char[2];
            char[] p4Arr = new char[2];
            char[][] pArrays = new char[][] {p1Arr, p2Arr, p3Arr, p4Arr};   //i tried to create this array of the four arrays

//The four arrays values
            p1First = p1.Substring(0, 1);
            p1Arr[0] = Convert.ToChar(p1First);
            p1Second = p1.Substring(1, 1);
            p1Arr[1] = Convert.ToChar(p1Second);

            p2First = p2.Substring(0, 1);
            p2Arr[0] = Convert.ToChar(p2First);
            p2Second = p2.Substring(1, 1);
            p2Arr[1] = Convert.ToChar(p2Second);

            p3First = p3.Substring(0, 1);
            p3Arr[0] = Convert.ToChar(p3First);
            p3Second = p3.Substring(1, 1);
            p3Arr[1] = Convert.ToChar(p3Second);

            p4First = p4.Substring(0, 1);
            p4Arr[0] = Convert.ToChar(p4First);
            p4Second = p4.Substring(1, 1);
            p4Arr[1] = Convert.ToChar(p4Second);

           //Loop on the four arrays and their two values
            for (int j = 0; j < 4; j++)
            {
                pArrays[][] = pArrays[0][]; //my problem is here, how can i access each array??

                //get the first array....fourth.
                for (int i = 0; i < 2; i++)
                {
                    //loop on the values of the first array...fourth.
                    if (i == 0)
                    {
                        if (pArrays[j][i] == 0)
                        {
                            row = 0;
                        }
                   ........
                  }

I can't get to access each array in the array of arrays, how can i fix that?

A: You could probably simplify what you are doing
char[][] pArrays =
   {
      p1.ToCharArray(0, 2),
      p2.ToCharArray(0, 2),
      p3.ToCharArray(0, 2),
      p4.ToCharArray(0, 2)
   };

// to looped the arrays
for (int j = 0; j < 4; j++)
{
   // to access the original array
   var originalArray = pArrays[j];

   // to loop the elements
   for (int i = 0; i < 2; i++)
   {
      // to access the elements
      // pArrays[j][i]
      // originalArray[I]
   }
}


text:
Q: Implement apple.ldif in an openldap I'm currently running an openldap server on a debian machine
Distributor ID: Debian
Description:    Debian GNU/Linux 8.7 (jessie)
Release:    8.7
Codename:   jessie

Slapd version
@(#) $OpenLDAP: slapd  (Jan 16 2016 23:00:08) $
    root@chimera:/tmp/buildd/openldap-2.4.40+dfsg/debian/build/servers/slapd

I've transform the official schema into an ldif with following tutorial here
Worked perfectly my kerberos ldifs, but when I try to apply the apple.ldif, I encounter a
SASL/EXTERNAL authentication started
SASL username: gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth
SASL SSF: 0
adding new entry "cn=apple,cn=schema,cn=config"
ldap_add: Other (e.g., implementation specific) error (80)
    additional info: olcObjectClasses: AttributeType not found: "acctFlags"

So far, some blogs say that this isn't a critical attribute, and could be directly removed.
I wanted to know if that's "normal" to just remove some attributes directly from the official schema (same schema I can also get from directly some iMacs in the infrastructure) ?

A: This question and 84104's answer ended up pointing me in the right direction. apple.schema doesn't list its dependencies, but most (if not all) of the others do.
Here are the schemas I needed to load (and in this order) to satisfy all the dependencies and convince slapd to load apple.schema:
core.schema
cosine.schema
inetorgperson.schema
nis.schema
samba.schema
apple_auxillary.schema
apple.schema

A: No, it's not normal to remove attributes. If you're missing an attribute it usually means you're missing some other dependent schema.
In this case it looks like Apple's samba schema. This may in turn rely on other schema, but I suspect they've provided the complete set.


text:
Q: Dolphin File manager List of devices disappeared While I was using Dolphin file manager, suddenly the list of devices disappeared while i was copy/pasting some files and the category itself called Devices. How do I bring this back?

A: Ok i figured it out using this post. I needed to right click on any empty space on the left pane of the dolphin file manager then > Show all
https://forum.kde.org/viewtopic.php?f=224&t=151675


text:
Q: ios notifications firebase when app killed redirect specific view Good morning, developing an app where I use firebase to receive notifications, I have a problem if I send a notification and the application is killed, I open the first page of the application instead I would like to open a specific view, here is my code
func application (_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    FirebaseApp.configure ()

    // locally save data for settings

    let launchedBefore = UserDefaults.standard.bool (forKey: "launchedBefore")
    if launchedBefore {
        print ("Not first launch.")
    } else {
        print ("First launch, setting UserDefault.")
        UserDefaults.standard.set (true, forKey: "isNotify")
        UserDefaults.standard.set (false, forKey: "isZoom")
        UserDefaults.standard.set (true, forKey: "isCookie")
        if UserDefaults.standard.bool (forKey: "isNotify") {
            registerNotification ()
        }
        UserDefaults.standard.set (true, forKey: "launchedBefore")
    }
    NotificationCenter.default.addObserver (self, selector: #selector (registerNotification), name: NSNotification.Name (rawValue: "isNotify"), object: nil)
    return true
}

func registerNotification () {
    if #available (iOS 10, *) {
        UNUserNotificationCenter.current (). RequestAuthorization (options: [. Badge, .alert, .sound]) {(granted, error) in}
        UIApplication.shared.registerForRemoteNotifications ()
    }
        // iOS 9 support
    else {
        UIApplication.shared.registerUserNotificationSettings (UIUserNotificationSettings (types: [.badge, .sound, .alert], categories: nil))
        UIApplication.shared.registerForRemoteNotifications ()
    }
}

A: inside the didFinishLaunchingWithOptions method, read the notification like that:
        let notification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary
    if notification != nil {
        // Read the notification payload and open related page
    }

A: let rootViewController = self.window.rootViewController
    // write a method named like openNotifyPage in rootViewController to push opennotify
    rootViewController.openNotifyPage

than push opennotify vewcontroller inside this method


text:
Q: How to filter lists in a list? I have, e.g., listy = [[1,-1,2], [3,-2,-4]]
I want to filter such that I get just the positive elements [[1,2], [3]]
This is easy to do with a loop and filter(lambda x: x > 0, listy), but I'd like to avoid a loop.

A: List comprehensions can be nested:
In [2]: [ [i for i in x if i>0] for x in listy ]
Out[2]: [[1, 2], [3]]

Regarding the choice between filter and list comprehension, Guido van Rossum, the BDFL, wrote that list comprehension is both clearer and faster;

filter(P, S) is almost always written clearer as [x for x in S if
  P(x)], and this has the huge advantage that the most common usages
  involve predicates that are comparisons, e.g. x==42, and defining a
  lambda for that just requires much more effort for the reader (plus
  the lambda is slower than the list comprehension).

Advanced Topic: Handling large datasets
If listy is large and your application permits, you may want to use generators in place of lists:
g = ( (i for i in x if i>0) for x in listy )

A: Your problem pretty much inherently requires a loop. You want to do something for each member of listy, the for is there even in English.
However, you can wrap the loop up inside a comprehension, or a call to map, etc. For example:
listy = map(lambda sublist: filter(lambda x: x>0, sublist), listy)
listy = [[x for x in sublist if x>0] for sublist in listy]

(Or, of course, the other two combinations of the above, a comprehension over filter, or a map over a comprehension.)
You can also do the looping lazily, so instead of wasting time up front creating the filtered lists, you just create iterators that will generate the positive values on demand:
itery = itertools.imap(lambda sublist: itertools.ifilter(lambda x: x>0, sublist), listy)
itery = ((x for x in sublist if x>0) for sublist in listy)

But that just means the looping happens later, when you iterate over each element of itery, rather than right away.
(And again, you can combine the above two ideas, e.g., a list of iterators or an iterator of lists, instead of an iterator of iterators or a list of lists.)
You can even hide the loop inside a NumPy element-wise operation by creating a 1D array of Python lists and calling vectorize(lambda lst: filter(lambda x: x>0, sublist)) on it. But the loop's still going to be there.

Of course you could also get around the loop by looping indirectly. For example, with recursion:
def filter_nonpositives(x):
    return x[:x[0]>0] + filter_nonpositives(x[1:])

Or even by unrolling the loop up to some maximum size:
def filter_nonpositives(x):
    result = []
    if len(x) == 0:
        return result
    if x[0] > 0:
        result.append(x[0])
    if len(x) == 1:
        return result
    if x[1] > 0:
        result.append(x[1])
    if len(x) == 2:
        return result
    if x[2] > 0:
        result.append(x[2])
    # ... repeat as far as you want
    return result

But either way, you're still effectively looping—and you'd be hard-pressed to find anyone who thinks either one is more Pythonic, or better.


text:
Q: Reason linking to pthreads causes a change in program behavior? When linking to pthreads I get unexpected behavior during program execution, the ncurses interface becomes unresponsive, but the program does not crash. This is without using any pthread functionality, no threading headers or anything related to threads, just linking.
Are there any reasons that linking to a library can change program behavior without issuing warnings?
Pertinent information:

*

*ncurses is also linked to the executable.

*Everything is in a namespace.

*Tried on current gcc and clang.

*No compiler/linker errors or warnings using -Wall.

*Arch Linux.

Linking ncurses and pthread together works fine on a smaller test program I made. So what I am looking for are more places to look, it's a library project and the codebase is a good size, it is all plain C++14 except for a small component that uses the ncurses library.

A: If you didn't changed anything in your code, didn't even include headers,  but behavior changed, then your project contains UB. Possible UBs defined in standard, that may cause this:

*

*Defining ANY function or global variables that match by name ones contained in standard headers

*Defining something in std namespace.

*Usage old C standard headers mixed with new C++ headers

*Usage of variables that were initialized with undetermined value.

*Array bound breaches, that do not lean to page fault or other kind of catastrophic result, may cause program change behavior.

*Illegal use of side-effects of operators, e.g.: a ^=b ^= a ^=b;

and so on.
I  recommend to check warnings, not only errors. There are certain warnings  that are actually signs of semantic error or UB. AT least for GCC. Many novice programmers just ignore warnings as non-essential. E.g. this kind sneaks in quite often:
const char a = 167;

if(a == 167)  // compiler makes warning here, a ==-89 in this example
{
    // code will never be executed or even compiled
}

The code compiles but doesn't execute in expected way.


text:
Q: WCF IsReference = true is resetting the values to Default I have a very simple WCF 4.0 service in which I am returning an POCO entity object whose IsReference is set to true. When I return the object from my service, the values of primitive types (int, double, etc) are set correctly and the ones having references are also getting serialized properly, I've verified that the serialization happen correctly putting following code just before return statement. I've also verified that the members are correctly marked with [DataMember] and they have public getters/setters. However, when the object is received by the caller, all the primitive types are set to 0 and the ones with references are set to NULL.
Would appreciate any help!
try
       {
           var stream = new MemoryStream();
           var dataContractSerializer = new DataContractSerializer(onlineSellItemDetail.GetType());

           dataContractSerializer.WriteObject(stream, onlineSellItemDetail);

       }

       catch (Exception ex)
       {
           Console.WriteLine(ex.InnerException.ToString());
       }

A: This is almost always because no XML, empty XML, or incompatible XML was received on the client end. Sometimes, this is because the stream was not flushed or closed properly on the service side. Other times, the client side is operating with completely valid XML in its own stream, but is reading the XML by perhaps not starting at the beginning of the stream. If you enable tracing on the service side and the client side, generate tracing logs, and analyze with SvcTraceViewer, and in parallel, use Fiddler to monitor the wire traffic on both the client side and the service side, I think you'll find the answer for sure!


text:
Q: How to pass non-fatal warnings from a library A library function parses a file and returns an object. If a parser encounters unknown data, missing values etc., it shouldn't throw an exception and stop parsing (because this is not fatal), but there should be a way to pass information about these things to a caller (so that warnings can be displayed in the UI, for example). How can these warning be returned? I'm thinking of passing a callback function/object into the library, are there any other possible solutions?

A: I would have a collection of errors easily accessible on the parser, something like this:
public class Parser
{
   public bool HasErrors {
     get { return ParseErrors != null && ParseErrors.Count > 0; }
   }
   public List<string> ParseErrors { get; set; }
   public object Parse(string fileName) {}
}

Or whatever error type you wanted of course, something with more detail maybe.
Code calling your library would look something like this:
var p = new Parser();
var o = p.Parse("file.txt"); //Get object
if(p.HasErrors) //Uh oh, abort, do something with p.ParseErrors

A: A common solution is to provide the warning(s) via a related function. That way the warning will only be read when the client code wants it.

A: Well the returned object could include the warnings. In webservices, I usually deal with wrapper classes pretty much like:
class Wrapper {
    List<Warning> Warnings { get; set; }
    bool HasWarnings { get { return Warnings != null && Warnings.Count > 0; } }
    MyObject Result { get; set; }
}

This way it will be the responsibility of the receiving end to decide whether to take action on any warnings, but from its structure, it also becomes apparent to the person invoking the webservices that there might be warnings. A returned object like this pretty much begs for some basic level of error checking on the receiving side.

A: In pseudocode:
class ParseResult (
    Outcome <succesful, warnings, failed completely>,
    ParseOutput <result>,
    List<Warning> warnings
)

So you get back a nugget where you can quickly unwrap the end result, but also get status and warnings

A: If your programming language supports it, I recommend using events to pass warnings.  Your calling program can capture the event and then decide what to do with it based on the severity or type of warning that is passed with the event notification.  With events, the user doesn't have to wait for the entire file to finish processing before they see if there are any errors.  If you also provide a method to cancel the file processing they can make the decision to stop the processing if they decide the errors raised are serious enough.


text:
Q: Bootstrap 3 to Bootstrap 4 conversion What is the equivalent code of Bootstrap 3

into Bootstrap 4 ?

A: Bootstrap 3 or Bootstrap 4 difference

This is my article on this topic you can see here as well.
link:
  https://www.includehelp.com/html/difference-between-bootstrap-3-and-bootstrap-4.aspx
you can see here as well
link: http://upgrade-bootstrap.bootply.com/

Bootstrap 3.x                 Bootstrap 4
.col-*-offset-*           .offset-*
.col-*-push-*             .order-*-2
.col-*-pull-*             .order-*-1
.panel                    .card
.panel-heading            .card-header
.panel-title              .card-title
.panel-body               .card-body
.panel-footer             .card-footer
.panel-primary            .card.bg-primary.text-white
.panel-success            .card.bg-success.text-white
.panel-info               .card.text-white.bg-info
.panel-warning            .card.bg-warning
.panel-danger             .card.bg-danger.text-white
.well                     .card.card-body
.thumbnail                .card.card-body
.list-inline > li         .list-inline-item
.dropdown-menu > li       .dropdown-item
.nav navbar > li          .nav-item
.nav navbar > li > a       .nav-link
.navbar-right             .ml-auto
.navbar-btn               .nav-item
.navbar-fixed-top         .fixed-top
.nav-stacked              .flex-column
.btn-default              .btn-secondary
.img-responsive           .img-fluid
.img-circle               .rounded-circle
.img-rounded              .rounded
.form-horizontal           (removed)
.radio                    .form-check
.checkbox                 .form-check
.input-lg                 .form-control-lg
.input-sm                 .form-control-sm
.control-label            .col-form-label
.table-condensed          .table-sm
.pagination > li          .page-item
.pagination > li > a      .page-link
.item                     .carousel-item
.help-block               .form-text
.pull-right               .float-right
.pull-left                .float-left
.center-block             .mx-auto.d-block
.hidden-xs                .d-none
.hidden-sm                .d-sm-none
.hidden-md                .d-md-none
.hidden-lg                .d-lg-none
.visible-xs               .d-block.d-sm-none
.visible-sm               .d-none.d-sm-block.d-md-none
.visible-md               .d-none.d-md-block.d-lg-none
.visible-lg               .d-none.d-lg-block.d-xl-none
.label                    .badge
.badge                    .badge.badge-pill

A: Equivalent code of Bootstrap 3

Equivalent code of Bootstrap 4

Try this it works on extra small device, ipad,ipad pro and laptop as
well as extra large device


text:
Q: Exclude files from being downloaded Im using a server. Id like to sync files with my home PC. Unfortunally there is no app that could remember what files was previously downloaded - so if the file is moved from the "incoming" folder, it will be redownloaded from the server.
Ive found a app (goodsync) that is able to run a script or batch pre-download. So I was thinking, Ill run a script in advance that writes all the filenames to a .txt according this -> http://stackoverflow.com/questions/8612324/is-this-possible-to-write-list-of-file-names-into-a-text-file-using-batch-file-w
So, how to script or batch something like "check what´s in C:\exclude.txt and dont download files with the exact same name"

A: Okay here's a little shell script which can be used to read which files are already downloaded, reads which files exist and then checks which files should be downloaded. But I recommend you to learn shell scripting to understand the script and to make the script better.
Basically what this code does is reading the downloaded.txt (or exclude.txt) file (Every line should containt filename and hash concatenated).
Then it reads all files from the file system and checks if the file is contained in the downloaded.txt file.
If the file is not contained in the downloaded.txt file you can decide what you would like to do.

*

*you could create a new textfile which contains the files you have to
download.

*you could add the files found to downloaded.txt (but use the searched variable because it contains the hash and the filename) and download these files.

    found=0
    array_contains () {
        local array="$1[@]"
        local seeking=$2
        found=0
        for element in "${!array}"; do
            if [[ $element == $seeking ]]; then
            found=1
            break
            fi
        done
    }

    downloaded_files=()

    #Load the downloaded files from downloaded.txt into the downloaded_files array
    old_IFS=$IFS      # save the field separator
    IFS=$'\n'     # new field separator, the end of line
    for line in $(cat downloaded.txt)
    do
       downloaded_files=("${downloaded_files[@]}" "$line")
    done

    #print the whole array just for testing
    echo ${downloaded_files[@]}

    filehashlist=($(find * -type f -exec sha1sum "{}" \; | cut -d ' ' -f 1))
    filenamelist=($(find * -type f -exec basename "{}" \;))
    filenamelistFullPath=($(find * -type f))

    to_download_files=()
    counter=0
    for filename in "${filenamelist[@]}"
    do
        searched=$filename${filehashlist[$counter]}
        array_contains downloaded_files "$searched"
        if [ $found == "0" ]; then
            echo "Please download file: $filename"
            echo "Location: ${filenamelistFullPath[$counter]}"
            echo "Hash: ${filehashlist[$counter]}"
            echo "Add this line to downloaded.txt after download: $searched"
            echo ""
        fi
        counter=$counter+1
    done

    IFS=$old_IFS     # restore default field separator

A: From command line or .CMD script:
xcopy /D /E /F /Y /EXCLUDE:exclude.txt

where exclude.txt is the file you mentioned containing your list of filenames to be excluded


text:
Q: Cycle() function on a class I would like to make use of the function cycle to rotate the players in my game. I did as it follows:
class Pong:
    """Summary of class here.

       Longer class information....
       Longer class information....

       """

    def __init__(self, max_score):
        self.max_score = max_score
        self.game_over = 0
        self.p1_score = 10000
        self.p2_score = 2
        self.players_list = [self.p1_score, self.p2_score]

    def play(self, ball_pos, player_pos):
        import itertools
        """" ball = 1 pixel height
            paddles = 7 pixels height

            """
        player_time = itertools.cycle(self.players_list)
        print(next(player_time))

        return ""
g = Pong(2)
g.play(50,51)
g.play(50,51)
g.play(50,51)
g.play(50,51)

But my output goes only to the first element p1_score. Can someone help me to understand why next() does not work in this case and how can I fix it?
Thanks in advance,

A: this answer was provided by @user3483203  on the comments

You create the cycle generator each time you call play, you probably
  want to do that in your init function

 class Pong:
    """Summary of class here.

       Longer class information....
       Longer class information....

       """

    def __init__(self, max_score):
        self.max_score = max_score
        self.game_over = 0
        self.p1_score = 10000
        self.p2_score = 2
        self.players_list = [self.p1_score, self.p2_score]
        self.player_time = itertools.cycle(self.players_list)

    def play(self, ball_pos, player_pos):
        import itertools
        """" ball = 1 pixel height
            paddles = 7 pixels height

            """

        print(next(self.player_time))

        return ""
g = Pong(2)
g.play(50,51)
g.play(50,51)
g.play(50,51)
g.play(50,51)


text:
Q: AWS IAM policy for everyone but yourself I currently have this policy (HCL)
data "aws_caller_identity" "current" {}

data "aws_iam_policy_document" "admin_policy_doc" {
  statement {
    sid = "DenyAccessToModifySelf"
    effect = "Deny"
    actions = [
      "iam:AddUserToGroup",
      "iam:AttachUserPolicy"
    ]

    resources = [
     "arn:aws:iam::${data.aws_caller_identity.current.account_id}:user/&{aws:username}",
    ]
  }

  statement {
    sid = "AllowIAMControl"
    effect = "Allow"
    actions = ["iam:*"]
    resources = ["*"]
  }
}

That's designed to give an admin the ability to update someone else's permissions without updating her own to conform to separation of duties and least privilege. It seems though, that using the resource in question on the AddUserToGroup permission is the group and not the user. Therefore a user can still add herself to a more privileged group if she has this permission.
I've also tried using conditions like so:
{
    "Sid": "DenyAccessToAddSelfToGroup",
    "Effect": "Deny",
    "Action": [
        "iam:AddUserToGroup"
    ],
    "Resource": "*",
    "Condition": {
        "StringEquals": {
            "aws:username": [
                "${aws:username}"
            ]
        }
    }
}

But no dice. This is just a global condition that disallows adding ALL users to group, which is not what I want. Has anyone figured out a solution to this?


text:
Q: Ruby continuously reading from beginning of file How am I able to read a text file in ruby from the beginning (first line) of the file?
For example this code:
while line = file.gets
[code here]
end

reads from the first line to the last line and STOPS.
BUT, I would like to start again from the first line, and scan all the way to the last line.
Any way to do this?
Thanks.

A: The code you have written is quite unusual in Ruby programming, most of the time a file is read line by line using Enumerable methods, for example:
file.each { |line| [code here] }

That said you could use the Enumerable#cycle method to read the file more than one time. Given the following file, say foo.txt:
foo
bar

You can read it two times using the following code:
open('foo.txt') do |file|
  file.cycle(2) { |line| puts line }
end

# Output:
#
# foo
# bar
# foo
# bar

If you pass nil, or no argument, to cycle it will read the file forever.

A: Use file.rewind to revert it to the beginning.


text:
Q: How to set up auto sync secondary MySQL server without changing IP Currently, I've 2 DB servers say, public 123.123.123.123 IP mapped to one of the servers 192.168.1.2 and 192.168.1.3
Anyone has an idea how to set up auto sync of both MySQL server.
And  192.168.1.2 is down, it will fallback to 192.168.1.3 with 123.123.123.123 mapped to it automatically without the need of manual configuration ?
Anyone has useful information to go towards this direction?

A: on my case i use haproxy (for lb, 1 active, 1 standby/backup mode) and keepalived (for ip failover). on norman condition, only 1 server active, 2nd server will standby. the synchronization between server1 and server2 using mysql master-master (circular replication).
 192.168.1.2 \
               - 192.168.1.1 (VIP) -- 123.123.123.123 - internet
 192.168.1.3 /

ref:
- http://www.alexwilliams.ca/blog/2009/08/10/using-haproxy-for-mysql-failover-and-redundancy/
- http://www.neocodesoftware.com/replication/


text:
Q: If $x+y+z=xyz$, find $\frac{3x-x^3}{1-3x^2}+\frac{3y-y^3}{1-3y^2}+\frac{3z-z^3}{1-3z^2}$ I found this question in a maths worksheet of trigonometry (kinda odd, right?), but I dont know how to figure it out.
If $\displaystyle x+y+z=xyz$, find $\displaystyle\frac{3x-x^3}{1-3x^2}+\frac{3y-y^3}{1-3y^2}+\frac{3z-z^3}{1-3z^2}$
First I thought of taking x,y and z as $\displaystyle \tan A, \tan B,$ and $\tan C,$ making $A+B+C=\pi$, but couldnt solve ahead. Any solution not involving trigonometry would do as well.
I also think that this question does not even relate to trigo.....or does it?

A: We can not make $A+B+C=\pi$
as $\displaystyle \tan(A+B+C)=\frac{\sum\tan A-\tan A\tan B\tan C}{1-\sum \tan A\tan B}$
$\displaystyle\sum\tan A=\tan A\tan B\tan C\implies \tan(A+B+C)=0\implies A+B+C=n\pi$ where $n$ is any integer [Clearly, you have taken a special value$(1)$ of $n$]
Now for any integer $m,$ $\displaystyle m(A+B+C)=mn\pi\implies \tan(mA+mB+mC)=\tan mn\pi=0$
$\displaystyle\implies\sum\tan mA=\tan mA\tan mB\tan mC$
Now set $m=3$ and apply $\tan3x$ formula

A: Hint: You are in the right track. Now observe that $\tan (3A+3B+3C)=0$ and hence $\tan 3A+\tan 3B+\tan 3C=\tan 3A\tan 3B \tan 3C$

A: Case I: At least one of $x^2$, $y^2$ and $z^2$ is equal to $1/3$. This case is possible, e.g., $x=\frac{\sqrt{3}}{3}=-y$ and $z=0$. In this case, the formula $\displaystyle \frac{3x-x^3}{1-3x^2}+\frac{3y-y^3}{1-3y^2}+\frac{3z-z^3}{1-3z^2}$ does not make any sense.
Case II: None of $x^2$, $y^2$ and $z^2$ is equal to $1/3$ and $xyz=0$. For example, we say $x=-y$ and $z=0$, which implies that
\begin{eqnarray*}
\frac{3x-x^3}{1-3x^2}+\frac{3y-y^3}{1-3y^2}+\frac{3z-z^3}{1-3z^2}=\frac{3x-x^3}{1-3x^2}+\frac{-3x+x^3}{1-3x^2}+0=0.
\end{eqnarray*}
Case III: None of $x^2$, $y^2$ and $z^2$ is equal to $1/3$ and $xyz\neq0$. Take $x=\tan A$, $y=\tan B$ and $z=\tan C$ for some $A,B,C\in(-\pi/2,\pi/2)$, since $x+y+z=xyz$, then $xy,xz,yz\neq 1$, which implies that $A+B$, $A+C$ and $B+C$ can not be $\pm\pi/2$.
Claim I: $A+B+C\neq\pm\pi/2$.
If not, then $\tan(A+B)=\cot C$, that is, $\displaystyle\frac{x+y}{1-xy}=\frac{1}{z}$, that is, $(x+y)z=1-xy$. Hence $(x+y)z^2=z-xyz=z-(x+y+z)=-(x+y)$, that is, $x+y=0$. Since $x+y+z=xyz$ and $z\neq0$, we get $xy=1$, contradiction.
In summary, we can define $\tan(3A)$, $\tan(3B)$, $\tan(3C)$ and $\tan(A+B+C)$. Since $\displaystyle \tan(3\theta)=\frac{3\tan\theta-\tan^3\theta}{1-3\tan^2\theta}$, then we have
\begin{eqnarray*}
\frac{3x-x^3}{1-3x^2}+\frac{3y-y^3}{1-3y^2}+\frac{3z-z^3}{1-3z^2}=\tan(3A)+\tan(3B)+\tan(3C).
\end{eqnarray*}
Notice that
\begin{eqnarray*}
\tan(A+B+C)&=&\frac{\tan A+\tan B+\tan C-\tan A\tan B\tan C}{1-\tan A\tan B-\tan A\tan C-\tan B\tan C}\\
&=&\frac{x+y+z-xyz}{1-xy-xz-yz}=0.
\end{eqnarray*}
Then there exists some $m\in\{-1,0,1\}$ such that $A+B+C=m\pi$. Hence $\tan(A+B)+\tan C=0$, which implies that $\tan^2(A+B)\neq1/3$. Hence we can define $\tan(3A+3B)$. So we have
\begin{eqnarray*}
0&=&\frac{\tan(3A)+\tan(3B)+\tan(3C)-\tan(3A)\tan(3B)\tan(3C)}{1-\tan(3A)\tan(3B)-\tan(3A)\tan(3C)-\tan(3B)\tan(3C)}.
\end{eqnarray*}
Then we get
\begin{eqnarray*}
\frac{3x-x^3}{1-3x^2}+\frac{3y-y^3}{1-3y^2}+\frac{3z-z^3}{1-3z^2}=\tan(3A)+\tan(3B)+\tan(3C)=\tan(3A)\tan(3B)\tan(3C).
\end{eqnarray*}


text:
Q: how to set jbutton icon for specific time to show when it is clicked and how to disappear the icon when time finished how to code java for set timer to my button for set button icon when i clicked and some time delay for process while my button icon has to show then the icon have to set null for time end.
i have tried following way but it is work when i am not to clicked the button
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {

  timer = new Timer(5000, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(chromeShown) {
                    jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/r/ajaxloading.gif")));
                    chromeShown = true;
                } else {
                    jButton3.setIcon(null);
                    chromeShown = false;
                }
            }
        });
        timer.start();

        this.getContentPane().add(JButton);
        this.setVisible(true);

A: Based on my understanding of your problem, your logic is a little skewed, the actions should following along something like
Button Clicked -> Icon Changed -> Timer Started ...(waiting)... -> Timer triggered -> Icon Changed.
At the moment, you're trying to change the initial state of the icon in the Timer, which doesn't make sense.  I think you want to do something more like this...
click.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        click.setEnabled(false);
        click.setText("I'm running >>");
        Timer timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                click.setText("I be done");
                click.setEnabled(true);
            }
        });
        timer.start();
    }
});

Basically, when the button is clicked, this sets the button's text and disables the button (so you can't click it again) and the after 1 second, it changes the text and enables the button


text:
Q: Powershell - Missing System.Collections.Generic in C:\windows\assembly\GAC_MSIL I'm trying to use this code in Powershell:
Add-Type -AssemblyName "System.Collections.Generic"

However I get this error:
Add-Type : Cannot add type. One or more required assemblies are missing.

I've looked in C:\windows\assembly\GAC_MSIL and can see that there is no folder named System.Collections.Generic.
Do I need to download this library, if so where?

A: There is no System.Collections.Generic assembly. That is a namespace. A large portion of the types in that namespace are in the core library assembly, mscorlib.dll which is already available in Powershell since Powershell is .Net.
Go to MSDN for the namespace, find the type you are trying to use, and you can see the assembly it is in, and remember that there is not necessarily a one to one relationship between assemblies and namespaces.
Using generic types is a bit involved in Powershell and can depend on using reflection, or formatting complex type names.
See this stackoverflow question for some more details.

A: Never mind,
not sure why that doesn't work, but turns out I don't need it anyway.
I had this code which for some reason wasn't working intially because it couldn't find [Collections.Generic.List[String]], but now it seems to work:
[string[]] $csvUserInfo = @([IO.File]::ReadAllLines($script:EmailListCsvFile))
[Collections.Generic.List[String]]$x = $csvUserInfo

A: I would answer by another question, Why do you need this assembly ?
Can you try to replace your code by :
$x = [IO.File]::ReadAllLines($script:EmailListCsvFile)

In PowerShell it should work.


text:
Q: How to merge several rows that share the same foreign key, into columns? I have a main table that stores information about the general details of a sample. There are also several rows in another table that have the main tables id as a foreign key. I want to merge the id's of these individual rows and the main table id into columns on a single row.
I've tried writing a view that creates rows joining data between sample_admittance. The problem is that it would create several rows to fit a unit id in only one column for each join.
 SELECT
    mt.project,
    mt.project_name,
    mt.client,
    mt.date,
    mt.location,
    u.unit,
    u.status
   FROM main_table mt
     JOIN units u ON u.main_table_id::text = mt.id::text;

I wanted it organized like:
main_table_id | unit_1 | unit_2 | unit_3 | ... | unit_10

but instead get multiple rows
main_table_id | unit

id_1          | un1
id_1          | un3
id_2          | un1


text:
Q: UNIQUE constraint failed in django project I have an application in django 1.11, where I have an app 'accounts' to manage users.
User can have assigned roles, with which there are problems when creating usera using manager.
When adding a username, I get an error:
IntegrityError at /accounts/add_user/

UNIQUE constraint failed: accounts_role.id

Here is my model:
class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(_('Email address'), unique=True)
    first_name = models.CharField(_('First name'), max_length=60, blank=True)
    last_name = models.CharField(_('Last name'), max_length=60, blank=True)
    roles = models.ManyToManyField(Role, unique=False)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    objects = UserManager()

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

Below is Role class:
class Role(models.Model):
    ADMIN = 1
    PLAYER = 2
    ROLE_CHOICES = (
        (ADMIN, 'admin'),
        (PLAYER, 'player'),
    )

    id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, default=2, primary_key=True, unique=False)

    def __str__(self):
        return self.get_id_display()

Here is manager:
class UserManager(BaseUserManager):
    def create_user(self, email, password):
        user = self.model(email=email, password=password)
        user.set_password(password)
        user.is_staff = False
        user.is_superuser = False
        user.save(using=self._db)
        role = Role.objects.create(id=2)
        user.roles.add(role)
        return user

A: In create_user, you should assign one or more existing roles to the new user rather than trying to create the same new role every time (with always the same primary key which obviously violates the unique constraint).
Your Role model defines only two roles. Create them separately from the user creation process and then assign them:
def create_user(self, email, password):
    # (...)
    role = Role.objects.get(id=2)
    user.roles.add(role)


text:
Q: PHP Get Variable avoid to remove & in URL page.php?clss_type=Boys%20&%20Girls
if I try to Echo the get variable I will automatically skip the '&' in the String
<?PHP echo $class = $_GET['clss_type'];?>
output:  Boys instead of Boys & Girls

A: By default PHP uses & as the variable separator in a query string.
You will need to escape that character to %26, or you can change PHP to use a different character as the separator using the arg_separator.input directive in the php.ini (https://www.php.net/manual/en/ini.core.php#ini.arg-separator.input).


text:
Q: React Router with nested children? Looking at the huge-apps example on the react-router github, I am not sure how to setup the routes I want.
URL        | Result
--------------------------
/sites     | List of sites
/sites/:id | One site

If I want to list multiple sites, the Site component/route would need to be nested in the Sites component/route. Therefore, my folder structure would look similar to the Assignments model in the react-router example.
/routes
    /Sites
        /components
        |   Sites.js
        /routes
        |   /Site
        |   |   /components
        |   |   |   Site.js
        |   |   index.js
        index.js

However, for the /sites/:id route, it is not dependent on the Sites component. Would I create another Site directory on the same level at the Sites directory, or would I make the Site component be able to render a list and singular view? What would my index.js files look like?

A: I would visualize your route tree this way:
/sites
(Sites.js)
- /:id1
  (Site1.js)
- /:id2
  (Site2.js)

Inside your index.js, something like this (using a client-side example):
render((
  <Router history={browserHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={Home} />
      <Route path="/sites" component={Sites}>
        <Route path="/sites/:id" component={Site}/>
      </Route>
    </Route>
  </Router>
), document.getElementById('app'));

Each route has an accompanying component. You can throw anything you want in those components, although it probably would be helpful to include some way to navigate to child routes.
PlainRoute version (though I'm not sure why you'd want to):
const rootRoute = {
  component: 'div',
  childRoutes: [{
    path: '/',
    component: require('./components/App'),
    childRoutes: [ require('./routes/Sites') ]
  }]
}

render(
  <Router history={browserHistory} routes={rootRoute} />,
  document.getElementById('example')
);

'./routes/Sites':
module.exports = {
  path: 'sites',
  getChildRoutes(location, cb) {
    require.ensure([], (require) => cb(null, [ require('./routes/Site') ]))
  },
  getComponent(nextState, cb) {
    require.ensure([], (require) => cb(null, require('./components/Sites')))
  }
}

'./routes/Site':
module.exports = {
  path: 'sites/:id',
  getComponent(nextState, cb) {
    require.ensure([], (require) => cb(null, require('./components/Site')))
  }
}

A: If I understand correctly what you're trying to achieve, you could do something like this inside your router:
<Route path="/sites/:id" component={SingleSite} />
<Route path="/sites" component={Sites} />

Where the SingleSite component takes the id param and uses it to display the site. React router should be able to use the SingleSite component if there is an ID and show the Sites component if not.


text:
Q: How to customize order of header values that are joined when answer is yes in Google Sheets How can I modify the equation in this Google Spreadsheet which I found as an answer to another question so that it can allow a user to customize the order of replaced values?
Goal
Replace "yes" answers in a range in a given row (ie A2:D4), with a header values separated by commas in E4 in an order that is desired.
Preliminary approach
The preliminary approach uses "helper" cells in the spreadsheet (more below image), but I would appreciate help in combining two independent formulas.

Specify order
The headers are labeled with a number in the desired order. The original formula will look for a "yes" and replace that with the header value for any questions in a range and outputs as an index
The second formula will then split and sort the values in alphabetical order and then REGEXREPLACE the numbers.
Any assitance to combine these two formulas is much appreciated!
SET #1:
=index(substitute(substitute(trim(transpose(query(transpose(if(B2:E<>"yes",,substitute(B1:E1," ","❄"))),,9^9)))," ",", "),"❄"," "))

AND
=TRIM(REGEXREPLACE(JOIN(",",SORT(TRANSPOSE(SPLIT(E2,",")))),"\b\d_",""))

ALTERNATIVE SET #2
INDEX(REGEXREPLACE(TRIM(FLATTEN(QUERY(TRANSPOSE( IF(B2:E="yes", B1:E1&",", )),,9^9))), ",$", ))

AND
=TRIM(REGEXREPLACE(JOIN(",",SORT(TRANSPOSE(SPLIT(E2,",")))),"\b\d_",""))

Thank you in advance for your help!
The shared google sheet is here

A: use:
=INDEX(REGEXREPLACE(TRIM(FLATTEN(QUERY(TRANSPOSE(
 IF(TRANSPOSE(SORT(TRANSPOSE(A2:D), FLATTEN(A1:D1), 1))="yes",
 REGEXREPLACE(TRANSPOSE(SORT(FLATTEN(A1:D1))), "(^\d+_)", )&",", )),,9^9))), ",$", ))


text:
Q: How to debug Lightning Accessory via Xcode on iOS I am developing an iOS application that talks to a lightning accessory. Now, when the accessory is attached, I cannot use the lightning port to debug my application in Xcode.
Is there a way to attach debugger to my application when a lightning accessory is connected to iOS device?
or
Can I somehow attach the lightning accessory to my Mac, and debug it in simulator?
I know some people are talking about WiFi debugging, but that is not supported in Xcode 6.

A: With Lightning accessories, there doesn't appear to be an option for connecting both Xcode & the Accessory at the same time. I think this has something to do with the way Lightning cables require authentication hardware inside (so nobody has been able to come up with a dongle/splitter). The solution I ended up using was a remote logging tool that sends log messages via network to your Mac. I use NSLogger but there is also CocoaLumberJack.
Granted, you have to pepper your code with log messages for this to be useful and there are other limitations, but it is better than nothing. You can also clean up your log messages by using a custom log macro (Objective-C only).

A: I am attempting the same thing.  I could do it on 30 pin device using the CableJive adapter.  But there does not appear to be a way to do this with Lightning.  I suspect that since lightning connections (including cable) are all secured though embedded serial number chip, it means that the iOS device only allows one authentication chip per lightning connector, which means no splitters / bridges / Y-Connectors or other items unless approved by Apple.
Apple does have some magic devices for MFI approved developers, but my MFI approval expired, so not sure what they have now for Lightning device testing.

A: You may be able to connect to XCode wirelessly and develop with the accessory connected. This question may help guide that process.
What does the Xcode 4.2 preference "Support Wirelessly Connected Devices" do?

A: Wireless debugging is now available as of Xcode 9 or later and iOS 11 or later. A nice write-up on how to connect your mobile device to remotely debug are here:

*

*https://medium.com/swiftist/wireless-debugging-xcode-b6e98e26e022

*How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?


text:
Q: Link Realm within a dynamic library ends in "ld: framework not found Realm for architecture i386" I've created a custom dynamic library (let's call in LogLibrary.framework) in Swift 2.1. No I'd like to link the Realm.framework and RealmSwift.framework with it.
I did follow the installation instructions provided on https://realm.io/docs/swift/latest/.
These steps are:

*

*Link Binary with Libraries (Realm.framework and RealmSwift.framework added)

*Build Phase -> Add copy files Phase -> Destination "Frameworks"

*Run Script Phase -> bash "${BUILT_PRODUCTS_DIR}/${FRAMEWORKS_FOLDER_PATH}/Realm.framework/strip-frameworks.sh"

Unfortionally, if l link the LogLibrary.framework in my sample Application, I always get the following compile error:

ld: framework not found Realm for architecture i386

I did not set any additional linker flags in the sample Application.

However, It works if I also link the Realm.framework and RealmSwift.framework in the sample Application - but that's not what I want, because they are already linked within the LogLibrary.framework
Any Ideas how I can get rid of the compile error?
Sample Project: https://github.com/sehdich/RealmLinkError.git

A: You should link Realm and RealmSwift.framework to PhotoApp target too. Because those frameworks are not static libraries. They are linked dynamically. So they are still specified to link app's target and included in app bundle.


text:
Q: Error 414 when logging in with multiple accounts We're using GAE Python and allow users to login using their existing Google accounts. The login code is straightforward:
def _require_login(self, target_url="/"):
    if not self.user_bundle.user:
        return self.redirect(
            self.user_bundle.create_login_url(target_url),
            abort=True
        )

This creates a redirect to Google for the user to login, then upon successful login gets sent back to wherever they were originally trying to navigate.
The problem seems to be that if a user has more than a certain number of Google / GApps accounts logged in simultaneously (we're guessing 3 or more I can successfully reproduce it once I hit 5 accounts), they get an "Error 414" from Google:

My brief search on the error states that the URL is too long, since it's a GET request. Just about all of the advice states to use POST instead. The problem is, we're using Google's built-in create_login_url method, which, as far as I can tell, doesn't provide a way to specify POST instead of GET.
How can we fix this?

A: According to the Google Cloud Platform's Twitter account:

Unfortunately, only current fix is to logout of some accounts. >4 accounts logged in makes the URL too long (> 2048 bytes).

So now we're going to either make a pre-login page where it tells the user to log out of enough user accounts to meet the maximum number, or find an external library that allows us to let users log in without having to work around the limit.


text:
Q: Error in using mt19937 with random_device as static class members I have a class called RandomNumberGenerator using which I want to generate a random number using mt19937 algorithm.
I am creating an object of random_device to work as seed.
When I compile, I am getting an error that says:
"No member named generate in std::__1::random_device".
I am not able to understand the error. Perhaps I am doing something wrong in the way I am initializing the objects of random_device and mt19937 but I am unable to figure out what's wrong.
Appreciate some help..
RandomNumberGenerator.h
class RandomNumberGenerator
{
    static std::random_device   m_rd;
    static std::mt19937         m_rng;
public:
    static double getRandomNumber(const double& rangeStart, const double& rangeEnd);
};

RandomNumberGenerator.cpp
#include "RandomNumberGenerator.h"

std::random_device   RandomNumberGenerator::m_rd;
std::mt19937         RandomNumberGenerator::m_rng(RandomNumberGenerator::m_rd);

double RandomNumberGenerator::getRandomNumber(const double& rangeStart, const double& rangeEnd)
{
    std::uniform_real_distribution<> randomizer(rangeStart, rangeEnd);
    return randomizer(m_rng);
}

A: Ah, you missed only one small item.
std::mt19937 RandomNumberGenerator::m_rng(RandomNumberGenerator::m_rd);

The above line is sending the instance and not the seed.  Therefore it must have a generate function to provide the seed, which it does not have.  Simply change that line to call the functor, and all is well.
std::mt19937 RandomNumberGenerator::m_rng(RandomNumberGenerator::m_rd());

NOTE:
One other item to note is that you are allocating a new std::uniform_real_distribution on each call.  While distribution objects are light weight, consider making that static as well, as long as the rangeStart and rangeEnd remain the same for subsequent calls.  However if you make that decision, initializing the range values will be a tougher call.
If your program doesn't use this class during the whole lifetime, consider making this an instance class, and take the range on the ctor,  allowing complete cleanup following the generation of numbers.
Hope this helps.
EDIT:
If you definitely want this to be static, another option would be to allocate and completely cleanup all objects in a function that will fill all needed values, similar to the following:
template<typename T, typename DISTRIBUTION_T>
static void fill(T* buffer, uint32_t const count, T const min, T const max)
{
    ASSERT(buffer);
    ASSERT(count);
    ASSERT(max > min);

    std::random_device randomDevice { };
    std::mt19937_64 twisterEngine { randomDevice() };
    DISTRIBUTION_T distribution(min, max);
    for (uint32_t i = 0u; i < count; ++i)
        buffer[i] = distribution(twisterEngine);
}

Then use this for various types like the following:
uint32_t const COUNT = 31u;
double realValues[COUNT];
uint32_t intValues[COUNT];

RandomNumberGenerator::fill<double, std::uniform_real_distribution<double>>(realValues, COUNT, 100.0, 200.0);
RandomNumberGenerator::fill<uint32_t, std::uniform_int_distribution<uint32_t>>(intValues, COUNT, 100u, 200u);

If that looks like an ugly interface then make fill private, and provide clean public methods to provide a few types you wish to support.


text:
Q: How to catch all PHP errors? I need a solution to catch all PHP fatal errors, exceptions, warnings, etc. and have a callback.
I want to display a friendly version of the error to the user and log that error.
I'm thinking about using a text file per day for logging error.
Any suggestion or PHP class (library)?

A: Try launch this web page, you should see "Message: Division by Zero".
// Set Error Handler

set_error_handler (
    function($errno, $errstr, $errfile, $errline) {
        throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
    }
);

// Trigger an exception in a try block

try {
    $a = 3/0;
    echo $a;
}
catch(Exception $e) {
    echo 'Message: ' .$e->getMessage();
}

A: php method: set_error_handler might be what you are looking for.
More at: http://www.php.net/manual/en/function.set-error-handler.php
and at: http://php.net/manual/en/book.errorfunc.php

A: This makes almost all errors become catchable instance of ErrorException:
set_error_handler(function($errno, $errstr, $errfile, $errline ){
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});

use it before of the code that can give errors, for instances at the very top of your php file or in a common header included
Limits: Severest errors (PHP engine, server, syntax) cannot be handled with a user defined function: E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT raised in the file where set_error_handler() is called compromise it.
But, if syntax is correct and server don't broke, these errors should not appear.
If needed, you could workaround it with the register_shutdown_function() and error_get_last()

A: As of PHP 8 the best way to catch any and all Exceptions is to catch the Throwable interface which "is the base interface for any object that can be thrown via a throw statement". So your code would look something like this.
try {
    # code...
} catch (\Throwable $th) {
    # code...
}

A: I quite like the error handling from the kohana framework. You'd have to do a bit of work to pull it out though.
http://kohanaframework.org/
It will allow you to do error logging to a file and email a recipient. It also enables you to redirect to your friendly error page.


text:
Q: Database Triggers and ECA ( Event Condition and Action ) I am new to Triggers in database and ECA.
According to my understanding, Triggers are the automated procedures in PL/SQl that are fired based upon some Event and Condition which is provide by ECA.
But does ECA has its own independent significance in database, it some independent system? or How do Triggers and ECA relate to each other ?
Any help on the above topics is highly appreciated .

A: Triggers mechanism allows to bind custom procedures to low level DML operations like insert, update and delete. Procedures are created by language used by data base, for example: oracle uses pl/sql, sql server uses tsql and other can use others.
For example:
Developer can create trigger on delete operation on table customers that invoke procedure that create log.
You can say Trigger is fulfilling ECA concept.
Event - is DML operation on data.
Condition - defined during trigger creation.
Action - procedure defined by developer.


text:
Q: How do I make an AI move in a human-like way var playerX;
var playerY;
var playerSize = 15;
var playerSpeed = (playerSize / Math.pow(playerSize, 1.44)) * 10;
var Newcelltimer = 0;
var cell = []
var cellEaten = 0;
var celliseaten = false;
var eaten = false;
var zoom = 1;
var n = 0;
var Xgrid = 600;
var Ygrid = 600;
var cpu = [];

function setup() {
  frameRate(999)
  createCanvas(600, 450);
  playerX = Xgrid / 2
  playerY = Ygrid / 2;

}

function draw() {
  background(220);
  push();
  var Newzoom = 10 / playerSize
  let newnewZoom = 1.3 * lerp(0.9, 10 / playerSize, 0.5)
  Newzoom = lerp(zoom, Newzoom, 0.3)
  translate(Xgrid / 2, Ygrid / 2 - 50);
  scale(newnewZoom)
  translate(-playerX, -playerY);

  playerSpeed = (playerSize / Math.pow(playerSize, 1.44)) * 10

  Newcelltimer++;

  for (var i = 0; i < cell.length / 2; i++) {
    let d = int(dist(cell[i * 2], cell[i * 2 + 1], playerX, playerY))
    if (d <= playerSize / 2) {
      playerSize += 5;
      cell.splice(i * 2, 2)
      celliseaten = true;
    }
  }
  if (keyIsDown(UP_ARROW)) {
    playerY -= playerSpeed;
  }
  if (keyIsDown(RIGHT_ARROW)) {
    playerX += playerSpeed;
  }
  if (keyIsDown(DOWN_ARROW)) {
    playerY += playerSpeed;
  }
  if (keyIsDown(LEFT_ARROW)) {
    playerX -= playerSpeed;
  }

  if (playerX < playerSize / 2 - Xgrid) {
    playerX = playerSize / 2 - Xgrid
  }

  if (playerY < playerSize / 2 - Ygrid) {
    playerY = playerSize / 2 - Ygrid
  }

  if (playerY > 2 * Ygrid - (playerSize / 2)) {
    playerY = 2 * Ygrid - (playerSize / 2)
  }
  if (playerX > 2 * Xgrid - (playerSize / 2)) {
    playerX = 2 * Xgrid - (playerSize / 2)
  }

  if (Newcelltimer % 30 == 0) {
    cell.push(ceil(random(0 - Xgrid, 2 * Xgrid)),
      ceil(random(0 - Ygrid, 2 * Ygrid)))
  }

  if (Newcelltimer % 100 == 0) {
    cpu.push(random(-Xgrid, 2 * Xgrid), random(-Ygrid, 2 * Ygrid), 20)
  }

  for (var j = 0; j < cpu.length / 3; j++) {
    fill(0, 255, 0, 100);
    circle(NewposX,NewposY, cpu[j * 3 + 2])
  }
  for (var k = 0; k < cell.length / 2; k++) {

    fill(0, 255, 255, 100)
    circle(cell[k * 2], cell[k * 2 + 1], 7)
  }

  stroke(0)
  fill(255,255,0)
  circle(playerX,playerY,playerSize);

  if (playerSize >= 3 * Xgrid | playerSize >= 3 * Ygrid) {
    if (Xgrid > Ygrid) {
      playerSize = 3 * Ygrid;
    } else {
      playerSize = 3 * Xgrid;
    }

  }
  noFill();
  stroke(0, 0, 0)
  rect(0 - Xgrid, 0 - Ygrid, 3 * Xgrid, 3 * Ygrid)
  pop();
  text("Your size is " + playerSize, 20, 20);
}

How would I make the programmed unit move in a human-like way, right now, I'm stuck on getting it to move, a way I thought was to use Perlin noise, but that may keep on forcing it to always go one direction, I could use random, and map out that value to degrees/radians, then use trigonometry to find the path. Although if I'm not sure what the trigonometry solution would be.
EDIT: When I say "In a more human-like way," I'm not talking about really anything complicated, just that the AI for example doesn't move like: Right,Left,Right,Up,Down,Left

A: To make something move like a human is a pretty complicated task! I understand you merely wish to give some movement a natural appearance. P5's noise function is the easiest way to achieve this.
P5's noise function returns a float between 0 and 1, which, if directly applied to an objects position, can only move it in a positive direction. Try using the map function to normalize this output to -1 and 1 instead:
map(noise(x, y, z), 0, 1, -1, 1)

Apply this to some kind of transformation and your agent will move in both positive and negative directions.
To displace an agent on the x-axis, therefore, you could do something along these lines:
let amp = 20; // how much you want the agent to move
let offsetX = map(noise, 0, 1, -1, 1) * amp;
ellipse(200 + offsetX, 200, 10, 10);

A: You're question is a bit vague but it sounds like what you want to do is give the AI a goal I.E. some location in which it wants to go to and then use a simple pathfinder program to let it figure out the best direction to move in


text:
Q: How to get a new database reference inside an onCreate function for sending mail? I'm creating a function to send mail whenever a new order is being placed and I want to get a reference to the user email which is inside the database whose path is => Users/uid/email to get the email id of the user to send the mail. How to get this reference inside my function?
I've tried firebase.database.ref(/Users/${userId}/email).val(), admin.database.ref(/Users/${userId}/email).val(). But none of these work.
exports.orderPlaced = functions.database.ref(/Users/{uid}/Bag/Books/{orderId}).onCreate((snapshot, context) => {

const userId = context.params.uid;
const orderid = context.params.orderId;

const refer = firebase.database.ref(/Users/${userId}/email).val();

const mailOptions = {
    from: '"abc" <abc@gmail.com>',
    to: 'xyz@gmail.com',
    subject: 'Order Details',
    html: `
${orderId}

        ` // email content in HTML
};

try {
    mailTransport.sendMail(mailOptions);
    console.log('mail send');

}
catch(error) {
    console.error('There was an error while sending the email:', error);
}

return null;
});

I want to get the email id of the user but I get the error that firebase is not defined at exports.orderPlaced.functions.database.ref

A: You are probably getting the not defined export.orderPlaced error because firebase uses export  functions to get to the document which in your code is the const refer
To give you an example: -------exports.sendNotification = functions.database.refer("Users/{user_id}/Email/{email_id}").onWrite(event =>{
    const user_id = event.params.user_id;
    const email_id = event.params.email_id;-----------------