text:
Q: Adding none value to entity in symfony form In a Symfony form I have one field called slot that matches an entity with a custom query. let's say something like this:
->add('slot', 'entity', array(
    'label'             => 'Slot',
    'class'             => 'FooBarBundle:Slot',
    'property'          => 'name',
    'required'          => false,
    'query_builder'     => function(\Foo\BarBundle\Entity\SlotRepository $er) use ($ids) {
        return $er->createQueryBuilder('u')
            ->where('u.id IN(:ids)')->setParameter('ids', $ids);
    }
))

so far every thing works. The slot is a ManyToOne matching on the Team entity (for which the form is), so there can only be one slot selected at a time. As I said, every thing going according to plan. The user can select a slot and save it and every one's happy.
The trouble starts when you try to "unselect" a slot (yep that has to be possible). So I need to add a none value with a caption like None of the listed items or what ever. The question is how can I do that?

A: You should use empty_data and empty_value:
->add('slot', 'entity', array(
    'label'             => 'Slot',
    'class'             => 'FooBarBundle:Slot',
    'property'          => 'name',
    'required'          => false,
    'query_builder'     => function(\Foo\BarBundle\Entity\SlotRepository $er) use ($ids) {
        return $er->createQueryBuilder('u')
            ->where('u.id IN(:ids)')->setParameter('ids', $ids);
    },

    'empty_data'  => null,
    'empty_value' => 'None of the listed items' /* or null */
))

A: The way that choice fields (which the entity field extends) are rendered within Symfony forms is defined by a certain kind of logic (documentation). I'm guessing that you're rendering a <select> dropdown, in which case if you're using Symfony 2.6 or above, placeholder is what you want (documentation). Be warned though, with certain databases (e.g. Postgres), the placeholder option was broken in Symfony 2.7.0 and (I think) 2.7.1.
The empty_data / empty_value issue with forms is part of a longstanding confusion. In short, use placeholder.


text:
Q: Stuck on an integral of form $\int\exp(-\frac{\alpha}{m^2} - \beta m)\frac{dm}{m}$. Any ideas? My statistical model involves the multiplication of a scalar random variable $X|X \geq 0 \sim 2\mathcal{N}(x;0,\sigma^2)\ \mathbb{I} \ [x \in \mathcal{R}_+]$, or a gaussian variable that must be strictly above zero, and and scalar exponentially distributed magnitude $M \sim \exp(m;\lambda)$.
I would like to find the distribution of $C =M\cdot X$ which is clearly still positive.
So far I have that:
$f_C(c) = \int_0^{\infty}f_{X|M}(\frac{c}{M}|M = m)f_M(m)\frac{dm}{m}$
$\ \ \ \ \ \ \ \ \ \ = \int_0^{\infty}f_{X}(\frac{c}{m})f_M(m)\frac{dm}{m}$
$\ \ \ \ \ \ \ \ \ \ = \sqrt{\frac{2}\pi} \frac{\lambda}{\sigma}\int_0^{\infty}\exp \left({-\frac{1}{2}\left(\frac{c}{\sigma m}\right)^2} \right) \cdot \exp \left(- \lambda m\right) \frac{dm}{m}$
I haven't really founding a promising direction to pursue to integrate this. Part of what makes it difficult is the integration of the form $\int\exp(-\frac{\alpha}{m^2} - \beta m)\frac{dm}{m}$ and everything I try seems fruitless. I've considered modifying the $M$ distribution, but the exponential seems reasonable for my application. It's modelling something physical (diffusion of a single particle), but the magnitude $M$ is not determined by some well-defined rigourous process so it's quite possible the $M$ distribution has nothing to do with physics inherently. But I thought I could change the magnitude to the form $\sim \frac{1}{Z}e^{(k_bT)^{-1}U(m)}$ or even $\sim \frac{1}{Z}e^{-(k_bT)^{-1}U(m,x)} $ for some $U(\cdots)$'s if necessary, but I'm not sure if either of those would be physically justifiable. Any ideas?
EDIT: for clarity.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is WFS 2.0 fully backwards compatible with prior versions? My team has inherited some code that claims to have been written against WFS 2.0 but we need to work with servers that support earlier versions.  Does anyone know whether WFS 2.0 is backward compatible with prior versions?

A: It is not. There are a lot of differences between 2.0 and 1.0, but one of the biggest is the fact that the axis order was switched.
Geoserver has a good breakdown of the changes here.


text:
Q: Unable to compare two dates in android I want to compare two dates to categories Browser History...
I have seen too many posts but didn't get any helpful,
My code is as :
 private static String calculateDate()
{
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, -10);
    return simpleDateFormat.format(new Date(calendar.getTimeInMillis()));
}
private static String today()
{
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR,0);
    return simpleDateFormat.format(new Date(calendar.getTimeInMillis()));
}

public void getBHistory()
{
    long startdates = 0;
    long enddates = 0;
    Date endDate = null;
    Date startDate=null;

    try
    {
        startDate = (Date)new SimpleDateFormat("yyyy-MM-dd")
                .parse(calculateDate());
        endDate = (Date)new SimpleDateFormat("yyyy-MM-dd")
                .parse(today());
        startdates = startDate.getTime();
        enddates = endDate.getTime();
    } catch (ParseException e)
    {
        e.printStackTrace();
    }

    // 0 = history, 1 = bookmark
    String sel = Browser.BookmarkColumns.BOOKMARK + " = 0" + " AND "
            + Browser.BookmarkColumns.DATE + " BETWEEN ? AND ?";
    Cursor mCur = m_oContext.getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, sel,
            new String[]{
                    "" + startdates, "" + enddates
            }, null);
    mCur.moveToFirst();
    String title = "";
    String date_time = "";
    if (mCur.moveToFirst() && mCur.getCount() > 0)
    {
        while (!mCur.isAfterLast())
        {

            title = mCur.getString(mCur
                    .getColumnIndex(Browser.BookmarkColumns.TITLE));
            date_time = mCur.getString(mCur
                    .getColumnIndex(Browser.BookmarkColumns.DATE));
            SimpleDateFormat simpleDate= new SimpleDateFormat("yyyy-MM-dd");
            String curDate=simpleDate.format(new Date(Long.parseLong(date_time)));

            Toast.makeText(m_oContext,"History Time : "+curDate,Toast.LENGTH_SHORT).show();
            Toast.makeText(m_oContext,"Limit Time : "+calculateDate(),Toast.LENGTH_SHORT).show();
            //TODO: Compare these two dates here

            mCur.moveToNext();
        }
    }

}

I want to do if the History date is earlier than ten days ago then notify the user.
Any kind of help will be appreciated ,thank you.

A: tl;dr
Boolean alertUser =
    LocalDate.parse( "2016-01-02" )
             .isBefore(
                 LocalDate.now( ZoneId.of( "America/Montreal" ) )
                          .minusDays( 10 )
             ) ;

java.time
You are using troublesome old date-time classes now supplanted by the java.time classes.
Time zone
Your code ignores the crucial issue of time zone in determining a date such as "today".
Example code
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still "yesterday" in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

Your input strings are in standard ISO 8601 format. The java.time classes use ISO 8601 formats by default when parsing/generating strings. So no need to specify a formatting pattern.
LocalDate target = LocalDate.parse( "2016-01-02" );

You say the boundary is ten days ago. Use the plus or minus methods to determine future/past dates.
LocalDate tenDaysAgo = today.minusDays( 10 );

Compare using compareTo, equals, isBefore, and isAfter methods.
Boolean alertUser = target.isBefore( tenDaysAgo );

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

A: Calendar is comparable so you can just use compare to. I would make curDate a calendar. Then (curDate.compareTo(calculatedDate) < 0) will be true if curDate is earlier than calculatedDate which you've set to ten days before today.

A: You can use
    before()
    Or
    after()
to compare your calculated date with today's date

A: public boolean isHDateEarlier(String historyDate){

      String[] historySplitStrings= historyDate.split("-");
      String[] tenDaysEarlierStrings = calculateDate().split("-");

      int historyYear = Integer.parseInt(historySplitStrings[0]);
      int daysYear = Integer.parseInt(tenDaysEarlierStrings [0]);
      int historyMonth = Integer.parseInt(historySplitStrings[1]);
      int daysMonth = Integer.parseInt(tenDaysEarlierStrings [1]);
      int historyDay = Integer.parseInt(historySplitStrings[2]);
      int daysDay = Integer.parseInt(tenDaysEarlierStrings [2]);

if(historyYear  < daysYear ){//check year
      return true;
}

    if(historyMonth  < daysMonth  &&
          historyYear   <= daysYear ){//check month
          return true;
    }

  if(historyDay < daysDay &&
        historyYear <= daysYear &&
        historyMonth <= daysMonth){//check day
          return true;
  }

return false;
}

Just call :
isHDateEarlier(curDate);

A: I had a problem with comparing dates a week ago, and searched for answers and this helped me: Find nearest date from a list. - The last answer talks about NavigableSet<>
Try using NavigableSet<Date> such as TreeSet<> and put your dates in the list.
Than compare with lower or higher


text:
Q: How to insert UTC datetimes to closedXML? In the c# closedXML plugin, I get this message
Unable to set cell value to 10/27/2017 10:14:23 AM +00:00

c#
    public static async Task<string> SaveToExcel(string command, Dictionary<string, object> h, string domain, string sheet_name, string[] headers)
    {
        SqlConnection myConnection = new SqlConnection(GetConnectionString(domain));
        await myConnection.OpenAsync();

        SqlCommand myCommand = new SqlCommand(command, myConnection);
        foreach (KeyValuePair<string, object> entry in h)
        {
            myCommand.Parameters.AddWithValue(entry.Key, entry.Value ?? DBNull.Value);
        }

        System.Diagnostics.Debug.WriteLine(myCommand.CommandText);

        SqlDataAdapter sda = new SqlDataAdapter();
        sda.SelectCommand = myCommand;

        DataTable dt = new DataTable();

        sda.Fill(dt);

        // add headers
        DataRow dr = dt.NewRow();
        for(int i=0; i<headers.Length; i++)
        {
            //dr[i] = headers[i];
        }
        //dt.Rows.InsertAt(dr, 0);

        string filepath = Excel.SaveExcel(dt, sheet_name);

        dt.Dispose();
        sda.Dispose();
        myCommand.Dispose();
        myConnection.Close();

        return filepath;
    }

    public static string SaveExcel(System.Data.DataTable dt, string SheetName)
    {
        // create the Excel workbook
        var wb = new XLWorkbook();

        // creates the worksheet
        var ws = wb.AddWorksheet(SheetName);

        // add data
        ws.Cell(1, 1).InsertTable(dt);

        // the range for which you want to add a table style
        var range = ws.Range(1, 1, dt.Rows.Count, dt.Columns.Count);

        // create the actual table
        var table = range.CreateTable();

        // adjust size
        ws.Columns().AdjustToContents();

        // apply style
        table.Theme = XLTableTheme.TableStyleMedium5;

        // save file as temp
        string result = Path.GetTempFileName();
        wb.SaveAs(result);

        return result;
    }

How can I fix this?
Thanks


text:
Q: Best way to store data in mongodb I am developing a project where there are lots of relations are there. I want to know which one is best method to store data.

*

*create child_model and then push _id to parent_model.

*create child_model inside parent model, we are pushing whole data not just _id.

