text:
Q: Error when caching flutter engine with custom dart entrypoint I'm trying to cache and reuse a FlutterEngine with a custom entry point (method different than main in main.dart). It's working well on debug mode but on profile or release I got an error when I'm creating the flutter engine. I don't know what else I could do since it's working on debug mode and it seems that everything is correct.
This is the error that I'm getting
E/flutter (25371): [ERROR:flutter/shell/common/shell.cc(94)] Dart Unhandled Exception: NoSuchMethodError: No top-level getter 'mainLockScreen' declared.
E/flutter (25371): Receiver: top-level
E/flutter (25371): Tried calling: mainLockScreen, stack trace: #0      NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:218)
E/flutter (25371):
E/flutter (25371): [ERROR:flutter/runtime/dart_isolate.cc(718)] Could not resolve main entrypoint function.
E/flutter (25371): [ERROR:flutter/runtime/dart_isolate.cc(202)] Could not run the run main Dart entrypoint.
E/flutter (25371): [ERROR:flutter/runtime/runtime_controller.cc(384)] Could not create root isolate.
E/flutter (25371): [ERROR:flutter/shell/common/shell.cc(574)] Could not launch engine with configuration.

I already use @pragma in my custom entry point like that:
@pragma('vm:entry-point')
void mainLockScreen() {
  debugPrint("mainLock");
  .... custom code that runs runApp
}

And I'm caching the engine in MyApplication class (I defined it in AndroidManifest, the class looks like that):
package productivity.timetracker.mytime

import android.content.Context
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache

class LockScreenActivity : FlutterActivity() {

    override fun provideFlutterEngine(context: Context): FlutterEngine? =
        FlutterEngineCache.getInstance().get("LockScreenEngine")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
            setShowWhenLocked(true)
        } else {
            window.addFlags(
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
                        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
            )
        }
    }

    override fun getDartEntrypointFunctionName(): String = "mainLockScreen"
}

A: it seems as though multiple entrypoints are kinda broken right now in flutter version 2.8.1 ...
Here is a github issue talking about it.
https://github.com/flutter/flutter/issues/91841
I'm facing the same issue right now. In the thread people say that if you are using cached flutter engine this might help.
https://github.com/flutter/flutter/issues/91841#issuecomment-1006026551


text:
Q: Determining voltage and current in a circuit
The question asks to determine V_x and I_y.
I tried to find it by using KVL in to lower LHS mesh and KCL in the middle node. But, my final value is a contradictory statement(such as I_x equal all real numbers). Any help would be appreciated.
Using KCL in the central node, the current that passes through the 10 ohm resistor is -5-0.1V_x+y(where y is the current that goes through V_x/20 ohms resistor). Then I used KVL in lower LHS mesh, so -50-10(-5-0.1V_x+y)-V_x=0 As you can see V_x cancel and 10y=0 is left. However V_x=20y.

A: This problem is, I think, a good case for using superposition with dependent sources.
Zero all sources (including dependent sources) except for the 50V DC source.
Then, by voltage division and Ohm's Law:
\$V_x = -50V \dfrac{20}{10 + 20} =  -33.33V\$
\$I_y = \dfrac{50}{20 + 25} = 1.111A \$
Now, zero that source and enable the 5A current source.
Then, by inspection and current division:
\$V_x = 5A \cdot 20\Omega || 10 \Omega = 33.33V\$
\$I_y = 5A \cdot \dfrac{20}{20 + 25} =  2.222A\$
Now, zero that source and enable the 5Iy source.
Then, by inspection:
\$V_x = 0V \$
\$I_y = -\dfrac{5I_y}{20 + 25} =  -0.1111 \cdot I_y\$
Finally, zero that source and enable the 0.1Vx source.
Then, by inspection:
\$V_x = 0.1V_x \cdot 20\Omega || 10 \Omega = 0.6667 V_x \$
\$I_y = 0A \$
The sums of the associated four terms give the answers:
\$V_x = -33.33V + 33.33V + 0V + 0.6667V_x \rightarrow V_x = 0V  \$
\$I_y = 1.111A + 2.222A +0A - 0.1111 \cdot I_y \rightarrow I_y =  3A\$

A: KCL at the center node gives:
$$ \frac{-V_x-50}{10} + 5 + 0.1V_x + \frac{-V_x}{20} = 0 $$
Which is only an equation of \$V_x\$ and can be immediately solved to get \$V_x = 0\$.
KCL at the top node (with voltage \$V_T\$):
$$ \frac{V_T - 50}{20} - 5 + I_Y = 0 $$
Ohm's law on the 25 ohm resistor gives \$ I_Y = \frac{V_T - 5I_Y}{25} \implies V_T = 30I_Y\$. Using this in the preceeding equation gives:
$$ \frac{30I_Y - 50}{20} - 5 + I_Y = 0 \implies I_Y = 3 \text{A}$$

So, along with your own answer and Alfred Centauri's answer, we can conclude that your book's answer of \$V_X = 70 V\$ is incorrect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mysql 80 client setup Hi everyone I don't understand BSD . MySQL client setup error .Do not try to explain the cause of the error because I won't understand just code thank's.(my English is bad)
/usr/ports/databases/mysql80-client/work/mysql-
8.0.14/mysys/stacktrace.cc:258:11: error: use of undeclared identifier
'backtrace'
 int n = backtrace(addrs, array_elements(addrs));
       ^
/usr/ports/databases/mysql80-client/work/mysql-
8.0.14/mysys/stacktrace.cc:262:18: error: use of undeclared identifier
'backtrace_symbols'
 if ((strings = backtrace_symbols(addrs, n))) {
                ^
/usr/ports/databases/mysql80-client/work/mysql-
8.0.14/mysys/stacktrace.cc:268:5: error: use of undeclared identifier 'backtrace_symbols_fd'
backtrace_symbols_fd(addrs, n, fileno(stderr));
           ^
 3 errors generated.
*** [mysys/CMakeFiles/mysys.dir/stacktrace.cc.o] Error code 1

make[3]: stopped in /usr/ports/databases/mysql80-client/work/.build
 1 error

make[3]: stopped in /usr/ports/databases/mysql80-client/work/.build
*** [mysys/CMakeFiles/mysys.dir/all] Error code 2

make[2]: stopped in /usr/ports/databases/mysql80-client/work/.build
1 error

make[2]: stopped in /usr/ports/databases/mysql80-client/work/.build
*** [all] Error code 2

make[1]: stopped in /usr/ports/databases/mysql80-client/work/.build
1 error

make[1]: stopped in /usr/ports/databases/mysql80-client/work/.build
===> Compilation failed unexpectedly.
Try to set MAKE_JOBS_UNSAFE=yes and rebuild before reporting the failure to
the maintainer.
*** Error code 1

Stop.
make: stopped in /usr/ports/databases/mysql80-client
root@black:/usr/ports/databases/mysql80-client #

A: Install the binary package(as root)
# pkg install mysql80-client

See 4.4.3. Installing and Removing Packages.


text:
Q: Why does my AP get refilled in AC: Project Legacy? I've just started playing Assassin's Creed: Project Legacy and something has me mystified. I've figured out that the following gain me AP:

*

*Having the game open for 2 minutes (+1)

*Increasing maximum AP by 1 (+1)

*Increasing Security Level (refill)

However, sometimes when I log on I find my AP has completely refilled, and I don't know why. Am I supposed to get a full load of AP every day? Or is something not realising I've closed the game, and 1. above is clocking up overnight?

A: Actually, I think AP goes up by 1 every two minutes whether or not the game is open.
However, my mobile browser keeps the flash application open overnight without allowing it to run (i.e. the in-game counter doesn't tick down), and so when I reopen the page later I have the same AP. If I completely refresh the page, my AP increases properly.


text:
Q: How can I retrieve multiple websites asynchronously? Using the silverlight Windows Phone 8.1 Project
I'm trying to load data from a website. I have to authenticate at that site first however.
So I do a post to the Website, using a lightly modified version of the CookieAwareWebClient from here.
class CookieAwareWebClient : WebClient
{
    public CookieContainer Cookies = new CookieContainer();

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
            (request as HttpWebRequest).CookieContainer = Cookies;

        return request;
    }
}

Now I make a WebClient send a POST with Username and Password and continue getting my sites async and processing the site data in my DownloadStringCompleted-EventHandler.
So far so good.
Now I want to expand on that and get multiple websites.
I don't have to get them all at once, in fact it would be better to get them one after another.
But I don't know how to go at this.
My code so far:
using System;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Windows.Web.Http;
using Microsoft.Phone.Shell;
using StackOverflowApp.Resources;

namespace StackOverflowApp
{
    public partial class MainPage
    {
        private const string URL_DATES = @"/subsite/dates";
        private const string URL_RESULTS = @"/subsite/results";

        private readonly ApplicationBarIconButton btn;

        private int runningOps = 0;
        //Regex's to parse websites
        private readonly Regex regexDates = new Regex(AppResources.regexDates);
        private readonly Regex regexResults = new Regex(AppResources.regexResults);

        private readonly CookieAwareWebClient client = new CookieAwareWebClient();
        private int status;

        // Konstruktor
        public MainPage()
        {
            InitializeComponent();

            btn = ((ApplicationBarIconButton)ApplicationBar.Buttons[0]);

            // = application/x-www-form-urlencoded
            client.Headers[HttpRequestHeader.ContentType] = AppResources.ContentType;
            client.UploadStringCompleted += UploadStringCompleted;
            client.DownloadStringCompleted += DownloadStringCompleted;
        }

        private void GetSite()
        {
            const string POST_STRING = "name={0}&password={1}";

            var settings = new AppSettings();

            if (settings.UsernameSetting.Length < 3 || settings.PasswordSetting.Length < 3)
            {
                MessageBox.Show(
                    (settings.UsernameSetting.Length < 3
                        ? "Bitte geben Sie in den Einstellungen einen Benutzernamen ein\r\n" : string.Empty)
                    +
                    (settings.PasswordSetting.Length < 3
                        ? "Bitte geben Sie in den Einstellungen ein Kennwort ein\r\n" : string.Empty)
                );
                return;
            }

            LoadingBar.IsEnabled = true;
            LoadingBar.Visibility = Visibility.Visible;
            client.UploadStringAsync(
                new Uri(AppResources.BaseAddress + "subsite/login"),
                "POST",
                string.Format(POST_STRING, settings.UsernameSetting, settings.PasswordSetting));
        }

        private void LoadDates()
        {
            status = 0; //Termine
            runningOps++;

            client.DownloadStringAsync(new Uri(AppResources.BaseAddress + URL_DATES));
        }

        private void LoadResults()
        {
            status = 1; //Ergebnisse
            runningOps++;
            client.DownloadStringAsync(new Uri(AppResources.BaseAddress + URL_RESULTS));
        }

        private void DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            runningOps--;
            if (runningOps == 0)
            {
                //alle Operationen sind fertig
                LoadingBar.IsEnabled = false;
                LoadingBar.Visibility = Visibility.Collapsed;
                btn.IsEnabled = true;
            }
            if (e.Cancelled || e.Error != null) return;

            //Antwort erhalten
            var source = e.Result.Replace("\r", "").Replace("\n", "");
            switch (status)
            {
                case 0: //Termine geladen

                    foreach (Match match in regexDates.Matches(source))
                    {
                        var tb = new TextBlock();
                        var g = match.Groups;

                        tb.Text = string.Format(
                            "{1} {2} {3}{0}{4} {5}{0}{6}",
                            Environment.NewLine,
                            g[1].Value,
                            g[2].Captures.Count > 0 ? g[2].Value : string.Empty,
                            g[3].Captures.Count > 0 ? "- " + g[3].Value : string.Empty,
                            g[5].Value,
                            g[6].Captures.Count > 0 ? "bei " + g[6].Value : string.Empty,
                            (
                                g[7].Captures.Count > 0
                                    ? g[7].Value
                                    : string.Empty
                            )
                                +
                            (
                                g[8].Captures.Count > 0
                                    ? g[8].Value != g[4].Value
                                        ? g[8].Value + " != " + g[4].Value
                                        : g[8].Value
                                    : g[4].Captures.Count > 0
                                        ? g[4].Value
                                        : string.Empty
                            )
                            );

                        DatesPanel.Children.Add(tb);
                    }

                    break;

                case 1: //Ergebnisse geladen
                    foreach (Match match in regexResults.Matches(source))
                    {
                        var tb = new TextBlock();
                        var g = match.Groups;

                        tb.Text = string.Format(
                            "{1} {2} {3}{0}{4} {5}{0}{6}",
                            Environment.NewLine,
                            g[1].Value,
                            g[2].Captures.Count > 0 ? g[2].Value : string.Empty,
                            g[3].Captures.Count > 0 ? "- " + g[3].Value : string.Empty,
                            g[5].Value,
                            g[6].Captures.Count > 0 ? "bei " + g[6].Value : string.Empty,
                            (
                                g[7].Captures.Count > 0
                                    ? g[7].Value
                                    : string.Empty
                            )
                                +
                            (
                                g[8].Captures.Count > 0
                                    ? g[8].Value != g[4].Value
                                        ? g[8].Value + " != " + g[4].Value
                                        : g[8].Value
                                    : g[4].Captures.Count > 0
                                        ? g[4].Value
                                        : string.Empty
                            )
                            );

                        ResultsPanel.Children.Add(tb);
                    }

                    break;
                default:
                    return;
            }
        }

        void UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            //Login completed
            LoadDates();
            //THIS WOULD YIELD AN ERROR FROM THE WEBCLIENT SAYING IT ISNT SUPPORTING MULTIPLE ASYNC ACTIONS
            //LoadResults();
        }

        private async void ClickOnRefresh(object sender, EventArgs e)
        {
            var isUp = await IsUp();
            if (isUp)
                GetSite();
            else
                MessageBox.Show("Die Seite ist down! :(");

        }

        private void ClickOnSettings(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
        }

        private async Task<bool> IsUp()
        {
            btn.IsEnabled = false;
            const string ISUPMELINK = "http://www.isup.me/{0}";
            var data = await RequestData(string.Format(ISUPMELINK, AppResources.BaseAddress.Replace("https://", string.Empty)));
            var isUp = !data.Contains("It's not just you!");
            btn.IsEnabled = true;

            return isUp;
        }

        private async void ClickOnTestConnection(object sender, EventArgs e)
        {
            var isUp = await IsUp();
            MessageBox.Show(string.Format("Die Seite ist {0}! :{1}", isUp ? "up" : "down", isUp ? ")" : "("));
        }

        private static async Task<string> RequestData(string url)
        {
            using (var httpClient = new HttpClient())
                return await httpClient.GetStringAsync(new Uri(url));
        }
    }
}

