Q: Dynamically add new field with same key name in MongoDB Im trying to create a list on one of my collections in a dynamic way, here is an example.
var user = mongoose.Schema({
"NAME": String,
"LAST": String,
"EMAIL": String,
"TasksUploaded": {}

})
And what I want to do in mongoose is update the user with the tasks he has already uploaded, what is the best way to do this? what i want at the end is this:
{
    "Name" : "John",
    "Last" : "Doh",
    "Email" : "john@doh.com",
    "TasksUploaded" : {
        "Task" : "Task A"
        "Task" : "Task B"
        "Task" : "Task H"
        "Task" : "Task F"
        "Task" : "Task C"
    }
}

As you can see the task are not always consecutive and the user can upload them as he wants.
Im new to all this new NoSQL and MongoDB stuff, so if you could tell what is the best practice i would appreciate it.
This is how I currently update it but what happens is that the "Level" gets replaced and y need to add a new line to the docuemnt.
User.findOneAndUpdate({ _id: id}, { $set: { 'TasksUploaded.Task': req.body.task} }, { returnNewDocument: true, new: true }, function (err, result) {
      if (err) {
        console.log("Error saving task: " + err);
        return;
      }
      console.log(result);
    })
  }

A: Nope, that's not possible. You can't have several keys with the same name in an object. Just imagine, how would you address them?
It seems that you need to restructure your data and use arrays.

A: thanks to @Sam,
I modified my structure to add the upload tasks in a form of an array
TasksUploaded ["TaskA","TaskB","TaskC"]
Thank you


Q: Overriding a forms OnPaint method in component class Im looking to override the OnPaint method of the parent form of my component..
However i face 2 errors while doing this, the first is assigning the parent forms event handler

*

*No overload for "OnPaint" matches delegate "PaintEventHandler"

*Member from "Region.FromHrgn(IntPtr)" cannot be accessed with an instance reference; Qualify it with a type name instead.
heres my code
    private Control hostControl;
    public override ISite Site
        {
            get { return base.Site; }
            set
            {
                base.Site = value;
                if (value == null)
                {
                    return;
                }

                IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost;
                if (host != null)
                {
                    IComponent componentHost = host.RootComponent;
                    if (componentHost is ContainerControl)
                    {
                        hostControl = componentHost as ContainerControl;
                        hostControl.FindForm().Paint += new PaintEventHandler(this.OnPaint);
                    }
                }
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            hostControl.Region = hostControl.Region.FromHrgn(CreateTriangle(0, 0, this.Width, this.Height, this.Width, this.Height));
        }

Where am i going wrong?

A: Overriding the OnPaint() method of a control is normally recommended for custom drawing of THAT control, not of drawing another control. What you are trying to do in your code is to attach the Paint event of the hosting form to the OnPaint() method of your control. That's probably not working.
As you can read in the MSDN documentation, the Paint event of a control is raised by the OnPaint() method. You can attach a custom event handler:
hostControl.FindForm().Paint += new PaintEventHandler(Form_Paint);

private void Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
  ...
}

In the PaintEventArgs argument you will get the required parameters for drawing.


Q: Values of array after cudaMemcpy I'd like to know if, when i'm calling cudaMemcpy(...) to get memory on the GPU, also the values inside the array are copied or not. I will explain better: I'm copying the values from one array to another and then i call cudaMalloc and cudaMemcpy.
// Copying values of the arrays
for(int i = 0; i<16; i++){
    array_device_1[i] = array_host_1[i];
    array_device_2[i] = array_host_2[i];
}

// Memory allocation of array_device_1 and array_device_2
cudaMalloc((void**) &array_device_1, SIZE_INT*size);
cudaMalloc((void**) &array_device_2, SIZE_INT*size);

// Transfer array_device_1 and array_device_2
cudaMemcpy(array_device_1, array_host_1, SIZE_INT*size, cudaMemcpyHostToDevice);
cudaMemcpy(array_device_2, array_host_2, SIZE_INT*size, cudaMemcpyHostToDevice);

kernel<<<N, N>>>(array_device_1, array_device_2);

cudaMemcpy(array_host_1, array_device_1, SIZE_INT*size, cudaMemcpyDeviceToHost);
cudaMemcpy(array_host_2, array_device_2, SIZE_INT*size, cudaMemcpyDeviceToHost);

cudaFree(array_device_1);
cudaFree(array_device_2);

So, when i'm executing all those instructions and I'm using all the arrays inside the kernel, are the values inside the array_device_1 and array_device_2 or not ? I tried to print out after the kernel and i noticed that all the arrays are empty! Really i can't understand how i can keep the values inside them and then changing their values with kernel function.

A: Yes they have their values inside. But you can't print them out on the host. For this you will need to copy your data back using
cudaMemcpy((void *) array_host_2, (void *) array_device_2, SIZE_INT*size, cudaMemcpyDeviceToHost);

And then you can print the values of array_host_2.
A bit more explanation: Your array_device_* lives on the GPU and from your CPU (that is printing your output) you do not have direct access to this data. So you need to copy it back to your CPUs memory first before printing it out.

A: Example of copying array with data to device, altering values in kernel, copy back to host and printing the new values:
// Function to run on device by many threads
__global__ void myKernel(int *d_arr) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    d_arr[idx] = d_arr[idx]*2;
}

int main(void) {
    int *h_arr, *d_arr;
    h_arr = (int *)malloc(10*sizeof(int));
    for (int i=0; i<10; ++i)
        h_arr[i] = i; // Or other values

    // Sends data to device
    cudaMalloc((void**) &d_arr, 10*sizeof(int));
    cudaMemcpy(d_arr, h_arr, 10*sizeof(int), cudaMemcpyHostToDevice);

    // Runs kernel on device
    myKernel<<< 2, 5 >>>(d_arr);

    // Retrieves data from device
    cudaMemcpy(h_arr, d_arr, 10*sizeof(int), cudaMemcpyDeviceToHost);

    for (int i = 0; i<10; ++i)
        printf("Post kernel value in h_arr[%d] is: %d\n", i,h_arr[i]);

    cudaFree(d_arr);
    free(h_arr);
    return 0;
}

A: The code snippet you provided seems correct, other than the first few lines as leftaroundabout pointed out. Are you sure the kernel is correct? Perhaps you are not writing the modified values back to global memory. If you make another set of host arrays and copy the GPU arrays back before running the kernel, are they correct? From what you have, the values inside array_host_* should have been copied to array_device_* properly.

A: You can use a kernel function to directly print values on GPU memory. Use can use something like:
__global__ void printFunc(int *devArray){
      printf("%d", devArray[0]);
}

Hope it helps.


Q: How do I locate data in a database with vague column names? In our database we have a number of tables that have non-descriptive columns names e.g. (Attribute1, Attribute2....Attribute60 etc).
What I am wanting to know is if given a particular piece of information e.g. I know that a  Job Code could be "123456", but I do not know what column in our database relates to Job Code, is it possible using a query to find out which column in which table contains data that is similar to that of 123456?
I am fairly confident my colleague used to have a query to achieve this but he has since left our organisation and I cannot seem to find his query.
Appreciate any help I can get!

A: sp_search_code is what I use to find any code items which are in the DB; however, what you need is a redgate tool which will index the db and help you search its contents.  I will suggest as Just Aguy did, that you spend some time cleaning up those generic column names and any gen table names for that matter, good luck.
http://vyaskn.tripod.com/sql_server_search_stored_procedure_code.htm


Q: how to upload to files to amazon EC2 I am trying to upload files to an amazon EC2 from android. however whenever i go to upload the files I get a Unexpected response code 500 error. From what I uderstand this is because the user doesnt have the correct permissions to upload files to the database? I know that the problem is with the amazon EC2 instance rather than the code. but below is my php code for uploading to the server. first of all is that the correct way to enter the upload folder (/var/www/html/uploads) ? Any help on how i can get this working would be great.
<?php
if(isset($_POST['image'])){
    echo "in";
    $image = $_POST['image'];
    upload($_POST['image']);
    exit;
}
else{
    echo "image_not_in";
    exit;
}

function upload($image){
    $now = DateTime::createFromFormat('U.u', microtime(true));
    $id = "pleeease";

    $upload_folder = "/var/www/html/upload";
    $path = "$upload_folder/$id.jpg";

    if(file_put_contents($path, base64_decode($image)) != false){
        echo "uploaded_success"
    }
    else{
        echo "uploaded_failed";
    }
}

?>

A: Just a few notes:
First, you should make sure to send your data from the app with the enctype of multipart/form-data before submitting to the server.
Second, try variants of this simplified code:
if(isset($_FILES['image']))
{
   $fileTmp = $_FILES['image']['tmp_name'];
   $fileName = $_FILES['image']['name'];

    move_uploaded_file($fileTmp, "/var/www/html/uploads/" . $fileName);
    echo "Success";
}
else
{
    echo "Error";
}

And finally, assuming you're using Apache and the user name is www-data, you'll need to make sure it can write to the upload folder:
sudo chown www-data:www-data /var/www/html/uploads
sudo chmod 755 /var/www/html/uploads


Q: Merge fields laravel collections I have two Laravel collections. Mi first collection called $custom_product:
Collection {#313 ▼
  #items: array:1 [▼
    0 => array:1 [▼
      "custom_description" => "insert description here"
    ]
  ]
}

And I have my other collection called $api_product:
Collection {#311 ▼
  #items: array:29 [▼
    "article_id" => 5570
    "active" => null
    "name" => "CORBATA POLIESTER"
    "detail" => "- Pesa: 43 gr."
    "constructor_name" => "gift"
    "stock_available" => true
    "stock" => null
    "prices" => array:6 [▶]
    "price_pvp" => 29.0
    "size" => "1410X100"
  ]
}

I want this result. The same collection but with the field custom_description added:
Collection {#311 ▼
  #items: array:29 [▼
    "article_id" => 5570
    "active" => null
    "custom_description" => "insert description here"//add this field
    "name" => "CORBATA POLIESTER"
    "detail" => "- Pesa: 43 gr."
    "constructor_name" => "gift"
    "stock_available" => true
    "stock" => null
    "prices" => array:6 [▶]
    "price_pvp" => 29.0
    "size" => "1410X100"
  ]
}

A: You may use put method of
laravel collection.
$collection = collect(['product_id' => 1, 'name' => 'Desk']);

$collection->put('price', 100);

$collection->all();

// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

A: You can itarete over collections and add fields manually as with simple array:
for ($i = 0; $i < count($secondCollection); $i++) {
    // Add field to an item.
    $secondCollection[$i]['custom_description'] = $firstCollection[$i]['custom_description'];
}

This code will give an idea. Actual code is really depends on collections structure.

A: In the case that you were doing this per individual record using the examples given, I think it would be:
$api_product->put($custom_product->toArray()[0]);

If you wanted to combine multiple records you could use the map() method
$api_products_collection->map(function($key,$item) {
    //combine the record
    return $item;
});