A: There is no "best way", both are sometimes the best. It really depends on your use case and questions like these:

*

*do you need to  load or store your children sometimes separately without loading your parent? -> separate models.

*or will you need to load the parent anyway all the time when you need a child? -> same model

*can your child always only belong to exactly one parent? -> same model

*will multiple parents or other objects ever reference a child? -> separate models

*is the lifetime of your child always identical to the lifetime of your parent -> same model

*can the lifetimes be different? can your child ever become "detached" from your parent -> separate models.

think about those questions and decide, whats best for your use case.


text:
Q: Pandas - Group by column and then create new columns from result I have a DataFrame containing 'test results' for different people over multiple tests per person.
It has the columns name, age, score
scores = pd.DataFrame({'name': ['Alex', 'Alex', 'Alex', 'Alex', 'Alex', 'James', 'James', 'James', 'James', 'James', 'James', 'Emily', 'Emily', 'Emily', 'Emily', 'Emily', 'Emily', 'Emily'], 'age': [25, 26, 26, 27, 27, 25, 26, 26, 26, 27, 27, 25, 25, 26, 26, 26, 27, 27], 'score': [10, 0, 2, 1, 2, 2, 4, 6, 6, 10, 8, 4, 7, 6, 10, 9, 7, 10]})
     name  age  score
0    Alex   25     10
1    Alex   26      0
2    Alex   26      2
3    Alex   27      1
4    Alex   27      2
5   James   25      2
6   James   26      4
7   James   26      6
8   James   26      6
9   James   27     10
10  James   27      8
11  Emily   25      4
12  Emily   25      7
13  Emily   26      6
14  Emily   26     10
15  Emily   26      9
16  Emily   27      7
17  Emily   27     10

I have performed a group by on name and age and aggregating to give the max_score for each group (which is the max value of the score column for an individual in each year)
age_scores = scores.groupby(['name','age']).agg({"score":'max'})
The result looks like
           score
name  age
Alex  25      10
      26       2
      27       2
Emily 25       7
      26      10
      27      10
James 25       2
      26       6
      27      10

I would like to have a dataframe with one row per person and then a column for the max score at each age
i.e
    name  max_25  max_26  max_27
0   Alex      10       2       2
1  James       7      10      10
2  Emily       2       6      10

A: Using pivot, if you want to transform age_scores:
(age_scores
     .reset_index()
     .pivot('name', 'age', 'score')
     .add_prefix('max_')
     .reset_index()
     .rename_axis(None, axis=1))

Output:
    name  max_25  max_26  max_27
0   Alex      10       2       2
1  Emily       7      10      10
2  James       2       6      10

Otherwise, if you don't need age_scores as an intermediate dataframe, solution with unstack proposed by Chris in comments is probably an easier one:
(scores
 .groupby(['name', 'age'])['score'].max()
 .unstack('age')
 .add_prefix('max_')
 .reset_index())

Output:
age   name  max_25  max_26  max_27
0     Alex      10       2       2
1    Emily       7      10      10
2    James       2       6      10


text:
Q: How to convert .ckpt to .pb? I am new to deep learning and I want to use a pretrained (EAST) model to serve from the AI Platform Serving, I have these files made available by the developer:

*

*model.ckpt-49491.data-00000-of-00001

*checkpoint

*model.ckpt-49491.index

*model.ckpt-49491.meta

I want to convert it into the TensorFlow .pb format. Is there a way to do it? I have taken the model from here
The full code is available here.
I have looked up here and it shows the following code to convert it:
From tensorflow/models/research/
INPUT_TYPE=image_tensor
PIPELINE_CONFIG_PATH={path to pipeline config file}
TRAINED_CKPT_PREFIX={path to model.ckpt}
EXPORT_DIR={path to folder that will be used for export}

python object_detection/export_inference_graph.py \
    --input_type=${INPUT_TYPE} \
    --pipeline_config_path=${PIPELINE_CONFIG_PATH} \
    --trained_checkpoint_prefix=${TRAINED_CKPT_PREFIX} \
    --output_directory=${EXPORT_DIR}

I am unable to figure out what value to pass:

*

*INPUT_TYPE

*PIPELINE_CONFIG_PATH.

A: Here's the code to convert the checkpoint to SavedModel
import os
import tensorflow as tf

trained_checkpoint_prefix = 'models/model.ckpt-49491'
export_dir = os.path.join('export_dir', '0')

graph = tf.Graph()
with tf.compat.v1.Session(graph=graph) as sess:
    # Restore from checkpoint
    loader = tf.compat.v1.train.import_meta_graph(trained_checkpoint_prefix + '.meta')
    loader.restore(sess, trained_checkpoint_prefix)

    # Export checkpoint to SavedModel
    builder = tf.compat.v1.saved_model.builder.SavedModelBuilder(export_dir)
    builder.add_meta_graph_and_variables(sess,
                                         [tf.saved_model.TRAINING, tf.saved_model.SERVING],
                                         strip_default_attrs=True)
    builder.save()

A: Following the answer of @Puneith Kaul, here is the syntax for tensorflow version 1.7:
import os
import tensorflow as tf

export_dir = 'export_dir'
trained_checkpoint_prefix = 'models/model.ckpt'
graph = tf.Graph()
loader = tf.train.import_meta_graph(trained_checkpoint_prefix + ".meta" )
sess = tf.Session()
loader.restore(sess,trained_checkpoint_prefix)
builder = tf.saved_model.builder.SavedModelBuilder(export_dir)
builder.add_meta_graph_and_variables(sess, [tf.saved_model.tag_constants.TRAINING, tf.saved_model.tag_constants.SERVING], strip_default_attrs=True)
builder.save()

A: If you specify INPUT_TYPE as image_tensor and
PIPELINE_CONFIG_PATH as your config file with this command.
python object_detection/export_inference_graph.py \
--input_type=${INPUT_TYPE} \
--pipeline_config_path=${PIPELINE_CONFIG_PATH} \
--trained_checkpoint_prefix=${TRAINED_CKPT_PREFIX} \
--output_directory=${EXPORT_DIR}

you can get your model in 3 formats in your export dir;

*

*frozen_graph.pb

*savedmodel.pb

*checkpoint

for more info https://github.com/tensorflow/models/tree/master/research/object_detection


text:
Q: GNU parallel with for loop function I would like to utilize all the cores (48) in AWS to run my job. I have 6 million lists to run and each job runs for a less than a sec [real    0m0.004s user   0m0.005s sys    0m0.000s].
My following execution uses all the cores but is NOT 100%.
gnu_parallel -a list.lst --load 100% --joblog process.log sh job_run.sh {} >>score.out

job_run.sh
#!/bin/bash
i=$1
TMP_DIR=/home/ubuntu/test/$i
mkdir -p $TMP_DIR
cd $TMP_DIR/
m=`echo $i|awk -F '-' '{print $2}'`
n=`echo $i|awk -F '-' '{print $3}'`
cp /home/ubuntu/aligned/$m $TMP_DIR/
cp /home/ubuntu/aligned/$n $TMP_DIR/
printf '%s ' "$i"
/home/ubuntu/test/prog -s1 $m -s2 $n | grep 'GA'
cd $TMP_DIR/../
rm -rf $TMP_DIR
exit 0

A: Your problem is GNU Parallel's overhead: It takes 5-10 ms to start a job. So you will likely see GNU Parallel running at 100% on one core but the rest are idle.
But you can run multiple GNU Parallels:
https://www.gnu.org/software/parallel/man.html#EXAMPLE:-Speeding-up-fast-jobs
So split the list into smaller chunks and run those in parallel:
cat list.lst | parallel --block 100k -q -I,, --pipe parallel --joblog process.log{#} sh job_run.sh {} >>score.out

This should run 48+1 GNU Parallels so it should use all your cores. Most of your cores will be used for overhead because your jobs are so fast.
If you are not using the process.log, then it can be done with less overhead:
perl -pe 's/^/sh job_run.sh /' list.lst | parallel --pipe --block 100k sh >>score.out

This will prepend each line with sh job_run.sh and give 100kb of lines to 48 shs running in parallel.


text:
Q: Why am I getting Synchronous reads are not supported in ImageSharp? I'm trying to use a Blazor input file, and also the Imagesharp library, to turn an IBrowserFile into an image.
My method looks like this
public async Task<byte[]> ConvertFileToByteArrayAsync(IBrowserFile file)
        {

            using var image = Image.Load(file.OpenReadStream());
            image.Mutate(x => x.Resize(new ResizeOptions
            {
                Mode = ResizeMode.Min,
                Size = new Size(128)
            }));

            MemoryStream memoryStream = new MemoryStream();
            if (file.ContentType == "image/png")
            {

                await image.SaveAsPngAsync(memoryStream);
            }
            else
            {
                await image.SaveAsJpegAsync(memoryStream);
            }
            var byteFile = memoryStream.ToArray();
            memoryStream.Close();
            memoryStream.Dispose();

            return byteFile;

        }

But I'm getting the following error  :
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Synchronous reads are not supported.
System.NotSupportedException: Synchronous reads are not supported.
   at Microsoft.AspNetCore.Components.Forms.BrowserFileStream.Read(Byte[] buffer, Int32 offset, Int32 count)
   at System.IO.Stream.CopyTo(Stream destination, Int32 bufferSize)
   at SixLabors.ImageSharp.Image.WithSeekableStream[ValueTuple`2](Configuration configuration, Stream stream, Func`2 action)
   at SixLabors.ImageSharp.Image.Load(Configuration configuration, Stream stream, IImageFormat& format)
   at SixLabors.ImageSharp.Image.Load(Configuration configuration, Stream stream)
   at SixLabors.ImageSharp.Image.Load(Stream stream)
   at MasterMealWA.Client.Services.FileService.ConvertFileToByteArrayAsync(IBrowserFile file) in F:\CoderFoundry\Code\MasterMealWA\MasterMealWA\Client\Services\FileService.cs:line 37
   at MasterMealWA.Client.Pages.RecipePages.RecipeCreate.CreateRecipeAsync() in F:\CoderFoundry\Code\MasterMealWA\MasterMealWA\Client\Pages\RecipePages\RecipeCreate.razor:line 128
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.Forms.EditForm.HandleSubmitAsync()
   at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)

for the record, line 37 is "using var image......",  I don't quite see where I'm using multiple streams, unless its the read stream and memory stream.  however, I also don't see how to close the stream I open with file.OpenReadStream.

A: Image.Load is a synchronous operation. Try with the async version instead:
using var image = await Image.LoadAsync(file.OpenReadStream());

A: Background:

*

*ASP.NET Core 3+ discourages devs from using non-async IO by having all Stream objects handled by ASP.NET Core (such as HttpRequest.Body and IBrowserFile.OpenReadStream()) throw an exception whenever the non-async Stream.Read and Stream.Write methods are called.

*

*See this thread: https://github.com/dotnet/aspnetcore/issues/7644

*And this thread: ASP.NET Core : Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead

*This behaviour is controlled by IHttpBodyControlFeature - so you can re-enable synchronous stream IO if you absolutely have to, but you really shouldn't.