What I tryed / What I expected / What did block that:

*

*My first thought was to let everything happen async and use await on all the requests.
So I did my research and found that WebClient has an new async/await implementation.
WebClient.DownloadStringTaskAsync however I can't find this method in my WebClient, so I assume there isn't an impementation for WP8.1 atm.

*2nd idea was to use the HttpClient.GetStringAsync(URI) methode which I use already and which supports async/await.
As I said, I need a Cookie to go with the request, so I did my research and found this.
However I can't find a HttpClientHandler and also no HttpClient.CookieContainer or equal attributes.

*I also tried waiting for one site to complete and then going to the next, but tbo I blocked my GUI thread and didn't want to struggle with writing the whole eventhandlers in separate threads and I don't know how to do so efficiently

A: Found a solution.
I can use the WebClient.DownloadStringTaskAsync, when I import the NUGET PACKAGE Microsoft Async.
This post made me think of nuget in the first place.


text:
Q: Display extra field of a many to many relationship inside a table I have been searching for a while but didn't find any solution to do the following.
I am trying to display a table containing list of let's say Users. It's not a big deal to display fields from users but it is more complicated for association fields. Let's say I have the following tables : User, Post and UserPosts, in UserPosts we have a flag main to indicate whether a given post is the user's main position or not.
In my datatable, I have to display user's information, it means fields in user table + his/her main post.
So far I have something like this :

        name
        FrstName
        Age
        Main position
        Action

           <c:forEach items="${listUsers}" var="user" varStatus="status">

                <c:out value="${user.name}" />
                <c:out value="${user.firstName}" />
                <c:out value="${user.age}" />
                <c:out value="Position here" />

                Delete
                Update

            </c:forEach>

I think for position I will have to retrieve from database main position of a given user in a given column, but then how to set this value (javascript, ajax?)
Am I thinking the wrong way, should I use the association class instead. By that I mean, retrieve all UserPosts where main field = true? And then iterate over userPosts instead of users, in that case, I will have something like this:
<c:forEach items="${listUserPosts}" var="userPost" varStatus="status">

            <c:out value="${userPost.user.name}" />
            <c:out value="${userPost.user.firstName}" />
            <c:out value="${userPost.user.age}" />
            <c:out value="${userPost.post.postName}" />

            Delete
            Update

</c:forEach>

It seems weird to me, maybe I'm wrong.

A: If I understand the layout of your data correctly, you have something like this:

If that's the case, you can structure your User object like this:
public class User {
  private int id;
  private String name;
  private String firstName;
  private int age;
  private Position mainPosition;
}

and your query would simply need to do a left join on the UserPosition that is marked as "main". That UserPosition would then join to the correct Position. Then your JSP would just need to check to see if your Position object was empty.
<c:forEach items="${listUsers}" var="user" varStatus="status">

    <c:out value="${user.name}" />
    <c:out value="${user.firstName}" />
    <c:out value="${user.age}" />

      <c:if test="empty ${user.position}">
        No main position
      </c:if>
      <c:if test="not empty ${user.position}">
        <c:out value="${user.position.title}" />
      </c:if>

      Delete
      Update

</c:forEach>


text:
Q: move up and down a treeview I'm populating a tkinter treeview in python using Os.walk() but after populating it I want to be able to reorder the tree leaves using buttons.
The command for moving up the tree works just fine (I want to be able to move multiple leaves at once)
def moveUp():
    leaves = Tree.selection()
    for i in leaves:
        Tree.move(i, Tree.parent(i), Tree.index(i)-1)

But when I reversed it to go down the tree I get a weird bug
def moveDown():
    leaves = Tree.selection()
    for i in leaves:
        Tree.move(i, Tree.parent(i), Tree.index(i)+1)

I can only move a single leaf down, if I select an odd number of leaves then the lowest one moves down, and if I pick an even number of leaves none of them move.