Q: Access parent object of Button in click event in UWP application with C# This is for a UWP application for raspberry pi (c#). I have a button as a public member of a class written by me. Since this is a member of class. Whenever an object of this class is created, it needs to have a Click event. I need to have the click event inside the MainPage.xaml.cs file in order for it to have access to other functions, instead of the actual class.
I am able to use the following code:
ExecutionSequence newSeq = new ExecutionSequence();
newSeq.SelectionButton.Click += SelectionButton_Click;

private void SelectionButton_Click(object sender, RoutedEventArgs e)
{
   Button tempbutton = sender as Button;
}

The above code gives full access of the properties of the Button.
However, I am looking for help in the above scenario to access the actual object of class to which this button belongs to as the event requires to access other members of class.
Please note that I considered making the click event as another member of the class itself. But it makes things complex in my case.


Q: JQuery Mobile clone page I having trouble cloning a page of jqm. Here is an example:
http://jsfiddle.net/QZKBw/
as you can see, the cloning and modifing the page is not the problem:
    var newPage = $('#page-1').clone();
    newPage.prop('id', 'page-2');
    newPage.find('#header-1')
        .prop('id', 'header-2')
        .find('h1')
        .html('Page 2');

The switch back to page 1 will end up with two active pages. Is it a problem with jqm?

A: This should do it: http://jsfiddle.net/Gajotres/Nc98p/
$(function () {
    $('#clone-page').click(function () {
        if($('#page-2').length == 0){
            var newPage = $('#page-1').clone();
            newPage.prop('id', 'page-2');
            newPage.find('#header-1')
                .prop('id', 'header-2')
                .find('h1')
                .html('Page 2');
            newPage.find('#content-1')
                .prop('id', '#content-2')
                .html(' to Page 1');
            newPage.appendTo($.mobile.pageContainer);
        }
        $.mobile.changePage('#page-2');
    });
});


Q: Cannot acces a disposed object I'm trying to change some of my linq codes to sp but in one my functions which is
private async Task getNodes()
{
    List<TreeViewNode> nodes = new List<TreeViewNode>();
    var activities = await _spConnections.GetActiveListBySpAsync(User.Identity.GetCookieUserCompId<int>());

    //Loop and add the Parent Nodes.
    foreach (var activity in activities)
    {
        var model1 = await _activitiesService.GetByIdWithFormsAsync(activity.ID);
        var model = model1.Forms.OrderBy(f => f.Order).ToList();
        var preformid = model1.PreFormId;

        nodes.Add(new TreeViewNode { id = activity.ID.ToString(), parent = "#", text = activity.Name });
        var Forms = await _spConnections.GetSpMainActiveFormListAsync(activity.ID);
        // Loop and add the Child Nodes.
        foreach (var form in Forms)
        {
            DigitalContentEnum enumType = EnumHelper<DigitalContentEnum>.Parse(form.Type);
            string typeName = EnumHelper<DigitalContentEnum>.GetDisplayValue(enumType);

            nodes.Add(new TreeViewNode { id = form.ActivitiesID.ToString() + "-" + form.ID.ToString(), parent = form.ActivitiesID.ToString(), text = form.Title + " (" + typeName + ")  "});
        }

        if (preformid != null)
        {
            var preformtags = await _activitiesService.GetByIdWithPreFormsAsync(preformid);
            var preformModel = preformtags.Forms.OrderBy(x => x.Order).ToList();

            foreach (var foorm in preformModel)
            {
                DigitalContentEnum enumType = EnumHelper<DigitalContentEnum>.Parse(foorm.Type);
                string typeName = EnumHelper<DigitalContentEnum>.GetDisplayValue(enumType);

                nodes.Add(new TreeViewNode { id = foorm.ActivitiesID.ToString() + "-" + foorm.ID.ToString(), parent = model1.ID.ToString(), text = foorm.Title + " (" + typeName + ")  " });
            }
        }
    }

    //Serialize to JSON string.
    var result = JsonConvert.SerializeObject(nodes);
    ViewBag.Json = result;
}

So as you see var activities is being filled by running a sp and it does work
but when it reaches
var model1 = await _activitiesService.GetByIdWithFormsAsync(activity.ID);

The Error:

Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'Context'.

appears
activitesservice is my repository which the runs the following :
public async Task<Activity> GetByIdWithFormsAsync(long id)
{
    return await _activities.Include(x => x.Forms).FirstOrDefaultAsync(x => x.ID == id);
}

and my sp is:
public async Task<List<Form>> GetSpMainActiveFormListAsync(long actId)
{
    var Check = new List<Form>();
    using (_unitOfWork)
    {
        using (var cmd = _unitOfWork.ExecuteCreateConnection())
        {
            cmd.CommandText = "SpGetMainActiveForm";
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            var param1 = cmd.CreateParameter();
            param1.ParameterName = "actId";
            param1.Value = actId;
            cmd.Parameters.Add(param1);

            _unitOfWork.ExecuteOpenConnection();
            using (var result = cmd.ExecuteReader())
            {
                if (result.HasRows)
                {
                    Check = (List<Form>)CommonFunctions.Conversions.MapToList<Form>(result);
                }
            }
            _unitOfWork.ExecuteCloseConnection();
        }
    }
    return Check;
}

UnitOfWork is my repository of my Context which is
public interface IUnitOfWork:IDisposable
{
    EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
    void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class;
    DbSet<TEntity> Set<TEntity>() where TEntity : class;
    int SaveChanges(bool acceptAllChangesOnSuccess);
    int SaveChanges();
    void ExecuteSqlCommand(string query);
    DbCommand ExecuteCreateConnection();
    void ExecuteOpenConnection();
    void ExecuteCloseConnection();
    void ExecuteSqlCommand(string query, params object[] parameters);
    Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken());
    Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken());
}

and my context is:
public class Context : DbContext, IUnitOfWork
{
    public Context(DbContextOptions<Context> options)
    : base(options)
    {

    }
    public virtual DbSet<Admin> Admin { set; get; }
    public virtual DbSet<Activity> Activities { set; get; }
    public virtual DbSet<ActivityCategory> ActivityCategories { set; get; }
    public virtual DbSet<ActivitiesPic> ActivitiesPics { set; get; }
    public virtual DbSet<ActivityRecord> ActivityRecords { set; get; }
    public virtual DbSet<Answer> Answers { set; get; }
    public virtual DbSet<Company> Companies { set; get; }
    public virtual DbSet<Form> Form { set; get; }
    public virtual DbSet<NazerOrTarah> NazerOrTarah { set; get; }

    //Added in 1398/12/13
    public virtual DbSet<ReportDynamicTemplate> ReportDynamicTemplate { set; get; }
    public virtual DbSet<ReportTemplateForms> ReportTemplateForms { set; get; }

    public virtual DbSet<User> Users { set; get; }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.HasDefaultSchema("dbo");
        builder.Entity<Activity>()
            .HasIndex(a => a.CompID);

        builder.Entity<ActivityRecord>()
            .HasIndex(a => new { a.ActivitiesID, a.NazerID });

        builder.Entity<Answer>()
            .HasIndex(a => new { a.ActRecordsID, a.FormID });

        builder.Entity<Form>()
            .HasIndex(a => new { a.ActivitiesID, a.ParentId });

        // it should be placed here, otherwise it will rewrite the following settings!
        foreach (var relationship in builder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
        {
            relationship.DeleteBehavior = DeleteBehavior.Restrict;
        }

        base.OnModelCreating(builder);
    }

    public void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class
    {
        Update(entity);
    }

    public void ExecuteSqlCommand(string query)
    {
        Database.ExecuteSqlCommand(query);
    }

    public DbCommand ExecuteCreateConnection()
    {
        return Database.GetDbConnection().CreateCommand();
    }

    public void ExecuteOpenConnection()
    {
        Database.OpenConnection();
    }
    public void ExecuteCloseConnection()
    {
        Database.CloseConnection();
    }
    public void ExecuteSqlCommand(string query, params object[] parameters)
    {
        Database.ExecuteSqlCommand(query, parameters);
    }
}

What am I doing wrong?


Q: Collecting custom Simple Analytics metadata in a Next.js app I am struggling to collect custom Simple Analytics metadata in my Next.js app. Looking at their docs, I can either set metadata on the window object (link) or add it via a callback function (link).
My Next.js app looks as follows:
_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  render() {
    return (

          [...snip...]

    )
  }
}

page.js
import Head from 'next/head'
import { useRouter } from 'next/router'
import Layout from '../components/layout'