*Also, you don't need the intermediate MemoryStream: you can write the ImageSharp output directly to the response.
Proper solution:
You're calling ImageSharp's Image.Load method, which uses non-async Stream methods. The fix is to simply use await Image.LoadAsync instead:
So change your code to this:
// I assume this is a Controller Action method
// This method does not return an IActionResult because it writes directly to the response in the action method. See examples here: https://stackoverflow.com/questions/42771409/how-to-stream-with-asp-net-core

public async Task ResizeImageAsync( IBrowserFile file )
{
    await using( Stream stream = file.OpenReadStream() )
    using( Image image = await Image.LoadAsync( stream ) )
    {
        ResizeOptions ro = new ResizeOptions
        {
            Mode = ResizeMode.Min,
            Size = new Size(128)
        };

        image.Mutate( img => img.Resize( ro ) );

        if( file.ContentType == "image/png" ) // <-- You should not do this: *never trust* the client to be correct and truthful about uploaded files' types and contents. In this case it's just images so it's not that big a deal, but always verify independently server-side.
        {
            this.Response.ContentType = "image/png";
            await image.SaveAsPngAsync( this.Response.Body );
        }
        else
        {
            this.Response.ContentType = "image/jpeg";
            await image.SaveAsJpegAsync( this.Response.Body );
        }
}

Alternative (non-)solution: Procrastinate:
Just disable ASP.NET Core's prohibition on non-async IO:
public void ConfigureServices(IServiceCollection services)
{
    // If using Kestrel:
    services.Configure<KestrelServerOptions>(options =>
    {
        options.AllowSynchronousIO = true;
    });

    // If using IIS:
    services.Configure<IISServerOptions>(options =>
    {
        options.AllowSynchronousIO = true;
    });
}

A: You have to call async methods, like LoadAsync, DisposeAsync() instead of the synchronous Dispose(). Use await using xxx to await the call to DisposeAsync().
public async Task<byte[]> ConvertFileToByteArrayAsync(IBrowserFile file)
{
    await using var image = await image.LoadAsync(file.OpenReadStream());
    image.Mutate(x => x.Resize(new ResizeOptions
    {
        Mode = ResizeMode.Min,
        Size = new Size(128)
    }));

    MemoryStream memoryStream = new MemoryStream();
    if (file.ContentType == "image/png")
    {

        await image.SaveAsPngAsync(memoryStream);
    }
    else
    {
        await image.SaveAsJpegAsync(memoryStream);
    }
    var byteFile = memoryStream.ToArray();
    memoryStream.Close();
    await memoryStream.DisposeAsync();

    return byteFile;
}


text:
Q: AttributeError: 'str' object has no attribute 'fit' - Pyspark I am trying to run the script below in PySpark3 and receiving the error message that follows. I am using this has something to do with formatting but I am not sure how to go about doing so. Any help would be much appreciated.
train,test = df.randomSplit([0.7,0.3])

models = ["LinearRegression()","DecisionTreeRegressor()","RandomForestRegressor()","GBTRegressor()"]

for model in models:

    # Fit our model
    M = model
    fitModel = M.fit(train)

    # Load the Summary
    trainingSummary = fitModel.summary

#     trainingSummary.residuals.show()
    print("Training RMSE: %f" % trainingSummary.rootMeanSquaredError)
    print("Training r2: %f" % trainingSummary.r2)

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-15-d0b941a7170e> in <module>()
      8     # Fit our model
      9     M = model
---> 10     fitModel = M.fit(train)
     11
     12     # Load the Summary

AttributeError: 'str' object has no attribute 'fit'

A: You have to modify your models
models = [LinearRegression, DecisionTreeRegressor, RandomForestRegressor, GBTRegressor]

Because with your current define, they are definitely a string. Better way is to add modules inside list and instance it every loop.
To be precies models = ["LinearRegression()"] the element inside is String, not an object which doesn't have any method.

A: I think this way is actually more efficient....
This way you can still iterate through a list.
def ClassTrainEval(model):

    fitModel = model.fit(train)

    # Load the Summary
    trainingSummary = fitModel.summary

    print("Training RMSE: %f" % trainingSummary.rootMeanSquaredError)
    print("Training r2: %f" % trainingSummary.r2)

models = [LogisticRegression(),NaiveBayes(),OneVsRest(),LinearSVC()]

for model in models:
    ClassTrainEval(classifier)


text:
Q: ¿Cómo puedo usar variables shell en awk? Estoy intentando escribir un script que filtre la información del comando sar y lo muestre en formato XML.
Para ello, se me ha ocurrido hacer un bucle que vaya mostrando los datos de cada CPU y, dentro de él, otro bucle que vaya recorriendo los campos filtrados en la variable last_time.
Mi código es el siguiente:
#Obtenemos el numero de nucleos de la CPU
NUM_CPU=$(grep processor /proc/cpuinfo | wc -l)

#Por cada nucleo, mostramos sus estadísticas
for i in $(seq 0 1 $(($NUM_CPU-1))); do

    #Guardamos la última medida de sar en una variable
    last_time=$(sar -P $i | tail -n 2 | head -n 1)

    for j in $(seq 3 1 8); do

            #Filtramos el campo correspondiente
        cpu_user=$(echo $last_time | gawk '{print $j}')

        #Mostramos el valor en XML
            echo "<module>"
            echo "<name><![CDATA[SAR: CPU$i $cpu_user]]></name>"
            echo "<description>Muestra el % de tiempo de usuario de la cpu $i</description>"
            echo "<type><![CDATA[generic_data]]></type>"
            echo "<![CDATA[15,1]]>"
            echo "</module>"

        #Imprimimos una linea en blanco para separar la siguiente seccion
             echo ""

    done;
done;

La mayoría del código se ejecuta bien, pero al intentar aplicar gawk con la variable $j (que indicaria el número de campo a filtrar), gawk no me detecta el valor de la variable y no me filtra nada
¿Cómo puedo resolverlo?

A: Para usar variables de Bash en awk debes pasárselas usando -v:
awk -v columna="$j" '{print $columna}'

Si quieres usarla para hacer comparaciones a nivel expresión regular, debes usar el operador ~:
awk -v columna="$j" '$0 ~ columna'

Por tanto, la línea:
cpu_user=$(echo $last_time | gawk '{print $j}')

Sería
cpu_user=$(echo $last_time | gawk -v col="$j" {print $col}')

Dicho lo cual, tu código podría escribirse como:
#Obtenemos el numero de nucleos de la CPU
#### Usa directamente `nproc`:  # https://stackoverflow.com/a/17089001/1983854
NUM_CPU=$(nproc --all)

#Por cada nucleo, mostramos sus estadísticas
#### Aquí se puede usar un bucle clásico
for ((i=0; i<$NUM_CPU; i++)); do

    #Guardamos la última medida de sar en una variable
    last_time="$(sar -P $i | tail -n 2 | head -n 1)"

    #### Entiendo que aquí el 8 debería ser $(($NUM_CPU))
    for j in $(seq 3 1 8); do

        #Filtramos el campo correspondiente
        cpu_user=$(echo $last_time | gawk '{print $j}')

        #Mostramos el valor en XML
        #### ¿Más limpio un heredoc?
            cat - <<EOF
<module>
<name><![CDATA[SAR: CPU$i $cpu_user]]></name>
<description>Muestra el % de tiempo de usuario de la cpu $i</description>
<type><![CDATA[generic_data]]></type>
<![CDATA[15,1]]>
</module>

EOF

    done
done

He encabezado las sugerencias con ####. Básicamente, usa nproc --all para contar los cores y usa un heredoc en lugar de muchos echos.


text:
Q: get Application pool version from IIS6-IIS7 Hello i want to get framework version from all my application pool (with IIS 6/7).
This is how i get application pool name:
Dim AppPools As DirectoryEntry = New DirectoryEntry("IIS://localhost/W3SVC/AppPools")Then
     For Each nextEntry As DirectoryEntry In AppPools.Children
            Dim nextAppPoolName As String = nextEntry.Name
            Dim pipelineMode As Integer = CInt(nextApplicationPool.Properties(MANAGED_PIPELINE_MODE).Value)
     Next

i can get framework from my web sites but i don't want this.
how i can to do?

A: We use IIS-api for IIS7:
using (var iisManager = ServerManager.OpenRemote(iisServer))
{
    var site = iisManager.Sites[IisSite];
    var app = site.Applications[0];

    var pool = iisManager.ApplicationPools[app.ApplicationPoolName];
}

Where iisServer is name of your server (localhost), IisSite - name of site on server, app - first (default) apllication of this site and pool - your apllication pool.
More information about pool api and ServerManager. I hope, you can translate it to VB.
IIS6 has no api and almost has any "good" way to get this information.


text:
Q: Clausius inequality leading to absurd result Background: After deriving Clausius inequality, the author of this book derives the following relation:
Consider the cycle shown in the figure in which leg $A \rightarrow B$ is irreversible. In the equation
$$
0>\oint\frac{\mathrm{d}Q}{T}=\int_{A \operatorname{irrev}}^{B} \frac{\mathrm{d}Q}{T}+ \int_{B \operatorname{rev}}^{A} \frac{\mathrm{d}Q}{T}
$$
the second term on the right-hand side of this equation is given by $S(A)-S(B)$ because it is taken over a reversible path. When we move this quantity to the left-hand side, we find that
$$
S(B)-S(A)>\int_{A \operatorname{irrev}}^{B} \frac{\mathrm{d} Q}{T}.
$$
Thus the difference in entropy between the points is greater than the integral of $\mathrm{d} Q / T$ over an irreversible change.

Problem: Entropy is a state function so $\int_{A \operatorname{irrev}}^{B} \frac{\mathrm{d} Q}{T}= {\Delta} S. $ By the inequality derived we have ${\Delta} S>{\Delta} S$ which is absurd.

A: Considering the result $$\int_{A \operatorname{irrev}}^{B} \frac{\mathrm{d} Q}{T}<S(B)-S(A)$$ for an infinitesimal path, we get $$\mathrm{d}S\ge\frac{\mathrm{d}Q}{T}$$ where the equality holds only for a reversible process (by the definition of entropy).
This means that in your expression $$\int_{A \operatorname{irrev}}^{B} \frac{\mathrm{d} Q}{T},$$ $\frac{\mathrm{d} Q}{T}$ is not equal to $\mathrm{d}S$ because the process is irreversible. Instead, you have $\frac{\mathrm{d} Q}{T}<\mathrm{d}S$ and so $$\int_{A \operatorname{irrev}}^{B} \frac{\mathrm{d} Q}{T}<\int_{A \operatorname{irrev}}^{B} \mathrm{d}S=S(B)-S(A)$$ which is the original result.

A: For the irreversible path between the same two end states, dQ is different than dQ for the reversible path, and in the integral of dQ/T for the irreversible path, you are supposed to use the temperature at the boundary interface between the system and surroundings $T_B$.  So for the irreversible path, you should be using $$\int{\frac{dQ_{irrev}}{T_B}}$$So the two integrals are nothing like one-another.  The correct form of the inequality should read:  $$\Delta S\geq \int{\frac{dQ_{irrev}}{T_B}}$$

A: I find the following from Enrico Fermi's book to be the most explicit derivation that shows:
$$dS \geq \frac{dQ}{T}$$
Looking at a closed loop integral of the ratio of heat absorbed (or surrendered, depending on sign) to the heat bath temperature along each isotherm in a cycle (reversible or not),
$$\oint \frac{dQ}{T}=\int_{A}^{B} \frac{dQ}{T}+\int_{B}^{A}\frac{dQ}{T} \leq0$$
We can take the forward part of the cycle $(A\rightarrow B)$ as an irreversible transformation, and the return part of the cycle $(B\rightarrow A)$ as a reversible transformation. It is valid to do this because even irreversible cycles behave the same along the forward part of the cycle. We are just saying that as a limiting case, our cycle behaves reversibly along the return path:
$$(TdS=dQ)_{B \rightarrow A}$$
Therefore,
$$\int_{B}^{A}dS=\int_{B}^{A}\frac{dQ}{T}=S(A)-S(B)$$
$$\int_{A}^{B}\frac{dQ}{T} + S(A)-S(B) = \int_{A}^{B}\frac{dQ}{T}-[S(B)-S(A)]  \leq 0$$
Conversely,
$$S(B)-S(A) \geq \int_{A}^{B}\frac{dQ}{T}$$
$$dS \geq \frac{dQ}{T} $$


text:
Q: How to obtain a 0 Attack IV ditto? I'm doing a test in pokemon village because my ditto friend safari is lost. I have a fainted synchronize Quiet Ralts in 1st slot.
I know that for level they are at in pokemon village, I need the exact speed star of a 0 IV, winning a speed tie means it has the 0 Speed IV. I also know that for testing HP IVs you need a pokemon with final gambit that is sure to outspeed the pokemon and with 1 hp less than desired.
How would I go about testing for attack stat? Using foul play?

A: The only sure fire method I can think of, as Ditto's attacks are entirely given by Transform, is to have a Pokemon with only one move, and use it's stats, along with the damage calculator, to figure out a scenario where if the Ditto has 0 attack IV that move will always deal a set amount of damage, different than if Ditto had any other IV value. Good luck finding this combination though, you'll probably find it quicker to simply catch every Ditto that matches the other things you're looking for and have them rated for that 1/32 chance.


text:
Q: What does "cyber-" actually mean? I'm heading into the postgraduate phase of my Computer Science-oriented studies, and I can't put my finger on what this root means.
According to Etymology Online it comes from Cybernetics, which in turn comes from the greek for "Helmsman" and is the study of governation or governing systems.
But modern usage, such as cyberspace, cybercafe, cyberattack, cyberterrorism, cybermosque, cybersex, cyberbullying, and such seem to use it synonymously with "Internet"
Of course, you could argue that you use a cybercafe to interact with a primitive virtual governor, a cyberspace is a place where a lot of virtual governors "reside", while  cyberattacks try to disrupt these governors.
But cyberbullying and "cybering" really don't fit into that scheme, unless you were to day that cyberbullying is "bullying by relaying domineering or intimidating messages with the help of a governor." but then again "physics" could be a governor. You shout mean things into the air and physics makes sure your overbearing soundwaves propagate to your target.
Bo that would mean that pretty much everything is cyber-, because everything is controlled by something.
The rational middle ground would be for "cyber-" to now mean "internet," unless it is followed by a greek or latin root, in which case it would mean "control systems"
Is it safe to assume this?

A: First off, attack, terrorism and sex all have Latin roots, so your proposed rule of thumb doesn't even work on your own examples.
The closest hypernym for all the newer things cyber is probably "virtual". But not necessarily Internet-related. Any LAN can be a cyberspace. (And some might even consider a single app or game a cyberspace.)
Cybernetics and cybernetic are the odd ones out, or rather the hinge point, as they cover various meanings each. Coincidentally, that nicely demonstrates that you can't arrive at the meaning simply by looking at the word. So any rule of thumb will fail.
Cybernetics is the exact same word in any context, and it is only from that context that you can tell if it means "the theory/science of communication and control in the animal and the machine", "the art/study of governing, controlling automatic processes and communication", or "technology related to computers and Internet".
Words can have more than one meaning, and so can morphemes. If we use a morpheme to mean "dog" in one word but "truck" in another, then there simply is no middle ground. Looking at the etymology at that point is at best useless, and at worst an etymological fallacy. If you don't like my invented example and think it is an exaggeration, try and find a hypernym for "door", "passageway", and "scandal", which are only some of the meanings -gate- can have.
Likewise, -cyber- can be as flexible as we choose to make it. Cybernetics can mean whatever it means regardless of what cybercafé happens to mean. And a cyborg can sit on the subway next to a cyberterrorist, but that's about as much as they have in common. Just like nobody is offended that the woman and the wife sitting opposite them are no longer related.

A: The meaning has been broadened through popular use and, in so doing, it has become diluted by people who either don't apply it properly, or seek to draw parallels which get mistaken for genuine associations as time passes. That's what popular culture does - I wince whenever I hear or read news about "hacking" which invariably demonstrates a complete lack of insight into what was perpetrated.
My degree was in Biomedical Engineering and Cybernetics. The etymology of cybyernetics has already correctly been given here as κυβερνητικός (kubernētikós), the Greek sailor exerting control over his environment, and that is the true meaning of the field. It is about intelligent systems of control, nothing more, and the essence of this is a very simple concept: feedback. Like the Greek sailor, it is not enough to exert force to achieve will - the results of the exertion must be perceived, and compared with the desired outcome. If the sailor finds he is veering to the right due to winds or currents, he must apply change using the rudder in order to maintain his course. Thus his actions in this instant are predicated on the results of his actions in the preceding instant(s); what is happening influences what will happen next.
Taking an example of technology, consider climate control within a building. Once the thermostat has been set, the system has been given its desired outcome: say 26 degrees Centigrade. If a room's temperature exceeds this, then the air conditioning will be triggered and the room will be actively cooled, until the point at which the desired temperature is reached, when the system will cease running the aircon. Conversely if the room is too cool, heating will be engaged in the same manner. We're all familiar with this form of feedback, and any system which incorporates it may be thought of as cybernetic, although it is generally only applied to systems created by humans.
The reason cyber has been applied so universally to mean all things internet-enabled is not because of the internet itself, but because of the properties of this system. I can say something to my friend while he is standing next to me, or I can write my message down on a piece of paper and show it to him - the outcome is the same (leaving out the lack of body language/intonation which is a subject for another discussion). The outcome remains the same if I type it on an electronic device, and show him the screen. It still remains the same if I type it on an electronic device and it appears on the screen of his electronic device - but now, the properties of the conversation have altered. The same message is conveyed, but (i) I no longer need to be next to him, so long as we are connected to the same infrastructure, and (ii) I don't have to be giving my message at the same time as he is able to receive it. Our communication paradigm has been decoupled in both space (we are telecommunicating, from the Greek τῆλε meaning afar, far away) and time (we are communicating asynchronously, from the Greek σύν (sún, "with") + χρόνος (khrónos, "time"), negated with a).
However, this decoupling is not to be confused with cybernetics. If we ignore all of the cybernetic systems that facilitate the actual internet, as parts of the infrastructure, then it becomes clear that use of the internet as a medium does not constitute a cybernetic system in itself. The outcome of me delivering a message and my audience receiving it is the same, whether I am standing on a podium in front of them or posting it on my Facebook page. The internet simply becomes a tool, a mechanism used to perform this action remotely and asynchronously; the fact that it utilises cybernetic principles does not make any system that involves it inherently cybernetic per se. If I follow someone down the road and hurl abuse at them, I am bullying. If I do it on Facebook, I am bullying. The fact that I did so using a different medium does not change the outcome, and words like "cyberbullying" are part of the reason why our legal system has been so insufficient and outmoded in tackling all of the issues that are arising from an internet-enabled world, such as online abuse and so-called piracy.
TL;DR: words like cyberspace, cybercafe and cyberterrorism all refer to the same thing as their real-world counterparts, which are taking place by leveraging (usually internet) technology. The conflation of this medium with the basic action itself does not alter the meaning of the word. In this context cyber, by itself, has no inherent meaning, in the same way that "app" is short for "application" and nothing more.

A: This is what etymology says to help us understand the meaning of cyber
cyber:
as an element in word formation, ultimately from cybernetics (q.v.). It enjoyed explosive use with the rise of the Internet early 1990s. One researcher (Nagel) counted 104 words formed from it by 1994. Cyberpunk (by 1986) and cyberspace were among the earliest.
Cyber is such a perfect prefix. Because nobody has any idea what it means, it can be grafted onto any old word to make it seem new, cool -- and therefore strange, spooky. ["New York" magazine, Dec. 23, 1996]
As a stand-alone, it is attested by 1998 as short for cybersex (which is attested by 1995).
Cybernatics(n.)
coined 1948 by U.S. mathematician Norbert Wiener (1894-1964) from Greek kybernetes "steersman" (metaphorically "guide, governor") + -ics; perhaps based on 1830s French cybernétique "the art of governing."
The future offers very little hope for those who expect that our new mechanical slaves will offer us a world in which we may rest from thinking. Help us they may, but at the cost of supreme demands upon our honesty and our intelligence. [Norbert Weiner, "God and Golem, Inc.," 1964]

A: The term 'cyberspace' was coined by William Gibson in his 1986 short sci-fi story "Burning Chrome". He chose it after some deliberation, as a cool-sounding phrase to describe the domain of connected computers, which he visualised very differently - "a mass consensual hallucination" in computer networks.
The fact the the word is pretty inappropriate (one could hardly describe the internet as 'control-space'!) was neither here not there to Gibson, he just wanted a catchy way to describe a literary entity. He did so very well, and the name has stuck.
BTW I highly recommend Burning Chrome, or indeed any of Gibson's work, the Sprawl trilogy especially (Neuromancer, Count Zero, Mon Lisa Overdrive) (which were an inspiration for the Matrix films, with Mona Lisa Overdrive being the name of a track from the Matrix Reloaded)

A: Cyber  is a prefix , derivation is the back formation of cybernetics.
Closest synonym is "virtual"
The word "Cyber" means computer , computer network or virtual reality.
Many words are formed with this prefix  e.g.
cyber-talk, cyberspace, cyberart , cyberfasshion meaning very uptodate.
I used to be intimidated by computers till my kids taught me how
to use a computer.  You can very well say that I had a cyberphobia.
I hope that this short explanation would add to your general understanding
of this prefix.
Tandon

A: The root "cyber" comes from English word-proper "cybernetic", which in turn comes from Greek kybernētikós (κυβερνάω / kybernao means "to guide").
Many Greek loan-words spelled with the Kappa [κ] were rendered in Latin script with a C, while others were spelled with K, some others evolved into a G. Compare English phrase "kinetic energy" with French "énergie cinétique". Likewise, "kyber" eventually became "cyber" with Soft C (pronounced as an ordinary S) as opposed to its earlier form where it was pronounced with Hard C (like modern letter K).
The root of the word has entered and re-entered Latin and other languages multiple times across centuries and hence one Greek root, could be seen transliterated into Latin script as "-cyber-", "-kyber-", "-guber-", and "-guver-", with the latter one giving birth to the English word "government".
In fact "cybernetic" (κυβερνητικός) in Greek simply means governmental, gobernatorial or related to government.
To answer your question, in terms of technology "cybernetic" is meant to mean "a thing that guides", in a looser ideologic sense "A machine that guides and helps humans solve tasks or problems".


text:
Q: jQuery AutoComplete vs Combobox I am calling a web service (using SPServices) to get all of my items into an array, then using that array in my autocomplete call. It works great, however I have a few questions/issues

*

*How can I deny the user from selecting values which are not in the pick list? I think a combo box does this, however I don't want to load up the entire list onto the page... which leads to #2

*I am using a picker list which will have a few thousand items in it (currently a few hundred), from what I'm gathering with autocomplete it loads up all of the choice values into an array and then uses that to pick from. is that correct? Is there a better way around this so I can call a web service with my partially entered words, and only array the results, not all of the items? Will this be a unique solution outside of autocomplete or combobox?
Thanks,
David

A: So here's what I did...
On key up, call my web service with the new term, and then put the returned results into the autocomplete. Also the results are then cached.
I am also checking when the user continues that the value specified is contained in the array, ensuring they didn't mess with the value.
function setVendorLookup() {
    var term = $(this).val().toLowerCase();
    if (term.length > 2) {
        if (vendors.join(" ").toLowerCase().indexOf(term) == -1) { //some caching
            vendors = [];
            $().SPServices({
                operation: "GetListItems",
                listName: "Yellow Pages",
                async: false,
                CAMLViewFields: "<ViewFields><FieldRef Name='VENDOR_ID'/><FieldRef Name='NAME1'/><FieldRef Name='CITY'/><FieldRef Name='STATE'/></ViewFields>",
                CAMLQuery: "<Query><Where><Or><Contains><FieldRef Name='VENDOR_ID' /><Value Type='Text'>" + term + "</Value></Contains>" +
                    "<Contains><FieldRef Name='NAME1' /><Value Type='Text'>" + term + "</Value></Contains></Or></Where></Query>",
                completefunc: function (xData, Status) {
                    $(xData.responseXML).find("[nodeName='z:row']").each(function () {
                        vendors.push($(this).attr("ows_VENDOR_ID") + " - " + $(this).attr("ows_NAME1") + ", " + $(this).attr("ows_CITY") + ", " + $(this).attr("ows_STATE"));
                    });
                }
            }); //SPServices
        }
        $(".vendor").autocomplete({
            source: vendors,
            minLength: 3
        });
    } else
        vendors = [];

}

function validate()
{
        if (jQuery.inArray($(".vendor").val(), vendors) == -1) {
            myAlert("Validation Error", "Please select a valid vendor");
            return false;
        }
}


text:
Q: Is there a way to embed Clifford algebras into the corresponding tensor algebra? $\newcommand{\talg}{\mathcal{T}(V)}$$\newcommand{\clalg}{\mathcal{Cl}_q(V)}$$\newcommand{\qalg}{\mathcal{I}_q(V)}$Is there a way to embed Clifford algebras into the corresponding tensor algebra?
There are simple and straightforward embeddings of the underlying vector space $V$ into its corresponding tensor algebra $\talg$ and any of its corresponding Clifford algebras $\clalg$ (where $q$ denotes the quadratic form defining the Clifford algebra).
This fact is what makes both tensor analysis and geometric (Clifford) algebra compatible with ordinary vector algebra or calculus.
However, even though any $\clalg$ can be formed as a quotient of $\talg$, or perhaps because of that fact, no $\clalg$ seems to be "compatible" with $\talg$ in a simple way, at least in the sense that there does not appear to exist any "simple" embedding of $\clalg$ into $\talg$, such that we could use all of the structure and geometric intuition afforded by the $\clalg$ framework while still working in the most general possible space, $\talg$.
This seems like a big problem to me, because even if one isn't interested in tensors of rank $>2$, rank 2 tensors (also known as matrices) are ubiquitous, and I have the impression that the greater compatibility of vector algebra with matrix algebra is the main obstacle to more widespread implementation of geometric algebra.
(I.e. because unlike vector algebra, geometric algebra doesn't "play nice" with matrix algebra or tensor algebra in general.)
This seems like a major pedagogical problem, since it seems like many subjects could be much more easily understood through the prism of geometric algebra, but the (seeming) incompatibility of any $\clalg$ with $\talg$ vastly (and arguably rightly) dampens any enthusiasm to pursue such an approach.
Even if there can not exist any simple embedding, what about a simple way to switch between the two systems? I am also doubtful in this regard, since the definition of exterior algebra and outer products in terms of tensor products is very unwieldy (a sum over the symmetric group). And the exterior algebra is the most degenerate type of Clifford algebra possible.
Here is a similar question on Math.SE, corroborating my claim that every multivector corresponds to a tensor but not vice versa: What is the relationship of tensor and multivector. These two documents explain how to represent some multivectors as tensors for the special case that $V=\mathbb{R}^3$ and $q=I$ i.e. just the identity, so that the inner product is just the dot product: (1) (2).

The best I could find so far is the following (see page 7 of this document):

Given $\qalg:= \{ \sum_k A_k \otimes (v\otimes v -q(v))\otimes B_k: v \in V, A_k, B_k \in \talg \} $
We have for $A,B \in \clalg$: $AB = A \otimes B + \qalg$, where $AB$ denotes the Clifford (geometric) product and $\otimes$ is of course the tensor product.

EDIT: Thinnking about Oscar Cunningham's comments below, I think we can write $$\talg = \clalg \oplus \qalg$$ (or something that's actually mathematically correct but similar "in spirit").
$\clalg$ are exactly those tensors which have a unique embedding as an element of the Clifford algebra, and $\qalg$ consists of exactly those tensors which can not be represented in the Clifford algebra, and hence are mapped to 0 by the quotient map.
Thus the problem reduces to:

Given any arbitrary tensor $t \in \talg$, determine its (unique since direct sum?) representation as $$t= C + \tau,$$ where $C \in \clalg$ is a member of the Clifford algebra, and $\tau \in \qalg$ is a member of the ideal $\qalg=\{ \sum_k A_k \otimes (v\otimes v -q(v))\otimes B_k: v \in V, A_k, B_k \in \talg \} $.

Since we have this explicit representation for $\qalg$, I think the problem might be much easier than I originally anticipated. For example, if $t$ is a rank 4 tensor in some four dimensional vector space $V$, we could write something like $$t=\sum_{\sigma \in S_4} \left[e_{\sigma(1)}\otimes(\langle e_{\sigma(2)},e_{\sigma(3)}\rangle_q)\otimes e_{\sigma(4)}\right] + \sum_{\sigma\in S_4} \left[e_{\sigma(1)}\otimes(e_{\sigma(2)}\otimes e_{\sigma(3)} - \langle e_{\sigma(2)}, e_{\sigma(3)} \rangle_q )\otimes e_{\sigma(4)}\right],$$ where $e_1, e_2, e_3, e_4$ are basis vectors and $\langle \cdot, \cdot\rangle_q$ is the inner product formed from the quadratic form $q$ via polarization.
Of course, I am going somewhat out on a limb here in assuming, i.e. I do not know how to prove that $$\sum_{\sigma \in S_4} \left[e_{\sigma(1)}\otimes(\langle e_{\sigma(2)},e_{\sigma(3)}\rangle_q)\otimes e_{\sigma(4)}\right]=C \in \clalg$$ or that $$\sum_{\sigma\in S_4} \left[e_{\sigma(1)}\otimes(e_{\sigma(2)}\otimes e_{\sigma(3)} - \langle e_{\sigma(2)}, e_{\sigma(3)} \rangle_q )\otimes e_{\sigma(4)}\right]=\tau\in \qalg.$$
The other strategy I was thinking of was to represent tensors of rank 2 or greater only via their isomorphisms with multilinear maps, since then that would come down to representing them as functions of (contravariant) vectors, a function of $k$ vectors, a $k$-linear map, for a $k$ tensor. This would work insofar as all contravariant vectors have canonical embeddings in both the Clifford and tensor algebras, but I think we still have as unresolved the problem of how to represent covariant vectors (row vectors) as well as general covariant/mixed variance tensors.

Some possible problems: The 0 element of a Clifford/geometric algebra has all grades (i.e. for any $k$ it is a $k$-blade/multivector), whereas I don't think this is true in the tensor algebra (at least thinking in terms of representing tensors via k-dimensional arrays -- you can have the scalar 0, but also 0 column vectors, 0 row vectors, 0 matrices, etc.).
Intuitively, one wants to think of a geometric/Clifford algebra as "symmetric algebra + exterior algebra" (commutative inner product $\frac{1}{2}(v\otimes w + w \otimes v)$ and anticommutative outer product $\frac{1}{2}(v\otimes w - w \otimes v)$), especially since (at least for vector spaces over fields of characteristic zero, which is what I personally am interested in) both the symmetric and exterior algebras can be identified with certain subclasses of tensors (see: Wikipedia - symmetric algebra vs. symmetric tensors). But how do we do this for a general Clifford algebra? Maybe $$vw = v \otimes w + \qalg \\= \frac{1}{2}(\langle v, w \rangle_q + v \wedge w)= \frac{1}{2}(v\otimes w + w \otimes v + \qalg)+\frac{1}{2}(v \otimes w - w \otimes v)?$$ It's clear that $v \wedge w$ can always be identified as a subalgebra of the Clifford algebra, and this sort of definition somewhat explains that, but then is it true that the inner product generated by polarization of $q$ must equal $\frac{1}{2}(v\otimes w + w \otimes v + \qalg)$? And even if it does, does that mean that the inner product of a Clifford algebra is commutative if and only if $q$ is a symmetric quadratic form? Since in general the product derived from a quadratic form via polarization need only be bilinear, but not necessarily symmetric (i.e. commutative) unless $q$ is symmetric too.

Related: Which concepts in differential geometry cannot be represented using geometric algebra? (The answer is essentially: tensors.)
How would one express the result of a tensor product (of two vectors) in the geometric algebra?
Is geometric algebra isomorphic to tensor algebra? (No. Most tensors do not admit of a unique representation in geometric algebra due to the quotient structure.)
What is the hierarchy of algebraic objects meant to capture geometric intuition? (Tensor algebras are essentially the most general possible, even though geometric algebras are in general less unwieldy.)

A: $\newcommand{\qalg}{\mathcal{I}_q(V)}$As K. Conrad points out, this question has actually been answered already on MathOverflow by user MTS: see these answers here and here.
The essential idea is this: despite the fact that Clifford algebras have non-zero quadratic form in general, we can still "piggyback" on the embedding of the exterior algebra in the tensor algebra to represent the Clifford algebra, regardless of the choice of quadratic form.
Note: The embedding of the exterior algebra into the tensor algebra can be given by defining the exterior=wedge product in terms of the tensor product. Discussion of two canonical ways of doing this are given here on MathOverflow (the top answer being again by MTS) as well as on Math.SE.
Beautiful and rigorous proofs of this fact are given in the two answers (1) (2) linked to above by user MTS; in what follows I will merely try to motivate this result for novices like me.
1. First, we might expect this result intuitively by considering the decomposition of the Clifford product for vectors into an "inner" and "outer" product. The former is the inner product generated by polarization of the quadratic form $q$ and the latter is "equivalent" in some sense to the exterior/wedge product from the exterior algebra. Since the inner product is grade-reducing, while the outer product is grade-increasing, we might expect that the inner product would be "incapable of producing new basis elements", hence the only basis elements of the Clifford algebra we should expect are those created by the corresponding exterior algebra, i.e. there is some reason to expect a priori that a given Clifford algebra is "no more rich than" making the corresponding exterior algebra an inner product space, i.e. by defining a quadratic form on the exterior algebra.
2. MTS's answers make this suspicion rigorous by showing that the ideals for the Clifford algebra and the exterior algebra are sufficiently similar so that the quotients of the tensor algebra by them can be related in a straightforward manner.
Let us motivate this fact by considering $\mathcal{I}_q(V)$ explicitly. Remember that $$\mathcal{I}_q(V):= \left\{ \sum_k A_k \otimes (v \otimes v - q(v)) \otimes B_k : v \in V, A_k, B_k \in \mathcal{T}(V) \right\}$$ Using the distributivity of the tensor product (e.g. here) I rewrite this as $$\qalg = \left\{ \sum_k \left[A_k \otimes v \otimes v \otimes B_k - A_k \otimes q(V) \otimes B_k \right] : v \in V, A_k, B_k \in \mathcal{T}(V)\right\} \\ \overset{?}{=} \left\{ \sum_k \left[A_k \otimes v \otimes v \otimes B_k - q(V) \cdot( A_k  \otimes B_k) \right] : v \in V, A_k, B_k \in \mathcal{T}(V)\right\}$$
In any case, the motivating idea here is that the right term arising from the quadratic form, always being of strictly lower grade than the left term, should in some sense be "negligible" compared to the left term (MTS's second answer makes this idea explicit and rigorous). In other words: $$\qalg \approx \left\{ \sum_k A_k \otimes v \otimes v \otimes B_k: v \in V, A_k, B_k \in \mathcal{T}(V) \right\}$$ where the right hand side is obviously $\mathcal{I}_0(V)$, the ideal which forms the exterior algebra.
3. In the very simple case of geometric algebra over $\mathbb{R}^n$, this fact is used all the time in creating a basis for the geometric algebra. Namely, it is stated that $\mathbb{G}^n \cong \mathbb{R}^{2^n}$ (vector space isomorphism), with the basis being given by: $$\{e_1, \dots, e_n, e_{\sigma_2(1)}\wedge e_{\sigma_2(2)}, e_{\sigma_3(1)}\wedge e_{\sigma_3(2)} \wedge e_{\sigma_3(3)}, \dots, e_1 \wedge \dots \wedge e_n : \sigma_i \in A_i \}$$ where $A_i$ denotes the set of all even permutations of $i$ elements selected from $\{1, \dots, n\}$ and $\{e_1,\dots,e_n\}$ is an orthonormal basis of $\mathbb{R}^n$, orthogonal with respect to the inner product of $\mathbb{G}^n$.
It should be evident that this basis is isomorphic to the basis of the exterior algebra over $\mathbb{R}^n$.
Since in any Clifford algebra $vw = v \wedge w$ ($vw$ denoting the Clifford/geometric product) if and only if $\langle v, w \rangle_q=0$ i.e. if and only if $v$ and $w$ are orthogonal with respect to the inner product induced by $q$ via polarization, the possible choices of orthonormal basis will in general depend on the choice of quadratic form for the geometric algebra. Nevertheless, the one-to-one correspondence of the bases with the basis for the exterior algebra $\mathbb{R}^n$ will still remain and will be sufficient to generate a vector space isomorphism, since vector space isomorphisms only depend on the linear independence and dimensions of the bases, and not their orthogonality under an inner product.
In other words, we can always use the vector space basis of the exterior algebra over $\mathbb{R}^n$ as a vector space basis for the geometric algebra $\mathbb{G}^n$ regardless of our choice of quadratic form, although this basis will not always be orthogonal. Hence by identifying the geometric algebra with the exterior algebra + inner product structure, we get a linear embedding of the geometric algebra into the tensor algebra "for free" by using the exterior algebra's embedding.
(See p.4 of this document for discussion of the canonical basis of a geometric algebra generated by an orthonormal basis of $\mathbb{R}^n$.)


text:
Q: Test NestJs Service with Jest I am looking for a way to test my NestJs PlayerController with Jest.
My controller and service declaration:
import { QueryBus, CommandBus, EventBus } from '@nestjs/cqrs';

/**
 * The service assigned to query the database by means of commands
 */
@Injectable()
export class PlayerService {
    /**
     * Ctor
     * @param queryBus
     */
    constructor(
        private readonly queryBus: QueryBus,
        private readonly commandBus: CommandBus,
        private readonly eventBus: EventBus
    ) { }

@Controller('player')
@ApiUseTags('player')
export class PlayerController {
    /**
     * Ctor
     * @param playerService
     */
    constructor(private readonly playerService: PlayerService) { }

My test:
describe('Player Controller', () => {
  let controller: PlayerController;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [PlayerService, CqrsModule],
      controllers: [PlayerController],
      providers: [
        PlayerService,
      ],
    }).compile();

    controller = module.get<PlayerController>(PlayerController);
  });

  it('should be defined', () => {
    expect(controller).toBeDefined();
  });
...

Nest can't resolve dependencies of the PlayerService (?, CommandBus,
  EventBus). Please make sure that the argument at index [0] is
  available in the PlayerService context.
  at Injector.lookupComponentInExports (../node_modules/@nestjs/core/injector/injector.js:180:19)

Any way to work around this dependency issue?

A: It does not work because you are importing PlayerService. You can only import modules, providers can be imported via a module or declared in the providers array:
imports: [PlayerService, CqrsModule]
          ^^^^^^^^^^^^^

However, in a unit test you want to test single units in isolation, not the interaction between different units and their dependencies. So better than importing or declaring your dependencies, would be providing mocks for the PlayerService or the providers of the CqrsModule.
See this answer for a distinction between unit and e2e tests.
See this answer on how to create mocks.

A: This worked for me.
import { UserEntity } from './user.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
const module = await Test.createTestingModule({
    controllers: [UsersController],
    providers: [UsersService],
    imports: [TypeOrmModule.forRoot(), TypeOrmModule.forFeature([UserEntity])], // <== This line
}).compile();


text:
Q: How can i handle many children viewmodels in MVVM? Let's suppose i have a viemwodel which requires a lot of different children viewmodels.
An example could be a settings menu: the main viewmodel should be able to load large number of children viewmodels (in the example image there are 3, but they could be an arbitrary number, even up to ~20)
All of the viewmodels are substantially different from each other.

The usual way i organize child viewmodels is the following:
MainViewModel(ChildViewModelFactory fac)
{
    this.factory = fac;
}

...
// later, when the child must be loaded

var newViewModel = fac.invoke();

While this works correctly when the MainViewModel has a small number of children (like 1-3) it can become verbose and "smelly" when the MainViewModel needs a lot of children (a constructor with ~20 parameter doesn't sound good).
How can i approach this?

A: Abstraction
Consider abstracting the layout problem. Eg:

*

*a MenuView is a list of children, arranged vertically following some rules.

*A GridView is a 2D array of children, each instantiated into its cell following some rules.

This reduces the problem of 20 unique children, with unique location information, and unique variable names to a standardised organisation.
Lifecycle
Don't have the view responsible for dealing with so much life-cycle on its child components. Have a ProtoView which holds the factories for each child, and when its called to instantiate it returns a real view with real children.


text:
Q: ASP MVC form to call specific action and not redirect but update original page I am using ASP.net MVC 3 for a project, and at a point now where I understand more of it, but also trying to learn differences between it and the WebForms world I have used for so long. Previously in WebForms you would just put the fields out there, add a button, and create an event, and then handle whatever you need to with with the postback.
For example, I have a simple view that shows details about an error. I want to push some of the information about this error to our issue tracker's API. Lets say just the subject and content of the error. I would in HTML do something like:
<form action="@Url.Action("Send")" method="post">
    <input id="subject" name="subject" type="text" value="@Model.subject" />

    <input id="content" name="content" type="text" value="@Model.content" />

    <input type="submit" value="Send" />
</form>

I found that naming my input ID's to match parameter names in my controller would then let me pass these parameters. This is similar to what you see in this older post by Scott Guthrie.
First of all, I want to call the 'Send' action in my Errors controller, and not my Details one. This actually does call my 'Send' action, but then redirects to localhost/Errors/Send, which I don't want it to.
I want to be able to submit this form, which calls and action and does the work with the remote API, and then update a message on the current page stating that the error has been transferred.
Once the issue had been submitted to the bug tracker, how do I then, for example, show a DIV on the original page passing content back to it (for example, a link to the issue in the issue tracker)?
Update: Here is what I am doing in my controller:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/redmine/issues.json");
request.Credentials = new NetworkCredential("username", "password");
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "application/json";

using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
    writer.Write("'issue': { " +
                      "'project_id': 'project', " +
                      "'subject': 'Test issue'" +
                      "}");
}

WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
string json = "";

using (StreamReader reader = new StreamReader(stream))
{
    json = reader.ReadToEnd();
}

Also, here is what I am doing in my view (simplified, and after help from Phillip)
@model webapp.Models.app_errors

<input type="button" onclick='SendErrors()'/>

A: In response to your first question, try this overload of Url.Action:
Url.Action("ActionName","ControllerName")

And your second question: You'll want to do it via AJAX.
Basically, for the first time the page is loaded, return whatever you want to display to the screen. Then, have an ajax function of this form:

A few things to note:
1) The url is automatically appended to include the data from data.
2) Your action method now needs to accept a parameter. There are many ways to go about this. I have added an example of what your action method might look like in the code below.
and then your button's onclick event will call that function, like this:
<input type="button" onclick='SendErrorsOrWhatever()'/>