A: As suggested in the comments going through leaves in the reverse order using reversed() fixes the problem. (Would be a comment but I don't have the reputation)
def moveDown():
    leaves = Tree.selection()
    for i in reversed(leaves):
        Tree.move(i, Tree.parent(i), Tree.index(i)+1)

A: Note, for moveUp, reversing the leaves would result in nothing actually changing in the tree. Simply iterating through the leaves in order is the ticket.
def moveUp():
    leaves = Tree.selection()
    for i in leaves:
        Tree.move(i, Tree.parent(i), Tree.index(i)-1)


text:
Q: Creating multiple objects on one-to-one relationship Helo, I had stuck with this problem.
Just to make things simple i'll explain it shorter.
Student has_many   :grades
        belongs_to :class

Grade belongs_to   :student
      belongs_to   :rubric

Rubric belongs_to  :course
       has_many    :students, :through => :class

To create new grade we need to find existent students. We can call @class.students to do so. Also, grade should be created with rubric_id.
I've already found out how to do nested forms. But how to pass plural student id's to new grades?
How to build controller and view to do so?

A: (Arg, I can't format my question properly in the comments, so I have to use an answer. Bear with me please because I don't think it answers your question yet.)
I don't think your model is setup properly to achieve that. In the scenario you are asking, Student and Grade seems to be in many-to-many association. I.e. a student has many rubric, but a rubric has many students, both through grade (which is your association model). Did I understand this correct?
Class   has_many   :students
        has_many   :grades
        has_many   :rubrics, :through => :grade

Student has_many   :grades
        has_many   :rubrics, :through => :grade
        belongs_to :class

# A grade is a particular rubric assigned to a student for a particular class
Grade belongs_to   :student
      belongs_to   :rubric
      belongs_to   :class

Rubric belongs_to  :course
       has_many    :grades
       has_many    :students, :through => :grade

Let me know if my interpretation above is correct and I can follow up with an answer on the controller and the view. I recently did something very similar for another project.
EDIT: Now that we have clarified the problem, here's my suggested answer.
The goal is to assign multiple students for a rubric in a particular class.
There is no built-in methods that will support something like this so we will have to build the records and the association with the right controller action and form.
In Grades model we add this function:
  def self.checked?(class_id, student_id, rubric_id)
    Grade.find(:all, :conditions => {:class_id => class_id, :student_id => student_id, :rubric_id => rubric_id}).present?
  end
In the form_for :rubric, we create something like this:
<%= form_for @rubric do |f| %>
  <% for @class.students.each do |student| %>
  <%= fields_for :grades do |builder| %>
    <%= check_box_tag "grades[" + @class.id.to_s + "][]", rubric.id, Grade.checked?(@class.id, student.id, @rubric.id) %>
  <% end %>
  <%= f.submit "Save" %>
<% end %>

Now in the RubricsController's create action you should have a params[:grades] which is a hash with key [:class] whose value is should just be an array of student ids. Now you can create the grades object that associates these models since you have a rubric id (@rubric.id), a class id (@class.id) and an array of student ids.
I hope I didn't screw the code above since I had to change it from my current implementation. But looking at the console log of the rails server should allow you to figure out what parameters are passed when the above form is submitted and make adjustments.


text:
Q: cakephp2x Model, View,Controller Naming Conventions i am new in the cakephp2x and i dont know how to named the controller and view and model files in the cakephp 2x.
for the simple Event module i have
contoller : EventsController.php
model : Event.php
vide : Events  ( folder Name )

now this look like http://example.com/events
Now my i want the link look like this http://example.com/itemsbidders
for the above url i have named the file as below
controller : ItemsBiddersController.php
model : ItemBidder.php
view : ItemsBidders

but i am getting 404 page not found Error in this page.
so can you tell me my mistake. advice me for this issue
Thanks in advance

A: With HABTM link tables you order model names alphabetically and first model kept plural:
Controller : BiddersItemsController.php
Model : BiddersItem.php
View : BiddersItems

And URL now looks like this: http://example.com/bidders_items (with underscore to separate models).
Remember, first letter capitalised and singular for folders: Controller / Model / View
Now to get URL you want above, you will need to create a router declaration in your Config/routes.php file like:
Router::connect('/itemsbidders',
    array('controller' => 'bidders_items', 'action' => 'index'));


text:
Q: Laravel - CNAME + Subdomain Routing I have my routes set up as follows:
<?php

Route::group([
    'domain' => '{username}.u.'.env('APP_DOMAIN'),
], function () {
    Route::get('/', 'FrontendController@site');
});

Route::group([
    'domain' => env('APP_DOMAIN'),
], function () {
    // Regular site routes
});

Route::group([
    'domain' => '{domain}',
], function () {
    Route::get('/', 'FrontendController@domain');
});

What I'm trying to achieve is allowing users to have their own sites, e.g. hello.u.domain.com, and for those sites to also be served through a custom domain that is CNAME'd to their subdomain. Using the routing above, the wildcard subdomain works perfectly fine. However the custom domain routing is never hit; whenever a custom domain that is CNAME'd to the subdomain is visited, the regular site routes are used.
APP_DOMAIN is not the same as the custom domain, and I have $router->pattern('domain', '[a-z0-9.]+'); in my RouteServiceProvider.php to allow {domain} as a full domain name.

A: Unfortunately I did not get an answer to my comment. This answer assumes the problem is that normal default routes are used instead of routes with subdomain.
Example:
A user is visiting sub.website.com but route() returns website.com/blabla instead of sub.website.com/blabla
You can solve this by dynamically create the pattern for domain inside routes.php
// routes.php
$url_parameters = @explode(".", $_SERVER['HTTP_HOST']);

if (count($url_parameters) == 3)
{
    $pattern = '{subdomain}.{domain}.{tld}';
}
else
{
    $pattern = '{domain}.{tld}';
}

Route::group(['domain' => $pattern], function () {

    Route::get('/', [
        'as' => 'get_index',
        'uses' => 'HomeController@getIndex'
    ]);

}

By using this method you will create a problem with your route() and controller parameters.
route() problem
When calling the route() function while using this method you will get a missing argument error. The route() function expects you to give the {subdomain}.{domain}.{tld} parameters.
You can solve this by creating your own route function. I named it mdroute() (multi domain route).
function mdroute($route, $parameters = [])
{

    $data = [
        'domain' => \Request::route()->domain,
        'tld' => \Request::route()->tld
    ];

    $subdomain = \Request::route()->subdomain;

    if ($subdomain) $data['subdomain'] = $subdomain;

    // You can use mdroute('blabla', 'parameter')
    // or mdroute('blabla', ['par1' => 'parameter1', 'par2' => 'parameter2'])
    //
    if (is_array($parameters))
    {
        $data = array_merge($data, $parameters);
    }
    else
    {
        $data[] = $parameters;
    }

    return route($route, $data);

}

Controller problem
The parameters {sub}.{domain}.{tld} are always send to your controller. You can't access other parameters the way you are used to be.
Example:
// Domain = sub.webite.com

// Your route
//
Route::get('/post/{id}/{param2}', [
    'uses' => 'PostController@getIndex'
]);

// PostController
//
public function getIndex($id, $param2)
{

    // $id will be 'sub'
    // $param2 will be 'website'

}

You can solve this by accessing your parameter through the Request object.
public function getIndex(Request $request)
{

    $id = $request->id;

    $param2 = $reqeust->param2;

}

A: You can't have a wildcard on the whole domain, at least not with one wildcard. What you can do is the following:
Route::group([
    'domain' => '{domain}.{suffix}',
], function () {
    Route::get('/', 'FrontendController@domain');
});

Just make sure that this group is the last one in your routes file, it will act as a fallback group on domains and will serve the requests that don't match any of the previous domains.
Also I'd recommend using this package, it might be helpful for what you are trying to do.

A: This has been answered, at least partially, by myself here: Creating a route in Laravel using subdomain and domain wildcards
In short, you cannot make the whole domain a parameter in the routes file. Instead, you assign a middleware that will check the current domain, match it against your pre-defined list of allowed user domains and based on that - take some decision (eg. what method to hit in your controller).
Consider:
Route::group([
    'middleware' => 'domain-check',
], function () {
    Route::get('/', 'FrontendController@handle');
});

And then in your FrontendController:
public function handle(Request $request)
{
    // Information about the current user/domain is here
    $request->client;

    // An example - let's imagine that client object contains a view ID
    return response()->view($request->client->view);
}


text:
Q: BinarySearch on javascript alright then, given an ordered array, find the index of a specific element passed as parameter using the method known as binary search. In the event that the searched number is not found in the array return -1.
Example:
array = [1,2,3,4,5,6,7,8,9,10];
binarySearch (array, 2) -> Would return 1 since array [1] = 2
[Where 2 would be the number on which we want to know its position in the array]

i have tryed this
var binarySearch = function (array, target) {
  var start = 0;
  var end = array.length-1
  while (start <= end) {
    let mid=Math.floor((start + end)/2);
    if (array[mid]===target) {
      return true;
    } else if (array[mid] < target) {
      start = mid + 1;
    } else {
      end = mid - 1;
    }
  }
  return array;

}

but not working am doing something wrong ?
AssertionError: expected true to equal 4

      160 | });
      161 | it ('Should return 4 for array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if bu
sca 5 ', function () {
    > 162 | expect (binarySearch ([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)). to.equal (4);
      163 | });
      164 |
      165 | it ('It should return -1 if it can't find the value searched in the array', fun
ction () {

A: You should return an index or -1, not true or array. See the demo:

var array = [1,2,3,4,5,6,7,8,9,10];

var binarySearch = function (array, target) {
  var start = 0;
  var end = array.length-1
  while (start <= end) {
    let mid=Math.floor((start + end)/2);
    if (array[mid]===target) {
      return mid;
    } else if (array[mid] < target) {
      start = mid + 1;
    } else {
      end = mid - 1;
    }
  }
  return -1;
}

console.log(binarySearch(array, 2));


text:
Q: "Philippines" vs. "Filipino" Why is Filipino spelled with an F? Philippines is spelled with a Ph. Some have said that it's because in Filipino, Philippines starts with F; but if this is so, why did we only change the beginning of Philippines?

A: As this article in the Spanish Wikipedia notes:

El vocablo «Filipinas» deriva del nombre del rey Felipe II de España.

The Philippines were named for King Philip II of Spain. They were «Las Islas Filipinas», which was anglicized to the Philippine Islands.
The noun form retains the F (Filipino), while the adjective form uses Ph (Philippine Embassy).
(I've seen older texts in British English that referred to the natives as "Philippinos.")
As to why, there's this answer:

English never had a suitable equivalent for Filipino – a "Philippine,"
  "Philippian" or "Philippinian" probably just didn't sound right, so
  English adopted the Spanish word Filipino, retaining the letter F and
  the suffix, "ino."

It's interesting to note that the country's official appellation in Pilipino is Repúblika ng Pilipinas. The Pilipino Express article explains that as well.
Edit: Slate has another take on Filipino/Philippines, but still doesn't explain the discrepancy in spelling between the noun and adjective forms.


text:
Q: Let me search for my drafts If I start typing an answer, until I post it a draft is automatically saved.
How can I find these drafts?
If there isn't a way, can one please be created?

The use case I have is I might start creating a post on my phone, but realize that it requires a lot more typing/effort than the phone easily supports so I want to switch to a another bigger device laptop/desktop.
It can be quite hard to find a specific question using search, so when this happens I read the question ID, which is not that easy on a mobile phone (especially if the title is long) and manually type it in on my laptop.
It would be very handy to click on a "Drafts" button (if one existed) and quickly pick up where I left off.


text:
Q: Android Bluetooth LE Connection issue with other bluetooth devices First of all, there's no problem with iOS, but the problem occurs when the app is running on Androids.
There's a BLE device that does pair / notification / write / read.
It seems all good until other bluetooth devices are connected and paired or synced.
For example, if the android phone is restarted (or Bluetooth is off and on again), my BLE device works great with the app.
If I open fitbit app and sync a fitbit device, then my device cannot connect anymore. (and not pairing as well)
Not only for fitbit but also for samsung smart watch, the same thing happens.
Anyone recommendation will be appreciated.

Tested with Android 6. Samsung GS6 and Nexus 5.

Update 1:
After synced with fitbit, I get the following messages from my app when connecting to my device.
11-11 09:02:41.811   781  1599 I ActivityManager: Killing 21073:com.android.chrome:privileged_process0/u0a34 (adj 13): empty #17
11-11 09:02:41.822 21010 21010 W cr_ChildProcessConnect: onServiceDisconnected (crash or killed by oom): pid=21073
11-11 09:02:41.838   781   952 D ActivityManager: cleanUpApplicationRecord -- 21073
11-11 09:02:41.838   781   952 W ActivityManager: Scheduling restart of crashed service com.android.chrome/org.chromium.content.app.PrivilegedProcessService0 in 1000ms
11-11 09:02:41.857   781  1226 I ActivityManager: Start proc 23634:com.android.chrome:privileged_process1/u0a34 for service com.android.chrome/org.chromium.content.app.PrivilegedProcessService1
11-11 09:02:41.902 21010 21010 W .android.chrome: type=1400 audit(0.0:21068): avc: denied { ioctl } for path="socket:[1799361]" dev="sockfs" ino=1799361 ioctlcmd=7704 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:r:untrusted_app:s0:c512,c768 tclass=unix_stream_socket permissive=0
11-11 09:02:41.902 23644 23644 W Binder_1: type=1400 audit(0.0:21069): avc: denied { ioctl } for path="socket:[1799361]" dev="sockfs" ino=1799361 ioctlcmd=7704 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:r:untrusted_app:s0:c512,c768 tclass=unix_stream_socket permissive=0
11-11 09:02:41.902 23644 23644 W Binder_1: type=1400 audit(0.0:21070): avc: denied { ioctl } for path="socket:[1799361]" dev="sockfs" ino=1799361 ioctlcmd=7704 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:r:untrusted_app:s0:c512,c768 tclass=unix_stream_socket permissive=0
11-11 09:02:41.905 23634 23634 I cr_ChildProcessService: Creating new ChildProcessService pid=23634
11-11 09:02:41.908   781  2450 I ActivityManager: Killing 21102:com.android.chrome:sandboxed_process0/u0a34i52 (adj 13): empty #17
11-11 09:02:41.912 21010 21010 W .android.chrome: type=1400 audit(0.0:21071): avc: denied { ioctl } for path="socket:[1799361]" dev="sockfs" ino=1799361 ioctlcmd=7704 scontext=u:r:untrusted_app:s0:c512,c768 tcontext=u:r:untrusted_app:s0:c512,c768 tclass=unix_stream_socket permissive=0
11-11 09:02:41.919 23634 23644 I cr_LibraryLoader: Using linker: org.chromium.base.library_loader.ModernLinker
11-11 09:02:41.920 21010 21010 W cr_ChildProcessConnect: onServiceDisconnected (crash or killed by oom): pid=21102
11-11 09:02:41.941 23634 23646 I cr_LibraryLoader: Loading chrome from within /data/app/com.android.chrome-1/base.apk
11-11 09:02:41.965 22521 22521 I System.out: writeCharacteristic(4, 8, AQAAAA==)
11-11 09:02:41.967   781  1226 D ActivityManager: cleanUpApplicationRecord -- 21102
11-11 09:02:41.967   781  1226 W ActivityManager: Scheduling restart of crashed service com.android.chrome/org.chromium.content.app.SandboxedProcessService0 in 1000ms
11-11 09:02:42.016 23634 23646 I cr_LibraryLoader: Time to load native libraries: 95 ms (timestamps 5253-5348)
11-11 09:02:42.016 23634 23646 I cr_LibraryLoader: Expected native library version number "54.0.2840.85", actual native library version number "54.0.2840.85"
11-11 09:02:42.016 23634 23646 I chromium: [INFO:library_loader_hooks.cc(151)] Chromium logging enabled: level = 0, default verbosity = 0
11-11 09:02:42.027 23634 23646 E libEGL  : validate_display:255 error 3008 (EGL_BAD_DISPLAY)
11-11 09:02:42.028 23634 23646 I Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb

After this, it does one more reading then disconnected.
If I goto bluetooth app and 'clear data', then it works fine again.


text:
Q: Starting over with Git I decided to learn how to use Version Control over Christmas break, so I downloaded Git, opened a GitHub account and started reading the online tutorial linked to from the GitHub website.  When I got to this part http://progit.org/book/ch2-2.html I got stuck because I wasn't sure how to add files.  For instance, I tried
git add C:/Finish.txt

And it said
Fatal:  'C:/Finish.txt' is outside repository

I was confused until I remember that a long time ago I had tried teaching myself Ruby on Rails and played around with Git back then.  It never really went anywhere, but there's all this residual stuff floating around my system and I don't know how to change it.  For instance, my Untracked files (which should be empty) are rails_projects/ and sample/.
How can I just erase all the old stuff and start over?

A: You should make a folder for your repository, move Finish.txt to that repository, then do git add.
For example:
# here you create C:\myrepo
cd C:\myrepo
git init .
# here you edit C:\myrepo\Finish.txt
git add Finish.txt
git commit -m "Added Finish.txt"

A: Start a new repository, e.g.
 c:
 md c:\newrepo
 cd c:\newrepo
 git init .
 copy \Finish.txt .
 git add Finish.txt
 git commit -m "started over"

I strongly recommend against adding anything to C:\, let alone putting a git repo there. Unless of course you want to accidentally add all of your system disk to git :)
I can also heartily recommend using TortoiseGit which has some excellent explorer integration.

A: Delete any .git folder that you find in your drive.
To create a repo go to a folder that you want the repo in ( and not just randomly), do:
git init

Then proceed... Add only files that you put within this repo and not randomly from some location.

A: It would be very unusual to have the root directory of your hard drive be a git repository.  That's probably why it's giving you the error.
git repositories are typically in a subdirectory and that subdirectory is typically a project.
To initialize a subdirectory as a git repository, you'd do:
git init (directory)

Then you'd add your files and commit.


text:
Q: Python script is hanging AFTER multithreading I know there are a few questions and answers related to hanging threads in Python, but my situation is slightly different as the script is hanging AFTER all the threads have been completed. The threading script is below, but obviously the first 2 functions are simplified massively.
When I run the script shown, it works. When I use my real functions, the script hangs AFTER THE LAST LINE. So, all the scenarios are processed (and a message printed to confirm), logStudyData() then collates all the results and writes to a csv. "Script Complete" is printed. And THEN it hangs.
The script with threading functionality removed runs fine.
I have tried enclosing the main script in try...except but no exception gets logged. If I use a debugger with a breakpoint on the final print and then step it forward, it hangs.
I know there is not much to go on here, but short of including the whole 1500-line script, I don't know hat else to do. Any suggestions welcome!
def runScenario(scenario):
    # Do a bunch of stuff
    with lock:
        # access global variables
        pass
    pass

def logStudyData():
    # Combine results from all scenarios into a df and write to csv
    pass

def worker():
    global q
    while True:
        next_scenario = q.get()
        if next_scenario is None:
            break
        runScenario(next_scenario)
        print(next_scenario , " is complete")
        q.task_done()

import threading
from queue import Queue
global q, lock
q = Queue()
threads = []

scenario_list = ['s1','s2','s3','s4','s5','s6','s7','s8','s9','s10','s11','s12']
num_worker_threads = 6
    lock = threading.Lock()
    for i in range(num_worker_threads):
        print("Thread number ",i)
        this_thread = threading.Thread(target=worker)
        this_thread.start()
        threads.append(this_thread)
    for scenario_name in scenario_list:
        q.put(scenario_name)
    q.join()
    print("q.join completed")
    logStudyData()
    print("script complete")

A: As the docs for Queue.get say:

Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Empty exception if no item was available within that time. Otherwise (block is false), return an item if one is immediately available, else raise the Empty exception (timeout is ignored in that case).

In other words, there is no way get can ever return None, except by you calling q.put(None) on the main thread, which you don't do.
Notice that the example directly below those docs does this:
for i in range(num_worker_threads):
    q.put(None)
for t in threads:
    t.join()

The second one is technically necessary, but you usually get away with not doing it.
But the first one is absolutely necessary. You need to either do this, or come up with some other mechanism to tell your workers to quit. Without that, your main thread just tries to exit, which means it tries to join every worker, but those workers are all blocked forever on a get that will never happen, so your program hangs forever.

Building a thread pool may not be rocket science (if only because rocket scientists tend to need their calculations to be deterministic and hard real-time…), but it's not trivial, either, and there are plenty of things you can get wrong. You may want to consider using one of the two already-built threadpools in the Python standard library, concurrent.futures.ThreadPoolExecutor or multiprocessing.dummy.Pool. This would reduce your entire program to:
import concurrent.futures

def work(scenario):
    runScenario(scenario)
    print(scenario , " is complete")

scenario_list = ['s1','s2','s3','s4','s5','s6','s7','s8','s9','s10','s11','s12']
with concurrent.futures.ThreadPoolExecutor(max_workers=6) as x:
    results = list(x.map(work, scenario_list))
print("q.join completed")
logStudyData()
print("script complete")

Obviously you'll still need a lock around any mutable variables you change inside runScenario—although if you're only using a mutable variable there because you couldn't figure out how to return values to the main thread, that's trivial with an Executor: just return the values from work, and then you can use them like this:
for result in x.map(work, scenario_list):
    do_something(result)


text:
Q: Generate PDF with Swift 2.0 So I am trying to generate a PDF with swift. I have been trying to convert from objective C to swift and for now there is some errors that I don't know how to fix.
Here is the code:
@IBAction func createPDFOnClick(sender: AnyObject!)
{
    pageSize = CGSizeMake(850,1100)
    let fileName: String = "makeME.pdf"
    var path: [AnyObject] = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,true)
    let documentDirectory: String = path[0] as! String
    let pdfPathWithFileName: String = documentDirectory.stringByAppendingString(fileName)
    self.createPDF(pdfPathWithFileName)

}

func createPDF(filePath: String){

 UIGraphicsBeginPDFContextToFile(filePath,CGRectZero,nil)
 UIGraphicsBeginPDFPageWithInfo(CGRectMake(0,0,850,1100),nil)
 self.drawBackground()
 self.drawText()
 UIGraphicsEndPDFContext()

}

func drawBackground() {
    let context: CGContextRef = UIGraphicsGetCurrentContext()!
    let rect: CGRect = CGRectMake(0,0,pageSize!.width,pageSize!.height)
    CGContextSetFillColorWithColor(context,UIColor.whiteColor().CGColor)
    CGContextFillRect(context,rect)
}

func drawText() {
    var context: CGContextRef = UIGraphicsGetCurrentContext()!
    CGContextSetFillColorWithColor(context,UIColor.blackColor().CGColor)
    var textRect: CGRect = CGRectMake(0,0,[[self myTextView]frame].size.with, self.myTextView.frame.size.height)
    var myString: String = self.myTextView.text!
    myString.drawInRect(textRect)
}

My errors are the following lines:

var path: [AnyObject] = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)