export default function Page() {
  const router = useRouter()
  const i = router.query.i

  return (
    <>

        [...snip...]

      // NOTE 1: This does not work

      // NOTE 2: I cannot access `i` here


Q: How to manipulate rendered data table that uses a reactive expression? I'm quite new with using Shiny. The code below is actually part of an Rmarkdown file with Shiny coding in it.
I have an issue in handling reactive expressions within Shiny. Basically after calling a reactive expression, I can render or plot the expressions. What I cannot easily do is to manipulate that data after calling it.
I've managed to render and output load_table(). This just tells it to load the csv file on a button click. See code below:
```{r UI inputs}
wellPanel(
  fileInput("dataset", label = "Select a .csv File to upload",
            accept=c("text/csv",
                     "text/comma-separated-values,text/plain",
                     ".csv")),

actionButton(inputId = "loadbutton", label = "Load Data")
)

dataTableOutput("df")

```

```{r Server Functions}
load_table <- eventReactive(input$loadbutton, {
    # input$file1 will be NULL initially. After the user selects
    # and uploads a file, it will be a data frame with 'name',
    # 'size', 'type', and 'datapath' columns. The 'datapath'
    # column will contain the local filenames where the data can
    # be found.
    inFile <- input$dataset

    if (is.null(inFile)){
      return(NULL)}
    else {
      read.csv(inFile$datapath)}
    })

output$df <- renderDataTable({
  load_table()
})
```

My output

An example of a file I loaded

However, once the user selects and loads the data - I can't seem to manipulate it because the reactive expression load_table() doesn't work like a dataframe I'm used to.
What I want to do next is to manipulate load_table() in any way possible. For example, filtering the data by date range or just simply adding additional columns. But I can't seem to manipulate load_table(). And I can't get the table without using a reactive function.
I know there are similar questions already being asked on StackExchange, but it never seems to be what I need. What am I missing here?
Regards
Z


Q: Adding another column to a numpy array I have two arrays of the following dimensions:
a = (6,1) b = (6,4)
I wish to add array (a) as additional column to array (c).
Tried:
c= np.column_stack([b,a])
and get an error due to mismatch of dimensions.

A: Try:
c = np.concatenate((b,a), axis=1)

This assumes that a.shape = (6,1). If a.shape = (6,) then you can do:
c = np.concatenate((b,a.reshape((6,1))), axis=1)


Q: Parse html page source with libcurl and C How can I print the source of a webpage, specified in curl_easy_setopt, without html tags? So, printing only the text in the source?

A: Curl/libcurl is just for fetching the HTML page. To extract information from it, you need other tools.
The most general solution is to use a HTML parser. A good one in C is HTMLparser from libxml.


Q: R nls exponential curve I have two vectors X and y2, and I wish to fit an exponential curve to the data.
I tried many approaches described on Stack Overflow topics but all of them give me just a straight line. e.g. I tried this:
model.three <- lm(log(y2) ~ log(X))
plot(X,predict(model.three))
abline(model.three)

My data:
X <- seq(1:50)
Y <- rnorm(50,mean=0,sd=1)
y2 <- exp(X)
y2 <- Y+y2

A: Is this what you are looking for?
model.three <- lm(log(y2) ~ log(X))
plot(X,predict(model.three))

## Instead of abline(), use this:

lines(model.three$fitted.values)

A: Your data expresses an exponential relationship between Y and X, which is Y = exp(X) + eps where eps is some noise.
Therefore, I would suggest fitting a model between log(Y) and X, to capture the linear relationship between the two:
model.three <- lm(log(y2) ~ X)
summary(model.three)
The summary confirms that the relationship captured is as expected (i.e. the coefficient for X is very close to 1).
Since plotting the data on a linear scale will not be useful, I think it is a good idea to plot the fitted straight line with abline.
Note: to be exact, it would be more accurate to capture the relationship between y2 and exp(X), but with your data, the fit is essentially perfect.


Q: Overlay numbers from 0000 to 9999 on a picture I have a picture with some white/blank space. My goal is to automatically generate a number from 0000 to 9999 and put it on top of the picture, then export/save it as a png.
the result should be
mypicture_0000.png
mypicture_0001.png
...
mypicture_9999.png
Has anyone tried something similar?
I am thinking about trying autoit, but will that work? If so which software should I use with autoit?
Thank You.

A: autoit may work.  i'd use python PIL.  i can specify font, convert it to a layer and overlay on top of preexisting image.
EDIT
actually imagemagick can be easier than PIL  http://www.imagemagick.org/Usage/text/

A: Should not be much of a problem if you have Python and the Python Imaging Library (PIL) installed:
from PIL import Image, ImageFont, ImageDraw

BACKGROUND = '/path/to/background.png'
OUTPUT = '/path/to/mypicture_{0:04d}.png'
START = 0
STOP = 9999

# Create a font object from a True-Type font file and specify the font size.
fontobj = ImageFont.truetype('/path/to/font/arial.ttf', 24)

for i in range(START, STOP + 1):
    img = Image.open(BACKGROUND)
    draw = ImageDraw.Draw(img)
    # Write a text over the background image.
    # Parameters: location(x, y), text, textcolor(R, G, B), fontobject
    draw.text((0, 0), '{0:04d}'.format(i), (255, 0, 0), font=fontobj)
    img.save(OUTPUT.format(i))

print 'Script done!'

Please consult the PIL manual for other ways of creating font objects for other font formats


Q: Having trouble sniffing for a DNS response in scapy (Python 3) I currently have this piece of code that is proven to sniff for the DNS query which is defined within DNSsniff(pkt).
I also have a second definition called DNSsniff2(pkt) that tries to sniff for the DNS response, however, I have had little to no luck in getting it to work.
any help would be greatly appriciated :)
import scapy.all as scapy

def DNSsniff(pkt):
    if scapy.IP in pkt:
        ip_src=pkt[scapy.IP].src
        ip_dst=pkt[scapy.IP].dst
        if pkt.haslayer(scapy.DNS) and pkt.getlayer(scapy.DNS.qr) == 1:
            qname=pkt.getlayer(scapy.DNS).qd.qname
            print(str(ip_src) + " -> " + str(ip_dst) + " : " + "(" + str(qname)+ ")")

def DNSsniff2(pkt):
    if scapy.IP in pkt:
        ip_src=pkt[scapy.IP].src
        ip_dst=pkt[scapy.IP].dst
        if pkt.haslayer(scapy.DNS) and pkt.getlayer(scapy.DNS.an) ==1:
            arname=pkt.getlayer(scapy.DNS).an.rdata
            print(str(ip_src) + " -> " + str(ip_dst) + " : " + "(" + str(arname) + ")")

#attempts to capture and filter the nessasery DNS response from the server.
capture = scapy.sniff(iface="Ethernet",filter="udp port 53", store=2, count=2)
print("\nsniffing....")
for i in capture:
    DNSsniff(i)
    DNSsniff2(i)

print("\nsniffing dun")

I have tried to change the scapy.DNS.an to scapy.DNS.rr but the code didnt work


Q: Recyclerview with multiple view types I created a recyclerview with multiple view types.First problem is that images don't show and second problem is when i scroll recyclerview,
values of its items changes and I don't know how can I fix it.
my adapter code:
public class HeterogenousRecyclerviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    private ArrayList<DataObject> mDataset;
    Context context;
    RecyclerView.ViewHolder viewHolder;

    public HeterogenousRecyclerviewAdapter(ArrayList<DataObject> myDataset) {
        this.mDataset = myDataset;
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    @Override
    public int getItemViewType(int position) {
        int view_type=mDataset.get(position).getView_type();
        return view_type;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        context=parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

        switch (viewType){
            case 0:
                View v1 = inflater.inflate(R.layout.layout_viewholder1, parent, false);
                viewHolder = new ViewHolder1(v1);
                break;
            case 1:
                View v2 = inflater.inflate(R.layout.layout_viewholder2, parent, false);
                viewHolder = new ViewHolder2(v2);
                break;
        }

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        switch (viewHolder.getItemViewType()){
            case 0:
                ViewHolder1 vh1 = (ViewHolder1) viewHolder;
                configureViewHolder1(vh1, position);
                break;
            case 1:
                ViewHolder2 vh2 = (ViewHolder2) viewHolder;
                configureViewHolder2(vh2, position);
                break;
        }

    }

    private void configureViewHolder1(ViewHolder1 vh1, int position) {
        if (mDataset != null) {
            vh1.getLabel1().setText(mDataset.get(position).getName());
            //vh1.getLabel2().setText("Hometown: " + user.hometown);
        }
    }

    private void configureViewHolder2(ViewHolder2 vh2, int position) {

        //vh2.getImageView().setImageResource(R.mipmap.img1);
        try {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier(mDataset.get(position).getImg(), "mipmap",
                    context.getPackageName());
            vh2.getImageView().setImageResource(resourceId);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

this is my ViewHolder1 class:
public class ViewHolder1 extends RecyclerView.ViewHolder {

    private TextView label1;

    public ViewHolder1(View v) {
        super(v);
        label1 = (TextView) v.findViewById(R.id.text1);
        //label2 = (TextView) v.findViewById(R.id.text2);
    }

    public TextView getLabel1() {
        return label1;
    }

    public void setLabel1(TextView label1) {
        this.label1 = label1;
    }

}

this is ViewHolder1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:textStyle="bold" />

</LinearLayout>

this is ViewHolder2 class:
public class ViewHolder2 extends RecyclerView.ViewHolder {

    private ImageView ivExample;

    public ViewHolder2(View v) {
        super(v);
        ivExample = (ImageView) v.findViewById(R.id.ivExample);
    }

    public ImageView getImageView() {
        return ivExample;
    }

    public void setImageView(ImageView ivExample) {
        this.ivExample = ivExample;
    }
}

this is ViewHolder2.xml:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ivExample"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    android:layout_width="200dp"
    android:layout_height="200dp"/>

this is my main activity code:
        ArrayList<DataObject> personList = new ArrayList<DataObject>();
        DataObjectDBAdapter dataObjectDBAdapter = new     DataObjectDBAdapter(getApplicationContext());
        personList = dataObjectDBAdapter.getALL();
        adapter = new HeterogenousRecyclerviewAdapter(personList);

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);

can sb help me?

A: I hadn't saved names of images in the SQLite database so the first problem was because of that, and the second problem was in my adapter code. I had to write "viewHolder" instead of "holder" in onBindViewHolder(), so the correct method is:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {

    switch (viewHolder.getItemViewType()){
        case 0:
            ViewHolder1 vh1 = (ViewHolder1) viewHolder;
            configureViewHolder1(vh1, position);
            break;
        case 1:
            ViewHolder2 vh2 = (ViewHolder2) viewHolder;
            configureViewHolder2(vh2, position);
            break;
    }

}

A:
First make sure the given statement must only return 0 or 1. because view type must start with 0

int view_type=mDataset.get(position).getView_type();

No need to create the below viewHolder as a member of class
RecyclerView.ViewHolder viewHolder;

Don't check viewType in onBindViewHolder . Instead check holder instanceOf
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if(holder instanceOf ViewHolder1){
            (ViewHolder1) holder.getLabel1().setText(mDataset.get(position).getName());
        }
        else
        {
            try {
                Resources res = context.getResources();
                int resourceId = res.getIdentifier(mDataset.get(position).getImg(), "mipmap",
                    context.getPackageName());
                (ViewHolder2) holder.getImageView().setImageResource(resourceId);
            } catch (Exception e) {}
        }
    }

A:
i had the same problem values changes after the scroll, then i overide these methods

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemCount() {
    return dataList.size();
},

This solved my problem and  for the Image heck the image resourceId is null or not
   i am not sure if your way is good to set the Resource.

A: While using multiple view types with dynamic data some users may face issues like duplicate data items, data being swapped between questions. To avoid that you have to set a unique view type id for every item.
@Override
public int getItemViewType(int position) {
    // Here you can get decide from your model's ArrayList, which type of view you need to load. Like
    if (list.get(position).type == Something) { // Put your condition, according to your requirements
        return VIEW_TYPE_ONE;
    }
    return VIEW_TYPE_TWO;
}

The above code for getItemViewType can fail where 3 consecutive items will have the same type. For example, if the user enters ans1 in item 1
edit text,ans2 in item 2 edit text, ans3 in item 3 edit text and scroll the recycler view up and down then some users may face issues like duplicate data items, data being swapped between questions.
Formula to create unique view type id :
Formula : pos * Constants.Max + viewType;
set value Constants.Max = 100000;
    class DataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final int VIEW_TYPE_EDIT_TEXT = 1;
    private final int VIEW_TYPE_IMAGE_VIEW = 2;
    private final ArrayList<DataModel> dataModelArrayList = new ArrayList<>();

    @Override
    public int getItemViewType(int position) {

        String dataType = dataModelArrayList.get(position).getDataType();
        int viewType = VIEW_TYPE_EDIT_TEXT;

        switch (dataType) {
            case "A":
            case "E":
                viewType = VIEW_TYPE_EDIT_TEXT;
                break;

            case "I":
                viewType = VIEW_TYPE_IMAGE_VIEW;
                break;
        }

        int pos = position + 1;
        return pos * Constants.Max + viewType;

    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int type) {

        int count = (int) Math.ceil(type / Constants.Max);
        int viewType = type - count * Constants.Max;

        if (viewType == VIEW_TYPE_EDIT_TEXT) {
            return new ViewHolderTypeEditText(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_et_item, parent, false));
        } else if (viewType == VIEW_TYPE_IMAGE_VIEW) {
            return new ViewHolderTypeImageView(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_sp_item, parent, false));
        }

        return new ViewHolderTypeEditText(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_et_item, parent, false));

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int pos) {

        int type = holder.getItemViewType();
        int count = (int) Math.ceil(type / Constants.Max);
        int viewType = type - count * Constants.Max;

        if (viewType == VIEW_TYPE_EDIT_TEXT) {

            DataAdapter.ViewHolderTypeEditText viewHolderTypeEditText = (DataAdapter.ViewHolderTypeEditText) holder;

        } else if (viewType == VIEW_TYPE_IMAGE_VIEW) {

            DataAdapter.ViewHolderTypeImageView viewHolderTypeImageView = (DataAdapter.ViewHolderTypeImageView) holder;

        }

    }

    @Override
    public int getItemCount() {
        return dataModelArrayList.size();
    }

    public class ViewHolderTypeEditText extends RecyclerView.ViewHolder {

        EditText etText;

        public ViewHolderTypeEditText(@NonNull View itemView) {
            super(itemView);

            etText = itemView.findViewById(R.id.et_text);

        }
    }

    public class ViewHolderTypeImageView extends RecyclerView.ViewHolder {

        ImageView imageView;

        public ViewHolderTypeImageView(@NonNull View itemView) {
            super(itemView);

            imageView = itemView.findViewById(R.id.image_view);

        }
    }

}