What happens here is that when your button is clicked, Ajax will asynchronously (by default) hit your action method, and your action method will do whatever it needs to do with the errors, and then when it is finished, the success callback will be hit.
EDIT: now, your action might look something like this:
[AcceptVerbs(HTTP.Get)]
public static Error GetErrors(Error error)
{
    //do all your processing stuff
}

Now, this assumes that the JSon object dummy has the same fields as the Error class. If so, MVC will do automatic data binding on it. You can also use a more generic FormCollection for the parameter as well. Really, you can use whatever you want, but you'll want to wrap whatever you want in a JSon object.
Edit-- for your last question, this should work:
Add the following extension method to your app:
public static class JsonExtensions
{
    public static string ToJson(this Object obj)
    {
        return new JavaScriptSerializer().Serialize(obj);
    }
}

Or if you want, you can just add a ToJson() method to your model class, and then:
var model = @Model.ToJson();

in the js right before the ajax call. Then use the model variable for your data parameter.

A: In MVC, an "action" is essentially a "page".  (not exactly, but with routing, this ends up being mostly true)
That is, your actions are grouped into categories and navigated to using routing within the MVC framework.
I think what you want to do here is make an AJAX call that sends your error message off to a web service.
Short of that, you can use jQuery to insert a hidden div that contains an IFrame with another action's page on it.  I wouldn't recommend it, though.