I getting error "use of unresolved identifier"

var textRect: CGRect = CGRectMake(0,0,[[self myTextView]frame].size.with, self.myTextView.frame.size.height)

Here i am getting "expect separator"
Thanks in advance.

A: Your errors have little to do with PDF creation and are related to Swift Syntax.

*

*The parameters specifying the directory is imported to Swift as an enum. So for the directory, your input should be some case of NSSearchPathDirectory, such as NSSearchPathDirectory.DocumentDirectory (Or more succinctly .DocumentDirectory). NSSearchPathDomainMask is a struct with static constants, so it gets treated like a struct. For example, NSSearchPathDomainMask.UserDomainMask (or more succinctly .UserDomainMask).

*Your second parameter is not Swift syntax. Try:
var textRect = CGRect(0,0,self.myTextView.frame.size.width, self.myTextView.frame.size.height)


text:
Q: C++ overloading of the plus operator I want to add 2 objects, by overloading the + operator, but my compiler says there's no matching function to call to point::point(int, int). Can somebody please help me with this code, and explain the error ? thank you
#include <iostream>

using namespace std;

class point{
int x,y;
public:
  point operator+ (point & first, point & second)
    {
        return point (first.x + second.x,first.y + second.y);
    }
};

int main()
{
    point lf (1,3)
    point ls (4,5)
    point el = lf + ls;
    return 0;
}

A: class point{
  int x,y;
public:
  point& operator+=(point const& rhs)& {
    x+=rhs.x;
    y+=rhs.y;
    return *this;
  }
  friend point operator+(point lhs, point const& rhs){
    lhs+=rhs;
    return lhs;
  }
};

There are a pile of little tricks above that make following this pattern a good "no brainer".

*

*You get both += and + with the "proper" semantics.

*If you chain +s together, you get elision of the left hand side operation.  (ie, a+b+c becomes (a+b)+c, the return value of a+b is elided into the _+c call).  If your objects have movable state, the proper moves happen for no design cost.

*a+b works if either a or b is a point, and the other has an implicit-conversion-to-point.  Member operator+ does not do this if a is not a point; this is pointless asymmetry.

*a+=b is often more efficient to implement than a=a+b.  When you implement += here, you get an efficient + as well.  And your += is in turn defined in terms of member variable +=s.

A: The error with gdb I get is
main.cpp:8:49: error: 'point point::operator+(point&, point&)' must take either zero or one argument
This is because the the object that you plan to perform the operation on is this (the left hand side) and then the right hand side is the argument.  If you wish to use the format that you've taken, then you can put the declaration outside the class - ie
struct point
{
  // note made into a struct to ensure that the below operator can access the variables.
  // alternatively one could make the function a friend if that's your preference
  int x,y;
};

point operator+ (const point & first, const point & second) {
  // note these {} are c++11 onwards.  if you don't use c++11 then
  // feel free to provide your own constructor.
  return point {first.x + second.x,first.y + second.y};
}

A: You can just change your code like this,
#include <iostream>

using namespace std;

class point {
    int x, y;
public:
    point(int i, int j)
    {
        x = i;
        y = j;
    }

    point operator+ (const point & first) const
    {
        return point(x + first.x, y + first.y);
    }

};

int main()
{
    point lf(1, 3);
    point ls(4, 5);
    point el = lf + ls;

    return 0;
}

Hope this helps...


text:
Q: Outlook API 401 Unauthorized I'm trying to access the Office 365 API to read the users calendar events. This happens inside a Chat Bot (MS Bot Framework) with the library AuthBot.
After the login process the access token can be returned with context.GetAccessToken("https://graph.windows.net").
This seems to work as a valid token is returned.
Next I tried to request some resources from Office365 and almost all attempts have resulted in a 401. In Azure AD the app has access to all permissions in the Office 365 Exchange Group.
When I try to access the discovery API at api.office.com/discovery/v1.0 it is the only time the request doesn't result in 401:
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("https://api.office.com/discovery/v1.0");
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    using (var response = await client.GetAsync("me"))
    using (var content = response.Content)
    {
        var result = await content.ReadAsStringAsync();
    }
}

