Q: How can I refer to what called a function in C++? I was wondering if there is a way in C++ to know what called a function? Like the this keyword in Java or JavaScript.
For example, I have a function called insert, which inserts an item into a linked list, I want the linked-list that called those the function insert to call two other functions. How would I do that?
I have this right now, is this valid?
bool linked_list::insert( int i )
{
    bool inserted = false;

    if( this.is_present(i) ) /* function is_present is defined earlier checks if an int is already in the linked-list. */
    {
        inserted = true // already inside the linked-list
    }
    else
    {
        this.Put( 0, i ); /* function Put is defined earlier and puts an int in a linked-list at a given position (first param.). */
        inserted = true; // it was put it.

    }
return inserted;
}

A: For historical reasons, this is a pointer. Use -> instead of ..
bool linked_list::insert(int i) {
    bool inserted = false;

    if(this->is_present(i)) {
        inserted = true; // fixed syntax error while I was at it.
    } else {
        this->put(0, i); // fixed inconsistent naming while I was at it.
        inserted = true;
    }
    return inserted;
}

Usually it is not needed to use this-> at all; you can just do if(is_present(i)).

A: this works in c++ the same as it does in Java. The only difference is that you need to use this-> instead of this. this is a pointer than therefor you cannot use the dot operator to access it's members.

A: why don't you just call the other functions in linked_list::insert(int)? And no, it is not valid, you should put this -> something instead of this.something


Q: Split the string at the word before the next colon? I am trying to split this string between the first colon entry and the next word that includes a colon. The string is a long text. It can have a period or comma between the colons.
For example, if I have the following string.
String s       = "Description: This is the description. Observation: This is the description.";
String[] parts = s.split("REGULAR_EXPRESSION");

The result would be:
This is the description.

For example if the string is
"Description: This is. The, description. Words: words words"

The result would be:
This is. The, description.

A: If you want what you ask, you need a regex that splits by colon and period.
Something like this?
:.+\.

EDIT: Here is a breakdown of this regular expression (as requested by Roman C)
: matches the colon character (:) literally
.+ matches any character one and unlimited times, greedy (except newline)
\. matches the period character (.) literally

A: This splits the string on both the colon or period. Element index 1 (the second element) is what you want. Just trim it.
String description = "Description: This is the description. Observation: This is the description.".
   split("[\\.:]")[1].trim();

You could also pre-trim it:
String description = "Description: This is the description. Observation: This is the description.".
   split("[\\.:] +")[1];

Use "[\\.:]\\s+" if there might be non-space whitespace.

A: Split is not the best method to use. This code gets you the part you want:
String part = string.replaceAll("\\w+:\\s+(.*?)\\s+\\w+:.*", "$1");

This also trims the part extracted.

Some test code:
String string = "Description: This is the description. Observation: This is the description.";
String part = string.replaceAll("\\w+:\\s+(.*?)\\s+\\w+:.*", "$1");
System.out.println(part);

Output:
This is the description.

A: What about the next?:
String string = "Description: This is the description. Observation: This is the description.";
String str = string.replaceFirst(".*:\\s+(.*)", "$1");


Q: BPEL Apache ODE .deployed file I have created a basic helloworld.bpel process file in eclipse in BPEL project and tried to deploy it Apache ODE. So I followed the steps in this link
   Apache ODE Eclipse BPEL guide.
But in the later stages, after putting the relevant files in WEB-INF folder and running the APACHE ODE the expected .deployed file was not created. And Apache ODE is not detecting the same in ODE browser when I use localhost:8080/ode/processes.
When I tried to launch ODE server in eclipse, I am getting the following errors.
Firstly, this was the error that I got.
"Another instance of derby may have booted into the database"
 Then I restarted Apache Tomcat in services.msc. Then that error stopped showing.
Now this is the error I am stuck with.
"Schema SA does not exist"
Database Class Loader started - derby.database.classpath=''
13:54:26,099 WARN  [GeronimoConnectionEventListener] connectionErrorOccurred called with null
  java.sql.SQLSyntaxErrorException: Schema 'SA' does not exist
  at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
  at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
  at org.apache.derby.impl.jdbc.TransactionResourceImpl.wrapInSQLException(Unknown     Source)
  at org.apache.derby.impl.jdbc.TransactionResourceImpl.handleException(Unknown Source)
  at org.apache.derby.impl.jdbc.EmbedConnection.handleException(Unknown Source)

A: Looks like there are some problems with the embedded derby database. I'd try to completely redeploy ODE so that the database is extracted from the .war again.

A: You have to execute Eclipse or NetBeans as Administrator.


Q: Django assign user to group during registration based on choice in another field I would like to automatically assign users to a group based on their choice in another field in the user registration field. I am new to Django and I am not sure of the best way to achieve this.
I want to assign the group based on the choice of the "business_location_county" field in the model. In simple terms the group should be the group id where the group "forum_id" equals the id of the business_location_county choice. The group "forum_id" is a custom column added to the Group model.
The models.py:
from django.contrib.auth.models import AbstractUser
from django.db import models
from machina.core.db.models import get_model
from django.db.models import Q
from django.contrib.auth.models import Group

Forum = get_model("forum", "Forum")

class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)
    business_location_state = models.ForeignKey(Forum, null=True,  on_delete=models.SET_NULL, limit_choices_to={"lft":1})
    business_location_county = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, related_name='county', limit_choices_to=(~Q(lft__in = (1,2))))

Group.add_to_class('forum_id', models.PositiveIntegerField(null=True, blank=True))

views.py:
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm
from .models import CustomUser
from django.shortcuts import render
from machina.core.db.models import get_model
from django.db.models import Q

Forum = get_model("forum", "Forum")

class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'registration/signup.html'

def load_counties(request):
    parent_id = request.GET.get('business_location_state')
    counties = Forum.objects.filter(parent_id=parent_id).order_by('name')
    return render(request, 'hr/county_dropdown_list_options.html', {'counties': counties})

forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm):
        model = CustomUser
        fields = UserCreationForm.Meta.fields + ('username', 'email', 'age', 'business_location_state', 'business_location_county')

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['business_location_county'].queryset = CustomUser.objects.none()

class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = ('username', 'email', 'age','business_location_state', 'business_location_county')

I am attempting to use post_save signal to accomplish this. However before I tackle trying to save the user to the group, I need to figure out how to get the Group id where business_location_state id is equal to Group forum_id.
I tried (unsuccessfully) adding this to the models.py
from django.db.models.signals import (
    post_save
)

def user_addgroup_handler(sender, instance, created, *args, **kwargs):
    g = Group.objects.get(id, limit_choices_to=(Q(forum_id__in = CustomUser.business_location_county)))
    print (g)

post_save.connect(user_addgroup_handler, sender=CustomUser)

Any suggestions on how to achieve this?

A: With help from an expert the following works:
def user_addgroup_handler(sender, instance, created, *args, **kwargs):
    # g = Group.objects.get(id, limit_choices_to=(Q(forum_id__in = CustomUser.business_location_county)))
    # group = Group.objects.get(name=instance.business_location_county.name)

    # for g in CustomUser.objects.all():
    #     print(g.business_location_county_id)

    if created:
        # Get or create group
        new_group, created = Group.objects.get_or_create(
            name=instance.business_location_county.name, forum_id=instance.business_location_county.id)

        # add new group to user
        instance.groups.add(new_group)

post_save.connect(user_addgroup_handler, sender=CustomUser)


Q: NodeJS, ExpressJS & Jade - passing model to knockout? I'm trying to get my expressJS-Model to my .jade-template, but the way I can access the Model with JS on the client-machine.
The idea is simple:
I want to use the Model with Knockout - so I need to give the Model-Object as it is to the client.
If I do the obvious - var t = #{customer} - I ending up with the rendered output var t = [object Object]
So how can I use the object on the client-side?
Thanks!

A: JSON.stringify the object on the server, and JSON.parse it on the client (will only work in IE >= 8, if you need to support older i3-browsers you could provide json-js from douglas crockford: https://github.com/douglascrockford/JSON-js


Q: How to get Bootstrap timepicker date object? Currently using bootstrap timepicker with Angularjs
http://jdewit.github.com/bootstrap-timepicker
The control is displaying well but when i set the ng-model and get the startTime

           <input type="text" class="form-control timepicker" ng-disabled="!useTime" data-template="dropdown" data-show-seconds="true" data-default-time="11:25 AM" data-show-meridian="true" data-minute-step="5" ng-model="startTime" />

The startTime assigned is a string like "11:25 AM" instead of a date object i can manipulate in javascript.
How can i get date object? Do i need to convert it manually?

A: Think this answer seems to be similar to your question.Hope it provides some insight.
Time Binding issue in Bootstrap timepicker


Q: Nested filters in angular for hierarchical data model I have an hierarchical data model with lines of products and then sublines, and then sublines of sublines etc. What I am trying to do is isolate only the sublines that are directly descendants (sons not grandchildren) of a particular line or subline.
Here is my existing data model:
items:[
  {
    "_id": "1",
    "description": "sth1",
    "name": "smname1",
    "level_type": "line",
    "ancestor": "",
    "descendant": "smname2"
   }
  },
  {
    "_id": "2",
    "description": "sth2",
    "name": "smname1",
    "level_type": "subline",
    "ancestor": "smname1",
    "descendant": ""
    }
  },
]

Also for the example above another thing I'm trying to accomplish is to get the children of all the product lines. What I have tried but is not working so far is:
Controller
$scope.prodClassIsALine = function(item) {
        return item.level_type=='line';
    };

    $scope.prodClassIsASubLineof = function(item) {
        return item.ancestor==$scope.prodClassIsALine.name;
};

Tragic proposal just to show you that I need all children of all lines i.e. all items with ancestor names of items that are lines.
Html

{[{item.name}]}

Is this the way we are nesting filters in AngularJS? It seems that filters are iterating over the list that are given as attribute but further than that I can't understand in detail how they work. Please help.
Solution
In script.js
//product is my ng-module
//filter to get all product classes that are lines
product.filter('prodClassIsALine', function() {
    return function(input) {
      var out = [];
      for (var i = 0; i < input.length; i++) {
        if (input[i].level_type=='line') {
            out.push(input[i])
        };
      };
      return out;
    };
});