A: There are two possiblities.

*

*In your Errors/Send action redirect the user back to the localhost/Errors/Details page. This can be done with a the Redirect() method on the controller. The problem with this approach is it's a blocking call. And the user will have to wait until the remote api has been called and responded.

*Use the AJAX approach as mentioned in the comments. The downside is it's a bit more complex and you may have to poll the service to retrieve the status, unless it's a fire and forget call, then it's money.
Using AJAX is the more elegant solution.

A: Using AJAX would be one of solving this. But you might want to rethink the behevior of the page. If this is your submit issue page, would you want to stay on this page after you submit an issue. What if I keep submitting issues, would you want to see the link only for the latest one? You might have to poll the server for getting a link for a submitted issue, which makes it even harder.
Without knowing the requirements, it's not easy to come up with any solution, but generally, I'd go to a different issue page once it's submitted from a submission page (something like ~/issue/id).
Also, you can use Html.TextboxFor(m=>m.subject) or some syntax like that, that way you won't have to match the input id manually for each property.


text:
Q: How to count the number of distinct values in a C++ std::map I have a c++ map declared as follows
std::map<std::string, int> wordMap= {
    { "is", 6 },
    { "the", 5 },
    { "hat", 9 },
    { "at", 6 }
    };

I would like to know how to find the number of distinct values of int existing in wordMap.
In this example, I would expect an output of 3 as i have 3 different distinct values (6,5,9).