What gets returned is this
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<service xml:base=\"https://api.office.com/discovery/me/\"
    xmlns=\"http://www.w3.org/2007/app\"
    xmlns:atom=\"http://www.w3.org/2005/Atom\">
<workspace>
    <atom:title type=\"text\">Default</atom:title>
    <collection href=\"allservices\">
        <atom:title type=\"text\">allservices</atom:title>
    </collection>
    <collection href=\"services\">
        <atom:title type=\"text\">services</atom:title>
    </collection>
</workspace>
</service>

After that I tried accessing some information in two ways. The OutlookServicesClient:
OutlookServicesClient wat = new OutlookServicesClient(baseUrl, async () => token);
var messages = await wat.Me.Messages.ExecuteAsync();

And a manual way using HttpClient:
AuthenticationContext auth = new AuthenticationContext("https://login.windows.net/"+ ConfigurationManager.AppSettings["AAD.Tenant"]);
        AuthenticationResult authenticationResult = await auth.AcquireTokenAsync(
            "https://outlook.office365.com/",
            new ClientCredential(ConfigurationManager.AppSettings["AAD.ClientId"], ConfigurationManager.AppSettings["AAD.ClientSecret"])
            );
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken);
        HttpResponseMessage msg = await client.GetAsync("https://outlook.office365.com/api/v1.0/me/events");

Both return 401. I tried two different resources: https://graph.windows.net/ for the authentication bot which returned a shorter token that didn't include roles; and https://outlook.office365.com/ for the manual method which returned a longer token with roles.

A: I just figured it out:
https://graph.windows.net seems to be a newer version which is not yet supported by my Outlook365 tenant. Hence the 401. When i switched to https://outlook.office365.com for the authbot it returned the correct results (calendars and events).
For the manual mode I assume https://login.windows.net is yet another domain apart from graph that is not compatible.
Side note: Using outlook.office365.com I got a 404 at first. This was a result of the user being used for testing not having an inbox.


text:
Q: How to have two buttons in a same form to do different actions in ajax? I have a form, which take name from form and it sends to javascript codes and show in php by Ajax. these actions are done with clicking by submit button, I need to have another button, as review in my main page. how can I address to ajax that in process.php page have "if isset(submit)" or "if isset(review)"?
I need to do different sql action when each of buttons are clicked.
how can I add another button and be able to do different action on php part in process.php page?

<form name="myform" id="myform" action="" method="POST">
      Name
    <input type="text" name="name" id="name" size="30" value=""/>

    <input type="submit" name="submit" value="Submit">
</form>

process.php:
<?php

    print "
Your name is ".$_POST['name']." ";
?>

A: Bind the event handlers to the buttons' click events instead of the form's submit event.
Use the different event handler functions to add different pieces of extra data to the data object you pass to the ajax method.

A: You just need to add a button and an onclick handler for it.
Html:
<input type="button" id="review" value="Review"/>

Js:
$("#review").click(function(){
            var myData = $("#myform").serialize() + "&review=review";
            $.post('process.php', myData , function(data) {
                    $('#results').html(data);
                });
            }
        );

Since you have set a variable review here, you can use it to know that is call has come by clicking the review button.


text:
Q: Controllability matrix cannot be defined $\implies$ the system cannot be controllable? Let $B\in\mathbb{R}^{n\times m}$ and $A=\lambda I$, for $\lambda\in\mathbb{R}$. I want to show that a necessarily condition for the controllability of $(A,B)$ is $m\ge n$.
I assume this means for $$A=\begin{bmatrix}\lambda_{1} & 0 & \cdots & 0 \\ 0 & \lambda_{2} & \cdots & 0 \\ \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & \cdots & \lambda_{n}\end{bmatrix} \qquad B=\begin{bmatrix} b_{11} & \cdots & b_{1m} \\ \vdots & \ddots & \vdots \\ b_{n1} & \cdots & b_{nm}\end{bmatrix}$$
Is it sufficient to state that the controllability matrix cannot be defined for $m<n$, since in order to compute the controllability matrix, we must compute $A\cdot b$, which cannot be done if $m<n$?...Or maybe I've misinterpreted the question?

A: I believe your interpretation of the question may be incomplete. It is usually assumed that $ A \in  \mathbb{R}^{n \times n} $ and $ B \in \mathbb{R}^{n \times m}$.
The controllability matrix ( assuming a linear time invaraint system) can be defined as
$$
C = \begin{bmatrix}B & AB & A^2B & \cdots & A^{n-1}B \end{bmatrix}
$$
and the system $ ( A, B) $ is controllable if $ C $ has full rank $ rank(C) = n $.
The rank of a matrix is the maximum number of linearly independent rows or columns. If $ m > n $ this means that $ rank(B) \leq n$.
From your description we know that $A $ is full rank, $ rank(A) = n$.
The rank of the product of two matrices obeys
$$
rank(AB) \leq \min(rank(A),rank(B))
$$
Combining all of this means that your system is only controllable if $ B $ is full rank. One intuitive way to think of this is having enough control inputs to control each of your states. Having a surplus of control inputs ($ m > n$) does not improve controllability.
Finally, $m<n$ is possible because the matrix product $ AB$ is well defined as long as $ B $ has $ n $ rows.
Hope this helps.


text:
Q: MongoDB query array for element size and $elemMatch comparison I need to retrieve only records that have at least one element in the format.prices array and every elements price are between 0 and 0.99:
So this works fine for the price comparison:
{ 'formats.prices': { $not: { $elemMatch: { price: { $gt: 0, $lte: 0.99 } } } } }

But how can I add the condition like $not: { $size: 0 } to exclude also the formats.prices without elements at all?

A: Well, I ended with this and it works fine, don't know if there is a better way:
{
    'formats.prices': { $not: { $elemMatch: { price: { $gt: 0, $lte: 0.99 } } } },
    'formats.prices.0.price': { $exists: true }
}


text:
Q: Python Guessing Game: Failing any of 5 quizzes skips all left quizzes and go straight to the results So I am working on a simple python guessing game. There are a total of 5 quizzes. But if I fail any one of them the rest of the quizzes are skipped and goes straight to the results. Please note that some portions of the code are for decoration purposes only.
movie_name = "WRECK IT RALPH"
movie_name2 = "AVENGERS ENDGAME"
movie_name3 = "AVENGERS AGE OF ULTRON"
movie_name4 = "CARS 3"
movie_name5 = "SPIDER-MAN: INTO THE SPIDER-VERSE"
guess_count = 0
guess_limit = 5
print('Guess The Movie!')
print('By Ahmed Shahir Samin')

print('''
Rules and Info:
''')
print('''1. This game is NOT case sensitive. That means you can enter the answers in either upper or lower case or a
   mixture of both of them.
2. Use the hints provided to guess the answer.
3. At the end results will be shown with a format like so:
   LEVEL NO.:CORRECT ANSWER :IF YOUR ANSWER WAS CORRECT OR NOT.''')

print('''LOADING ASSETS........
ASSETS LOADED SUCCESSFULLY.
STARTING GAME FROM LEVEL 1'

GOOD LUCK''')

print('''LEVEL 1: Fill the unfilled movie name:
W___K __ _AL__
TYPE: Animated, Adventure
STUDIO: DISNEY''')
while guess_count < guess_limit:
    guess = input('LEVEL 1: Fill the Movie Name: ')
    guess_count += 1
    if guess.upper() == movie_name:
        print('YOU WON!')
        lvl1win = True
        break
else:
    print('SORRY. YOU FAILED LEVEL 1!')
    lvl1win = False

print('''LEVEL 2: Fill the unfilled movie name:
A___G__S ____A__
TYPE: Action
STUDIO: MARVEL''')
while guess_count < guess_limit:
    guess = input('LEVEL 2: Fill the Movie Name: ')
    guess_count += 1
    if guess.upper() == movie_name2:
        print('YOU WON!')
        lvl2win = True
        break
else:
    print('SORRY. YOU FAILED LEVEL 2!')
    lvl2win = False

print('''LEVEL 3: Fill the unfilled movie name:
A___G__S _G_ __ _L_R__
TYPE: Action
STUDIO: MARVEL''')
while guess_count < guess_limit:
    guess = input('LEVEL 3: Fill the Movie Name: ')
    guess_count += 1
    if guess.upper() == movie_name3:
        print('YOU WON!')
        lvl3win = True
        break
else:
    print('SORRY. YOU FAILED LEVEL 3!')
    lvl3win = False

print('''LEVEL 4: Fill the unfilled movie name:
___S 3
TYPE: Animated, Racing, Adventure
STUDIO: DISNEY''')
while guess_count < guess_limit:
    guess = input('LEVEL 4: Fill the Movie Name: ')
    guess_count += 1
    if guess.upper() == movie_name4:
        print('YOU WON!')
        lvl4win = True
        break
else:
    print('SORRY. YOU FAILED LEVEL 4!')
    lvl4win = False

print('''LEVEL 5: Fill the unfilled movie name:
S____R-M__: I__O T_E ____ER-V___E
TYPE: Action, Animated
STUDIO: MARVEL''')
while guess_count < guess_limit:
    guess = input('LEVEL 5: Fill the Movie Name: ')
    guess_count += 1
    if guess.upper() == movie_name5:
        print('YOU WON!')
        lvl5win = True
        break
else:
    print('SORRY. YOU FAILED LEVEL 5!')
    lvl5win = False

print('''
Results:
''')

if lvl1win == True:
    print(f'LEVEL 1: {movie_name}: CORRECT!')
if lvl1win == False:
    print(f'LEVEL 1: {movie_name}: WRONG!')
if lvl2win == True:
    print(f'LEVEL 2: {movie_name2}: CORRECT!')
if lvl2win == False:
    print(f'LEVEL 2: {movie_name2}: WRONG!')
if lvl3win == True:
    print(f'LEVEL 3: {movie_name3}: CORRECT!')
if lvl3win == False:
    print(f'LEVEL 3: {movie_name3}: WRONG!')
if lvl4win == True:
    print(f'LEVEL 1: {movie_name4}: CORRECT!')
if lvl4win == False:
    print(f'LEVEL 1: {movie_name4}: WRONG!')
if lvl5win == True:
    print(f'LEVEL 1: {movie_name5}: CORRECT!')
if lvl5win == False:
    print(f'LEVEL 1: {movie_name5}: WRONG!')
print('----------------------END----------------------')

print('''

Credits:
''')

print('''A GAME BY Ahmed Shahir Samin
Hope you guys enjoyed the game. This game was about 102 lines of raw code.
Eid Mubarak and Goodbye.''')

The expected result should be if any of the quizzes are failed then it will show the failed message and move on to the next one.


text:
Q: Averaging multiple 2D data sets I have multiple data sets, each of which is a 2D matrix. I want to construct a new 2D Matrix in which each element is the average of that element for all the original data sets. i.e
NewMatrix[i][j] =1/N *(Matrix1[i][j] + Matrix2[i][j] + ... + MatrixN[i][j])

I can't quite figure out how to do it in Mathematica.
Thanks