//filter to get all children of product classes that are lines
product.filter('prodClassLineChild', function() {
    return function(input) {
      var out = [];
      var out2 = [];
      for (var i = 0; i < input.length; i++) {
        if (input[i].level_type=='line') {
            out2.push(input[i])
        };
      };
      for (var i = 0; i < out2.length; i++) {
        for (var j = 0; j < input.length; j++) {
            if (input[j].ancestor==out2[i].name) {
                out.push(input[j])
            };
        };
      };
      return out;
    };
});

Html

{[{item.name}]}

A: do u mean this?

more info here
http://docs.angularjs.org/guide/dev_guide.templates.filters.using_filters
EDIT:
now i got that u didnt wrote filters but scope function, u need something like this
myModule.filter('iif', function () {
    return function (input, trueValue, falseValue) {
        return input ? trueValue : falseValue;
    };
});

my use is class="{{ catalogItem.IS_FINAL | iif : 'IsFinalCatalogItem' : '' }}"
should look like this
myModule.filter('prodClassIsALine', function() {
    return function(item) {
        return item.level_type=='line';
    };
});

p.s. in angular 1.2 they added the standard iif syntax


Q: How do I save my resized image to my Azure Blob Storage in my ASP.NET Core Application? I'm using the ImageSharp library to rescale my images before they are uploaded to Azure, the application hangs with no errors when it reaches the UploadBlob action and I think it's the stream causing it.  When the image is uploaded the information is gathered from the image stream, I create an empty MemoryStream, resize the image using ImageSharp, stuff the MemoryStream with my newly scaled image and try to upload that MemoryStream to Azure and I don't think it likes it as that is where it hangs.
Is MemoryStream the correct thing to use in this instance or is it something else?
CarController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Car car)
{
    // Define the cancellation token.
    CancellationTokenSource source = new CancellationTokenSource();
    CancellationToken token = source.Token;

    if (ModelState.IsValid)
    {
        //Access the car record
        _carService.InsertCar(car);

        //Get the newly created ID
        int id = car.Id;

        //Give it a name with some virtual directories within the container
        string fileName = "car/" + id + "/car-image.jpg";
        string strContainerName = "uploads";

        //I create a memory stream ready for the rescaled image, not sure this is right.
        Stream outStream = new MemoryStream();

        //Access my storage account
        BlobServiceClient blobServiceClient = new BlobServiceClient(accessKey);
        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(strContainerName);

        //Open the image read stream
        var carImage = car.ImageFile.OpenReadStream();

        //Rescale the image, save as jpeg.
        using (Image image = Image.Load(carImage))
        {
            int width = 250;
            int height = 0;
            image.Mutate(x => x.Resize(width, height));
            image.SaveAsJpeg(outStream);
        }

        var blobs = containerClient.UploadBlob(fileName, outStream);
        return RedirectToAction(nameof(Index));
    }
    return View(car);
}

A: It's not got anything to do with the ImageSharp library.
You need to reset your outStream position after saving. BlobContainerClient is trying to read from the end of the stream.


Q: How can an untrusted client prove that an ID isn't human meaningful? I have a situation where an untrusted client is generating string IDs, but I don't want them to be human readable.
They don't need to be crytographically random or even unique, I just don't want IDs like "idiot" to be accepted.
How can I go about preventing this?
EDIT: It would be nice if the IDs were "aspirationally-unique", like GUIDs.

A: Here are some ideas:

*

*Convert the supplied ID to a hash or encrypt it. This will result in meaningless strings

*Create a dictionary of words you don't want used, and when the supplied ID contains one of those words, reject it... a PHP example can be found at https://scvinodkumar.wordpress.com/2009/06/17/bad-word-filter-and-replace/

*Require that the IDs not contain sequences where two (or however many) alpha characters are next to each other

If you have any additional info/preference/requirements, let me know.


Q: Fill List with strings from Regex.Matches I'm writing a WPF client for an online browser game as a learning project for C#. I want to import the data that is shown on the website, store it in a model and display it through binding. Usually, i go about it this way:
Retreive data with HttpWebRequest, perform Regex to receive the wanted data, and then store it for further use in the Models. With this particular item, a list of cars and their properties in a table, i need 6 properties of the cars, which i can retrieve with 1 Regex query:
var carInfos = Regex.Matches(HTMLBody, @"(?<== }"">).*(?=</td>)");