A: Try to use std::set for counting:
std::set<int> st;
for (const auto &e : wordMap)
  st.insert(e.second);
std::cout << st.size() << std::endl;

A: One way is to store all keys of wordMap in a set and then query its size:
#include <unordered_set>
#include <algorithm>

std::map<std::string, int> wordMap= { /* ... */ };
std::unordered_set<int> values;

std::transform(wordMap.cbegin(), wordMap.cend(), std::insert_iterator(values, keys.end()),
     [](const auto& pair){ return pair.second; });

const std::size_t nDistinctValues = values.size();

Note that in C++20, the above presumably boils down to
#include <ranges>
#include <unordered_set>

const std::unordered_set<int> values = wordMap | std::ranges::values_view;
const std::size_t nDistinctValues = values.size();


text:
Q: create a php proxy page I'm looking for a way to load a full-functional copy of a web site inside a php proxy page in order to be able to grab and change part of its elements and styles.
I decided to post this question to merge my previous two into a more relevant evolution:
live change any site visualization properties
load external site and change its visualization
I have found cURL functions useful to load the page (eg. www.google.it; for google.com I received a 302 redirection, but I won't face it now).
Some of the page elements, like the image logo, are not properly loaded; this should be due to the original relative path to the site resources. I have to manually add "//google.it" before them to fix, and it worked.
Now I have another issue:
How is it possible to go further in the site navigation?
When I click any link the page is reloaded with its "real" destination. I suppose I have to reload my php and use the href link attribute as url to load (I can do that).
But what about the submit buttons? How can I redirect their destination?

A: Use an existing proxy for that.
Generally you'll have to just find all the strings matching the old domain name and change them into your url, so every link on the page will turn from being www.bla.com/page.htm into proxy.com/page.htm.
This will also require some server setup thanks to possible ajax requests and relative paths. Besides, super hard would be to catch dynamically constructed url's such as: var add r = 'b'+'la.com';


text:
Q: moq callbase for methods that do not return value (void methods) I am trying to mock my class that is under test, so that I can callbase on individual methods when testing them. This will allow me to test the method setup as callbase only, and all other methods (of the same class) called from within the test method will be mocked.
However, I am unable to do this for the methods that do not return a value. The intellisense just doesn't display the option of callbase, for methods that do not return value.
Is this possible?
The Service Class:
public class Service
{
    public Service()
    {
    }

    public virtual void StartProcess()
    {
        //do some work
        string ref = GetReference(id);
        //do more work
        SendReport();
    }

    public virtual string GetReference(int id)
    {
        //...
    }

    public virtual void SendReport()
    {
        //...
    }
}

Test Class setup:
var fakeService = new Mock<Service>();
fakeService.Setup(x => x.StartProcess());
fakeService.Setup(x => x.GetReference(It.IsAny<int>())).Returns(string.Empty);
fakeService.Setup(x => SendReport());
fakeService.CallBase = true;

Now in my test method for testing GetReference I can do this:
fakeService.Setup(x => x.GetReference(It.IsAny<int>())).CallBase();

but when i want to do the same for StartProcess, .CallBase is just not there:
fakeService.Setup(x => x.StartProcess()).CallBase();

it becomes available as soon as i make the method to return some thing, such a boolean value.

A: First of all, your mock will not work because methods on Service class are not virtual. When this is a case, Moq cannot intercept calls to insert its own mocking logic (for details have a look here).
Setting mock.CallBase = true instructs Moq to delegate any call not matched by explicit Setup call to its base implementation. Remove the fakeService.Setup(x => x.StartProcess()); call so that Moq can call base implementation.


text:
Q: NOT condition in elasticsearch I am trying to implement NOT condition in elasticsearch query.
Can I Implement filter inside bool or I need to write separate
filter as below. Any optimum solution is there?
{
   "query": {
      "bool": {
     "must": [
        {
           "query_string": {
          "query": "fashion"
           }
        },
        {
           "term": {
          "post_status": "publish"
           }
        }
     ]
      }
   },
   "filter": {
      "not": {
     "filter": {
        "term": {
           "post_type": "page"
        }
     }
      }
   }
}

A: You can use a must_not clause:
{
    "query": {
        "bool": {
            "must": [
                {
                    "match": {
                        "_all": "fashion"
                    }
                },
                {
                    "term": {
                        "post_status": "publish"
                    }
                }
            ],
            "must_not": {
                "term": {
                    "post_type": "page"
                }
            }
        }
    }
}

Also, I'd recommend using a match filter instead of query_string, as query_string requires the much more strict Lucene syntax (and is therefor more error prone), whereas match works more like a search box: it will automatically transform a human readable query to a Lucene query.


text:
Q: Bootstrap - alignment issues with container-fluid I have a comics site, http://hittingtreeswithsticks.com, and want to maintain a 100% width for my header (so it stretches 100% on any browser), but a fixed width for my content (want to maintain fixed 950px width).
Therefore, I put the header and footer in
 and the main content in
 to achieve that.
I've been testing locally on IE9, Chrome, and FireFox on a 1920 x 1080 resolution and it the header looked fine.

But when I tested on a smaller monitor, 1366 x 768, the header items seems to mush together.

In the header.php file, I have this set up (simplified) for the heading logo and links

         <logo>

        <comics link>

        <about link>

      And so on...

In header.php, I put an opening
 so that all other templates that include the header will be within containter and not container-fluid.
Any ideas why that might be happening?
Thanks!

A: You do not have a minimum width set for your content, and thus the browser will "mush" it to make it adapt to smaller resolutions.
You can try to use a CSS rule such as
#header { min-width: 1000px; }

(1000px is arbitrary here). This will prevent the header from wrapping to two lines, but will obviously cause some part of it to be outside the visiable area in smaller screens.
Edit: if you provide a fiddle with your code or a link to a working page, we'd be able to see if there are paddings/margins at play that affect this as well.

A: Try to change the overflow property in your #header element in your comic_style.css
#header {
background: url("images/SiteDesign/Comic_Header.png") repeat scroll 0 0 transparent;
height: 50px;
overflow: auto;scroll;
}