A: This is a pretty basic question but since you're new here let me get you started.  Many functions in Mathematica are natively designed to work on vectors, arrays, and tensors.  That means that such an operation is or at least may be directly analogous to the non-array form.  Suppose you have:
a1 = RandomInteger[9, {5, 5}];
a2 = RandomInteger[9, {5, 5}];
a3 = RandomInteger[9, {5, 5}];

You then need merely:
(a1 + a2 + a3) / 3

Or:
Mean[{a1, a2, a3}]

Just as you would if a1, a2 and a3 were individual numbers.  This will be much faster than a manual procedural operation, unless you are going to compile that procedural code.

A sidebar
You could define all three arrays at once using:
{a1, a2, a3} = RandomInteger[9, {3, 5, 5}];

There is a subtle yet important difference however.  This more concise form will unpack the packed integer array that is produced by RandomInteger, resulting in slower numeric operations on those expressions.


text:
Q: Why does input tensor contain more dimensions than the shape of the input? I have converted a custom trained image segmentation TensorFlow model to TF Lite format and am now trying to run inference on the model using the CPP API.
I'm investigating the input and output tensors and was following the following link to do so.
The weird thing is that the shape of my input tensor is bigger than the images I need to feed to my model. The images have shape 480x640x3 but dims->data in the snippet below incorporates much more info than that (see screenshot of my console). How come?
#include <cstdio>
#include <iostream>
#include <iomanip>
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/optional_debug_tools.h"
#include <time.h>

using namespace tflite;
using namespace std;

#define TFLITE_MINIMAL_CHECK(x)                              \
  if (!(x)) {                                                \
    fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); \
    exit(1);                                                 \
  }

int main(int argc, char* argv[]) {
  if (argc != 2) {
    fprintf(stderr, "minimal <tflite model>\n");
    return 1;
  }
  const char* filename = argv[1];
  int startt, endd;
  startt = clock();

  // Load model
  // Load model
  std::unique_ptr<tflite::FlatBufferModel> model =
      tflite::FlatBufferModel::BuildFromFile(filename);
  TFLITE_MINIMAL_CHECK(model != nullptr);

  // Build the interpreter
  tflite::ops::builtin::BuiltinOpResolver resolver;
  std::unique_ptr<Interpreter> interpreter(new Interpreter());
  InterpreterBuilder builder(*model, resolver);
  std::cout << "allocating a number of threads" << std::endl;
  int numthreads=4;
  interpreter->SetNumThreads(numthreads);
  std::cout << "threads allocated" << std::endl;

  builder(&interpreter);
  TFLITE_MINIMAL_CHECK(interpreter != nullptr);
  endd = clock();

  // Allocate tensor buffers.
  TFLITE_MINIMAL_CHECK(interpreter->AllocateTensors() == kTfLiteOk);
  printf("=== Pre-invoke Interpreter State ===\n");
  tflite::PrintInterpreterState(interpreter.get());

  double time_taken = double(endd-startt)/double(CLOCKS_PER_SEC);
  std::cout << "a number of threads should be selected" << std::endl;
  std::cout << "Time taken to load in the model in tflite using CPP API :" << fixed << time_taken << std::setprecision(5);
  std::cout << " sec " << std::endl;

  // Fill input buffers
  std::cout << "inputs : " << interpreter->inputs().size() << "\n";
  std::cout << "inputs(0) name : " << interpreter->GetInputName(0) << "\n";
  std::cout << "tensors size: " << interpreter->tensors_size() << "\n";
  std::cout << "nodes size: " << interpreter->nodes_size() << "\n";
  int startinput = clock();
  int input = interpreter->inputs()[0];
  std::cout << "input.1 : " << input <<"\n";
  const std::vector<int> inputs = interpreter->inputs();
  const std::vector<int> outputs = interpreter->outputs();
  std::cout << "number of inputs: " <<inputs.size() << "\n";
  std::cout << "number of outputs: " <<outputs.size() << "\n";

  TfLiteIntArray* dims = interpreter->tensor(input)->dims;
  int test0 = dims->data[0];
  int wanted_channels = dims->data[1];
  int wanted_height = dims->data[2];
  int wanted_width = dims->data[3];
  int test4 = dims->data[4];
  int test5 = dims->data[5];
  int test6 = dims->data[6];
  std::cout << "type of input tensor: " << interpreter->tensor(input)->type << std::endl;
  std::cout << "height, width, channels of input : " << wanted_height << " " << wanted_width << " "<< wanted_channels <<  " " << test0 << " " << test4 << " " << test5 << " " << test6 << std::endl;
}


text:
Q: Google Custom Search tabs How can I create tabs to refine search results in Google Custom Search? An example is this: http://goo.gl/gftKp
Here, the results can be filtered as All Results, Blogs, Forum, Help, etc.. I am looking to do something like that. My website has different sections like articles, games, forum, gallery, etc.. How can I create tabs like these in the google custom search (free service) so users can filter the results and choose which section of the website they want to search?

A: I was searching for a solution for the same context few months back and at last found a solution.
After adding refinements in google cse control panel you'll see refinements as 'filter labels' for your search. But this feature, ie matching labels is too broad.
If your site has a specific path for each sections like,

*

*articles under mysite/articles/

*games under mysite/games/

then, you can map these paths to each filter or refinement you created before.
See the image below, I've added few refinements here as news,blog,media

See the mapping below for each label/refinement

and if you really want the refinement to appear like tabs..

Happy 'custom search engin-ing' :)