Q: Laravel groupBy rank resulting in multiple grouped rows I'm using the groupby() function on my query to get some stats on two groups of athletes.
I have a table with my athletes and one with their performance.
- athletes table
-- id
-- name
-- group_id

-performance table
-- id
-- DateTime
-- athlete_id
-- sport_id
-- time

Each athlete do the same sport for multiples days (which is not the same for all athletes). I would like to see the evolution of the time average over days per group in a given sport.
I run this query
$query = '*, AVG(time) as average_time' ;
$Performance = Performance::join('athletes','performance.athlete_id','=','athletes.id')
                            ->select(\DB::raw($query))
                            ->where('performance.sport_id', '=', '43')
                            ->orderBy('group_id', 'asc')
                            ->groupBy('group_id')
                            ->get()
                            ->toArray();

However, this give me the average for a given sport_id but not over each days.
How can I see the average for every day in a given sport groupby group_id?

A: If DateTime is a timestamp then you can use the mysql date functions. Specifically GROUP BY WEEKDAY(timestamp_field).
Added into your query it looks like this
$query = '*, AVG(time) as average_time' ;
$Performance = Performance::join('athletes','performance.athlete_id','=','athletes.id')
                            ->select(\DB::raw($query))
                            ->where('performance.sport_id', '=', '43')
                            ->orderBy('group_id', 'asc')
                            ->groupBy('WEEKDAY(DateTime)')
                            ->groupBy('group_id')
                            ->get()
                            ->toArray();


Q: Vue: Setting data from binded prop is using the default value When I pass in name as a prop, it works as expected and sets the nameData data field so that I can change it within the component.
Parent
<child name="charles"></child>

Child
data() {
    return {
        nameData: this.name
    }
},
props: {
     name: {type: String, default: "NONE"}
}

When I bind the prop like below, the nameData data field is set to the default prop, which is "None".  Why is that?
Parent
data() {
   return {
      firstName: "Charles"
  }
}

<child :name="firstName"></child>

Child
data() {
    return {
        nameData: this.name
    }
},
props: {
     name: {type: String, default: "NONE"}
}

A: See my example

*

*First child component works as expected (your code)

*Second displays "NONE" because it's data is initialized with prop value, which is undefined  at the time the (child's) data() is executed. Any change to the prop in the future (in mounted in my example) wont affect child's data...

const child = Vue.component('child', {
  data() {
    return {
      nameData: this.name
    }
  },
  props: {
    name: {
      type: String,
      default: "NONE"
    }
  },
  template: `<div> {{ nameData }} </div>`
})

const vm = new Vue({
  el: "#app",
  components: {
    child
  },
  data() {
    return {
      firstName: "Charles",
      secondName: undefined
    }
  },
  mounted() {
    this.secondName = "Fred"
  }
})

  <child :name="firstName"></child>
  <child :name="secondName"></child>

A: name="charles" - you passed down the string "charles";
:name="firstName" - you passed down a variable "firstName" which seems to be undefined in the parent component at the time of child rendering and the prop in the child component gets the default value you provided it with.
UPD: I played a little with Michal's example. You can use computed instead of data() {} or directly a prop itself if you don't need any data transformation. Because it seems that you assign parent's firstName value in async mode or just later.

const child = Vue.component('child', {
  computed: {
      nameData() {
          return this.name;
      }
  },
  props: {
    name: {
      type: String,
      default: "NONE"
    }
  },
  template: `<div> {{ nameData }} </div>`
})

const vm = new Vue({
  el: "#app",
  components: {
    child
  },
  data() {
    return {
      firstName: "Charles",
      secondName: undefined
    }
  },
  mounted() {
    this.secondName = "Fred"
  }
})

  <child :name="firstName"></child>
  <child :name="secondName"></child>


Q: Android app security test failed! ... Saying, component is not Protected. An intent-filter exists There is security issue reported from our client about some of the Activity and BroadcastReceiver.
The security test result was talking about
(com.****.*****.Activity / BroadcastReceiver) is
not Protected.
An intent-filter exists.

Thing which is common is that all contains  intent-filter

Please suggest me what should I do?

A: You can set android:exported="false" for the activity in your manifest:

android:exported :
  This element sets whether the activity can be
  launched by components of other applications — "true" if it can be,
  and "false" if not. If "false", the activity can be launched only by
  components of the same application or applications with the same user
  ID. If you are using intent filters, you should not set this element
  "false". If you do so, and an app tries to call the activity, system
  throws an ActivityNotFoundException. Instead, you should prevent other
  apps from calling the activity by not setting intent filters for it.
If you do not have intent filters, the default value for this element
  is "false". If you set the element "true", the activity is accessible
  to any app that knows its exact class name, but does not resolve when
  the system tries to match an implicit intent.
This attribute is not the only way to limit an activity's exposure to
  other applications. You can also use a permission to limit the
  external entities that can invoke the activity (see the permission
  attribute).

<activity
        android:name=".activities.YourActivity"
        android:exported="false" />

You can do same for BroadcastReceiver.


Q: ADF pipeline going into queue state I have a Copy activity where the source and destination are both Blobs.
When i tried the copy pipeline previously,it ran successfully.
But currently it is going into queue state for a long time i.e. 30 minutes.

Can i know the reason behind it?

A: This is not an answer/solution to the problem. Since i cannot comment yet, had to put it in the Answer section. It could be delay in assigning the compute resources. Please check the details.
You can check the details by hovering mouse pointer between Name and Type beside Copy.


Q: Generating Random Number In Each Row In Oracle Query I want to select all rows of a table followed by a random number between 1 to 9:
select t.*, (select dbms_random.value(1,9) num from dual) as RandomNumber
from myTable t

But the random number is the same from row to row, only different from each run of the query. How do I make the number different from row to row in the same execution?

A: you don’t need a select … from dual, just write:
SELECT t.*, dbms_random.value(1,9) RandomNumber
  FROM myTable t

A: Something like?
select t.*, round(dbms_random.value() * 8) + 1 from foo t;

Edit:
David has pointed out this gives uneven distribution for 1 and 9.
As he points out, the following gives a better distribution:
select t.*, floor(dbms_random.value(1, 10)) from foo t;

A: If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:
SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL

A: At first I thought that this would work:
select DBMS_Random.Value(1,9) output
from   ...

However, this does not generate an even distribution of output values:
select output,
       count(*)