or the img tag in bootstrap.css might be creating problem
img {
    border: 0 none;
    height: auto;
    vertical-align: middle;
}

create another tag for the header image

A: Well first of all don't mess anything in the bootstrap.css also it's not so clever to correct something by writing a new css class or something like.
In other words don't try to fix that by css because you will have more problems later.
So here we go

That has to go below not at the top.

you don't need that div except if you want a whatever
Be careful with the offset and if try something like that:

And the most important remember that if you fix something for other size then you have to do it and for other and so on.That means you are not going responsive!
My suggestion is to try with the order of the divs classes and not at all with css.

A: I looked at the code on your page, and I believe this may solve your problem:

A: Instead of using spans, you could use the bootstrap nav element:

Charts

Life

Office

Political

Misc


text:
Q: Get emails whenever a file is uploaded on s3 bucket using serverless i want to get emails whenever a file is uploaded to s3 bucket as described in the title above, i am using serverless, the issue is that the event that i have created on s3 gives me just notification on s3-aws console, and  don't know how to configure cloudwatch event on S3 to trigger lambda. So please if someone knows how to triggered events on S3 using cloudwatch i am all ears.
Here is my code:
import json
import boto3
import botocore
import logging
import sys
import os
import traceback

from botocore.exceptions import ClientError
from pprint import pprint
from time import strftime, gmtime

email_from = '*****@******.com'
email_to = '******@******.com'
#email_cc = '********@gmail.com'
email_subject = 'new event on s3 '
email_body = 'a new file is uploaded'

#setup simple logging for INFO
logger = logging.getLogger()
logger.setLevel(logging.INFO)

from botocore.exceptions import ClientError

def sthree(event, context):
 """Send email whenever a file is uploaded to S3"""
body = {}
status_code = 200

try:
    s3 = boto3.client('s3')
    ses = boto3.client('ses')
    response = ses.send_email(Source = email_from,
                    Destination = {'ToAddresses': [email_to,],},
                        Message = {'Subject': {'Data': email_subject}, 'Body':{'Text' : {'Data': email_body}}}
         )

response = {
    "statusCode": 200,
    "body": json.dumps(body)
}

return response

and here is my serverless.yml file
service: aws-python # NOTE: update this with your service name

plugins:
  - serverless-external-s3-event

provider:   name: aws
runtime: python2.7
stage: dev
region: us-east-1
iamRoleStatements:
        - Effect: "Allow"
          Action:
              - s3:*
              - "ses:SendEmail"
              - "ses:SendRawEmail"
              - "s3:PutBucketNotification"
          Resource: "*"

 functions:   sthree:
    handler: handler.sthree
    description: send mail whenever a file is uploaded on S3
    events:
       - s3:
          bucket: cartegie-nirmine
          event: s3:ObjectCreated:*
          rules:
            - prefix: uploads/
            - suffix: .jpg
      - cloudwatchEvent:
              description: 'CloudWatch Event triggered '
              event:
                  source:
                      - "aws.S3"
                  detail-type:
                      - "S3 event Notification"
              enabled : true

A: If your motto is just to receive email notification of operations on a S3 bucket, then you dont need lambda functions for that. For the use-case mentioned in the question, you can achieve that using SNS topic and S3 events. I will mention the steps to follow from console(through the same can be achieved via sdk or cli).
1) Create a Topic using SNS console.
2) Subscribe to the topic. Use email as the communications protocol and provide your email-id.
3) You will get email requesting you to confirm your subscription to the topic. Confirm the subscription.
4) IMPORTANT: Replace the access policy of the topic with the below policy:
{
  "Version": "2008-10-17",
  "Id": "__default_policy_ID",
  "Statement": [
    {
      "Sid": "__default_statement_ID",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": "SNS:Publish",
      "Resource": "sns-topic-arn",
      "Condition": {
        "ArnLike": {
          "aws:SourceArn": "arn:aws:s3:*:*:s3-bucket-name"
        }
      }
    }
  ]
}

Basically you are giving permission for your s3-bucket to publish to the SNS topic.
Replace sns-topic-arn with your ARN of the topic you created above.
Replce s3-bucket-name with your bucket name, for which you want to receive notifications.
5) Go to S3 Console. Click on your S3 bucket and open the Properties tab.
6) Under Advanced settings, Click on Events Card.
7) Click Add Notifications and enter values. A sample has been shown below.

Select the required s3-events to monitor and the SNS topic you created.
8) Click Save. Now you should start receiving notifications to your email.