text:
Q: Checkbox style not toggled correctly when action set on parent, updated data is sent from parent to child I have a card component with a checkbox, to which the checked status is passed from the parent.
The checkbox is hidden and the label is styled to look like a checkbox. The whole card containing the checkbox has the action handler. When I click the checkbox label or the card directly it toggles correctly, but when using Space, the action is fired correctly but the checkbox is not toggled. I see that the checked property is not set in DOM for the hidden checkbox, hence the style for checked checkbox is not rendered. I tried to make checked a computed property on the card component to force a re-render when the checked value is updated, but no luck.
<!-- parent -->
{{#each userList as |user|}}
<li {{action "selectCard" user}}>
  {{member-card
     name=user.name
     checkboxId=user.checkboxId
     checked=user.checked
  }}
</li>
<!-- child -->
<div>
  <input
    type="checkbox"
    id={{checkboxId}}
    checked={{checked}}
  />
  <label for={{checkboxId}} class="result-card__name-label">
   {{name}}
  </label>
</div>

On inspecting I found that the checked DOM property is not getting set correctly. When I tried:
<!-- child -->
{{#if checked}}
<input
    type="checkbox"
    id={{checkboxId}}
    checked
  />
{{else}}
<input
    type="checkbox"
    id={{checkboxId}} />
{{/if}}

this seems to give the result I want.
One solution that works is if I set the same action handler on the checkbox label as well, and prevent the event from bubbling when it is clicked. But this doesn't seem like an elegant solution. Wanted to understand that why checkbox not getting re-rendered correctly.
I would suppose that since the checked property is updated when I click on the card (I verified this using ember inspector) I would assume that checked property would be check on the checkbox. But for some reason this isn't how it is working.
I ended but using prevent default on the label, to stop the propagation of event from it to checkbox to stop it from firing the event again.
Ember version: 3.8

A: What you show, should work. Here's a Twiddle demonstrating it: https://ember-twiddle.com/0631193dc09a3646ca9e9a1efe351607?numColumns=2&openFiles=controllers.application.js%2Ctemplates.application.hbs
Your problem likely lies elsewhere.
How are you setting the checked property on the user object? Is user an instance of EmberObject or a POJO?
If it's a POJO and you're doing user.checked = true, the template won't update. There's no way for Ember to know that the property has changed.
Make it an instance of EmberObject and use user.set() to set it.
Or, if you're on Ember Octane (recommended), user can be an instance of a simple class, and you can use the @tracked decorator on the checked class property. Then you can use user.checked = true to change the checkbox state.


text:
Q: Grouping in Rails 4 I have a calendar and I want to group this data..so I have this in my controller
  @entry_by_date = Entry.where("emp_mail_addr = ? and emp_first_name = ? and  emp_last_name = ? and emp_dept = ?", current_user.email, current_user.emp_first_name, current_user.emp_last_name, current_user.emp_dept).group_by {|i| i.leave_start.to_date}
  @date = params[:date] ? Date.parse(params[:date]) : Date.today

Question is for @entry_by_date I have it .group_by {|i| i.leave_start.to_date}
how can I make this have group by two dates for example....
@entry_by_date........group_by {|i| i.leave_start.to_date} {|i| i.leave_end.to_date}
So it will now group by leave_start and leave_end so now on my calendar it will show up with leave start and leave end dates..
I tried doing it like this
 @entry_by_date = Entry.where("emp_mail_addr = ? and emp_first_name = ? and  emp_last_name = ? and emp_dept = ?", current_user.email, current_user.emp_first_name, current_user.emp_last_name, current_user.emp_dept).group_by {|i| i.leave_start.to_date}
 @entry_by_date = Entry.where("emp_mail_addr = ? and emp_first_name = ? and  emp_last_name = ? and emp_dept = ?", current_user.email, current_user.emp_first_name, current_user.emp_last_name, current_user.emp_dept).group_by {|i| i.leave_end.to_date}

but only leave start showed up or if I switched them leave end would show up. I would like for both to show up and suggestions are greatly appreciated!!!!
Thank you!

A: *

*Be aware that there is a critical difference between group_by and group APIs - the former works on lists (after they have been fetched from the database), while the latter is used in the database query itself (adding it a GROUP BY clause)

*I'm not sure what you are trying to achieve, but if you want to have the keys of your group to be an array of dates, you could do it in a single group_by block:
@entry_by_date = entries.group_by { |i| [i.leave_start.to_date, i.leave_end.to_date] }

If you want each entry to be grouped twice (once with its start date, and once with its end date), you need to create 2 grouped maps, and join them:
entry_by_start_date = entries.group_by {|i| i.leave_start.to_date}
entry_by_end_date = entries.group_by {|i| i.leave_end.to_date}
@entry_by_date = entry_by_start_date.merge(entry_by_end_date) {|key, oldval, newval| newval + oldval}


text:
Q: Variable/Changing ember number in Intercom HTML. Selenium Python I am trying to automate some tasks at work. Requests wont work because I don't have admin access to my works Intercom App. Therefore I use Selenium.
I want to write "Hey" in the chat box of Intercom, and send the message.
** The problem is a changing ember number every time I have a new conversation. It works when I copy the right ember number every time, but when changing the conversation, it doesn't work anymore. **
I am looking for some kind of script to change the ember = XXXXX into the right number each time
Not really relevant to the code problem, but I am using Chrome in debugging mode, to avoid logging in every time I need to test the code, and I am using tkinter to have a button to press, every time I want to write "Hey" in the chat box.
Sorry, I understand it is difficult to replicate this problem.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

#___________
#In order to run Selenium in an already opened browser / session, I need to run this code in CMD:
#cd C:\Program Files (x86)\Google\Chrome\Application
#
#chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\Users\peter\testprogram"
#___________

opt=Options()
opt.add_experimental_option("debuggerAddress","localhost:9222")
driver=webdriver.Chrome(executable_path="
C:\\ProgramFiles\\crromedriver\\chromedriver.exe",options=opt)

def hey():

    ember = 32890
    hey = driver.find_element_by_xpath('//*[@id="ember'+str(ember)+'"]/div/div[3]/div[1]/div/p')

    hey.send_keys("Hey!")

The specific HTML element where I want to write "Hey!": (This is under the big HTML code below)

Hey! This is where I want my text

One might suggest to use
hey = driver.find_element_by_class_name('intercom-interblocks-align-left embercom-prosemirror-composer-block-selected')
hey.send_keys("Hey!")

But this doesn't work for me.
The HTML element where the ember number is changing:

Hey!Hey!Hey!Hey!Hey!

A: If you want to use ember here is a possible solution:
hey = driver.find_element_by_xpath('//*[contains(@id="ember")]/div/div[3]/div[1]/div/p')
hey.send_keys("Hey!")

This will probably fail if there are multiple elements with id="ember[0-9]+".

If you want to access the p tag directly use find_element_by_css_selector, like so:
hey = driver.find_element_by_css_selector('.intercom-interblocks-align-left.embercom-prosemirror-composer-block-selected')
hey.send_keys("Hey!")

Your code with find_element_by_class_name did not work because it's expecting one class name and you are passing two class names (class names are separated by space).


text:
Q: Algebraic Data Types in Postgres Is it possible to create an Algebraic Data Type in Postgres and then use it as a column type?
For example:
CREATE TYPE hoofed AS ENUM('horse', 'goat');

CREATE TYPE monkey AS ENUM('chimp','macaque');

CREATE TYPE ANIMAL AS ENUM(hoofed, monkey);

This fails with:
syntax error at or near "hoofed"
LINE 1: CREATE TYPE ANIMAL AS ENUM(hoofed, monkey);

Is it possible to do something like this?
Ultimately what I would then like to be able to do is something like so:
CREATE TABLE zoo (
    a ANIMAL,
    name text
);

INSERT INTO zoo(a, name) VALUES('horse', 'bob');
INSERT INTO zoo(a, name) VALUES('macaque', 'jimmy');

And for both of the records to be independently valid.
EDIT: @Abihabi87's response below does allow me to create, in effect, a product type, but it still does not allow me to create a union type as desired.

A: You cant create type enum from others enum type:
you can create ANIMAL that like:
CREATE TYPE ANIMAL AS (h hoofed,m monkey);

Example in use:
CREATE TABLE your_table
(
    a ANIMAL
);

INSERT INTO your_table(a) select (select ('horse','macaque')::ANIMAL);

A: With ENUM types, you cannot achieve dynamic type composition/union. However, with DOMAIN types, you could achieve something similar:
create function valid_any_domain(anyelement, variadic regtype[])
  returns boolean
  language plpgsql
  immutable
as $func$
declare
  t regtype;
begin
  foreach t in array $2 loop
    begin
      execute format('select $1::%s', t) using $1;
    exception
      when not_null_violation or check_violation then
        continue;
    end;
    return true;
  end loop;

  return false;
end;
$func$;

create domain hoofed as text
  check (value in ('horse', 'goat'));

create domain monkey as text
  check (value in ('chimp','macaque'));

create domain animal as text
  check (valid_any_domain(value, 'hoofed', 'monkey'));

Changing the base types will dynamically change the composite/union type too, but still requires a manual constraint validation (especially, when some value(s) are removed from the valid spectrum):
alter domain hoofed drop constraint hoofed_check;
alter domain hoofed add check (value in ('horse', 'goat', 'zebra'));
alter domain animal validate constraint animal_check;

http://rextester.com/MBVC62095
Note: however, with DOMAIN types, you will lose an ENUM property: the custom ordering. DOMAINs will always use the underlying type's ordering.

A: Use the function:
create or replace function create_enum(name, variadic regtype[])
returns void language plpgsql as $$
begin
    execute format(
        'create type %I as enum(%s)',
        $1,
        string_agg(quote_literal(enumlabel), ',' order by enumtypid, enumsortorder))
    from pg_enum
    where enumtypid = any($2);
end $$;

Pass the name of a new type and a list of enum types as arguments:
select create_enum('animal', 'hoofed', 'monkey');

select enum_range(null::animal) as animal;

           animal
----------------------------
 {horse,goat,chimp,macaque}
(1 row)

A: Effectively you are trying to merge two enum types.
There are some open questions:

*

*Can there be duplicate strings?

*Is the design supposed to be static (changes to enum type hoofed do not change type animal later) or dynamic (the opposite).

*Merge exactly two enum types or more?

*Since the order of elements is significant, what is the order of elements in animal supposed to be?

*Is this a one-time operation or intended for repeated use?

Assuming no duplicates, static design, two enum types, existing order of elements as appended and one-time operation.
You can use the built-in enum support function enum_range(anyenum) to get an array of all elements for a given enum type.
DO
$$
BEGIN
EXECUTE (
   SELECT 'CREATE TYPE animal AS ENUM ('
        || array_to_string(enum_range(null::hoofed)::text[]
                        || enum_range(null::monkey)::text[], ''',''')
        || ''')'
   );
END
$$;


text:
Q: Server running error in parcel by starting the external file index.html I Ignoring the main but it also doesn't work(Build Failed) [Build Error in parcel @ 2.7.0 start when I am trying to add external index.html file in the main I also ignored  the main but it also doesn't work for me. Will please someone help me to solve this problem It also not working with JavaScript file when I added externally and also getting error with html file  but I want to add the html file but as a solution I try to add JavaScript file but it also doesn't work for me. Will please someone solve this issue or tell me how to solve this issue
{
  "name": "forkify",
  "version": "1.0.0",
  "description": "",
  "main": "unrelated.js",
  "targets": {
    "main": false
  },
  "scripts": {
    "start": "parcel start index.html",
    "build": "parcel build index.html"
  },
  "author": "Meelad Sultan",
  "license": "ISC",
  "devDependencies": {
    "parcel": "^2.7.0"
  }
}

enter code here

A: At last I can find the solution of my problem after almost a day if someone else facing the same problem they just do add the **Browsers list ** in the  package.json file before script and ignore the main target and also set the parcel to latest then the parcel will run successfully and do not give any server  error or build error. And don't forget to run periodically npx browerlist@latest --update-db. It will update your package-lock file with new caniuse-lite version. In this case, you will be sure that last two version or > 0.2% will target what you expect
{
"name": "forkify",
"version": "1.0.0",
"description": "",
"main": "unrelated.js",
"target": {
"main": false
},
"browserslist": "> 0.5%, last 2 versions, not dead",
"scripts": {
"start": "parcel  index.html "
},
"author": "Meelad Sultan",
"license": "ISC",
"devDependencies": {
"@parcel/transformer-sass": "^2.7.0",
"parcel": "latest"
},
"dependencies": {
"sass": "^1.55.0"
}
}


text:
Q: How to unflatten flattened json in C# from this Answer I learned how to flatten a JSON object in c#.
from JSON String:
{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

To:
The following are lines of strings, not an object
menu.id:file
menu.value:File
menu.popup.menuitem[0].value:New
menu.popup.menuitem[0].onclick:CreateNewDoc()
menu.popup.menuitem[1].value:Open
menu.popup.menuitem[1].onclick:OpenDoc()
menu.popup.menuitem[2].value:Close
menu.popup.menuitem[2].onclick:CloseDoc()

Now, i want to reverse the process.
I can found implementations from this question but it is in JavaScript.
How do I unflatten (return structured JSON from lines) it in C# with json.net?

A: I managed to solve it out.
Below is my code combined with Sarath Rachuri's flattening code.
I did not test it in too many cases, so it could be buggy.
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace JSONHelper
{
    class JSONFlattener
    {
        private enum JSONType{
            OBJECT, ARRAY
        }
        public static Dictionary<string, string> Flatten(JObject jsonObject)
        {
            IEnumerable<JToken> jTokens = jsonObject.Descendants().Where(p => p.Count() == 0);
            Dictionary<string, string> results = jTokens.Aggregate(new Dictionary<string, string>(), (properties, jToken) =>
            {
                properties.Add(jToken.Path, jToken.ToString());
                return properties;
            });
            return results;
        }

        public static JObject Unflatten(IDictionary<string, string> keyValues)
        {
            JContainer result = null;
            JsonMergeSettings setting = new JsonMergeSettings();
            setting.MergeArrayHandling = MergeArrayHandling.Merge;
            foreach (var pathValue in keyValues)
            {
                if (result == null)
                {
                    result = UnflatenSingle(pathValue);
                }
                else
                {
                    result.Merge(UnflatenSingle(pathValue), setting);
                }
            }
            return result as JObject;
        }

        private static JContainer UnflatenSingle(KeyValuePair<string, string> keyValue)
        {
            string path = keyValue.Key;
            string value = keyValue.Value;
            var pathSegments = SplitPath(path);

            JContainer lastItem = null;
            //build from leaf to root
            foreach (var pathSegment in pathSegments.Reverse())
            {
                var type = GetJSONType(pathSegment);
                switch (type)
                {
                    case JSONType.OBJECT:
                        var obj = new JObject();
                        if (null == lastItem)
                        {
                            obj.Add(pathSegment,value);
                        }
                        else
                        {
                            obj.Add(pathSegment,lastItem);
                        }
                        lastItem = obj;
                        break;
                    case JSONType.ARRAY:
                        var array = new JArray();
                        int index = GetArrayIndex(pathSegment);
                        array = FillEmpty(array, index);
                        if (lastItem == null)
                        {
                            array[index] = value;
                        }
                        else
                        {
                            array[index] = lastItem;
                        }
                        lastItem = array;
                        break;
                }
            }
            return lastItem;
        }

        public static IList<string> SplitPath(string path){
            IList<string> result = new List<string>();
            Regex reg = new Regex(@"(?!\.)([^. ^\[\]]+)|(?!\[)(\d+)(?=\])");
            foreach (Match match in reg.Matches(path))
            {
                result.Add(match.Value);
            }
            return result;
        }

        private static JArray FillEmpty(JArray array, int index)
        {
            for (int i = 0; i <= index; i++)
            {
                array.Add(null);
            }
            return array;
        }

        private static JSONType GetJSONType(string pathSegment)
        {
            int x;
            return int.TryParse(pathSegment, out x) ? JSONType.ARRAY : JSONType.OBJECT;
        }

        private static int GetArrayIndex(string pathSegment)
        {
            int result;
            if (int.TryParse(pathSegment, out result))
            {
                return result;
            }
            throw new Exception("Unable to parse array index: " + pathSegment);
        }

    }
}

A: Purely System.Text.Json solution for unflatteing JSON. Requires .Net 6.
private static JsonNode Unflatten(Dictionary<string, JsonValue> source)
{
    var regex = new System.Text.RegularExpressions.Regex(@"(?!\.)([^. ^\[\]]+)|(?!\[)(\d+)(?=\])");
    JsonNode node = JsonNode.Parse("{}");

    foreach (var keyValue in source)
    {
        var pathSegments = regex.Matches(keyValue.Key).Select(m => m.Value).ToArray();

        for (int i = 0; i < pathSegments.Length; i++)
        {
            var currentSegmentType = GetSegmentKind(pathSegments[i]);

            if (currentSegmentType == JsonValueKind.Object)
            {
                if (node[pathSegments[i]] == null)
                {
                    if (pathSegments[i] == pathSegments[pathSegments.Length - 1])
                    {
                        node[pathSegments[i]] = keyValue.Value;
                        node = node.Root;
                    }
                    else
                    {
                        var nextSegmentType = GetSegmentKind(pathSegments[i + 1]);

                        if (nextSegmentType == JsonValueKind.Object)
                        {
                            node[pathSegments[i]] = JsonNode.Parse("{}");
                        }
                        else
                        {
                            node[pathSegments[i]] = JsonNode.Parse("[]");
                        }
                            node = node[pathSegments[i]];
                        }
                    }
                    else
                    {
                        node = node[pathSegments[i]];
                    }
                }
                else
                {
                    if (!int.TryParse(pathSegments[i], out int index))
                    {
                        throw new Exception("Cannot parse index");
                    }

                    while (node.AsArray().Count - 1 < index)
                    {
                        node.AsArray().Add(null);
                    }

                    if (i == pathSegments.Length - 1)
                    {
                        node[index] = keyValue.Value;
                        node = node.Root;
                    }
                    else
                    {
                        if (node[index] == null)
                        {
                            var nextSegmentType = GetSegmentKind(pathSegments[i + 1]);

                            if (nextSegmentType == JsonValueKind.Object)
                            {
                                node[index] = JsonNode.Parse("{}");
                            }
                            else
                            {
                                node[index] = JsonNode.Parse("[]");
                            }
                        }

                        node = node[index];
                    }
                }
            }
        }

    return node;
}

private static JsonValueKind GetSegmentKind(string pathSegment) =>
    int.TryParse(pathSegment, out _) ? JsonValueKind.Array : JsonValueKind.Object;

A: To flatten a JSON object:
arrayJSON.stringify()


text:
Q: Counting toxicity character variables across multiple columns in R and maintaining that information in the dataset I have a dataset that contains toxicity data for medications. The rows are the observations (patients) and the columns contain a type of toxicity (these are multiple columns eg. tox1, tox2, tox3...), the time it occurred, and severity.
eg.

focusing on say fatigue
rows 4 and 5, 6,9 had fatigue listed in Tox 1
rows 7,8,10 had fatigue listed in Tox 2
I think the best way to gather this tox data will be to create a column for each toxicity
So I want to create a Fatigue column with Yes and No Response
I have used this:
Dataset$Fatigue.any.grade <- ifelse(Dataset$Toxicity.1 == "Fatigue", "Yes","No")

which works fine for 1 column
but I can't do it for multiple columns,
Dataset$Fatigue.any.grade <- ifelse(Dataset$Toxicity.1|Dataset$Toxicity.2|Dataset$Toxicity.3|Dataset$Toxicity.4|Datase$Toxicity.4 == "Fatigue", "Yes","No")

Is there any way that I can create 1 toxicity column for fatigue incorporated from the 5 toxicity columns?
example of what  I aim to achieve:

A: A melt and dcast should do what you want:
library(data.table)

dt <- setnames(cbind(data.table(obs = sample(10, 10)), as.data.table(t(replicate(10, sample(c("fatigue", "diarrhoea", "nausia", "rash", "ulcer"), 3))))), new = c("obs", "tox1", "tox2", "tox3"))
> dt
    obs      tox1      tox2      tox3
 1:   4   fatigue diarrhoea      rash
 2:   5   fatigue      rash     ulcer
 3:  10      rash     ulcer    nausia
 4:   9      rash    nausia     ulcer
 5:   8     ulcer    nausia diarrhoea
 6:   3     ulcer diarrhoea    nausia
 7:   6    nausia     ulcer   fatigue
 8:   2    nausia     ulcer   fatigue
 9:   7 diarrhoea   fatigue     ulcer
10:   1 diarrhoea      rash    nausia

> cbind(setorder(dt, obs), dcast(melt(dt, id.var = "obs"), obs ~ value, value.var = "variable")[, -1])
    obs      tox1      tox2      tox3 diarrhoea fatigue nausia rash ulcer
 1:   1 diarrhoea      rash    nausia      tox1    <NA>   tox3 tox2  <NA>
 2:   2    nausia     ulcer   fatigue      <NA>    tox3   tox1 <NA>  tox2
 3:   3     ulcer diarrhoea    nausia      tox2    <NA>   tox3 <NA>  tox1
 4:   4   fatigue diarrhoea      rash      tox2    tox1   <NA> tox3  <NA>
 5:   5   fatigue      rash     ulcer      <NA>    tox1   <NA> tox2  tox3
 6:   6    nausia     ulcer   fatigue      <NA>    tox3   tox1 <NA>  tox2
 7:   7 diarrhoea   fatigue     ulcer      tox1    tox2   <NA> <NA>  tox3
 8:   8     ulcer    nausia diarrhoea      tox3    <NA>   tox2 <NA>  tox1
 9:   9      rash    nausia     ulcer      <NA>    <NA>   tox2 tox1  tox3
10:  10      rash     ulcer    nausia      <NA>    <NA>   tox3 tox1  tox2

A value of NA indicates that the toxicity type was not found in that row. Otherwise, the value under fatigue etc. indicates which toxicity column it came from.
UPDATE: If you'd rather have just TRUE/FALSE under your toxicity type columns, it's an easy modification:
> cbind(setorder(dt, obs), dcast(melt(dt, id.var = "obs")[, present := TRUE], obs ~ value, value.var = "present")[, -1])
    obs      tox1      tox2      tox3 diarrhoea fatigue nausia rash ulcer
 1:   1 diarrhoea      rash    nausia      TRUE      NA   TRUE TRUE    NA
 2:   2    nausia     ulcer   fatigue        NA    TRUE   TRUE   NA  TRUE
 3:   3     ulcer diarrhoea    nausia      TRUE      NA   TRUE   NA  TRUE
 4:   4   fatigue diarrhoea      rash      TRUE    TRUE     NA TRUE    NA
 5:   5   fatigue      rash     ulcer        NA    TRUE     NA TRUE  TRUE
 6:   6    nausia     ulcer   fatigue        NA    TRUE   TRUE   NA  TRUE
 7:   7 diarrhoea   fatigue     ulcer      TRUE    TRUE     NA   NA  TRUE
 8:   8     ulcer    nausia diarrhoea      TRUE      NA   TRUE   NA  TRUE
 9:   9      rash    nausia     ulcer        NA      NA   TRUE TRUE  TRUE
10:  10      rash     ulcer    nausia        NA      NA   TRUE TRUE  TRUE

A: Where You Went Wrong
Unsurprisingly, your condition works as intended on a single column:
Dataset$Toxicity.1 == "Fatigue"

After all, you simply compare (using ==) the character column Dataset$Toxicity.1 to the character value "Fatigue".  So the operation Dataset$Toxicity.1 == "Fatigue" will yield a logical column, with TRUE wherever Dataset$Toxicity.1 contains "Fatigue" and FALSE wherever it does not.
However, in your attempt on multiple columns, you really misinterpret the usage of |.  The logical | operator works on logical columns (or more generally "vectors") of TRUEs and FALSEs, and uses OR to compare their corresponding values:
c(TRUE, FALSE, TRUE, FALSE) | c(TRUE, TRUE, FALSE, FALSE)

# [1] TRUE  TRUE  TRUE  FALSE

So if you were expecting your condition
Dataset$Toxicity.1 | Dataset$Toxicity.2 | Dataset$Toxicity.3 | Dataset$Toxicity.4 | Dataset$Toxicity.5 == "Fatigue"

to expand into something like this
(Dataset$Toxicity.1 == "Fatigue") | (Dataset$Toxicity.2 == "Fatigue") | (Dataset$Toxicity.3 == "Fatigue") | (Dataset$Toxicity.4 == "Fatigue") | (Dataset$Toxicity.5 == "Fatigue")

you are sadly mistaken.  By the order of operations, the clump of |s is evaluated first
# |------------------------------------------------------------------------------------------------------|
  (Dataset$Toxicity.1 | Dataset$Toxicity.2 | Dataset$Toxicity.3 | Dataset$Toxicity.4 | Dataset$Toxicity.5) == "Fatigue"

and that result is compared to the string "Fatigue".
The problem is that your Dataset$Toxicity.* columns are character rather than logical, so it makes no sense to compare them to each other using |.  Even if you could, the result would be a logical vector that could not be compared for equality (==) against the string "Fatigue".
How to Fix It
If you want to do your implementation properly, you need to write out each character comparison, and then use | on the logical results:
Dataset$Fatigue.any.grade <- ifelse(
  Dataset$Toxicity.1 == "Fatigue" | Dataset$Toxicity.2 == "Fatigue" | Dataset$Toxicity.3 == "Fatigue" | Dataset$Toxicity.4 == "Fatigue" | Dataset$Toxicity.5 == "Fatigue",
  "Yes","No"
)

How to Do Even Better
The dplyr package offers mutate() to create (or transform) columns, and across() to manipulate multiple columns at once.
You can operate across() all your Toxicity.* columns with an improvised formula ~. == "Fatigue", which compares each (.) of those columns against the string "Fatigue"; and then you can use Reduce() to consolidate those (logical) results using |.
library(dplyr)

Dataset <- Dataset %>%
  mutate(
    # Create a new column: 'Fatigue.any.grade'.
    Fatigue.any.grade = across(
      # Look across all the columns whose names start with "Toxicity."...
        starts_with("Toxicity."),
        # ...and compare each column against the string "Fatigue".
        ~. == "Fatigue"
      ) %>%

        # Consolidate those logical results using OR (|), to show (TRUE) where ANY of
        # those columns contained "Fatigue".
        Reduce(f = `|`) %>%

        # Change the TRUEs and FALSEs into "Yes"s and "No"s.
        if_else("Yes", "No")
  )

Note
I've written it with lots of comments, but you can easily shorten this mutate():
mutate(
  Fatigue.any.grade = across(starts_with("Toxicity."), ~. == "Fatigue") %>% Reduce(f = `|`) %>% if_else("Yes", "No")
)

Naturally, you can do the same for diarrhea as for fatigue.  Just replicate the mutate() above, but with the column name Diarrhoea.any.grade and the formula ~. == "diarhhoea".
You can also make the comparison case insensitive by altering the formula like so: ~tolower(.) == "fatigue".  Thus, you can detect "FATIGUE" and "fatigue" and "fATigUe", in addition to "Fatigue".

Update
By request

...say now I want to look at toxicity that was classifed as grade 2 or higher i.e Fatige grade 2 accross the columns. what would be the best way to code?

here is a more advanced solution that is conditional upon the grade (tox*_Grade):
# Define a grade range: 2 and higher.
min_grade <- 2
max_grade <- Inf

Dataset <- Dataset %>%
  mutate(
    Fatigue_Grade_n = (
      # Count fatigues...
      across(starts_with("Toxicity."), ~. == "Fatigue") &
      # ...whose grades are in a certain range.
      across(matches("tox\\d+_Grade"), ~ . >= min_grade & . <= max_grade)
      #                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      #                                CUSTOM FORMULA: Just use '.'
    ) %>%
      # Consolidate those logical results, to show (TRUE) where 'any()' of those columns
      # contained "Fatigue".
      apply(MARGIN = 1, FUN = any)

    # ...
  )

Note
You can make the tox*_Grade formula arbitrarily complex to suit your needs.  Just remember the following:

*

*Precede the formula with the ~ symbol.

*Represent the tox*_Grade column as the . symbol.

*Treat the . column as the vector it is. So use vectorized operations (like & instead of &&).