from   (
       select round(dbms_random.value(1,9)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   62423
2   125302
3   125038
4   125207
5   124892
6   124235
7   124832
8   125514
9   62557

The reasons are pretty obvious I think.
I'd suggest using something like:
floor(dbms_random.value(1,10))

Hence:
select output,
       count(*)
from   (
       select floor(dbms_random.value(1,10)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   111038
2   110912
3   111155
4   111125
5   111084
6   111328
7   110873
8   111532
9   110953


Q: "Possible multiple enumeration of IEnumerable" issue? I'm getting a Possible multiple enumeration of IEnumerable with Resharper and I'm trying to find out if it's really an issue or not. This is my method:
public IEnumerable<Contact> GetContacts(IContactManager contactManager, string query)
{
    IEnumerable<Contact> contacts = contactManager.GetContacts(query);
    if (contacts.Any()) return contacts; // Get the warning on this line
    // Do some other stuff
    return new[] {
        new Contact { Name = "Example" }
    }
}

Should be obvious, but I'm doing a search for Contact and if the search returns no results I'm returning an array of default values. The consumer should just receive a list which can be enumerated, not modified.
Where is the "multiple enumeration" here? And if there is indeed one, is this not the best type to use in the situation?

A: The multiple enumeration potential is you calling Any, which will cause the first enumeration, and then a potential second enumeration by the caller of that method.
In this instance, I'd guess it is mostly guaranteed that two enumerations will occur at least.
The warning exists because an IEnumerable can disguise something expensive such as a database call (most likely an IQueryable), and as IEnumerable doesn't have caching as part of it's contract, it will re-enumerate the source fresh. This can lead to performance issues later on (we have been stung by this a surprising amount and we don't even use IQueryable, ours was on domain model traversal).
That said, it is still only a warning, and if you are aware of the potential expense of calling an enumerable over potentially slow source multiple times then you can suppress it.
The standard answer to caching the results is ToList or ToArray.
Although I do remember making an IRepeatable version of IEnumerable once that internally cached as it went along. That was lost in the depths of my gratuitous code library :-)

A: Enumerable.Any executes the query to check whether or not the sequnce contains elements. You could use DefaultIfEmpty to provide a different default value if there are no elements:
public IEnumerable<Contact> GetContacts(IContactManager contactManager, string query)
{
    IEnumerable<Contact> contacts = contactManager.GetContacts(query)
        .DefaultIfEmpty(new Contact { Name = "Example" });
    return contacts;
}

Note that this overload is not supported in LINQ-To-SQL.


Q: Filtering with two conditions - Remove duplicates less than a certain value while keeping the original I have a table

total
type

23
Original

3
Duplicate

11
Duplicate

5
Original

16
Duplicate

4
Duplicate

I want to Filter the df['total'] column for only values greater than 10, however, I want to remove only the Duplicates less or equal than 10. So if an Original row is less than 10 it can still be in the df.
This is my Desirable output:

total
type

23
Original

11
Duplicate

5
Original

16
Duplicate

I tried this:
df[(df['total'] > 10) & df['type'] == "Duplicate"]

is not working.
Any idea?

A: The conditions should be enclosed in parentheses, on the right you have square ones. And to get what you showed. You need to add a condition(df['type'] =="Original"), in my opinion.
a = df[(df['total'] > 10) & (df['type'] == "Duplicate")|(df['type'] == "Original")]
print(a)

Output a
   total       type
0     23   Original
2     11  Duplicate
3      5   Original
4     16  Duplicate


Q: Firebase do not return ascending order as expected by using orderByKey I have some data which stored on Firebase by using timestamp as its key value,
but I cannot get all of them by sorting it with orderByKey as expected: returning value do not back in ascending order.
My JSON structure looks like:
{
  "1476986154" : {
    "Cons" : {
      "Black" : 91.531099,
      "Cancel" : 98.832554,
      "Happy" : 97.104925,
      "Pair" : 95.515542
    },
    "Fairy" : {
      "Apple" : {
        "Chair" : {
          "Area" : 1,
          "Count" : 96,
          "Teen" : 0.162139,
          "Score" : 95.16093
        },
        "Fake" : {
          "Area" : 3,
          "Count" : 98,
          "Teen" : 0.683259,
          "Score" : 98.249105
        }
      },
      "Dark" : {
        "Lake" : {
          "Read" : {
            "Height" : 0,
            "Width" : 0,
            "X" : 0,
            "Y" : 0
          }
        },
        "Red" : {
          "Read" : {
            "Height" : 0,
            "Width" : 0,
            "X" : 0,
            "Y" : 0
          }
        }
      }
    },
    "PhotoName" : "oo",
    "Versions" : {
      "Library" : "5.5.6.6"
    }
  },
  "1477280739" : {
    "Cons" : {
      "Black" : 96.389055,
      "Cancel" : 98.265668,
      "Happy" : 93.661556,
      "Pair" : 91.361142
    },
    "Fairy" : {
      "Apple" : {
        "Chair" : {
          "Area" : 1,
          "Count" : 100,
          "Teen" : 0.171286,
          "Score" : 90.849593
        },
        "Fake" : {
          "Area" : 3,
          "Count" : 99,
          "Teen" : 0.200965,
          "Score" : 92.367154
        }
      },
      "Dark" : {
        "Lake" : {
          "Read" : {
            "Height" : 0,
            "Width" : 0,
            "X" : 0,
            "Y" : 0
          }
        },
        "Red" : {
          "Read" : {
            "Height" : 0,
            "Width" : 0,
            "X" : 0,
            "Y" : 0
          }
        }
      },
    },
    "Name" : "pp",
    "Versions" : {
      "Library" : "5.5.6.6"
    }
  }
}

It returns me the largest one first(1490034200), then from smallest to second-largest value(from 1476510510 to 1488805137).
Which confused me since I need to know if the callback is going to the last now.
Code is here: I just query for last data before query for all data with same ValueEventListener:
DatabaseReference.orderByKey().limitToLast(recordQty).addValueEventListener(valueEventListener);
//...
DatabaseReference.orderByKey().addValueEventListener(valueEventListener);

Can anyone understand why this attempt not work?

Here's how my listener looks:
private class ValueEventOnChangeListener implements ValueEventListener {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (mDataArrayList == null) {
                mDataArrayList = new ArrayList<>();
            } else {
                mDataArrayList.clear();
            }

            getDataChange(dataSnapshot);

            if (mListener != null) {
                mListener.success(mDataArrayList);
            }
        }

        private void getDataChange(DataSnapshot dataSnapshot){
            try {
                if (mSubDataType == null){
                    for (DataSnapshot data : dataSnapshot.getChildren()){
                        long timestamp = Long.parseLong(data.getKey());
                        mDataArrayList.add(timestamp);
                    }
                }
            }
            catch (Exception e){
                Log.e(TAG, "onDataChange Exception: " + e.toString());
            }
        }
}

A: I can't reproduce the problem.
If I run this snippet of code:
myRef.orderByKey().addValueEventListener(new ValueEventListener() {

    public ArrayList<Long> mDataArrayList;

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (mDataArrayList == null) {
            mDataArrayList = new ArrayList<>();
        } else {
            mDataArrayList.clear();
        }

        getDataChange(dataSnapshot);

        System.out.println(mDataArrayList);

    }

    private void getDataChange(DataSnapshot dataSnapshot){
        try {
            for (DataSnapshot data : dataSnapshot.getChildren()){
                long timestamp = Long.parseLong(data.getKey());
                mDataArrayList.add(timestamp);
            }
        }
        catch (Exception e){
            System.err.println("onDataChange Exception: " + e.toString());
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});

With this JSON:
{ "1476986154" : true, "1477280739" : true }

It prints:
[1476986154, 1477280739]

Which seems the correct order to me since 1476986154 < 1477280739.


Q: cancancan manage a relationship Rails I am running into an issue with the cancancan gem for rails
gem 'cancancan', '~> 1.10'

I have four models: User, Company, Locations, Groups
User: Belongs to Company
Company: Has many Locations
Location: Belongs to company
Group: Belongs to Location
In the abilities model I have this:
can :manage, Group, :location => {:id => user.company.locations.map{|l| l.id}}

When creating a new group I am denied (don't have access)
I am looking for the correct way to allow a User to create a group with one of the companies location id's (NOTE: Without cancancan on this all works and all ID's are related and so on).

A: To make sure I'm understanding your question completely...
You're looking for a way to limit a User's ability to manage Groups based on the locations of the Company that User belongs to?
Assuming I've got that correct, I would recommend using #pluck:
can :manage, Group, location_id: user.company.locations.pluck(:id)

This collects all the :id's on a User's Company's Locations, and ensures a User can only manage Groups that have a :location_id contained within that collection.
Functionally, this is identical to what you've done, but is more efficient in two ways:

*

*It doesn't involve any unnecessary Ruby logic

*Using #pluck only queries the :id on a location, as opposed to the entire location and all its attributes
Generally speaking, whenever you're accessing your database in Rails, you're better off doing so entirely with ActiveRecord methods. This will help prevent you from wasting time querying for extra information you don't need, and eliminate the extra overhead of using Ruby to re-structure your data.
Hope that helps!


Q: Celery receives periodic tasks but doesn't execute them I use celery to run periodic tasks in my Django DRF app. Unfortunately, registered tasks are not executed.
Project structure:
project_name
___ cron_tasks
______ __init__.py
______ celery.py

celery.py:
app = Celery('cron_tasks', include=['cron_tasks.celery'])
app.conf.broker_url = settings.RABBITMQ_URL
app.autodiscover_tasks()
app.conf.redbeat_redis_url = settings.REDBEAT_REDIS_URL
app.conf.broker_pool_limit = 1
app.conf.broker_heartbeat = None
app.conf.broker_connection_timeout = 30
app.conf.worker_prefetch_multiplier = 1

app.conf.beat_schedule = {
    'first_warning_overdue': {
        'task': 'cron_tasks.celery.test_task',
        'schedule': 60.0, # seconds
        'options': {'queue': 'default', 'expires': 43100.0}
    }
}

@shared_task
def test_task():
    app.send_task('cron_tasks.celery.test_action')

def test_action():
    print('action!') # print is not executed

    # I also tried to change the data, but it never happens too.
    from django.contrib.auth import get_user_model
    u = get_user_model().objects.get(id=1)
    u.first_name = "testttt"
    u.save()

setting.py:
RABBITMQ_URL = os.environ.get('RABBITMQ_URL')
REDBEAT_REDIS_URL = os.environ.get('REDBEAT_REDIS_URL')
CELERY_BROKER_URL = os.environ.get('RABBITMQ_URL')
CELERYD_TASK_SOFT_TIME_LIMIT = 60
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_RESULT_BACKEND = os.environ.get('REDBEAT_REDIS_URL')
CELERY_IMPORTS = ("cron_tasks.celery", )

from kombu import Queue
CELERY_DEFAULT_QUEUE = 'default'
CELERY_QUEUES = (
    Queue('default'),
)
CELERY_CREATE_MISSING_QUEUES = True
redbeat_redis_url = REDBEAT_REDIS_URL

Rabbitmq is running properly. I can see it's there in the celery worker terminal output:
- ** ---------- .> transport:   amqp://admin:**@localhost:5672/my_vhost

Redis is pinging well. I use redis to send beats.
I run:
celery beat -S redbeat.RedBeatScheduler -A cron_tasks.celery:app  --loglevel=debug

It shows:
[2019-02-15 09:32:44,477: DEBUG/MainProcess] beat: Waking up in 10.00 seconds.
[2019-02-15 09:32:54,480: DEBUG/MainProcess] beat: Extending lock...
[2019-02-15 09:32:54,481: DEBUG/MainProcess] Selecting tasks
[2019-02-15 09:32:54,482: INFO/MainProcess] Loading 1 tasks
[2019-02-15 09:32:54,483: INFO/MainProcess] Scheduler: Sending due task first_warning_overdue (cron_tasks.celery.test_task)
[2019-02-15 09:32:54,484: DEBUG/MainProcess] cron_tasks.celery.test_task sent. id->f89083aa-11dc-41fc-9ebe-541840951f8f

Celery worker is run this way:
celery worker -Q default -A cron_tasks.celery:app -n .%%h --without-gossip --without-mingle --without-heartbeat --loglevel=info  --max-memory-per-child=512000

It says:
-------------- celery@.%me.local v4.2.1 (windowlicker)
---- **** -----
--- * ***  * -- Darwin-16.7.0-x86_64-i386-64bit 2019-02-15 09:31:50
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app:         cron_tasks:0x10e2a5ac8
- ** ---------- .> transport:   amqp://admin:**@localhost:5672/my_vhost
- ** ---------- .> results:     disabled://
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> default          exchange=default(direct) key=default

[tasks]
  . cron_tasks.celery.test_task

[2019-02-15 09:31:50,833: INFO/MainProcess] Connected to amqp://admin:**@127.0.0.1:5672/my_vhost
[2019-02-15 09:31:50,867: INFO/MainProcess] celery@.%me.local ready.
[2019-02-15 09:41:46,218: INFO/MainProcess] Received task: cron_tasks.celery.test_task[3c121f04-af3b-4cbe-826b-a32da6cc156e]   expires:[2019-02-15 21:40:05.779231+00:00]
[2019-02-15 09:41:46,220: INFO/ForkPoolWorker-2] Task cron_tasks.celery.test_task[3c121f04-af3b-4cbe-826b-a32da6cc156e] succeeded in 0.001324941000000024s: None

Expected behavior:
This should run my test_action().
But, even though the celery worker output says succeeded in 0.001324941000000024s, the function never executes.


Q: strange behavior when using list of another class objects as class attribute in python I am having some issues with the classes below:
class book:
    def __init__(self,name=None):
        self.name=name
        return

class bookshelf:
    def __init__(self,books=[]):
        self.books=books
        return
    def add_book(self,name):
        self.books.append(
            book(name)
        )
        return

Next, I initialize list a list of bookshelves:
bookshelves = [bookshelf() for i in range(3)]

With all of them empty, both bookshelfs[0].books and bookshelfs[1].books are [].
However, after adding a book to the first bookshelf,
bookshelves[0].add_book('Book1')

all books have a book named "Book1": both bookshelves[0].books[0].name and bookshelves[1].books[0].name have the value 'Book1'.
This does not change even after I reinitialize the list of bookshelf. But if I rerun the section defining the classes, the bookshelfs will be cleared.
Any ideas how does this happen? How should I implement this part correctly? By the way, I am running Python 3.8.3 .

A: Python Mutable Default Arguments are counter-intuitive!
Python creates the list once when the method is defined not when it is called. Therefore the list obj is shared between instances. Here's A good article on the issue.
I would instead remove the default argument and check/set it in the init method.
class bookshelf:
    def __init__(self,books):
        self.books = []
        if books:
            self.books = books


Q: Is there any good tool/framework to profile performance for C/C++ application I'm new to C/C++ and facing a performance issue that my program is running very slow. I want to find what's the hot spot is to reduce the overall execution time for my code.
What's the most popular and the easiest way to profile a  C/C++ application in Windows?
I've been very amazed by how easy it is to profile a .NET application using Mini Proler. Do we have any similiar library in C/C++ that gives us that high quality and reliable of result with a minimal added code?
Or is there any tool that is similiar to RedGate ANTS performance profiler  that also provider insightful information about the running code?

A: Intel's VTune or AMD's CodeAnalyst are both very good tools. On Linux, Perf or OProfile will do the same thing.

A: While you are hunting around for a profiler, run the program in the debugger IDE and try this method.
Some programmers rely on it. There's an example here of how it is used.
In that example here's what happens. A series of problems are found and removed.

*

*The first iteration saved 33% of the time. (Speedup factor 1.5)

*Of the time remaining, the second iteration saved 17%. (Speedup factor 1.2)

*Of the time remaining, the third iteration saved 13%. (Speedup factor 1.15)

*Of the time remaining, the fourth iteration saved 66%. (Speedup factor 2.95)

*Of the time remaining, the fifth iteration saved 61%. (Speedup factor 2.59)

*Of the time remaining, the sixth iteration saved 98%. (Speedup factor 45.9)
All those big-percent changes were not big percents of the original time, but they became so after other problems were removed.
The total amount of time saved from the original program was over 99.8%.
The speedup was 730 times.
Most programs that have not gone through a process like this have lots of room for speedup, but you're not likely to realize it using only a profiler because all they do is make measurements. They don't always point out to you what you need to fix, and each problem you miss keeps you from getting the really significant speedup.
To put it another way, the final speedup factor is the product of all those individual factors, and if any one of them is missed, it is not only absent from the product, but it reduces the following factors.
That's why, in performance diagnosis, "good enough" is not good enough.
You have to find every problem.


Q: Selenium Unable to select a date from date picker unable to select a date from date picker
this is the website working on https://www.phptravels.net/
when i used developer options and Ctrl + F on firebug
//div[@style='display: block; top: 390px; left: 680px;']//text()[contains(.,'15')]
i am able to find the date on the page
but when i am trying from the code i am unable to select the element
This is my code
self.driver.find_element(By.XPATH, "//div[@style='display: block; top: 390px; left: 680px;']//text()[contains(.,'"+start_date+"')]").click()

test_Flight.py:37:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\pages\search_flights_form.py:68: in set_start_date_pick
    self.driver.find_element(By.XPATH, "//div[@style='display: block; top: 390px; left: 680px;']//text()[contains(.,'15')]").click()
..\..\..\..\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py:976: in find_element
    return self.execute(Command.FIND_ELEMENT, {
..\..\..\..\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py:321: in execute
    self.error_handler.check_response(response)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x052D6D18>
response = {'status': 404, 'value': '{"value":{"error":"no such element","message":"Unable to locate element: //div[@style=\'disp...ntent/shared/webdriver/Errors.jsm:395:5\\nelement.find/</<@chrome://remote/content/marionette/element.js:300:16\\n"}}'}

A: Try like below and confirm.
driver.get("https://www.phptravels.net/")

wait = WebDriverWait(driver,30)

checkin = wait.until(EC.element_to_be_clickable((By.ID,"checkin")))
checkin.click()

date = 15
select_date = wait.until(EC.element_to_be_clickable((By.XPATH,f"//div[@class='datepicker-days']//td[text()='{date}']")))
select_date.click()

Update: As per comments to select date from Flights section.
driver.get("https://www.phptravels.net/")

wait = WebDriverWait(driver,30)

flights = wait.until(EC.element_to_be_clickable((By.XPATH,"//button[@aria-controls='flights']")))
flights.click()

departure_date = wait.until(EC.element_to_be_clickable((By.XPATH,"//input[contains(@class,'depart')]")))
departure_date.click()

date = 15
select_date = wait.until(EC.element_to_be_clickable((By.XPATH,f"(//div[@class='datepicker-days'])[3]/table/tbody/tr[3]/td[text()='{date}']")))
select_date.click()


Q: PHP-FPM (7.4.2) doesn't stop gracefully? During updating, we want to stop php-fpm and wait for all running scripts to be finished before we make any file changes.
We found out that we needed to set process_control_timeout, so we placed "process_control_timeout = 36000s" in "/etc/php/7.4/fpm/pool.d/zz-00-overrides.ini" (and we restarted php-fpm).
Then we created a test script to test it out. Our test script creates a file, then 30 seconds later, it creates another file. The script:
$id = random_int(10000, 99999);
file_put_contents(__DIR__ . '/' . $id . '-start', '');
sleep(30);
file_put_contents(__DIR__ . '/' . $id . '-end', '');

When we run the script normally (browser -> nginx -> php-fpm), it creates the 1st file, 30 seconds later it creates the 2nd file.
When we run the script, wait a few seconds, and then try to stop it (run the same way as before: browser -> nginx -> php-fpm) (stopped by: "service php7.4-fpm stop"), it will create the 1st file, then the service stop command is run which only takes 2-3 seconds, then the browser says "502 Bad Gateway", and then the 2nd file is never created.
It doesn't gracefully stop. The desired outcome for us is that "service php7.4-fpm stop" waits for all the scripts to be done, and then stops, instead of it killing off any running scripts the way it is doing now in order to forcefully stop.
Are we missing something, are we doing something wrong? Is it a bug somewhere somehow? Any help would be really appreciated.

*

*Debian 10 (Linux 4.19.0-6-cloud-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64 GNU/Linux)

*PHP 7.4.2

*Nginx 1.14.2

A: Running kill -QUIT $(cat /run/php/php7.4-fpm.pid) does take the process_control_timeout config in account. It will cause the PHP-FPM process to stop as soon as all the scripts have finished their execution. At that point the PID will be removed. So, in order to make it work:

*

*run $(kill -QUIT $(cat /run/php/php7.4-fpm.pid))

*in a loop, check if /run/php/php7.4-fpm.pid still exists, if not, break the loop.


Q: Can one cast an EnvDTE.Project into a VCProject I have seen two posts so far that concern my question. I am wondering how can one cast an EnvDTE.Project into a VCProject.
In this post, fun4jimmy's answer does that exactly in the following line of code (taken from his answer) :

VCProject vcProject = project.Object as VCProject;

I have tried doing the same thing in my solution :
using EnvDTE;
using Microsoft.VisualStudio.VCProjectEngine;
[...]
private List<string> BuildAssembliesAndReturnTheirName(EnvDTE80.DTE2 dte)
{
    Solution sln = dte.Solution;

    bool isDirty = false;
    foreach (Project project in sln.Projects)
    {
        VCProject vcProject = project.Object as VCProject;
        Configuration activeConfiguration = project.ConfigurationManager.ActiveConfiguration;
        foreach (VCConfiguration vcConfiguration in vcProject.Configurations)
        {
            //business logic
        }
    }
[...]

A solution is opened in VS. The solution contains a few C# projects. Everything seems to be in order for this code to execute until I reach
foreach (VCConfiguration vcConfiguration in vcProject.Configurations)

only to realise that this cast
VCProject vcProject = project.Object as VCProject;

returns null.
Can anyone tell me why that is? I've seen this post in which hveiras suggests

There is a VCCodeModel.dll for each VS version.

If that's the case for VCProjectEngine.dll as well, how can I fix my issue?
I have changed my reference to VCProjectEngine.dll so that it uses the one for Visual Studio 2012 (what I'm working with) but vcProject remains null.

A: VCProject is for C++ projects, in order to use a similar interface with C#/VB project you'll have to use VSProject.
There are a number of VSLangProj overloads/extensions and you'll have to find the one that is specific to the version you need to use. See: https://msdn.microsoft.com/en-us/library/1xt0ezx9.aspx for all the VSLangProj interfaces from 2 through 100 (I think thats Version 2 through Version 10).

A: You can't cast the Project object itself, because there's no inheritance relationship.
But you can use the inner object:
VCProject vcProject = project.Object as VCProject;


Q: Is it possible to retrieve a Javascript file from a server? In Python, I can retrieve Javascript from an HTML document using the following code.
import urllib2, jsbeautifier
from bs4 import BeautifulSoup

f = urllib2.urlopen("http://www.google.com.ph/")

soup = BeautifulSoup(f, "lxml")
script_raw = str(soup.script)

script_pretty = jsbeautifier.beautify(script_raw)
print(script_pretty)

But how about if the script comes from a Javascript file on the server, like:
<script src="some/directory/example.js" type="text/javascript">

Is it possible to retrieve "example.js"? If so, how?
Context: I'm examining the Javascript of phishing web pages.

A: <script src="some/directory/example.js" type="text/javascript">

the code above will get some/directory/example.js from server
you just make folders and file structure follow the pattern above

A: The easiest way is to right click on that page in your browser, choose page script, click on that .js link, and it will be there.

A: If you want to load at run time, like some part of your javascript is dependent on other javascript, then for loading javascript at run time, you can use require.js .


Q: Switching Permissions of User Files I am new to Bash and trying to write a find command that finds all files that don't have read, write, or execute permissions for the user, and then changes the mode to enable read access.
I've tried a few different ways including:
find . ! -perm /u+rwx | -exec chmod u+r {} \;
Am I on the right track?


Q: how to get the file sent in xml response in perl? Using the LWP user agent I am sending the request and getting the response.
I will get the response in html format and a file attached in it.
eg:
     `

      <title>Download Files</title>
      <meta http-equiv=\'Content-Type\' content=\'text/html; charset=utf-8\'>
      <link rel=\'stylesheet\' href=\'http://res.mytoday.com/css/main.css\' type=\'text/css\'>
      <link rel=\'stylesheet\' href=\'http://res.mytoday.com/css/Menu.css\' type=\'text/css\'>
      <link rel=\'stylesheet\' href=\'/statsdoc/freeze.css\' type=\'text/css\'>

      No.
      File Name
      File Size

      1
      1-1.csv.zip
     	487 bytes

     Download all
    `

From this response I need to get the file. Can anyone help me to get the file from response.

A: Use a parser to extract the information. I used XML::LibXML, but I had to remove the closing br tags that made the parser fail.
#!/usr/bin/perl
use warnings;
use strict;

my $html = '

      <title>Download Files</title>
      <meta http-equiv=\'Content-Type\' content=\'text/html; charset=utf-8\'>
      <link rel=\'stylesheet\' href=\'http://res.mytoday.com/css/main.css\' type=\'text/css\'>
      <link rel=\'stylesheet\' href=\'http://res.mytoday.com/css/Menu.css\' type=\'text/css\'>
      <link rel=\'stylesheet\' href=\'/statsdoc/freeze.css\' type=\'text/css\'>

      No.
      File Name
      File Size

      1
      1-1.csv.zip
     	487 bytes

     Download all
    ';

use XML::LibXML;
my $dom = 'XML::LibXML'->load_html( string => $html );
print $dom->findvalue('/html/body/table/tr[2]/td[2]/a/@href');

You could also use the recover flag to parse invalid HTML:
my $dom = 'XML::LibXML'->load_html( string => $html, recover => 1 );


Q: Failed to use Apache RewriteRule I would like to use Apache RewriteRule to change the URL target page to abc.php. I have set RewriteEngine On but I found this problem.
Regexp I used:
RewriteRule ^viewthread\.php.tid=12345$ abc.php

The URL string to match:
viewthread.php?tid=12345

Why it is not successfully matched?

A: Rewriting URLs with query strings is slightly more complicated than rewriting plain URLs. You'll have to write something like this:
RewriteCond %{REQUEST_URI}  ^/viewthread\.php$
RewriteCond %{QUERY_STRING} ^tid=12345$
RewriteRule ^(.*)$ http://mydomain.site/abc.php [R=302,L]

See those articles for more help:

*

*http://www.simonecarletti.com/blog/2009/01/apache-query-string-redirects/

*http://www.simonecarletti.com/blog/2009/01/apache-rewriterule-and-query-string/

A: i think because you have missed the ? in the rule...
RewriteRule ^viewthread.php?tid=12345$ abc.php

A: Shouldn't it be:
RewriteRule ^/viewthread\.php\?tid=12345$ /abc.php


Q: unable to create sqlite database in Android i have class CreateDB
public class CreateDB extends SQLiteOpenHelper{   // SQLiteOpenHelper auto create if db not exists.

    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "mydb.db";

    public CreateDB(Context ctx) {
        super(ctx, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE friends (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phonenumber INTEGER);");
    }}

i call createdb in another class which act as background thread
public class manager extends AsyncTask<Void, Void, String> {

 public  Context context;

    @Override
    protected String doInBackground(Void... params) {

        CreateDB dbhelp = new CreateDB(context);
}

}
when i run it then it stop working and emulator give error that app stop responding
but when i run `CreateDB dbhelp = new CreateDB(this);   in main activity then it works and database is created .  so please help so that i can create database in background thread .

A:
but when i run CreateDB dbhelp = new CreateDB(this); in main
  activity then it works and database is created

Because you forgot to initialize your context object in your AsyncTask.
public class manager extends AsyncTask<Void, Void, String> {

 public  Context context; <-- Declared but not initialized

    @Override
    protected String doInBackground(Void... params) {

        CreateDB dbhelp = new CreateDB(context);
}

You could create a constructor for your AsyncTask :
public manager(Context context) {
   this.context = context;
}

And then in your activity :
new manager(this).execute();

Also try to respect name conventions.

A: You need to pass valid context as a parameter:
CreateDB dbhelp = new CreateDB(getContext());


Q: Dispatch all methods in class C# Is there any way to dispatch all methods in class in easy way?
For example my class is a adapter for UI items and contains static methods.
So instead of dispatching all methods separately in class, it could be done like this: Who ever is calling a method from this class, everything is dispatched through UI thread.
Like from:
public MyClass
{
   ...

   public static void Method1
   {
      Application.Current.Dispatcher.Invoke(() =>
      {
          /* do something */
      }
   }

   public static bool Method2
   {
      return Application.Current.Dispatcher.Invoke(() =>
      {
          return UIitem.SomeProperty;
      }
   }
}

To this:
[DispatcherAttribute] /* or something similar */
public MyClass
{
   ...

   public static void Method1
   {
      /* do something */
   }

   public static bool Method2
   {
      return UIitem.SomeProperty;
   }
}


Q: AppLocalizations missing reference - Internationalization - Flutter flutter_gen applocalizations missing reference in Visual Studio Code.

I already tried

*

*flutter upgrade

*flutter pub cache clean

*flutter clean / flutter pub get

*Dart: Restart Analysis Server (VS Code)

*Developer: Reload Window (VS Code)

My pubspec.yaml has

*

*generate: true

*flutter_localizations:sdk: flutter

A: Solution:

*

*My machine was with 2 flutter sdk installed. I unnistalled one, and everything worked again.


Q: how to use actors in akka client side websockets i am using akka client websockets https://doc.akka.io/docs/akka-http/current/client-side/websocket-support.html
i have a server which takes requests and respond in json
this is the pattern of my request and response
request #1

{
        "janus" : "create",
        "transaction" : "<random alphanumeric string>"
}
response #1
{
   "janus": "success",
   "session_id": 2630959283560140,
   "transaction": "asqeasd4as3d4asdasddas",
   "data": {
        "id": 4574061985075210
   }
}

then based on response #1 i need to initiate request #2 and upon receiving response #2 i need to initiate request #3 and so on
for example
then based on id 4574061985075210 i will send request #2 and receive it response
request # 2 {
 }

response # 2 {
}
----

how can i use the actors with source and sink and re use the flow
here is my initial code
import akka.http.scaladsl.model.ws._

import scala.concurrent.Future

object WebSocketClientFlow {
  def main(args: Array[String]) = {
    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()
    import system.dispatcher

    val incoming: Sink[Message, Future[Done]] =
      Sink.foreach[Message] {
        case message: TextMessage.Strict =>
          println(message.text)
//suppose here based on the server response i need to send another message to the server and so on do i need to repeat this same code here again ?????

      }

    val outgoing = Source.single(TextMessage("hello world!"))

    val webSocketFlow = Http().webSocketClientFlow(WebSocketRequest("ws://echo.websocket.org"))

    val (upgradeResponse, closed) =
      outgoing
        .viaMat(webSocketFlow)(Keep.right) // keep the materialized Future[WebSocketUpgradeResponse]
        .toMat(incoming)(Keep.both) // also keep the Future[Done]
        .run()

    val connected = upgradeResponse.flatMap { upgrade =>
      if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
        Future.successful(Done)
      } else {
        throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
      }
    }
connected.onComplete(println)
    closed.foreach(_ => println("closed"))
  }
}

and here i used Source.ActorRef
   val url = "ws://0.0.0.0:8188"
    val req = WebSocketRequest(url, Nil, Option("janus-protocol"))

    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()

    import system.dispatcher

    val webSocketFlow = Http().webSocketClientFlow(req)

    val messageSource: Source[Message, ActorRef] =
      Source.actorRef[TextMessage.Strict](bufferSize = 10, OverflowStrategy.fail)

    val messageSink: Sink[Message, NotUsed] =
      Flow[Message]
        .map(message => println(s"Received text message: [$message]"))
        .to(Sink.ignore)

    val ((ws, upgradeResponse), closed) =
      messageSource
        .viaMat(webSocketFlow)(Keep.both)
        .toMat(messageSink)(Keep.both)
        .run()

    val connected = upgradeResponse.flatMap { upgrade =>
      if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
        Future.successful(Done)
      } else {
        throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
      }
    }

    val source =
      """{ "janus": "create", "transaction":"d1403sa54a5s3d4as3das"}"""
    val jsonAst = source.parseJson

    ws ! TextMessage.Strict(jsonAst.toString())

now i need help in
how can i initiate the second request here because i need the "id" returned from the server to initiate request #2


Q: C# Property Grid Pass Constructor Variable I'm using the C# property grid to add new objects and change settings of a specific object.  I need to know how to pass a a variable to the constructor using the Component Model.  Reason why is because a parameter is required to correctly define the initial values of the chart object.
List<Chart> charts = new List<Chart>();
[Description("Charts")]
[Category("4. Collection Charts")]
[DisplayName("Charts")]
public List<Chart> _charts
{
    get { return charts; }
    set { charts = value ; }
}

public class Chart
{
    public static string collectionName = "";

     int chartPosition = GetMaxChartIndex(collectionName);
     [Description("Chart posiion in document")]
     [Category("Control Chart Settings")]
     [DisplayName("Chart Position")]
     public int _chartPosition
     {
         get { return chartPosition; }
         set { chartPosition = value; }
     }

    public Chart(string _collectionName)
    {
        collectionName = _collectionName;

    }
}

A: What you can do is declare a custom TypeDescriptionProvider for the Chart type, early before you select your object into the PropertyGrid:
...
TypeDescriptor.AddProvider(new ChartDescriptionProvider(), typeof(Chart));
...

And here is the custom provider (you'll need to implement the CreateInstance method):
public class ChartDescriptionProvider : TypeDescriptionProvider
{
    private static TypeDescriptionProvider _baseProvider = TypeDescriptor.GetProvider(typeof(Chart));

    public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args)
    {
        // TODO: implement this
        return new Chart(...);
    }

    public override IDictionary GetCache(object instance)
    {
        return _baseProvider.GetCache(instance);
    }

    public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance)
    {
        return _baseProvider.GetExtendedTypeDescriptor(instance);
    }

    public override string GetFullComponentName(object component)
    {
        return _baseProvider.GetFullComponentName(component);
    }

    public override Type GetReflectionType(Type objectType, object instance)
    {
        return _baseProvider.GetReflectionType(objectType, instance);
    }

    public override Type GetRuntimeType(Type reflectionType)
    {
        return _baseProvider.GetRuntimeType(reflectionType);
    }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
    {
        return _baseProvider.GetTypeDescriptor(objectType, instance);
    }

    public override bool IsSupportedType(Type type)
    {
        return _baseProvider.IsSupportedType(type);
    }
}


Q: HTML- HREF Tag inside a Button This is my button code, which has a reference tag, and the URL takes me to an index action correctly
<button type="submit" class="btn btn-primary"><a style="color:white" href="<?php echo $this->basePath('calendar/details/index').'?month='.$this->previousMonth?>"> Previous </button>

and this is the picture of the button

The problem is that only the text Previous on button is clickable, other than that any click on the blue part of the button does not work. How to make the whole area of the button work, without disturbing the URL?

A:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
Previous

<a class="btn btn-primary" style="color: white" href="<?php echo $this->basePath('calendar/details/index').'?month='.$this->previousMonth?>">Previous


Q: How do I override a plugin registration in MVVMCross I'm using the WPF Sqlite plugin in MVVMCross, but I want to override the directory that the database is written to. I've written a custom ISQLiteConnectionFactory which currently resides in my WPF bootstrapper project:
internal class CustomMvxWpfSqLiteConnectionFactory : ISQLiteConnectionFactory
{
    const string DirectoryName = "ProductName";

    public ISQLiteConnection Create(string address)
    {
        var appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        var dir = Path.Combine(appData, DirectoryName);
        Directory.CreateDirectory(dir);

        var path = Path.Combine(dir, address);
        return new SQLiteConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, false);
    }
}

What I can't figure out is how to override the Mvx.RegisterSingleton<ISQLiteConnectionFactory>(new MvxWpfSqLiteConnectionFactory()); that Cirrious.MvvmCross.Plugins.Sqlite.Wpf.Plugin does.
My PCL project's App registers a singleton service that depends on ISQLiteConnectionFactory during Initialize, so I obviously want to override the IOC registration before then. But no matter what I do, the plugin's registration of MvxWpfSqLiteConnectionFactory rather than my own registration of CustomMvxWpfSqLiteConnectionFactory seems to take precedence.
I've tried putting my register call in all sorts of overrides in my WPF Setup.cs, but nothing has worked so far.

A: An article on how plugins are loaded is included in https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#how-plugins-are-loaded
The Sqlite plugin by default is initialised during PerformBootstrapActions in Setup - see https://github.com/MvvmCross/MvvmCross/wiki/Customising-using-App-and-Setup#setupcs for where this occurs in the start sequence.
From your question, it's not clear which overrides in Setup you've tried - I'm not sure which positions "all sorts" includes. However, it sounds like want to register your ISQLiteConnectionFactory at any point after PerformBootstrapActions and before InitializeApp - so one way to do this would be to override InitializeApp:
protected virtual void InitializeApp(IMvxPluginManager pluginManager)
{
    // your code here
     base.InitializeApp(pluginManager);
}

Some possible other ideas to consider:

*

*if you want to prevent the Sqlite plugin from self-initializing in the Wpf case, then you could remove the Sqlite bootstrap file from your Wpf project (but beware that nuget might try to add it again later)

*the new "community fork" of the MvvmCross sqlite project has source code updated to the latest SQLite-net version (via @jarroda) and has a BasePath CreateEx option to allow the folder to be specified - see https://github.com/MvvmCross/MvvmCross-SQLite/blob/master/Sqlite/Cirrious.MvvmCross.Community.Plugins.Sqlite.Wpf/MvxWpfSqLiteConnectionFactory.cs#L24


Q: How to set select all data up to data_upload_max_number_fields (example 500) in django admin listing page First of all sorry if is there any question already please let me know that because I am fresh in this community
And thanks in advance for your valuable responses
In the below screenshot in Django admin, How can I override the select all 1005 with some custom number like select up to 500. As you know data_upload_max_number_fields has only a 1000 limit but I don't want to increase the limit every time. Because it might be possible I have 100000 data then how much will increase the
data_upload_max_number_fields in django settings.
So is there any way that I can override this select all thing to less than the upload max field
for example select all up to first 500 data

I don't want like the default one shown in the 2nd image

A: Well, there does not seem to be a direct attribute/method to change the max limit but what you can do is set a custom value in the 'list_per_page' attribute of the ModelAdmin class admin.py like below:
class MyAppAdmin(admin.ModelAdmin):

    list_per_page = 500

    class Meta:
        model = MyApp

The default value of list_per_page is 100 hence now after modifying it you can directly select all 500(in your case) at once per page and perform the requisite operation.


Q: Unable to Update Global State for Redux Flow in SwiftUI I am trying to implement the Redux state in SwiftUI and I am stuck with updating the global state after the action creator has been executed. I am lost as what to do in the Store dispatch function.
// Store.swift

typealias ActionCreator = (_ dispatch: @escaping (Action) -> ()) -> ()

func getMovies() -> ActionCreator {
    return { dispatch in

        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            dispatch(.populateMovies([Movie(title: "ABC")]))
        }

    }
}

class Store: ObservableObject {

    var reducer: Reducer
    @Published private (set) var appState: AppState

    init(appState: AppState, reducer: Reducer) {
        self.appState = appState
        self.reducer = reducer
    }

    func dispatch(_ dispatch: ActionCreator) {
        // how to send the movies to the reducer to update the state
        //self.reducer.update(&appState, dispatch)
    }
}

// ContentView:

store.dispatch(getMovies())


Q: Speed of "sum" comprehension in Python I was under the impression that using a sum construction was much faster than running a for loop.  However, in the following code, the for loop actually runs faster:
import time

Score = [[3,4,5,6,7,8] for i in range(40)]

a=[0,1,2,3,4,5,4,5,2,1,3,0,5,1,0,3,4,2,2,4,4,5,1,2,5,4,3,2,0,1,1,0,2,0,0,0,1,3,2,1]

def ver1():
    for i in range(100000):
        total = 0
        for j in range(40):
            total+=Score[j][a[j]]
    print (total)

def ver2():
    for i in range(100000):
        total = sum(Score[j][a[j]] for j in range(40))
    print (total)

t0 = time.time()
ver1()
t1 = time.time()
ver2()
t2 = time.time()

print("Version 1 time: ", t1-t0)
print("Version 2 time: ", t2-t1)

The output is:
208
208
Version 1 time:  0.9300529956817627
Version 2 time:  1.066061019897461

Am I doing something wrong? Is there a way to do this faster?
(Note that this is just a demo I set up, in my real application the scores will not be repeated in this manner)
Some additional info: This is run on Python 3.4.4 64-bit, on Windows 7 64-bit, on an i7.

A: This seems to depend on the system, probably the python version. On my system, the difference is is about 13%:
python sum.py
208
208
('Version 1 time: ', 0.6371259689331055)
('Version 2 time: ', 0.7342419624328613)

The two version are not measuring sum versus manual looping because the loop "bodies" are not identical. ver2 does more work because it creates the generator expression 100000 times, while ver1's loop body is almost trivial, but it creates a list with 40 elements for every iteration. You can change the example to be identical, and then you see the effect of sum:
def ver1():
    r = [Score[j][a[j]] for j in range(40)]
    for i in xrange(100000):
        total = 0
        for j in r:
            total+=j
    print (total)

def ver2():
    r = [Score[j][a[j]] for j in xrange(40)]
    for i in xrange(100000):
        total = sum(r)
    print (total)

I've moved everything out of the inner loop body and out of the sum call to make sure that we are measuring only the overhead of hand-crafted loops. Using xrange instead of range further improves the overall runtime, but this applies to both versions and thus does not change the comparison. The results of the modified code on my system is:
python sum.py
208
208
('Version 1 time: ', 0.2034609317779541)
('Version 2 time: ', 0.04234910011291504)

ver2 is five times faster than ver1. This is the pure performance gain of using sum instead of a hand-crafted loop.
Inspired by ShadowRanger's comment on the question about lookups, I have modified the example to compare the original code and check if the lookup of bound symbols:
def gen(s,b):
    for j in xrange(40):
        yield s[j][b[j]]

def ver2():
    for i in range(100000):
        total = sum(gen(Score, a))
    print (total)

I create a small custom generator which locally binds Score and a to prevent expensive lookups in parent scopes. Executing this:
python sum.py
208
208
('Version 1 time: ', 0.6167840957641602)
('Version 2 time: ', 0.6198039054870605)

The symbol lookups alone account for ~12% of the runtime.

A: Since j is iterating over both lists, I thought I'd see if zip worked any better:
def ver3():
    for i in range(100000):
        total = sum(s[i] for s,i in zip(Score,a))
    print (total)

On Py2 this runs about 30% slower than version 2, but on Py3 about 20% faster than version 1. If I change zip to izip (imported from itertools), this cuts the time down to between versions 1 and 2.


Q: Help with Generics in VB Im new to VB. I am coming from a Java background. In the following code

Sub PrintList(Of T)(ByVal list As List(Of T))
        For Each obj As T In list
            Console.Write(obj.ToString() + " ")
        Next
        Console.WriteLine()
    End Sub

Can someone help me to understand what Sub PrintList(Of T)(ByVal list As List(Of T)) means?
Why do you need the (Of T) part? Why isn't (ByVal list As List(Of T)) sufficient?

A: In Java, this would be something like:
public static <T> void printList(List<T> list)

The (Of T) after PrintList is the equivalent to the <T> before void in the Java version. In other words, it's declaring the type parameter for the generic method.

A: Adding to what Jon Skeet said, this sub appears to be able to take any type of list.  If PrintList(Of T) was just PrintList, then you would be stuck specifying what type of List you want to use for your parameter.  You could no longer have 2 calls to this sub taking two different types of lists without overloading the sub.
What I mean by 2 different types of lists is:
List(of string)
List(of integer)


Q: Add a border around parts of a region, matplotlib/geopandas I'll have a map showing the municipalities of Stockholm. Displayed below.

fig, ax = plt.subplots(1, figsize=(4, 4))

matplotlib.rcParams["figure.dpi"] = 250
ax.axis('off')

ax1 = geo_df1.plot(edgecolor='black', column=geo_df1.rel_grp, cmap=my_cmp, linewidth=0.3, ax=ax, categorical=True)#,

plt.show(ax1)

I want to add an amplified border to the east. Something like this. How can I do this in matplotlib?

A: *

*question does not include geometry, so have sourced

*it's a simple case of plotting a LineString that is the eastern edge.  Have generated one for purpose of example

import requests
import geopandas as gpd
import shapely.ops
import shapely.geometry
res = requests.get("http://data.insideairbnb.com/sweden/stockholms-län/stockholm/2021-10-29/visualisations/neighbourhoods.geojson")

# get geometry of stockholm
gdf = gpd.GeoDataFrame.from_features(res.json()).set_crs("epsg:4326")

# plot regions of stockholm
ax = gdf.plot()

# get linestring of exterior of all regions in stockhold
ls = shapely.geometry.LineString(shapely.ops.unary_union(gdf["geometry"]).exterior.coords)
b = ls.bounds
# clip boundary of stockholm to left edge
ls = ls.intersection(shapely.geometry.box(*[x-.2 if i==2 else x  for i,x in enumerate(b)]))

# add left edge to plot
gpd.GeoSeries(ls).plot(edgecolor="yellow", lw=5, ax=ax)


Q: MySQL insert record I have this SQL query:
insert into messages
(message, hash, date_add)
values
('message', 'hash', NOW())
ON DUPLICATE KEY IGNORE

hash is unique, what is wrong with query? i got the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IGNORE' at line 1

A: According to MySQL doc the syntax should be :
INSERT IGNORE INTO messages (message, hash, date_add)
  VALUES('message', 'hash', NOW());