text:
Q: REST API Performance issue in Magento 2 Is anyone here heavily using Magento rest API for catalog data (products/categories/attributes/sets/groups) persistence? like not once in a while but more as a system integration. how is the performance in general? what throughput could you achieve and do you make use of async/bulk endpoints?
I am getting responses with a single POST/PUT in about 6s - 7s which I think is too much. As I have about 25000 products in my store
Do you have any suggestions on what can be done to improve the performance of REST APIS?
Any help is appreciated.

A: I found that this was because of the B2B feature of shared catalogs enabled I try to disable the shared catalog from the Admin Configurations and REST API performance just boost drastically.
As shared catalogs are like having lots of permissions for specific products for all the shared catalog groups created and that's why it's taking a lot to respond.
We customized the shared catalogs and bypass the permissions logic when the products have been created from REST APIS


text:
Q: Mirrored taskbar icons My brother tried to install some junk on his laptop (Windows 7) and ever since then the icons in the taskbar got mirrored. I tried rebuilding IconCache.db but it didn't work the problem out. He says he only tried to install alternative orbs for start button but I can't be sure.
Any ideas?

A: I think your graphic card setting is manipulated.

*

*try right-click on desktop and choose screen resolution. then  then check the Orientation
property to Landscape that may solve your problem .

*check your graphic card 'Rotate' property to 'Normal'

*at last check windows project by pressing windows key+P and select 'PC Screen Only'

A: It is indeed normal for RTL systems to have the start-orb on the right and tray on the left (figures 1 and 2), but notice that the icons in the taskbar face the same way as the ones on a LTR system (figure 3). In your screenshot, the Explorer icon is indeed facing backwards (though the start-orb is facing the right way).
What has likely happened is that the taskbar-modifying program that he installed did not support "i18n" correctly, if at all, and the modifications it made broke something.
Without knowing specifically which program it is, there's not much anyone can do, and even then, the damage may be specific to that system.
Your/his best chance, in order of difficulty/complication is as follows:

*

*Use the undo/reset function of the program to hopefully revert its changes

*Fully uninstsall the program (re-installing it first if necessary)

*Try running the System-File Checker in case the program modified system files

*Perform a System Restore to the point before the program was used if possible

*Try the Recovery Options

*Fall back to a repair-install

*As a last resort, do a full re-install and learn a lesson the hard way about trying random software and not backing up

Figure 1: Arabic Windows 7

Figure 2: Hebrew Windows 7

Figure 3: English Windows 7


text:
Q: Python example for scipy dia_matrix Running this code
d0  = np.ones(N)
dp1 = np.ones(N - 1)
dm1 = np.ones(N - 1)

diag = [[d0],[dp1],[dm1]]
offsets = [0,1,-1]

A = dia_matrix( (diag,offsets), shape=(N,N), dtype=float)

I get the following error:
File "/usr/local/lib/python2.7/dist-packages/scipy/sparse/dia.py", line 109, in __init__
self.data = np.atleast_2d(np.array(arg1[0], dtype=dtype, copy=copy))

ValueError: setting an array element with a sequence.
I can't understand what I'm doing wrong! Can someone provide me a correct example to do what I'm trying to do?

A: When the first argument of dia_matrix has the form (data, offsets), data is expected to be a 2-d array, with each row of data holding a diagonal of the matrix.  Since data is a rectangular matrix, some of the elements in data are ignored.  Subdiagonals are "left aligned", and superdiagonals are "right aligned".  (Specifically, the mapping between data and the sparse matrix A is data[i,j] == A[j - offsets[i], j].)  For example, consider the following that will be used to create a 5x5 matrix:
In [28]: data
Out[28]:
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15]])

In [29]: offsets
Out[29]: [0, 1, -1]

data contains three diagonals.  The since offset[0] is 0, row 0 of data contains the main diagonal.  All 5 elements in this row are used in the matrix.  offset[1] is 1, so the data in data[1] becomes the first superdiagonal.  Only the values [7, 8, 9, 10] will be used; the first value, 6, is ignored.  Similarly, the third row of data gives the first subdiagonal, and only the values [11, 12, 13, 14] are used.
In [30]: a = dia_matrix((data, offsets), shape=(5, 5))

In [31]: a.A
Out[31]:
array([[ 1,  7,  0,  0,  0],
       [11,  2,  8,  0,  0],
       [ 0, 12,  3,  9,  0],
       [ 0,  0, 13,  4, 10],
       [ 0,  0,  0, 14,  5]])

Your example can be rewritten as follows:
In [32]: N = 5

In [33]: data = np.ones((3, 5))

In [34]: A = dia_matrix((data, offsets), shape=(N, N), dtype=float)

In [35]: A.A
Out[35]:
array([[ 1.,  1.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  1.,  1.]])

The dia_matrix docstring has another example.
Alternatively, you can use scipy.sparse.diags to create the matrix.  This is useful if you already have code that generates the "correctly" sized diagonals.  With diags, you don't have to create the rectangular data matrix.  For example,
In [104]: from scipy.sparse import diags

In [105]: d0 = ones(n)

In [106]: dp1 = np.ones(N - 1)

In [107]: dm1 = np.ones(N - 1)

In [108]: d = [d0, dp1, dm1]

In [109]: B = diags(d, offsets, dtype=float)

In [110]: B.A
Out[110]:
array([[ 1.,  1.,  0.,  0.,  0.],
       [ 1.,  1.,  1.,  0.,  0.],
       [ 0.,  1.,  1.,  1.,  0.],
       [ 0.,  0.,  1.,  1.,  1.],
       [ 0.,  0.,  0.,  1.,  1.]])


text:
Q: Echoing Jquery "contains" statement doesn't work I have php file where I echo JQuery code where I check if checkboxes are checked and than do stuff if they are. But if I use contains() code does nothing.
This code works:
"<script type='text/javascript'>
  $(document).ready(function(){

    $('#filterbutton').click(function() {
      if($('#znackaasus').is(':checked')) {
        console.log('checked');
      }
    });
  });
</script>"

But this code breaks whole jQuery and does nothing:
"<script type='text/javascript'>
  $(document).ready(function(){

    $('#filterbutton').click(function() {
      if($('#znackaasus').is(':checked')) {
        $('.tovar:contains('ASUS')').hide();
      }
    });
  });
</script>"

A: Try This:
"<script type='text/javascript'>
$(document).ready(function(){

$('#filterbutton').click(function() {
if($('#znackaasus').is(':checked'))
    {
     $(\".tovar:contains('ASUS')\").hide();
    }
});
});
</script>"

Unsure if this will work as expected, but it might.


text:
Q: Getting Unable to find specification exception while running Concordion Fixure file I have kept fixure and html (specification) file under the same package 'test/java/com/mypckg/'. I'm using 2.0.2 concordion version.
But when I run the test I get below mentioned error. Please help me in resolving this.
java.lang.RuntimeException: Unable to find specification: 'com/mypckg/Testing.html' or 'com/mypckg/Testing.xhtml' or 'com/mypckg/Testing.md' or 'com/mypckg/Testing.markdown'
at org.concordion.Concordion.<init>(Concordion.java:64)
at org.concordion.internal.ConcordionBuilder.build(ConcordionBuilder.java:310)
at org.concordion.internal.FixtureRunner.<init>(FixtureRunner.java:19)
at org.concordion.integration.junit4.ConcordionRunner.<init>(ConcordionRunner.java:62)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)

I have tried to debug Concordion.class resource path sent till here is proper.
Below is my code.
@RunWith(ConcordionRunner.class)
public class TestingFixture {
Testing system = new Testing();

    public String greetingFor(String firstName) {
        return "Hello " + firstName + "!";
    }

}


text:
Q: Connected React Router and TypeScript for `match` Connected React Router exports types for RouterState which is great! However I don't see typings for match. Would assume those could also be imported and added to reducer such as RouterState is used below and in reducer:
https://github.com/supasate/connected-react-router/blob/master/examples/typescript/src/reducers/index.ts#L13
const rootReducer = (history: History) => combineReducers({
  count: counterReducer,
  router: connectRouter(history)

})

export interface State {
  count: number
  router: RouterState
}

Without which you can't really use this.props.match in connected components and such to match params, etc. Is there a workaround here for those using TypeScript who also need to add to reducer? Or am I missing a key part here? Thanks so much!

A: You have 2 ways to do it.

*

*You can use createMatchSelector function inside mapStateToProps to extract match from your state. DEMO
import * as React from "react";
import { connect } from "react-redux";
import { createMatchSelector } from "connected-react-router";
import { match } from "react-router";
import { State } from "./reducers";

interface StateProps {
  match: match<{ name?: string }>;
}

const Hello = (props: StateProps) => (

Hello {props.match.params.name}!

);

const mapStateToProps = (state: State) => {
  const matchSelector = createMatchSelector("/hello/:name");
  return {
    match: matchSelector(state)
  };
};

export default connect<StateProps>(
  mapStateToProps,
  null
)(Hello);

*You can get match directly from router, not from the state. DEMO
import * as React from "react";
import { RouteComponentProps, withRouter } from "react-router";

const Hello = (props: RouteComponentProps<{ name?: string }>) => (

Hello {props.match.params.name}!

);

export default withRouter(Hello);


text:
Q: Using pivot_wider or other solution to output my dataset in R I'm still new to R but making progress with the help
of this group. I'm struggling with what I consider to be a problem
that can be solved with pivot_wider, though i've not succeeded yet.
Thanks in advance for any assistance!
I have a dataset as below:
    RaceNum Horse             DrawA row_c
     <int> <chr>              <dbl> <int>
 1   21127 A'Ali            -0.242      1
 2   20260 A'Ali             0.128      2
 3   17889 A'Ali            NA          3
 4   21712 A'Shamardi       -0.519      1
 5   20340 A'Shamardi        0.767      2
 6    5285 A Bit Of A Touch NA          1
 7    4825 A Bit Of A Touch -0.0256     2
 8    4207 A Bit Of A Touch  0.139      3
 9    3397 A Bit Of Ginger   0.704      1
10    3206 A Bit Of Ginger   0.152      2
# ... with 64,290 more rows

My goal is to create an output that gives:
Horse           DrawA_1     DrawA_2     DrawA_3
A'Ali           -0.242      0.128       NA
A'Shamardi      -0.519      0.767       NA
A Bit of a Touch    NA      -0.0256     0.139
etc

Basically for every Horse, I need to output the DrawA value for the 3
instances.
Perhaps pivot_wider is not the optimal way to do this?
I was trying to output what I needed using group_by(Horse) and then
using summarise to display the output in a dataset 4 columns wide.
Hope someone can help!

A: You can use pivot_wider on your data quite easily if you use row_c as the names. Here's an example with some simple data.
library(tidyr)

df <- data.frame(Horse = c("A", "A", "A", "B", "B"),
                 DrawA = runif(5),
                 row_c = c(1:3, 1:2))

pivot_wider(df,
            names_from = row_c,
            names_prefix = "DrawA_",
            values_from = DrawA)
#> # A tibble: 2 x 4
#>   Horse DrawA_1 DrawA_2 DrawA_3
#>   <chr>   <dbl>   <dbl>   <dbl>
#> 1 A       0.979   0.153   0.427
#> 2 B       0.853   0.210  NA

A: Base R solution:
df1 <- as.data.frame.matrix(xtabs(DrawA~Horse+row_c, df))
within(setNames(df1, paste0("DrawA_", names(df1))), {horse <- row.names(df1)})