I get 42 matches from that string, which means there are 7 CarModels to be filled. Now, if i want to fill the models i would go about it this way:
            Cars.AllCars.Add(new CarModel{
                                             Plate = carInfos[0].Value,
                                             Type = carInfos[1].Value,
                                             NetWorth = int.Parse(carInfos[3].Value,
                                             etc, etc..

                                         });

This is my CarModel:
  public class CarModel : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;
    private string _plate;

    public string Plate{
        get { return _plate; }
        set{
            if (value == _plate) return;
            _plate = value;
            OnPropertyChanged();
        }
    public string Type { get; set; }
    public int NetWorth { get; set; }
    public State CurrentWorth { get; set; }
    public State Location { get; set; }
    public int Condition { get; set; }
    public int Issues { get; set; }

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

How can i do this dynamically? Every 6th property is the car type, location etc. I want to be able to bind hundreds of cars eventually.
Let's say, for instance, i get 12 matches from the Regex, i.e. two cars. the carInfos[0].value would be a Plate, and the carInfos[6].value would also contain a plate. How can i loop through the results in such a manner that these models will be filled accordingly?

A: This should work for you then -
for (int index = 0; index < carInfos.Count/6; index++)
{
    int offest = index * 6;
    Cars.AllCars.Add(new CarModel{
                                 Plate = carInfos[0 + offest].Value,
                                 Type = carInfos[1 + offest].Value,
                                 NetWorth = int.Parse(carInfos[3 + offest].Value,
                                 etc, etc..
                                 });
}

Since you have total of 7 items that's why (42/6) = 7 and item is at offset of multiple of 6 hence the logic for calculation of offset (offest = index * 6)


Q: overpass-turbo.eu find all cities on maps maybe someone can help me with a overpass-turbo.eu-query.
I'd like to highlight (center of it) all cities of a country or region (or current map).
Is there maybe an "simple" example on web?
(Google was not a good friend with this special request, yet. But I am sure someone must tried to search this way already.)
Many thanks for every idea.

A: Here is an example for finding all cities, towns, villages and hamlets in the country Andorra:
[out:json][timeout:25];
// fetch area “Andorra” to search in
{{geocodeArea:Andorra}}->.searchArea;
// gather results
(
  node[place~"city|town|village|hamlet"](area.searchArea);
);
// print results
out body;
>;
out skel qt;

You can view the result at overpass-turbo.eu after clicking the run button.
Note: When running this query for larger countries you might need to increase the timeout value. Also rendering the result in the browser might not be possible due to performance reasons. In this case use the export button and download the raw data instead.


Q: Download multiple MP3 files in the background in Android LEVEL: Beginner
Language: Java
IDE: Android Studio
CASE: Downloading multiple MP3 files from multiple URL's in a row in the background.
ISSUE: download task in the loop to download all the urls.
the songs did download in the following path but aren't fully downloaded (every song is downloaded for 3 seconds/4 seconds basically very less).
don't know what's the problem, It'll be great if i can get any help

*

*receive mp3 url's from API

*download them using the following code. (ISSUE)

*get the path of all and store them in the Database

*fetch the path and play one by one continuously.
private class DownloadTask extends AsyncTask<SongDetails, Integer, String> {
Context context;

public DownloadTask(Context context) {
    this.context = context;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    Utilities.showProgressDialog(getActivity(), getFragmentManager());
}

@Override
protected String doInBackground(SongDetails... songDetails) {
    for (SongDetails songs : songDetails
    ) {
        donwloadsong(songs);
    }
    return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    Utilities.dismissProgressDialog();
}
}

 for (SongDetails songs : songDetails
    ) {
        downloadTask(songs);
    }

 public void downloadTask(SongDetails songs){
   HttpURLConnection httpURLConnection = null;
   try {
     URL url = new URL(songs.getUrl());
     httpURLConnection = (HttpURLConnection) url.openConnection();
     httpURLConnection.setRequestMethod("GET");
     httpURLConnection.connect();

    int fileLength = httpURLConnection.getContentLength();
         InputStream inputStream = new
    BufferedInputStream(url.openStream(), 8192);
    OutputStream outputStream1;
    outputStream1 = new
    FileOutputStream(Environment.getExternalStorageDirectory() + "/gbeduwarssongs/" + songDetails.getTitle().trim() + ".mp3");
    int count = 0;
         byte data[] = new byte[1024];
    int buffer_length;

    while ((buffer_length = inputStream.read(data)) != -1) {
        outputStream1.write(data, 0, count);
          count += buffer_length;
    }
    outputStream1.flush();
    outputStream1.close();
    inputStream.close();

} catch (Exception e) {
    e.printStackTrace();
    Log.e("Error", "Download Error Exception " + e.getMessage());
} finally {
    if (httpURLConnection != null)
        httpURLConnection.disconnect();
  }
}

A: Rather calling iteration inside a new thread, use iteration first and then start new thread in every iteration. I hope it will help you. I am posting code for your help.
for (SongDetails songs : songDetails) {
        new DownloadTask(pass your song object in constructor).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

and in doInBackground call your downloading method stuff.

A: I offer to use DownloadManager or workmanager for it. AsyncTask has used a bad idea. It has a problem with a memory leak.
The asyncTask use only one thread
The same question


Q: Accessing Shared Calendars with Exchange Web Services I'm trying to access shared calendars from exchange using exchange web services, can someone provide me with info on how I can do this?
I have tried:
ExchangeService myService = new ExchangeService (ExchangeVersion.Exchange2007_SP1);
myService.Credentials = new NetworkCredential ("user@domain.com", "12345");

But I may not always have the passwords for these accounts and the account I'm logged into does has shared calendar access.

A: I have managed to get it working now
Dim _cal As New Microsoft.Exchange.WebServices.Data.FolderId(Microsoft.Exchange.WebServices.Data.WellKnownFolderName.Calendar, New Microsoft.Exchange.WebServices.Data.Mailbox(_otherAddress))
Dim _calendarView As New Microsoft.Exchange.WebServices.Data.CalendarView(_startTime.Date, _endTime.Date.AddDays(1))

For Each appointmentItem As Microsoft.Exchange.WebServices.Data.Appointment In _
    service.FindAppointments( _
    _cal, _
    _calendarView)
Next


Q: Access WPF Treeview selected index through a TreeViewItem object I have a treeview with checkboxes for each item using a DataTemplate.
<TreeView ItemsSource="{Binding}">
<DataTemplate DataType="{x:Type local:MatchDataLeaf}">
    <Grid Margin="3">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="240"/>
            <ColumnDefinition Width="100"/>
            <ColumnDefinition Width="150"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="60"/>
        </Grid.ColumnDefinitions>

        <StackPanel Grid.Column="0" Orientation="Horizontal">
            <CheckBox x:Name="selectCheckBtn" Grid.Column="0" IsChecked="True" Click="select_Click"
                      Tag="{Binding}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}}}"/>
            <TextBlock Grid.Column="1" Margin="5,0,0,0" Text="{Binding Path=Name}" FontFamily="Arial" FontSize="12" FontWeight="Bold" Foreground="Black" VerticalAlignment="Center"/>
    </StackPanel>
 </Grid>
</DataTemplate>

In the checkbox click event, I'm trying to figure out the selected index in the main tree's binded list. The closest I got is passing the TreeViewItem object along in the CommandParameter, but I can't do anything with it. I was able to the the parent ItemsControl using:
ItemsControl parent = ItemsControl.ItemsControlFromItemContainer(selectedItem);
int s = parent.Items.IndexOf(selectedItem);

But s = -1 here.
I also have the Tag on the checkbox that has the underlying object in it. Sure, I can do a Find on my list for the object, but it just seems like there must be a simpler way to find the index.

A: The ItemsControl you are fetching might be the StackPanel, or the Grid.  You should be able to access the Checkbox through the event sender, and navigate up to the TreeViewItem and TreeView and use IndexOf.
 private void CheckBox_Click(object sender, RoutedEventArgs e)
 {
        CheckBox cb = (CheckBox)sender;
        StackPanel sp = (StackPanel)cb.Parent;
        Grid g = (Grid)sp.Parent;
        ContentPresenter cp = (ContentPresenter)VisualTreeHelper.GetParent(g);
        IList l = (IList)myTreeView.ItemsSource;
        object o = cp.Content;
        MessageBox.Show(l.IndexOf(o).ToString());
 }


Q: iOS 9 simulator can't show the whole screen For some reason, when I run some old projects, the simulator can't load the full screen:

Any suggestion?


Q: Azure FreeRtos middleware and DPS, on ESP32 I am working on a project, where I am using the Azure FreeRTOS Middleware Stack on ESP32.
I would like to introduce DPS to provision all my 3K upcoming devices.
The Stack has got a DPS option, but I would like some advice as I would like to generate one global bin file, for all 3K devices. I would like DPS to create the device on IoT Hub and also provide the necessary keys to the device so it can generate the SAS token for each device id.
The device ID will be either the serial number or mac number of the ESP32 device.
What i want to avoid is creating a seperate bin file for each device.
Can this be possible? or am i miss understanding DPS?

A: DPS will not provide you neccessary keys for each device. To work with Azure IoT (either DPS or Hub), you must have per-device credential flash to your device, this is usually done during manufacturing phase.
When you use DPS group enrollment, you get a group key from DPS and use a formula to generate per-device key (hash the group key and enrollment/device id), you need a method to flash 3k keys to 3k devices on production line.

A: DPS do actually provision a device AUTOMATICALLY. You don't extra step.
Let me explain how.
Step 1: Things you have to do once from the Azure portal:

*

*You create/you have an Azure IoT Hub up and running;

*Your create/you have azure DPS up and running;

*You create/you have a group enrolment with symmetric key from within DPS;

*You keep the primary key of your group enrolment for use in a bit. Let’s call the primary key “KEY”

Step 2: programming
From your firmware source code:

*

*Write a code function that returns a device ID that’s unique for a device. You can use a string followed by the device MAC address, that you usually get from the Wifi interface (or Ethernet interface). For example: “3Kdevice-3454e210228c” the prefix will be the same for all devices you’ll have, but the hex numeric suffix will be different for each device. Let’s call this string REG_ID.

*Write a code function that creates for the device it runs on, the symmetric key from both the primary key (aka KEY) of your enrolment and the registration ID (aka REG_ID). You do that by doing a SHA256 (see DPS doc for that). Let’s call the computed symmetric key “SYM_KEY”;

*Use the azure SDK to  get the credentials from DPS by presenting the registration ID (aka REG_ID) and the computed symmetric key (SYM_KEY) to it;

*You can connect to the IoT Hub with the credentials you got at point 3.


Q: Reading multiple cookie I would like to know how do I detect multiple cookies. I have two button with class- .attack_enabled and .restore_enabled, both create cookie called attackcompletecookie and restorecompletecookie, respectively.
How do I detect both cookies and add a class to .territory_middle_complete
Here's my code:
$(".attack_enabled").click(function(){

   createCookie('attackcompletecookie','attack_cookie');

});

$(".restore_enabled").click(function(){

   createCookie('attackcompletecookie','restore_cookie');
   var atkcomplete = readCookie('attackcompletecookie');

});

if(atkcomplete){
   console.log(atkcomplete);
   $(".territory_middle_complete").addClass("displayblockzindex2");
}

A: Try to use id instead class to refer in jQuery, leave the classes for CSS.
Check it here http://jsfiddle.net/hbzqnrm8/5/
I hope it helps you.
<button id="attack_enabled">ATTACK</button>
<button id="restore_enabled">RESTORE</button>

ADD A CLASS HERE

I've edited your jQuery code, and add what I think you want to achieve. Of course if you want to check the existance of the cookie when clicking the "restore" button, if not, just move the if condition wherever you needed, but not outside the click function, because it will be executed only on loading the file.
$("#attack_enabled").click(function(){
   createCookie('attackcompletecookie','attack_cookie');
});

$("#restore_enabled").click(function(){
   createCookie('restorecompletecookie','restore_cookie');
   var atkcomplete = readCookie('attackcompletecookie');
   if(atkcomplete)
   {
       alert(atkcomplete);
       $(".territory_middle_complete").addClass("displayblockzindex2");
    }
});

function createCookie(cookieName, cookieId) {
    document.cookie = cookieName + '=' + cookieId;
}

function readCookie(name) {
    var nameEQ = encodeURIComponent(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}


Q: Error Code:1262 when loading to mySQL I have a little bit of an issue when trying to load tsv file 2gb to mysql database. Error Code:1262
As this is quite big file how can i open/change so i can load it into the system?

A: this will be csv file and as you aware that it is to big.
if you are in local server you can change in .ini file and increase the limit for uploading file and if you are using web server add in .htaccess file
in the .htcaccess file add the following:
php_value upload_max_filesize 500M
php_value post_max_size 500M

in php.ini add:
upload_max_filesize = 500M
post_max_size = 500M

or you can split your csv file


Q: Putting regex into a variable REG=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/g
(echo "1.2.3" | grep -Eq "$REG" ) && echo "matched" || echo "did not match"

I get the error:
test.sh: line 2: syntax error near unexpected token `('
test.sh: line 2: `REG=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/g'

Not very much to go on here. Trying to see if 1.2.3 meets the regex expression.
The expression I got from here: https://github.com/mojombo/semver/issues/232

A: Use quotes so the shell doesn't barf on special characters.
REG='/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$/g'

Note that this regex will not work with grep. POSIX regex syntax is different and more limited than Perl syntax, which is what you've got.

A: You ran into two major problems

*

*Bash handling special characters, escapes, and anything else it found in your string before storing it. This is solved by single quoting your string to prevent bash expansion/interpretation.

*The Regex was written in Perl syntax, which grep does not support, it uses POSIX which is slightly different from Perl even though the two are similar. This is solved by removing the surrounding / /g and replacing all instances of \d which is not recognized by POSIX with [0-9].
Result:
REG='^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\+[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*)?$'


Q: C# tableAdapter.Update() won't change the database record I want my program to be able to change one row in my Access database with the data from my form.
The problem is that the update-function doesn't do anything.
There are no error messages and the program compiles correct. Nothing changes in the database.
Here is the code:
private void btnTallenna_Click(object sender, EventArgs e)
{
    string[] vanhat = new string[9];
    lueVanhatTiedot(vanhat);

    hevosetTableAdapter.Connection.Close();
    hevosetTableAdapter.Connection.Open();
    try
    {
        hevosetTableAdapter.Update(txtNimi.Text, txtIka.Text, cmbPaino.Text, cmbKaytto.Text, cmbRotu.Text, cmbSukupuoli.Text, cmbKunto.Text, cmbRehunkayttokyky.Text, int.Parse(vanhat[0]), vanhat[1], vanhat[2],vanhat[3], vanhat[4], vanhat[5], vanhat[6], vanhat[7], vanhat[8]);
        this.hevosetBindingSource.EndEdit();
        hevosetTableAdapter.Update(this.dsHevonen.Hevoset);
        hevosetTableAdapter.Connection.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
    hevosetTableAdapter.Connection.Close();
}

lueVanhatTiedot() function gets the original data for the record.
Still learning to program so there may be stupid mistakes which I just can't notice. :)

A: Have you called the "AcceptChanges" method on the DataSet?


Q: Mongoose ignores $ne while updating document I'm building a persistent html fields framework using Node, Mongoose, and Socket.io for the backend. I've run into what seems like a bug in Mongoose's update method.
The documents in mongo look like this:
{
    "_id" : "pickable_qty",
    "currently_connected" : [ ],
    "locks" : [
        {
            socket_id: 'eQYVyz1z28rJZRPpAAAB',
            unique_values:{
                merchant_warehouse_id: 11.1,
                product_item_id: 5555
            }
        },
        {
            socket_id: 'eQYVyz1z28rJZRPpAAAB',
            unique_values:{
                merchant_warehouse_id: 11.2,
                product_item_id: 5555
            }
        },
        {
            socket_id: 'eQYVyz1z28rJZRPpAAAB',
            unique_values:{
                merchant_warehouse_id: 11.1,
                product_item_id: 1234
            }
        }
    ],
    "definition" : {
        "ajax_url" : "/persistent-fields/pickable_qty",
        "unique_keys" : [
            "product_item_id",
            "merchant_warehouse_id"
        ],
        "max_idle_seconds" : 30,
        "field_type" : "text"
    },
    "__v" : 0
}

The problem arises when I start inserting subdocuments into the locks array.
I insert them using Mongoose's update method like so:
FieldSchema.update(
    {
        _id: 'pickable_qty',
        'locks.unique_values': {
            '$ne': {
                merchant_warehouse_id: 11.1,
                product_item_id: 5334
            }
        },
        'definition.unique_keys': {
            '$all': [
                'merchant_warehouse_id',
                'product_item_id'
            ]
        }
    },
    {
        '$push': {
            locks: {
                socket_id: 'eQYVyz1z28rJZRPpAAAB',
                unique_values: {
                    merchant_warehouse_id: 11.1,
                    product_item_id: 5334
                }
            }
        }
    },
    function(err, count, res){
        console.log('err:', err, 'count:', count, 'res:', res);
        //err: null count: 1 res: { ok: true, n: 1, updatedExisting: true }
    }
);

The first insert works exactly as expected, there were no locks in the array containing the unique values {merchant_warehouse_id: 11.1,product_item_id: 5334} so the document was found and the lock subdocument was inserted.
However running this same update the second time should not insert a new locks subdocument because one already exists with the same unique_values and the $ne part of the query should cause it to return no matches to update.
I have confirmed that doing a find with the same query returns no documents both on the MongoDB command line and using Mongoose's own Schema.find method, but the Schema.update method still finds a document and inserts a duplicate lock subdoc.
Am I just going crazy or is there a reason why Mongoose's find method won't retrieve the document while update will?

A: The problem is that you are querying whether or not an object matches a subdocument, and this can be tricky. What you want to do use a combination of $elemMatch and $ne in your query.
var query = {
    _id: 'pickable_qty',
    'locks': {
        $elemMatch: {
            merchant_warehouse_id: {
                $ne: 11.1
            },
            product_item_id: {
                $ne: 5334
            }
        }
    },
    'definition.unique_keys': {
        '$all': [
            'merchant_warehouse_id',
            'product_item_id'
        ]
    }
}

It's basically a query for a document inside of an array.

A: After using MongoDB's query profiler, I figured out that Mongoose was switching the order of the keys in the lock's unique_values object while doing the update query. Then it was inserting the duplicate subdocuments with the keys in the correct order. So apparently MongoDB's $ne operator will match nested subdocument arrays only if the keys in the subdocument are in the same order as your query.


Q: Why does my SURF.detectAndCompute returns none before the array? I am trying to extract key point and descriptors but my SURF.detectAndCompute returns None in front of the array and because of that I cannot do the clustering. Below is my code:
image_paths = []
image_group_id = []
image_group_names = os.listdir(train_path)
descriptors = []
SURF = cv2.xfeatures2d.SURF_create()
SURF.setHessianThreshold(5000)
for group_id, train_group_path in enumerate(os.listdir(train_path)):
    image_path = train_path + '/' + train_group_path
    for path in os.listdir(image_path):
        full_image_path = image_path + '/' + path
        image_paths.append(full_image_path)
        image_group_id.append(group_id)
        _, des = SURF.detectAndCompute(cv2.imread(full_image_path), None)
        descriptors.append(des)

And this is the  of the descriptors that I tried to print:
[None, array([[ 0.00140431,  0.00414569,  0.00156097,  0.00508978, -0.01072729,
         0.03109567,  0.01673188,  0.04477221, -0.04659119,  0.0652261 ,
         0.04661125,  0.08301401, -0.00103816,  0.0069982 ,  0.00168295,
         0.00876924,  0.01606237, -0.00151245,  0.01966742,  0.01294267,
        -0.2951115 , -0.14716513,  0.32090443,  0.18698329,  0.21934257,
        -0.02404423,  0.29070902,  0.17538053, -0.03951943,  0.02635496,
         0.04406727,  0.02923489,  0.03092461, -0.04000381,  0.03236163,
         0.04539306, -0.26897454, -0.112547  ,  0.33476326,  0.29709056,
         0.2916087 , -0.01106649,  0.351532  ,  0.19272245, -0.07418256,
        -0.04663706,  0.07452377,  0.04671762,  0.00109221,  0.00404389,
         0.0019812 ,  0.0101865 ,  0.00381939, -0.01452297,  0.05944061,
         0.05199388,  0.0035292 , -0.04607308,  0.03296318,  0.04701661,
        -0.00757545, -0.00286426,  0.00760168,  0.00306828]],
      dtype=float32)

The None isn't supposed to be there. What can I do to fix this? I am new in this field, any advice is very appreciated. Thank you!


Q: Reset scrollbar state on switching content I have a sample code with one button and 2 images that are shown conditionally. I need to scroll to the top of the content div, where images are shown but it stays in the same position as the previous content.
I tried to separate buttons and content between separate divs but it didn't help. Is there a way to achieve this with only CSS.
Here is the code and working example in codesandbox:
https://codesandbox.io/s/upbeat-sutherland-9r0kh?file=/src/styles.css:0-206
The page:
import { useState } from "react";
import "./styles.css";

export default function App() {
  const [isOpen, setIsOpen] = useState(true);

  return (

        <button onClick={() => setIsOpen(!isOpen)}>switch</button>

        {isOpen ? (

        ) : (

        )}

  );
}

CSS:
.App {
  font-family: sans-serif;
  text-align: center;
  display: flex;
  align-items: center;
}

.buttonContainer {
  position: fixed;
  height: 100vh;
}

button {
  position: absolute;
  height: 100px;
}


Q: Xpath - Extracting multiple specific differnt parts of text strings from one text node I have three samples of text nodes that and I want to extract three different parts of the text, using a universal x-path.
First

                This is an amazing game from the company Midway Games. Excellent gameplay. Very good game.

Second

                New Line Cinema distributed this movie in 1995.

Third

                New game from 2011, with new 3D graphics. This game was made by NetherRealm Studios.

The extraction should be either Midway Games or New Line Cinema or NetherRealm Studios
Note that the text node allways include just one company, never two or three (just one).
My try is from this question but the problem is that it dosen't work nor include all three companies.
substring('Midway Games',1,12*contains(//p[@class='product-summary']/following-sibling::text()[1], 'Midway Games'))

A: As the input will only contain one of them, you can use concat to join the results.
concat(
  substring('Midway Games', 1,
      12*contains(//p[@class='product-summary'], 'Midway Games')),
  substring('Line Cinema', 1,
      11*contains(//p[@class='product-summary'], 'Line Cinema')),
  substring('NetherRealm Studios', 1,
      19*contains(//p[@class='product-summary'], 'NetherRealm Studios'))
)

You can remove the line breaks that I added for readability as you want.
I had to fix the query you provided: the text nodes are no following-siblings, but children. Your XPath processor will query the (concatenated) text nodes below that element anyway as contains works on strings.


Q: How do you create a read-only user in PostgreSQL? I'd like to create a user in PostgreSQL that can only do SELECTs from a particular database. In MySQL the command would be:
GRANT SELECT ON mydb.* TO 'xxx'@'%' IDENTIFIED BY 'yyy';

What is the equivalent command or series of commands in PostgreSQL?
I tried...
postgres=# CREATE ROLE xxx LOGIN PASSWORD 'yyy';
postgres=# GRANT SELECT ON DATABASE mydb TO xxx;

But it appears that the only things you can grant on a database are CREATE, CONNECT, TEMPORARY, and TEMP.

A: Grant usage/select to a single table
If you only grant CONNECT to a database, the user can connect but has no other privileges. You have to grant USAGE on namespaces (schemas) and SELECT on tables and views individually like so:
GRANT CONNECT ON DATABASE mydb TO xxx;
-- This assumes you're actually connected to mydb..
GRANT USAGE ON SCHEMA public TO xxx;
GRANT SELECT ON mytable TO xxx;

Multiple tables/views (PostgreSQL 9.0+)
In the latest versions of PostgreSQL, you can grant permissions on all tables/views/etc in the schema using a single command rather than having to type them one by one:
GRANT SELECT ON ALL TABLES IN SCHEMA public TO xxx;

This only affects tables that have already been created. More powerfully, you can automatically have default roles assigned to new objects in future:
ALTER DEFAULT PRIVILEGES IN SCHEMA public
   GRANT SELECT ON TABLES TO xxx;

Note that by default this will only affect objects (tables) created by the user that issued this command: although it can also be set on any role that the issuing user is a member of. However, you don't pick up default privileges for all roles you're a member of when creating new objects... so there's still some faffing around. If you adopt the approach that a database has an owning role, and schema changes are performed as that owning role, then you should assign default privileges to that owning role. IMHO this is all a bit confusing and you may need to experiment to come up with a functional workflow.
Multiple tables/views (PostgreSQL versions before 9.0)
To avoid errors in lengthy, multi-table changes, it is recommended to use the following 'automatic' process to generate the required GRANT SELECT to each table/view:
SELECT 'GRANT SELECT ON ' || relname || ' TO xxx;'
FROM pg_class JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace
WHERE nspname = 'public' AND relkind IN ('r', 'v', 'S');

This should output the relevant GRANT commands to GRANT SELECT on all tables, views, and sequences in public, for copy-n-paste love. Naturally, this will only be applied to tables that have already been created.

A: From PostgreSQL v14 on, you can do that simply by granting the predefined pg_read_all_data role:
GRANT pg_read_all_data TO xxx;

A: Do note that PostgreSQL 9.0 (today in beta testing) will have a simple way to do that:
test=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO joeuser;

A: If your database is in the public schema, it is easy (this assumes you have already created the readonlyuser)
db=> GRANT SELECT ON ALL TABLES IN SCHEMA public to readonlyuser;
GRANT
db=> GRANT CONNECT ON DATABASE mydatabase to readonlyuser;
GRANT
db=> GRANT SELECT ON ALL SEQUENCES IN SCHEMA public to readonlyuser;
GRANT

If your database is using customschema, execute the above but add one more command:
db=> ALTER USER readonlyuser SET search_path=customschema, public;
ALTER ROLE

A: The not straightforward way of doing it would be granting select on each table of the database:
postgres=# grant select on db_name.table_name to read_only_user;

You could automate that by generating your grant statements from the database metadata.

A: Here is the best way I've found to add read-only users (using PostgreSQL 9.0 or newer):
$ sudo -upostgres psql postgres
postgres=# CREATE ROLE readonly WITH LOGIN ENCRYPTED PASSWORD '<USE_A_NICE_STRONG_PASSWORD_PLEASE';
postgres=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;

Then log in to all related machines (master + read-slave(s)/hot-standby(s), etc..) and run:
$ echo "hostssl <PUT_DBNAME_HERE> <PUT_READONLY_USERNAME_HERE> 0.0.0.0/0 md5" | sudo tee -a /etc/postgresql/9.2/main/pg_hba.conf
$ sudo service postgresql reload

A: By default new users will have permission to create tables. If you are planning to create a read-only user, this is probably not what you want.
To create a true read-only user with PostgreSQL 9.0+, run the following steps:
# This will prevent default users from creating tables
REVOKE CREATE ON SCHEMA public FROM public;

# If you want to grant a write user permission to create tables
# note that superusers will always be able to create tables anyway
GRANT CREATE ON SCHEMA public to writeuser;

# Now create the read-only user
CREATE ROLE readonlyuser WITH LOGIN ENCRYPTED PASSWORD 'strongpassword';
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonlyuser;

If your read-only user doesn't have permission to list tables (i.e. \d returns no results), it's probably because you don't have USAGE permissions for the schema. USAGE is a permission that allows users to actually use the permissions they have been assigned. What's the point of this? I'm not sure. To fix:
# You can either grant USAGE to everyone
GRANT USAGE ON SCHEMA public TO public;

# Or grant it just to your read only user
GRANT USAGE ON SCHEMA public TO readonlyuser;

A: Reference taken from this blog:
Script to Create Read-Only user:
CREATE ROLE Read_Only_User WITH LOGIN PASSWORD 'Test1234'
NOSUPERUSER INHERIT NOCREATEDB NOCREATEROLE NOREPLICATION VALID UNTIL 'infinity';
\connect YourDatabaseName;

Assign permission to this read-only user:
GRANT CONNECT ON DATABASE YourDatabaseName TO Read_Only_User;
GRANT USAGE ON SCHEMA public TO Read_Only_User;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO Read_Only_User;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO Read_Only_User;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;

Assign permissions to read all newly tables created in the future
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO Read_Only_User;

A: I’ve created a convenient script for that; pg_grant_read_to_db.sh. This script grants read-only privileges to a specified role on all tables, views and sequences in a database schema and sets them as default.

A: I read trough all the possible solutions, which are all fine, if you remember to connect to the database before you grant the things ;) Thanks anyway to all other solutions!!!
user@server:~$ sudo su - postgres

create psql user:
postgres@server:~$ createuser --interactive
Enter name of role to add: readonly
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) n
Shall the new role be allowed to create more new roles? (y/n) n

start psql cli and set a password for the created user:
postgres@server:~$ psql
psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)
Type "help" for help.

postgres=# alter user readonly with password 'readonly';
ALTER ROLE

connect to the target database:
postgres=# \c target_database
psql (10.6 (Ubuntu 10.6-0ubuntu0.18.04.1), server 9.5.14)
You are now connected to database "target_database" as user "postgres".

grant all the needed privileges:
target_database=# GRANT CONNECT ON DATABASE target_database TO readonly;
GRANT

target_database=# GRANT USAGE ON SCHEMA public TO readonly ;
GRANT

target_database=# GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly ;
GRANT

alter default privileges for targets db public shema:
target_database=# ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;
ALTER DEFAULT PRIVILEGES

A: Taken from a link posted in response to despesz' link.
Postgres 9.x appears to have the capability to do what is requested.  See the Grant On Database Objects paragraph of:
http://www.postgresql.org/docs/current/interactive/sql-grant.html
Where it says: "There is also an option to grant privileges on all objects of the same type within one or more schemas. This functionality is currently supported only for tables, sequences, and functions (but note that ALL TABLES is considered to include views and foreign tables)."
This page also discusses use of ROLEs and a PRIVILEGE called "ALL PRIVILEGES".
Also present is information about how GRANT functionalities compare to SQL standards.

A: CREATE USER username SUPERUSER  password 'userpass';
ALTER USER username set default_transaction_read_only = on;


Q: MongoDB Conditional Projection based on existence of query of subdocument in Array I have a schema in which properties can have respective "override" documents stored in an Array("overrides")
E.g.
{
    foo:'original foo',
    overrides: [
        {property:'foo', value:'foo override'},
        {property:'bar', value:'bar override'},
    ]
}

I want to project a field for the override value if it exists, otherwise, the original property.
So something like this
project: { overrideOrOriginal: {$cond: fooOverrideExists ? fooOverrideValue : originalFooValue }

So in this example, I would expect overrideOrOriginal to equal 'foo override' . If -  {property:'foo', value:'foo override'} subDoc didn't exist in the overrides array (or if overrides array itself didn't even exist)...then I'd expect overrideOrOriginal = 'original foo'
How can I do this?
I was thinking I'd need $exists in tandem with $cond. But the complication here is that I'm searching for a subDoc in an Array based on a query
Thanks!

A: *

*$ifNull to check if field is null then return empty array

*$in to check "foo" is in overrides.property array

*$indexOfArray to get index of array element in overrides.property array

*$arrayElemAt to get element by specific index return from above operator

let fooOverrideExists = "foo";
db.collection.find({},
{
  overrideOrOriginal: {
    $cond: [
      {
        $in: [
          fooOverrideExists,
          { $ifNull: ["$overrides.property", []] }
        ]
      },
      {
        $arrayElemAt: [
          "$overrides.value",
          { $indexOfArray: ["$overrides.property", fooOverrideExists] }
        ]
      },
      "$foo"
    ]
  }
})

Playground

A: Query

*

*find the property , key-value(kv) (it works for all property names)
(assumes your schema with only string value the value of that   property)

*checks if that it exists in the overrides array

*if it exists, takes the value from the array

*else keeps the original

*checks also cases where override doesnt exists, or its empty array, or property doesn't exist
*in case you want to do it only for a specific "foo" ignore the big first $set and use this code
Test code here
db.collection.aggregate([
  {
    "$set": {
      "kv": {
        "$arrayElemAt": [
          {
            "$filter": {
              "input": {
                "$objectToArray": "$$ROOT"
              },
              "cond": {
                "$eq": [
                  {
                    "$type": "$$this.v"
                  },
                  "string"
                ]
              }
            }
          },
          0
        ]
      }
    }
  },
  {
    "$set": {
      "index": {
        "$indexOfArray": [
          "$overrides.property",
          "$kv.k"
        ]
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "overrideOrOriginal": {
        "$cond": [
          {
            "$or": [
              {
                "$eq": [
                  "$index",
                  -1
                ]
              },
              {
                "$not": [
                  "$overrides"
                ]
              }
            ]
          },
          "$kv.v",
          {
            "$arrayElemAt": [
              "$overrides.value",
              "$index"
            ]
          }
        ]
      }
    }
  }
])


Q: Using OpenCV to take a particular amount of images without pressing any key I wish to write a program for face recognition. I want my program to automatically take a specific number of images(say,5). Here is what I am currently doing:
import cv2

cam=cv2.VideoCapture(0)
a=0
count=0
for a in range(5):
    ret,img=cam.read()

    cv2.imshow("Test",img)

    if not ret:
        break

    k=cv2.waitKey(1)

    print("Image"+str(count)+"saved")
    file='C:/Users/User/Desktop/FACEREC/known_faces/img_test/ad2'+str(count)+'.jpg'
    cv2.imwrite(file,img)
    a+=1

cam.release()
cv2.destroyAllWindows()

cam.release()
cv2.destroyAllWindows()

It shows "Image 0 saved" five times but in the folder(ad2), there is only a single image. Need some guidance.
Thank you

A: Lets start interpreting the code line-by-line:

*

*

*

*Variable initialization

*

*
import cv2

cam=cv2.VideoCapture(0)
a=0
count=0

*You load the opencv library and initialize the cam variable for webcam display. Then both a and count are intialized to 0. Now count variable is understandable, most probably count count the frames. What does a do?

*

*Display and save frames

*

*First-part

*
for a in range(0, 5):
    ret,img=cam.read()
    cv2.imshow("Test",img)

    if not ret:
        break

*variable a declared again so we don't need to intialize at the beginning. Then current web-frame is being fetched. The frame is given as an input to imshow without even the current frame returned or not. The correct logic should be:

*
for a in range(5):
    ret,img=cam.read()

    if ret:
        cv2.imshow("Test",img)

*Second-part

*
k=cv2.waitKey(1)

print("Image"+str(count)+"saved")
file='C:/Users/User/Desktop/FACEREC/known_faces/img_test/ad2'+str(count)+'.jpg'
cv2.imwrite(file,img)
a+=1

*Now, the k variable is initialized as a key for quiting the program when a key is pressed. Say, when q is pressed program terminates.

*
k=cv2.waitKey(1) & 0xFF

if k == ord('q'):
     break

*But if you break during the process, then you can't save the images. Therefore break should be at the end of the line.

*For the rest of the code, you can use a as a counter. If you specify the start and end values. For each value a is increased by one. Then you can use it to discriminate the frames.

Code:
# Load the library
import cv2

# Initialize webcam
cam = cv2.VideoCapture(0)

# Save the frames
for a in range(0, 5):

    # Get current frame
    ret, img=cam.read()

    # If frame is returned
    if ret:

        # Set the file-name
        file='C:/Users/User/Desktop/FACEREC/known_faces/img_test/ad2' + str(a) + '.jpg'

        # Write the frame
        cv2.imwrite(file, img)

        # Inform the user
        print("Image" + str(a) + "saved")

        # Display the frame
        cv2.imshow("Test", img)

        # If q is pressed quit
        k=cv2.waitKey(1) & 0xFF
        if k == ord('q'):
            break

# Release the object
cam.release()

# Close the window
cv2.destroyAllWindows()


Q: Gradle Script To call a REST Web service without any 3rd party plugins, any pointers? Hi I need to call a REST service as part of the buildscript (Gradle) without any 3rd party plugins, how could I use Groovy to do that?
(My first attempt)
repositories {
    mavenCentral()
}
      dependencies {
            complie "org.codehaus.groovy.modules.http-builder:http-builder:0.5.2"
    }

task hello {
    def http = new HTTPBuilder("http://myserver.com:8983/solr/select?q=*&wt=json")
    http.auth.basic 'username', 'password'
    http.request(GET, JSON ) { req ->
    }
}

A: I'm using the JsonSlurper it looks quite simple and OS independent:
import groovy.json.JsonSlurper

String url = "http://<SONAR_URL>/api/qualitygates/project_status?projectKey=first"
def json = new JsonSlurper().parseText(url.toURL().text)
print json['projectStatus']['status']

A: Can't you just do
new URL( 'http://username:password@myserver.com:8983/solr/select?q=*&wt=json' ).text

A: Java has had a proper HTTP Client in the standard library since Java 9.
Here's how you can use that from a Gradle script (Groovy):
import groovy.json.JsonSlurper

import java.net.http.*
import static java.nio.charset.StandardCharsets.UTF_8

tasks.register('hello') {
    def url = new URL("http://myserver.com:8983/solr/select?q=*&wt=json")
    def req = HttpRequest.newBuilder(url.toURI()).GET().build()
    def res = HttpClient.newHttpClient()
       .send(req, HttpResponse.BodyHandlers.ofString(UTF_8))
    def parsedJson = new JsonSlurper().parseText(res.body())
    println parsedJson
}

A: this is working guys
import java.io.*
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.EncoderRegistry
import static groovyx.net.http.Method.*
import static groovyx.net.http.ContentType.*

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.codehaus.groovy.modules.http-builder:http-builder:0.5.2'
    }
}

task hello {
    def http = new groovyx.net.http.HTTPBuilder("http://local.com:8983/solr/update/json")

    http.request(POST, JSON ) { req ->
        req.body{

        }
        response.success = { resp, reader ->
            println "$resp.statusLine   Respond rec"

        }
    }
}

A: This question is ranking so well on search engines that I keep stumbling on it.
However, as others commented, I don't really like the accepted answer because it relies on curl.
So here is a complete example w/o any prerequisite (no plugin, no curl, ...):
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
task getExample {
    doLast {
        def req = new URL('https://jsonplaceholder.typicode.com/posts/1').openConnection()
        logger.quiet "Status code: ${req.getResponseCode()}"
        def resp = new JsonSlurper().parseText(req.getInputStream().getText())
        logger.quiet "Response: ${resp}"
    }
}
task postExample {
    doLast {
        def body = [title: "foo", body: "bar", userId: 1]
        def req = new URL('https://jsonplaceholder.typicode.com/posts').openConnection()
        req.setRequestMethod("POST")
        req.setRequestProperty("Content-Type", "application/json; charset=UTF-8")
        req.setDoOutput(true)
        req.getOutputStream().write(JsonOutput.toJson(body).getBytes("UTF-8"))
        logger.quiet "Status code: ${req.getResponseCode()}" // HTTP request done on first read
        def resp = new JsonSlurper().parseText(req.getInputStream().getText())
        logger.quiet "Response: ${resp}"
    }
}

You can run this on your box as they use a public development API.

A: The easiest way to call REST from groovy without external libraries is executing CURL. Here's an example of calling Artifactory, getting JSON back and parsing it:
import groovy.json.JsonSlurper

task hello {
    def p = ['curl', '-u', '"admin:password"', "\"http://localhost:8081/api/storage/libs-release-local?list&deep=1\""].execute()
    def json = new JsonSlurper().parseText(p.text)
}

A: The solution using Kotlin DSL and Fuel HTTP Client:
import com.github.kittinunf.fuel.httpPost
import com.github.kittinunf.result.Result

buildscript {
    dependencies {
        "classpath"("com.github.kittinunf.fuel:fuel:2.3.1")
    }
}

tasks {
    register("post") {
        val (request, response, result) = "https://httpbin.org/post".httpPost().responseString()
        if (result is Result.Success) {
            println(result.get())
        }
    }
}


Q: Quickly finding custom class in xib file I am in a kind of situation to check if any of components (say UILabel) in my nib file specified custom class in identity inspector.
Currently the only way to find out is to go and check each component in every xib, is there any way we can search for it, similar to way where we can search for the occurrence of particular class in the Xcode, and the Xcode will quickly tell us which xib file contains the UILabel of that specific custom classes.

A: Currently I would suggest to use command grep in terminal(Xcode could not search .xib file):
grep -i -r --include=*.xib "TextToFindHere" /PathToSearchHere

Another way is to right click your .xib file and Open As Source Code and use Command+F to search. But this method can only search one file a time.


Q: TypeError: Cannot read property 'quote' of undefined React js Just to summarise, I'm creating a quote-generator using React js. The data is getting fetched from a mock API using React axios.
However, when I'm trying to display the quote it gives me that above error
line where I get error: {quotes[quoteIndex].quote}
(quotes) gets populated with the data
(quoteIndex) is basically an index in an array
(.quote) is the attribute from the data
Please find the relevant code
// sample from .json file data
"quotes": [
    {
    "id":0,
    "quote": "Genius is one percent inspiration and ninety-nine percent perspiration.",
    "author": "Thomas Edison"
  },
  {
    "id":1,
    "quote": "You can observe a lot just by watching.",
    "author": "Yogi Berra"
  }
 ]
}

const [quotes, setQuotes] = useState([]);
const [quoteIndex, setQuoteIndex] = useState(0);

// fetching the data
const getData = async() =>{
        try{
            const response = await Axios.get("/quotes");

            if(response && response.data){
                setQuotes(response.data);
                console.log(response.data);
            }

        }catch(error){
            console.log(error);
        }

    }

//this inside the return statement

{quotes[quoteIndex].quote}

A: This is a very common problem when dealing with data that is loaded asynchronously.
Here's how I would suggest debugging this to understand your problem:

*

*Remove the offending code so that you can observe what's happening.

*Add console.log(quotes) in your component. You will see that it logs [] and then again with your array.

*Next add console.log(quotes[quoteIndex]). Notice that it logs undefined and then an object.
Consider that while the value is undefined, you cannot treat it like an object and attempt to access properties on it.

*Add a check to make sure the value is an object before using it:

// Nullsafe operator
quotes[quoteIndex]?.quote
// Or ternary
quotes[quoteIndex] ? quotes[quoteIndex].quote : null

Here is a simulated example:

const async_quotes = [
  {
    "id":0,
    "quote": "Genius is one percent inspiration and ninety-nine percent perspiration.",
    "author": "Thomas Edison"
  },
  {
    "id":1,
    "quote": "You can observe a lot just by watching.",
    "author": "Yogi Berra"
  }
 ]

const {useState, useEffect} = React;

const index = 1;

const Example = () => {
  const [quotes, setQuotes] = useState([]);

   useEffect(() => {
     setTimeout(() => {
       setQuotes(async_quotes);
     }, 3000);
   }, []);

   console.log("quotes:", quotes);
   console.log("single quote:", quotes[index]);

   return
{quotes[index] ? quotes[index].quote : ''}

}

ReactDOM.render(<Example />, document.getElementById('root'));


Q: Stop the Banner and Profile picture get change on MouseOver I have a MVC project which has a Banner in _Layout.cshtml

and a Img tag to get the Profile Pic according to the currect logges user

and I have implemented Rating with Jason

My Issue Is whe I run the Program My Banner and Profile picture also get changed into Empty or Filled Starts when it runs over/Out mouse pointer..
Please help me to stop the Banner and Profile picture get change on MouseOver

A: Short Answer :
Add a class to the images for rating, say a class "rating" and then replace $("img") with  $("img.rating")
Long Answer :
Ok, the jquery selector you are using is this $("img") which says select all images from the page. Hence the problem.
Now what you should do,
As you want to have the jquery run only for the 5 Rating images, you can have all the images have a common class like as shown below..

and Now you can use your code like this...

A: Brilliant..... Thanks a lot Yasser... Code required a bit fixes but thanks to u now its working. Bellow I have given the working code.. its almost the same code u hv corrected for me but with capital letters in necessary places.

Yahooo .. Thanks a lot


Q: Stream_get_contents() not working with Cron Job I have a script called index.php "public_html" folder in my host (see below for script content). A cronjob executes the "index.php" file once per minute.
$handle = fopen('example.com', 'r');
$source= stream_get_contents($handle);
echo $source;
fclose($handle);

The problem is every time "index.php" is executed using the cronjob, $source will be '' (an empty string)!
But when I manually execute index.php using Firefox and refreshing it's tab, $source will be a string including the html source codes of example.com
Is there any restriction settings in my web-host or somewhere else, preventing stream_get_contects() to log websites information?


Q: Windows Server 2003: Any disadvantages to moving website outside of wwwroot? My boss recently asked me if I could move our website outside of the wwwroot folder and place it into "C:\MySite", on windows server 2003.  I tried doing so, and setting this up in IIS 6, but had no luck.  The website wouldn't start up, so I placed the site back into wwwroot.
So I have 2 questions: One, is there any disadvantage to moving a website outside of the wwwroot folder?  I found it peculiar the site works fine in wwwroot, but won't start outside of it...and two, if there's no disadvantage, how can I get IIS to run the website properly if outside wwwroot?
Thanks.

A: Site can be anywhere, especially  on local machine. Check if

*

*you copied all files to new location

*you changed location of the root of the site in IIS Manager (Start->run->inetmgr)

*check event log for any errors

*check if accoutn app pool for the site runs under have permissions to read from new folder.

A: It is quite simple and easy. Follow the steps here: http://support.microsoft.com/kb/172138
or http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5adfcce1-030d-45b8-997c-bdbfa08ea459.mspx?mfr=true


Q: In Rails, how do I output my date as a time in milliseconds in my CSV file? I'm using Rails 5.0.1.  I use the following code to output my table data to CSV form ...
  def self.to_csv(from_date, to_date)
    attributes = %w{index_date value} #customize columns here
    values = CryptoIndexValue.where('index_date >= ? and index_date <= ?', from_date, to_date)
                                     .order(index_date: :desc)

    CSV.generate(headers: true) do |csv|
      csv << attributes

      values.each do |value|
        csv << attributes.map{ |attr| value.send(attr) }
      end
    end
  end

The problem is, when my date (a PostGres 9.5 timestamp column) is output, it is output as
2017-08-01 20:00:09 UTC

I would like it to get output as the time in milliseconds.  How can I adjust the above to output my time as a time in milliseconds rather than the default date format?

A: You can simply call .to_i on a DateTime object:
timestamp = DateTime.now.to_i
# => 1501617998
DateTime.strptime(timestamp.to_s, '%s')
# => Tue, 01 Aug 2017 20:07:10 +0000

The timestamp is the seconds since Epoch. Multiply it by a thousand and you get milliseconds.
In your case, you must make a hook for this case:
attr_values = attributes.map do |attr|
  attr_value = value.send(attr)
  attr_value = attr_value.to_i * 1000 if attr_value.is_a?(DateTime)
  attr_value
end
csv << attr_values

This means everytime an attribute returns a DateTime object, it will be converted to a timestamp * 1000. If you want to filter only few attrs to convert DateTime -> Timestamp, test the attr with a whitelist instead of testing attr_value's class.


Q: what login should I keep for app (for appstore approval) I have created an app for Real estate where there are 4 sections.

*

*Home (where list of rent and sale are shown)

*Admin (admin can login and enter data)

*Search

*More
Now I will be uploading this app on the app store.
For Admin section, what username and password should I keep so that Apple team can login into those for review purpose. Once approved, I will delete that user.
Is there default username and password for Apple for review purpose?
I am asking as while submitting the app, I cannot write username and password anywhere so that we can tell to Review team.

A: You need to decide yourself what is the username and password you want Apple to use for review. When you submit the app or update the app, there is a section where you can supply those information, under App Review Information:


Q: Adding extenal library to compiler toolchain for ARM I have downloaded compiler tool chain for ARM Target.
My host machine: Linux
Target H/w : ARM7
But i need to add some additional library with that tool chain.
I need to know how to add new library to existing tool chain?
Thanks
Hari


Q: Custom Django field does not return Enum instances from query I have a simple custom field implemented to utilize Python 3 Enum instances. Assigning enum instances to my model attribute, and saving to the database works correctly. However, fetching model instances using a QuerySet results in the enum attribute being a string, instead of the respective Enum instance.
How do I get the below EnumField to return valid Enum instances, rather than strings?
fields.py:
from enum import Enum

from django.core.exceptions import ValidationError
from django.db import models

class EnumField(models.CharField):
    description = 'Enum with strictly typed choices'

    def __init__(self, enum_class, *args, **kwargs):
        self._enum_class = enum_class
        choices = []
        for enum in self._enum_class:
            title_case = enum.name.replace('_', ' ').title()
            entry = (enum, title_case)
            choices.append(entry)
        kwargs['choices'] = choices
        kwargs['blank'] = False  # blank doesn't make sense for enum's
        super().__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super().deconstruct()
        args.insert(0, self._enum_class)
        del kwargs['choices']
        return name, path, args, kwargs

    def from_db_values(self, value, expression, connection, context):
        return self.to_python(value)

    def to_python(self, value):
        if value is None or isinstance(value, self._enum_class):
            return value
        else:
            return self._parse_enum(value)

    def _parse_enum(self, value):
        try:
            enum = self._enum_class[value]
        except KeyError:
            raise ValidationError("Invalid type '{}' for {}".format(
                value, self._enum_class))
        else:
            return enum

    def get_prep_value(self, value):
        if value is None:
            return None
        elif isinstance(value, Enum):
            return value.name
        else:
            msg = "'{}' must have type {}".format(
                value, self._enum_class.__name__)
            if self.null:
                msg += ', or `None`'
            raise TypeError(msg)

    def get_choices(self, **kwargs):
        kwargs['include_blank'] = False  # Blank is not a valid option
        choices = super().get_choices(**kwargs)
        return choices

A: After a lot of digging, I was able to answer my own question:
SubfieldBase has been deprecated, and will be removed in Django 1.10; which is why I left it out of the implementation above. However, it seems that what it does is still important. Adding the following method to replaces the functionality that SubfieldBase would have added.
def contribute_to_class(self, cls, name, **kwargs):
    super(EnumField, self).contribute_to_class(cls, name, **kwargs)
    setattr(cls, self.name, Creator(self))

The Creator descriptor is what calls to_python on attributes. If this didn't happen, querys on models would result in the EnumField fields in the model instances being simply strings, instead of Enum instances like I wanted.


Q: Flutter: How to draw a star I am trying to custom my container shape to look like this:

I tried to do it with customPaint but I don't know very well this widget so I need help.
How can I draw a shape like this? Is customPaint the right solution?

A: You can copy paste run full code below
modified code of package https://pub.dev/packages/flutter_custom_clippers 's
StarClipper https://github.com/lohanidamodar/flutter_custom_clippers/blob/master/lib/src/star_clipper.dart
code snippet
class StarClipper extends CustomClipper<Path>
 @override
   Path getClip(Size size) {
     ...
     double radius = halfWidth / 1.3;
...
Container(
      height: 200,
      width: 200,
      child: ClipPath(
        clipper: StarClipper(14),
        child: Container(
          height: 150,
          color: Colors.green[500],
          child: Center(child: Text("+6", style: TextStyle(fontSize: 50),)),
        ),
      ),
    ),

working demo

full code
import 'package:flutter/material.dart';
import 'dart:math' as math;

class StarClipper extends CustomClipper<Path> {
  StarClipper(this.numberOfPoints);

  /// The number of points of the star
  final int numberOfPoints;

  @override
  Path getClip(Size size) {
    double width = size.width;
    print(width);
    double halfWidth = width / 2;

    double bigRadius = halfWidth;

    double radius = halfWidth / 1.3;

    double degreesPerStep = _degToRad(360 / numberOfPoints);

    double halfDegreesPerStep = degreesPerStep / 2;

    var path = Path();

    double max = 2 * math.pi;

    path.moveTo(width, halfWidth);

    for (double step = 0; step < max; step += degreesPerStep) {
      path.lineTo(halfWidth + bigRadius * math.cos(step),
          halfWidth + bigRadius * math.sin(step));
      path.lineTo(halfWidth + radius * math.cos(step + halfDegreesPerStep),
          halfWidth + radius * math.sin(step + halfDegreesPerStep));
    }

    path.close();
    return path;
  }

  num _degToRad(num deg) => deg * (math.pi / 180.0);

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    StarClipper oldie = oldClipper as StarClipper;
    return numberOfPoints != oldie.numberOfPoints;
  }
}

void main() {
  runApp(MyApp());
}

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

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              height: 200,
              width: 200,
              child: ClipPath(
                clipper: StarClipper(14),
                child: Container(
                  height: 150,
                  color: Colors.green[500],
                  child: Center(child: Text("+6", style: TextStyle(fontSize: 50),)),
                ),
              ),
            ),

          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

A: I was trying to create Turkish flag for fun. Creating crescent was easy but creating star is not look easy. so I just tried to use my geometric and trigonometric knowledge to draw but no success. while continuing searching I encountered this link . Yeess I found what I look for. of course it was about different topic but functions was useful. so I reach my goal at the end of night.
So creating custom stars are possible with CustomPainter since now.  Because I m sleepy and tired of being awake whole night I share all of code block with no further explanation. You can adjust offsetts according to your need.  if any question. I m ready to answer. Enjoy coding.
 class TurkishFlagPaint extends CustomPainter {
      @override
      void paint(Canvas canvas, Size size) {
        // x and y coordinates of starting point

        final bx = 95;
        final by = 0;

        final paint = Paint();
        paint.color = Colors.white;
        final innerCirclePoints = 5; //how many edges you need?
        final innerRadius = 80 / innerCirclePoints;
        final innerOuterRadiusRatio = 2.5;
        final outerRadius = innerRadius * innerOuterRadiusRatio;

        List<Map> points =
            calcStarPoints(bx, by, innerCirclePoints, innerRadius, outerRadius);
        var star = Path()..moveTo(points[0]['x'], points[0]['y']);
        points.forEach((point) {
          star.lineTo(point['x'], point['y']);
        });

        canvas.drawPath(
          Path.combine(
            PathOperation.union,

            //this combine for crescent
            Path.combine(
              PathOperation.difference,
              Path()..addOval(Rect.fromCircle(center: Offset(-20, 0), radius: 80)),
              Path()
                ..addOval(Rect.fromCircle(center: Offset(2, 0), radius: 60))
                ..close(),
            ),
            star,// I also combine cresscent with star
          ),
          paint,
        );
      }

      //This function is life saver.
//it produces points for star edges inner and outer. if you need to //rotation of star edges.
// just play with - 0.3  value in currX and currY equations.

      List<Map> calcStarPoints(
          centerX, centerY, innerCirclePoints, innerRadius, outerRadius) {
        final angle = ((math.pi) / innerCirclePoints);
        var angleOffsetToCenterStar = 0;

        var totalPoints = innerCirclePoints * 2; // 10 in a 5-points star
        List<Map> points = [];
        for (int i = 0; i < totalPoints; i++) {
          bool isEvenIndex = i % 2 == 0;
          var r = isEvenIndex ? outerRadius : innerRadius;

          var currY =
              centerY + math.cos(i * angle + angleOffsetToCenterStar - 0.3) * r;
          var currX =
              centerX + math.sin(i * angle + angleOffsetToCenterStar - 0.3) * r;
          points.add({'x': currX, 'y': currY});
        }
        return points;
      }

      @override
      bool shouldRepaint(CustomPainter oldDelegate) => true;
    }

now you can use painter in a widget;
Center(
   child: CustomPaint(
       painter: TurkishFlagPaint(),
     ),
   ),

and the result will be like this :

A: Yes, CustomPaint is the right solution. You can calculate the Path (series of points around the Container) and then paint it with the drawPath method of the canvas.
For example, the path of a triangle would look like this:
return Path()
      ..moveTo(0, y)
      ..lineTo(x / 2, 0)
      ..lineTo(x, y)
      ..lineTo(0, y);

The Path starts at (0,y) (top-left), then a line to (x/2,0) (bottom-center) gets added and so on. This snipped was taken from this answer.

A: This code will help you build a centered star, to use it you just have to instantiate it in a ClipPath
import 'package:flutter/material.dart';
import 'dart:math' as math;

const STAR_POINTS = 5;

class StarClipper extends CustomClipper<Path> {
   @override
   Path getClip(Size size) {
   var centerX = size.width / 2;
   var centerY = size.height / 2;

   var path = Path();

   var radius = size.width / 2;
   var inner = radius / 2;
   var rotation = math.pi / 2 * 3;
   var step = math.pi / STAR_POINTS;

   path.lineTo(centerX, centerY - radius);

   for (var i = 0; i < STAR_POINTS; i++) {
    var x = centerX + math.cos(rotation) * radius;
    var y = centerY + math.sin(rotation) * radius;
    path.lineTo(x, y);
    rotation += step;

    x = centerX + math.cos(rotation) * inner;
    y = centerY + math.sin(rotation) * inner;
    path.lineTo(x, y);
    rotation += step;
  }

  path.lineTo(centerX, centerY - radius);
  path.close();

  return path;
 }

 @override
 bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}

///  Instance
ClipPath(
 clipper: StarClipper(),
 child: Container(
    color: Colors.red,
    width: 80,
    height: 80,
    ),
)


Q: How to avoid file content repetition zipfile I need to compress multiple xml files and I achieved this with lxml, zipfile and a for loop.
My problem is that every time I re run my function the content of the compressed files are repeating (being appended in the end) and getting longer. I believe that it has to do with the writing mode a+b. I thought that by using with open at the end of the code block the files would be deleted and no more content would be added to them. I was wrong and with the other modes I do not get the intended result.
Here is my code:
def compress_package_file(self):
   bytes_buffer = BytesIO()
   with zipfile.ZipFile(bytes_buffer, 'w') as invoices_package:
       i = 1
       for invoice in record.invoice_ids.sorted('sin_number'):
           invoice_file_name = 'Invoice_' + invoice.number + '.xml'
           with open(invoice_file_name, 'a+b') as invoice_file:
               invoice_file.write(invoice._get_invoice_xml().getvalue())
               invoices_package.write(invoice_file_name, compress_type=zipfile.ZIP_DEFLATED)
           i += 1
   compressed_package = bytes_buffer.getvalue()
   encoded_compressed_file = base64.b64encode(compressed_package)

My xml generator is in another function and works fine. But the content repeats each time I run this function. For example if I run it two times, the content of the files in the compressed file look something like this (simplified content):
<?xml version='1.0' encoding='UTF-8'?>
<invoice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="invoice.xsd">
    <header>
        <invoiceNumber>9</invoiceNumber>
    </header>
</facturaComputarizadaCompraVenta><?xml version='1.0' encoding='UTF-8'?>
<invoice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="invoice.xsd">
    <header>
        <invoiceNumber>9</invoiceNumber>
    </header>
</facturaComputarizadaCompraVenta>

If I use w+b mode, the content of the files are blank.
How should my code look like to avoid this behavior?

A: I suggest you do use w+b mode, but move writing to zipfile after closing the invoice XML file.
From what you wrote it looks as you are trying to compress a file that is not yet flushed to disk, therefore with w+b it is still empty at time of compression.
So, try remove 1 level of indent for               invoices_package.write line (I can't format code properly on mobile, so can't post whole section).


Q: odbc_exec error with progress I am using Codeigniter Database Active Record (ODBC Driver). The application run well. But starting this day, there are error when trying to fetch data from Progress database (connected via odbc). The error message:

Severity: Warning  --> odbc_exec() [function.odbc-exec]: SQL error:
  [DataDirect][ODBC Progress OpenEdge Wire Protocol driver]Unexpected
  Network Error.  ErrNum = 10054, SQL state 08S01 in SQLExecDirect
  D:\xampp\htdocs\wavinet2-permana\system\database\drivers\odbc\odbc_driver.php
  153

Error is in odbc_exec command. When I try to fetch data without using Codeigniter Active Record, it work. Data fetched. Trying to var_dump($this->db_odbc->conn_id) it return Resource. Network error ? I try to set up LinkedServer on my SQLServer and run the query generated by ActiveRecord, it work, data fetched successfully.
I'm confuse, what is another posibilities that cause the error ?

A: First make  certain that you have started up your database properly. There is a fairly substantial thread that has what sounds like it may be your problem here: http://www.progresstalk.com/showthread.php?116855-102B-ODBC-connection-Problem
Also something else to look at if you are running over SSL:

Change the data source PacketSize setting. The correct setting is 32.
PacketSize=32
On Windows this will require a registry edit to make this change.

See: http://knowledgebase.progress.com/articles/Article/8500


Q: How to avoid outside of request scope exception in silex application? After restructuring my silex1.2 application, I am now getting hit by:

exception 'RuntimeException' with message 'Accessed request service
  outside of request scope. Try moving that call to a before handler or
  controller.' in
  ../vendor/silex/silex/src/Silex/Application.php:150

I used to setup the appilcation's config this way:
$app = new Silex\Application();
$app->register(new ServiceControllerServiceProvider());
$app->register(new ConfigServiceProvider($configFile));
$fileFinder = new \Symfony\Component\Finder\Finder();
foreach ($fileFinder->in($configPath . 'country') as $file) {
   /* @var SplFileInfo $file */
    $app->register(new ConfigServiceProvider($file->getRealPath()));
}

I now wanted to replace the foreach loop by injecting a specific value which I get from the user's request. So I wanted to access $request->query->get('country'); yet I cannot since app['request'] is out of scope at that point.
I don't understand the error message, as in:

*

*When and why are request objects out of scope in silex?

*How am I supposed to move the call before handler and controllers when it is the very first thing I do on setting up my application?

Basically, I want to access request data early on on in order to get one value. How can I achieve that in order to bootstrap application accordingly?

A: You try to use Request before it is initialized, before $app->run().
You can manually initialize Request:
$app = new \Silex\Application();
$app['request'] = \Symfony\Component\HttpFoundation\Request::createFromGlobals();
.....
$app->run($app['request']);

or make lazy loading in service providers:
$app['object1'] = $app->share(function ($app) {
    return new Object1($app['request']->query->get('country'));
});
...

and somewhere in controller get these variable as $app['object1']


Q: Login page is not appearing when the session expires I have one project developed using codeigniter
In that when session expires I need to redirect to the login page.
controller file
//inherit the parent constructor
        parent::__construct();
    //check whether it is an ajax call or not
    if($this->input->is_ajax_request())
    {
        //check the session exist or not
        $status = $this->common_functions->verify_session('ajax_call');

        //if session doesnot exist
        if(! $status)
        {
            //return the json
            echo json_encode(array("session_timeout"=>"true", "msg"=>"
Session timed out.
 Please login once again."));

            //exit
            exit;
        }
    }
    else
    {
        //Initialize the private property
        $this->_section = '';

        //check the session exist or not
        $this->common_functions->verify_session();

    }

And in common function
I have the code to redirect into login page


Q: Google Auth Popup not working for React 17 App; Getting React warning is this why or how to fix? As shown in description, I am working on a React project and utilizing Firebase for Auth and popup is not firing but I think it might have to do with this warning from React. The warning I am getting from React is that Warning: Expected onClick listener to be a function, instead got a value of object type.
I have been researching this and trying to problem solve for 2 days. Any pointers would be greatly appreciated :) Thank you!!
Here is my Firebase Utils code for the auth:

const config = {
  My config info
};

firebase.initializeApp(config);

const provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({ prompt: 'select_account' });
export const signInWithGoogle = () => auth.signInWithPopup(provider)
.then(function (result) {
}).catch(error => {
  console.log(error);
})

export default firebase;

Now my Custom Button Component in React 17

import React from 'react';
import './custom-button.styles.scss';

const CustomButton = ({children, isGoogleSignIn, ...otherProps}) => (
    <button
      className={`${isGoogleSignIn ? 'google-sign-in' : ''} custom-button`}
      {...otherProps}>
        {children}
    </button>
);

export default CustomButton;

Lastly my signin component in React

lass SignIn extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            email: '',
            password: ''
        }
    }

    handleSubmit = event => {
        event.preventDefault();

        this.setState({ email: '', password: '' })
    }

    handleChange = event => {
        const { value, name } = event.target;

        this.setState({ [name]: value })
    }

    render() {
        return (

I already have an account

            Sign in with your email and password

        <form onSubmit={this.handleSubmit}>
          <FormInput
            name='email'
            type='email'
            handleChange={this.handleChange}
            value={this.state.email}
            label='email'
            required
          />
          <FormInput
            name='password'
            type='password'
            value={this.state.password}
            handleChange={this.handleChange}
            label='password'
            required
          />

            <CustomButton type='submit'> Sign in </CustomButton>
            <CustomButton onClick={signInWithGoogle} isGoogleSignIn>
                Sign in with Google
            </CustomButton>

        </form>

    );
  }
}

export default SignIn;

A: I finally figured this out. The firebase config file should have had a .then and .catch for the promise. Once I added this, it works fine now. I researched 3 days to figure this out. Taking a course, and the guy who produced this course didn't add this, although it was two years ago maybe it wasn't required then, but it is now.


Q: Upload JAR to Nexus OSS 3 I have just installed Nexus OSS 3.0.1-01 on my server and I don't know how to upload artifacts to my maven repository. I need to upload JDBC and other dependencies to it, but I cannot find how!
It seems there is no section "Upload artifacts" as Nexus 2.


Q: In Grails, is "property" a reserved word? In Grails, is "property" a reserved word? That is, can I name a domain class Property and have its owner reference it by properties? Example:
class Thing {
    static hasMany = [properties: Property]
}

class Property {
    static belongsTo = [thing: Thing]
}

When I try to add a Property to a Thing I get the error:
Exception thrown: No signature of method: org.codehaus.groovy.grails.web.binding.DataBindingLazyMetaPropertyMap.add() is applicable for argument types: (Property) values: [Property : null]

groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.grails.web.binding.DataBindingLazyMetaPropertyMap.add() is applicable for argument types: (Property) values: [Property : null]

    at ConsoleScript10.run(ConsoleScript10:3)

Is there a list of all Grails reserved words?

A: I'm not sure that Property is reserved, but properties is treated specially for domain classes since it's used for data binding. What happens when you change:
static hasMany = [properties: Property]

to something like
static hasMany = [myProperties: Property]

A: Grails is a web framework. In general, only languages really have reserved words. The reserved words of Groovy are all those reserved by Java, plus a few others. The complete list is shown here.
You'll notice that it does include "property", which was a big surprise to me, as I've no idea what it's used for, and I think/thought I know Groovy reasonably well. Perhaps it's reserved for future use?

A: While I cant find any file with the name Property in grails, it is wise not to use such a common word - who knows when it might become reserved in the future?
What would happen if you just prepended your classname with something, like BlahProperty?