text:
Q: Fatal error: Call to undefined method on specific line Codeigniter throw the next error when trying to render the register page. It looks like the method Register::render() is not defined on line 21 but i don't understand the problem at all

The Register.php file
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Register extends MY_Controller
{

    public function index()
    {
        $this->load->library('form_validation');
        $this->form_validation->set_rules('first_name', 'First name','trim|required');
        $this->form_validation->set_rules('last_name', 'Last name','trim|required');
        $this->form_validation->set_rules('username','Username','trim|required|is_unique[users.username]');
        $this->form_validation->set_rules('email','Email','trim|valid_email|required');
        $this->form_validation->set_rules('password','Password','trim|min_length[8]|max_length[20]|required');
        $this->form_validation->set_rules('confirm_password','Confirm password','trim|matches[password]|required');

        if($this->form_validation->run()===FALSE)
        {
            $this->load->helper('form');
            $this->render('register/index_view');
        }
        else
        {
            $first_name = $this->input->post('first_name');
            $last_name = $this->input->post('last_name');
            $username = $this->input->post('username');
            $email = $this->input->post('email');
            $password = $this->input->post('password');

            $additional_data = array(
                'first_name' => $first_name,
                'last_name' => $last_name
            );

            $this->load->library('ion_auth');
            if($this->ion_auth->register($username,$password,$email,$additional_data))
            {
                $_SESSION['auth_message'] = 'The account has been created. You may now login.';
                $this->session->mark_as_flash('auth_message');
                redirect('user/login');
            }
            else
            {
                $_SESSION['auth_message'] = $this->ion_auth->errors();
                $this->session->mark_as_flash('auth_message');
                redirect('register');
            }
        }
    }
}

A: You should use:
  $this->load->view('register/index_view');

When I started with codeigniter I had a similar issue. Render() is used by some libraries and, like you, I followed a tutorial, but there was nothing about that library. After a while I saw some comments in that article and I found out about render(). If you want to use this, try to find some library that has it implemented.


text:
Q: How to allow a user to exit from the Console at any time C# with an input I am very new to programming in C# so bare with me.
I am currently trying to make a block of code for a BMI Calculator within a menu based Console that allows the user to select from different options and it gives them different results.
I have not completed my code yet but everything has been relatively smooth sailing until I got to the point where I have been told -
"There should also be an option to 'exit' or terminate at any stage when the program is running."
I have looked on multiple forums and have tried to find an answer, none of which I have been able to get to work with my code.
I was hoping someone here would be able to help me out and point me in the right direction.
Here is the code I am currently working with.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BMI_Application
{
    class Program
    {
        static void Main(string[] args)
        {
            bool showMenu = true;
            while (showMenu)
            {
                showMenu = MainMenu();
            }

        }

        private static void Calculator()
        {

        }
        private static bool MainMenu()
        {

            string bmi = "You have selected the BMI Calculator";
            float height;
            float weight;
            float sum1; // Heightx2
            float sum2; // Weight / sum1

            Console.WriteLine("Please select an option");
                Console.WriteLine("1: BMI Calculator");
                Console.WriteLine("2: Membership Rates");
                Console.WriteLine("3: Close Menu");
                Console.WriteLine("\r\nPlease enter 1, 2 or 3");
                Console.WriteLine("\r\nYou can also write 'bye' at any time to leave");

            switch (Console.ReadLine())
            {
                case "1":
                    Console.Clear();
                        Console.WriteLine(bmi);
                        Console.WriteLine("Please enter your Height in Metres");
                        height = float.Parse(Console.ReadLine());
                        Console.WriteLine("Please enter your Weight in Kilograms");
                        weight = float.Parse(Console.ReadLine());
                        sum1 = height * height;
                        sum2 = weight / sum1;
                        Console.WriteLine("Your BMI is : {0}", sum2); // Next part is - based on their BMI Level, writing if they are underweight etc
                    if (sum2 <= 18.5)
                    {
                        Console.WriteLine("Your BMI level indicates that your are 'Underweight' "); // Underweight
                    }
                    if (sum2 >= 18.5 && sum2 <= 25)
                    {
                        Console.WriteLine("Your BMI level indicates that you are 'Normal' weight"); // Normal
                    }
                    if (sum2 >= 25 && sum2 <= 30)
                    {
                        Console.WriteLine("Your BMI level indicates that you are 'Overweight' ");// Overweight
                    }
                    if (sum2 >= 30)
                    {
                        Console.WriteLine("Your BMI level indicates that you are 'Obese' "); // Obese
                    }
                        Console.WriteLine("\r\nPress any key to return back to main menu");
                        Console.ReadKey();
                        Console.Clear();
                        return true;

                    case "2":
                        Console.Clear();
                        Console.WriteLine("You have selected the Membership Rates");
                        Console.WriteLine("What Membership would you like?");
                        return true;
                    case "3":
                        Console.WriteLine("You have selected to close the menu, press any key to continue"); // Terminate
                        Console.ReadKey();
                        return false;
                    case "bye":
                        Console.WriteLine("Goodbye! Push any key to get out of here!");
                        Console.ReadKey();
                        return false;

                    default:
                        Console.Clear();
                        Console.WriteLine("That is not a valid number, please enter 1, 2 or 3"); // Not valid entry
                        Console.WriteLine(" ");
                        return true;
                }
            }
        }

    }

Any ideas of how I would be able to get a user to exit out of the console by entering the word 'exit'  for example?
Thanks very much

A: So if you want to allow the user to enter a text such as "exit" to quit the program at any stage, then at every point where you read input you need to support this.
The way your code is structured at the moment then this is difficult as you basically have 1 method in your code which is doing everything.  And you are actually mixing your "calculator" together with your "menu", which should be separated.
And if you look at your code then you will actually see that you are repeating sections of code multiple times with just slight differences (Writing and reading to/from console).
Instead, you need to structure your code so that you have less repeat of code and instead split this out into separate methods.
This is actually the crux of your program.  Because the way your code is structured, you can't easily adapt it to support the new requirement without re-writing it.
Now I'm not going to re-write your code for you, but I will give you hints on one way to partly do this (there are other ways!)
Try and separate out the writing & reading into a separate method.  Then you can also check for the word "exit" in a separate method.
So Pseudo code would be like this;
//do something in your method
var inputText = WriteAndGetInput("Please select option 1,2,3\r\nBlah blah blah \r\n");
CheckForExit(inputText);

//If you reach here, then Exit was not entered so carry on with your program and check for your real input.
//Try to use methods as to not repeat code.

//Method to write to console and get input
private static string WriteAndGetInput(string textToOutput)
{
       Console.WriteLine(textToOutput);
       return Console.ReadLine();
}

//method to check if user typed exit
private static void CheckForExit(string inputText)
{
    if (inputText.Equals("exit"))
    {
        Console.WriteLine("You chose to exit.   Goodbye!");
        System.Environment.Exit(0);
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: conditional compilation in yacc how to do conditional compilation in yacc. Similar to done in C using ifdef.
I want to create a rule based on a condition. Is it possible in yacc. Example. based on condition rule A is defined as follows:
ruleA : A | B, /* For condition 1 */
ruleA : C      /* If condition 1 is not satisfied */

A: btyacc has conditional compilation based on defined flags, similar to the C preprocessor.  You can say:
%ifdef VERSION_A
ruleA: A | B ;
%endif
%ifdef VERSION_B
ruleA: C ;
%endif

and then use a -DVERSION_A or -DVERSION_B command line argument to get one version or the other.  Its pretty primitive (you can only test a single flag per %ifdef, can't nest %ifdefs and there's no %else), but its adequate for simple things.

A: If you can't preprocess your Yacc grammar with an appropriate preprocessor, then you can use a solution based on actions:
ruleA : A { if  (condition1) { process OK; } else YYERROR; }
      | B { if  (condition1) { process OK; } else YYERROR; }
      | C { if (!condition1) { process OK; } else YYERROR; }
      ;

The YYERROR action triggers Yacc's normal error processing mechanism.  This means your grammar must 'work' with both sets of rules in operation as far as Yacc is concerned.  If this leads to complexity because of shift/reduce (or even reduce/reduce) conflicts, then preprocessing is the way to go.  The result grammar will be smaller and more focussed.

A: My suggestion is that you expose the conditional flag as a terminal symbol, we can call it the mode terminal. (So, technically, it's a run-time not compile-time condition.)
You need to return the mode terminal at every point that it would make a difference in the parse. Your grammar can ignore it when it receives extra ones. It can return the mode terminal only in the "condition 1" case, only in the "not condition 1" case, or you can return a different one in both cases. So say you have two tokens C1 and C2, one for each mode.
This may not work out so well if you are parsing an existing grammar, but if you are designing the grammar and the parser together all problems are solvable.
Then you end up with:
ruleA : C1 A | C1 B | C2 C ;


text:
Q: Get only users that do not have the id equal to a condition and are admin(SQL) I have two tables, user:

id
full_name
is_admin

1
jane
0

2
Helio
0

3
fran
0

4
mila
0

5
admin
1

approver :

id
subordinate_id
approver_id

1
1
2

2
3
4

and I would like to perform a query that brings up the user names that do not have the id in the subordinate_id column of the approvers table.
I tried it this way:
SELECT
    full_name
FROM user AS U
WHERE NOT EXISTS(
SELECT * FROM approver AS A
WHERE A.subordinate_id = U.id AND U.is_admin = 0);

but in this case the admin user is still coming, and I would like to not bring whoever has the is_admin column of the usuario table = 1. I want to bring only common users and not admin.
Can someone help me with this?

A: Try this query
SELECT full_name FROM user AS U
left join approver as A on U.id = a.subordinate_id
where A.id is null AND U.is_admin = 0

A: You need to put AND U.is_admin = 0 outside EXISTS
create table `user`(
 id int,
 full_name varchar(20),
 is_admin int
);

create table `approver`(
 id int,
 subordinate_id int,
 approver_id int
);

insert into `user`(id,full_name,is_admin) values
(1,'jane',0),
(2,'Helio',0),
(3,'fran',0),
(4,'mila',0),
(5,'admin',1);

insert into `approver`(id,subordinate_id,approver_id) values
(1,1,2),
(2,3,4);

SELECT
    full_name
FROM user AS U
 WHERE NOT EXISTS(SELECT A.* FROM approver AS A WHERE A.subordinate_id = U.id )
AND U.is_admin = 0

DB Fiddle Demo

A: You can try this query. We can select the admin="0" in the first table the can left join on second table. And after that We can do the inverse of inner join to get the results you are expecting.
SELECT fullname
FROM
(SELECT * FROM user WHERE is_admin="0") U
LEFT JOIN Approver A
ON U.id=A.subordinate_id
WHERE A.subordinate_id IS NULL;


text:
Q: Join + count on second table i just want to know how much prods are linked with the id from the table emp and i can't find that. I want to get all the emp fields + field called totalProducts with the number of the linked rows with the id so, how can I do it? I'm trying this and not working:
 select emp.*,
        COUNT(prod.*) AS totalProducts
 from emp_fin emp
      JOIN product2 prod on emp.id = prod.id_emp group by emp.id;

Getting error like: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) ...
Thank you all!

A: Don't use aliases with count(*):
select emp.*, COUNT(*) AS totalProducts
from emp_fin emp JOIN
     product2 prod
     on emp.id = prod.id_emp
group by emp.id;

If you wanted to include emps with no products, use left join and do the count like this:
select emp.*, count(prod.id_emp) AS totalProducts
from emp_fin emp left join
     product2 prod
     on emp.id = prod.id_emp
group by emp.id;

A: if you want count all the prod records, select the id_emp (or another notnull field) of toe prod table to count them.
SELECT
    emp.*,
    COUNT(prod.id_emp) AS totalProducts
FROM emp_fin emp
LEFT OUTER JOIN product2 prod
    on emp.id= prod.id_emp
group by emp.id


text:
Q: HTML Agility Pack link correction I'm working on a small project and I got a little problem, hope you could help me.
I got this basic few lines that load a given url and takes out some tags:
var webGet2 = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = webGet2.Load(pattern);
var htmlMatches = doc.DocumentNode.SelectNodes("//li[@class=''] | //li[@class='f']");

After I'm receiving the collection, I need to run a foreach loop
that can take all the href and src link and make them valid, because when I'm downloading the source, the link looks like /folder/folder/image.jpg
I want to add http://www.site.com before each link.
I've build this project with Regex and had no problem doing that, but with HTML agility its not getting straight with my mind.
Thank you!

A: So you want to search some nodes for certain attributes that contain relative urls and change them to absolute urls?  You could do this:
static void AdjustAttributes(HtmlNode root, string baseUrl, string attrName)
{
    var query =
        from node in root.Descendants()
        let attr = node.Attributes[attrName]
        where attr != null
        select attr;
    foreach (var attr in query)
    {
        var url = GetAbsoluteUrlString(baseUrl, attr.Value);
        attr.Value = url;
    }
}

static string GetAbsoluteUrlString(string baseUrl, string url)
{
    var uri = new Uri(url, UriKind.RelativeOrAbsolute);
    if (!uri.IsAbsoluteUri)
        uri = new Uri(new Uri(baseUrl), uri);
    return uri.ToString();
}

var web = new HtmlWeb();
var doc = web.Load(pattern);
var selectedNodes = doc.DocumentNode.SelectNodes("//li[@class=''] | //li[@class='f']");
foreach (var node in selectedNodes)
{
    AdjustAttributes(node, url, "href");
    AdjustAttributes(node, url, "src");
}


text:
Q: EmberJS: How to trigger a parent model refresh when transitioning between children? This is my router:
  this.route('bundle', { path: 'bundles/:slug', resetNamespace: true }, function () {
      this.route('pricing');
  });

So there are two child routes: index and pricing.
Index is a listing of all the products in the bundle, while pricing is where you can purchase the bundle. When somebody purchases a bundle, the pricing page displays a link-to:
{{#link-to 'bundle' bundle.slug}}View Bundle{{/link-to}}`

This hits the model hook of bundle.index, but not of the parent route bundle. I need to refresh the parent route's model after a purchase though because there are server-side changes to the model that need to be displayed in the front-end.
How can I make that happen?

A: On transition hook you can ask for parent model with modelFor.
willTransition(){
  let model = this.modelFor('bundle');
}

Although it may be possible that you will have to redefine your routes because it look like your base router has path with parameter.


text:
Q: Check for empty instance of a class I have a class with an empty constructor to support array creation. Suppose:
classdef MyClass < handle

  properties
    input1 = 0;
  end
  methods
  function obj = MyClass(input1)
    if nargin > 0
      obj.input1 = input1
    end
  end
  end
end

And I create a empty array of this class:
emptyArray(666) = MyClass

Then I fill some of the emptyArray indexes with full MyClass instances. Is there a matlab function to check if MyClass function is the same as the MyClass instance? Otherwise, how do I check if:
emptyArray==MyClass

to know the indexes in which the emptyArray contains empty instances of MyClass.
Thanks.
Note: It is a handle class.

A: Would you consider overloaind isempty method for this class?
function tf = isempty( obj )
    tf = isempty( obj.input1 );
end


text:
Q: How do I convert a mixed case array to lowercase using the map function in Javascript? I am attempting to convert a javascript mixed case Array to lowercase.  I've been searching for solutions, but the answers I am finding are for C#, C, or Java.  Can anyone give me suggestions on how to proceed?
Here's the relevant JS code I'm working with:
var newArray = oldArray.map(oldArray.toLowerCase);

A: Try:

let array = ["abC", "aDB", "bdD"];
let newArray = array.map((item) => {
  return item.toLowerCase();
});
console.log(newArray);

Remember: the map method takes a callback with three arguments, with the first being the current value being processed in the array. Think of it as an iterative function, iterating on each item in the array. The map method must also return a value for each iteration, otherwise it will return undefined for that specific value in the process/iteration.

A: ["ABC", "dEf"].map(function(item) { return item.toLowerCase(); });
oldArray.map(function(item) { return item.toLowerCase(); });

Depending on the language, you may prefer using toLocaleLowerCase (Turkish example).

A: Try
var newArray = oldArray.map(function (val) { return val.toLowerCase(); });

Here is some documentation on the map function.

A: var newArray = oldArray.map(function(x){ return x.toLowerCase() })


text:
Q: Let $(X, \mathcal{M})$ be a measurable space and $\mu : \mathcal{M} → [0, \infty]$. Show that $\mu$ is a measure. Let $(X, \mathcal{M})$ be a measurable space and $\mu : \mathcal{M} → [0, \infty]$ such that
(a) $µ (A) <\infty$ for some $A \in \mathcal{M}$
(b) $µ(A \cup B) = \mu(A) + \mu(B)$ if $A, B \in \mathcal{M}$ and $A \cap B = \emptyset$, and
(c) $\mu (\bigcup_{n=1}^{\infty} A_{n}) \leq \sum_{n=1}^{\infty}\mu(A_n) $ if $A_n \in \mathcal{M}$ for $n=1,2,3,...$
Show that $\mu$ is a measure.
In my context, we define a measure as follows:
Definition:
A function µ is called a positive measure, defined in a $\sigma$-algebra $\mathcal{M}$ with values in $[0, \infty]$ and which is countably additive. This means that if $\{E_i\}$ is a disjoint countable collection of elements of $\mathcal{M}$, then $\mu (\bigcup_{i=1}^{\infty} E_{i}) = \sum_{i=1}^{\infty}\mu(E_i)$.
To avoid trivial cases, we will further assume that $\mu (A) < \infty $ for at least one $A \in \mathcal{M}$
My attempt:
From the definition, it only remains for me to prove that $\mu$ is countably additive. To do this, let $\{A_n\}$ be a disjoint countable collection of elements of $\mathcal{M}$. Then, $$ \bigcup_{n=1}^{\infty}A_n  \supset \bigcup_{n=1}^{N}A_n$$ And so
$$\mu \left(\bigcup_{n=1}^{\infty}A_n \right)  \geq \mu \left(\bigcup_{n=1}^{N}A_n \right) = \sum_{n=1}^{N}\mu(A_n)$$
Since the left side of this inequality is independent of $N$, we have $$\mu \left(\bigcup_{n=1}^{\infty}A_n \right)  \geq \sum_{n=1}^{\infty}\mu(A_n)$$
For part (c) we have the equality.
First of all I want to know if there are any errors in my reasoning and, on the other hand, I don't see where I used the hypothesis of part (b) in my proof; This really does have me worried. I appreciate any help you can give me.

A: What you have done seems correct. In fact, what you have done shows that given any $\sigma$-algebra $\mathcal{M}$ and any map $\mu : \mathcal{M} \to [0, \infty]$ with the property (b) alone, it follows that given a disjoint collection $\{A_i\}_i$, it is the case that $$\sum_{i = 1}^\infty \mu(A_i) \le \mu\left(\bigcup_{i = 1}^\infty A_i\right).$$
(As pointed in the comments, you used (b) to conclude that $$\mu \left(\bigcup_{n=1}^{N}A_n \right) \color{red}{=} \sum_{n=1}^{N}\mu(A_n),$$
which really follows by induction and (b).)
Property (c) was then just the minimum required for you to conclude equality.
As an exercise, you could try to come up with an example to show that (c) is really needed and doesn't just follow from (b).

I have ignored (a) in the above. Clearly, it is only there to avoid the case that $\mu$ is identically $\infty$, which is what your definition also demands. However, note that it is equivalent to demanding that $\mu(\varnothing) = 0$, assuming either (b) or countable additivity. (How?)


text:
Q: Is it possible in an "if-statement" to execute the actual statement if the condition is false? I encountered the code example below in the JavaNotes book. The answer was that after execution the x is equal to 2.
My question is how exactly does this work?
I see it is not an if-else flow, but in the second "if" the boolean expression is false, so X shall not obtain value 2.
How is this happening?
int x;
x = -1;
if (x < 0)
  x = 1;
if (x >= 0)
  x = 2;

A: Try rubber duck debugging! Read the comment in the code so you can understand how your code work :
int x;
x = -1;
if (x < 0) { //-1 < 0 = true
    x = 1;   //enter here -> change x = 1
}//end of the first if

if (x >= 0) {//1 >= 0 = true
    x = 2;   //enter here -> change x = 2
}//end of the second if

System.out.println(x);//result is 2

If you expect x = 1 then your code should look like this :
if (x < 0) { //-1 < 0
    x = 1;   //enter here -> change x = 1
} else if (x >= 0) {//1 >= 0
//^^^^------------------------------------------note the else
    x = 2;   //enter here -> change x = 2
}

A: x = -1;
first if: x < 0 is true,
so x gets new value 1
second if: x > 0 is true
so x gets new value 2
x = 2;


text:
Q: Вращение круга SVG с элементом группы Я хотел бы вращать SVG-круг, не давая вращаться другим элементам

Когда я пытаюсь повернуть круг (белого цвета) с помощью rotateZ (15 градусов),  то это выглядит, как на рисунке ниже:

Это мой прогресс до сих пор: jsfiddle
Я хотел бы достичь
Круг (белого цвета) вращается, когда происходит клик по белому кругу
Свободный перевод вопроса Rotating a SVG circle with group element от участника  @JackPowell.
<svg viewBox="0 0 1400 900" style="outline:1px solid red;">
    <g>
       <clipPath id="hexagonal-mask">
          <circle cx="700" cy="100" r="705" ></circle>
       </clipPath>
    </g>

     <image clip-path="url(#hexagonal-mask)" height="100%" width="100%" xlink:href="http://placekitten.com/800/400"  style="transform: translateY(-140px);"/>

    <g  style="transform-origin: 701px -5%; transform: rotateZ(15deg)">
        <circle cx="701" cy="0" r="665" stroke="#fff" stroke-width="1px" fill="transparent"  style="transform: translateY(-50px);" ></circle>

        <g id="f" class="fuck">
            <circle cx="701" cy="615" r="15" fill="#fff" stroke-width="4" stroke="#000">

            </circle>
            <path  stroke="#000" stroke-width="1px" d="M701 630 701 690"></path>

            <text x="672" y="720" font-family="'Playfair Display', serif" font-size="2em" font-weight="bold" fill="#9d9e9f">2007</text>
            <text x="640" y="730" font-family="'Playfair Display', serif" font-size="2.85em" font-weight="bold" fill="#000">
                <tspan x="640" dy="40">Lorem</tspan>
                <tspan x="640" dy="45">Ipsum</tspan>
            </text>

            <animateMotion
               xlink:href="#f"
               dur="1s"
               begin="click"
               fill="freeze"
               path="M0 100 Q50 80 -399 -135"
               repeatCount="1">

            </animateMotion>
        </g>

        <g>

            <circle cx="302" cy="480" r="15" fill="#fff" stroke-width="4" stroke="#000"></circle>
            <path stroke="#000" stroke-width="1px" d="M302 495 305 675"></path>
        </g>

        <g>
            <circle cx="1100" cy="480" r="15" fill="#fff" stroke-width="4" stroke="#000"></circle>
            <path  stroke="#000" stroke-width="1px" d="M1100 495 1100 675"></path>
        </g>
    </g>

</svg>

A: Вместо того, чтобы вращать все, я бы вычислял положение точек на круге и использовал координаты точек, чтобы нарисовать линию и текст.
Для этого я использую JavaScript. Наиболее важной частью в скрипте является функция, используемая для вычисления новой позиции повернутой точки: rotatePoint (p, c, rot)
Обратите внимание, что в SVG я устранил бесполезные преобразования.

let theG = document.querySelector("#theG");
//координаты центра круга
let center = { x: 700, y: -40 };
//вращение в радианах
let rot = .6;
//функция для расчета новой позиции повернутой точки
function rotatePoint(p, c, rot) {
  // p: точка
  // c: центр вращеня
  // rot: вращение
  let cos = Math.cos(rot);
  let sin = Math.sin(rot);
  return {
    x: c.x + (p.x - c.x) * cos - (p.y - c.y) * sin,
    y: c.y + (p.x - c.x) * sin + (p.y - c.y) * cos
  };
}

//все группы с классом .dot
let groups = theG.querySelectorAll(".dot");
let points = [];

groups.forEach((g) => {
  let dot = g.querySelector("circle");
  let p = {};

  p.x = dot.getAttribute("cx");
  p.y = dot.getAttribute("cy");

  points.push(p)
});

itr.addEventListener("input",()=>{

let rot = itr.value;

groups.forEach((g,i) => {

  let dot = g.querySelector("circle");
  let line = g.querySelector("line");
  let t1 = g.querySelectorAll("text")[0];

  let newPoint = rotatePoint(points[i], center, rot);

  dot.setAttribute("cx", newPoint.x);
  dot.setAttribute("cy", newPoint.y);

  line.setAttribute("x1", newPoint.x);
  line.setAttribute("x2", newPoint.x);
  line.setAttribute("y1", newPoint.y);
  line.setAttribute("y2", newPoint.y + 180);

  t1.setAttribute("x", newPoint.x);
  t1.setAttribute("y", newPoint.y + 200);

});

});
input{width:90vw;}
p{text-align:center;}
text{text-anchor:middle}

line{stroke:#000; stroke-width:1px; }

<input type="range" id="itr" min="-.85" max=".85" value="0" step=".01" />

<svg viewBox="0 0 1400 900" style="outline:1px solid red;" >
   <defs>
    <clipPath id="hexagonal-mask">
      <circle cx="700" cy="-40" r="705"></circle>
    </clipPath>
  </defs>
  <image clip-path="url(#hexagonal-mask)" height="100%" width="100%" xlink:href="https://assets.codepen.io/222579/castell.jpg"></image>
  <circle cx="700" cy="-40" r="655" stroke="#fff" stroke-width="1px" fill="transparent"></circle>
  <g id="theG">

    <g class="dot">
      <circle cx="700" cy="615" r="15" fill="#fff"></circle>
      <line x1="700" y1="615" x2="700" y2="795"></line>
      <text x="700" y="815" font-family="'Playfair Display', serif" font-size="2em" font-weight="bold" fill="#9d9e9f">2007</text>
    </g>

    <g class="dot">
      <circle cx="302" cy="480" r="15" fill="#fff"></circle>
      <line x1="302" y1="480" x2="302" y2="660"></line>
      <text x="302" y="680" font-family="'Playfair Display', serif" font-size="2em" font-weight="bold" fill="#9d9e9f">2006</text>
    </g>

    <g class="dot">
      <circle cx="1100" cy="480" r="15" fill="#fff"></circle>
      <line x1="1100" y1="480" x2="1100" y2="660"></line>
      <text x="1100" y="680" font-family="'Playfair Display', serif" font-size="2em" font-weight="bold" fill="#9d9e9f">2008</text>
    </g>
  </g>
</svg>

Свободный перевод ответа Rotating a SVG circle with group element от участника  @enxaneta.

A: Мне было интересно,  можно ли  сделать это без JavaScript. В следующей демонстрации я использую JavaScript только для того, чтобы изменить значение поворота.
Поскольку я использую svg-преобразования, углы в градусах, а не в радианах.
Основная идея заключается в следующем: я создаю вложенный элемент SVG. Пока я поворачиваю theG в одном направлении, мне нужно повернуть линию и текст на одинаковое количество градусов в противоположном направлении. Проблема в том, что при вращении theG точки меняют положение, и мне нужно знать это положение, чтобы использовать его в качестве отправной точки для строки и текста.
Решение состоит в том, чтобы поместить всё в вложенный SVG, где всё остается в том же положении, и вращать вложенный SVG. Как видно в SVG 1.1, элемент не допускает атрибут transform. Поэтому я поместил все вложенные svg в группу и вместо этого повернул группу.

itr.addEventListener("input",()=>{

let rot = itr.value;
theG.setAttribute("transform",`rotate(${rot} 700 -40)`)
dot2006.setAttribute("transform",`rotate(${-rot} 302 480)`);
dot2007.setAttribute("transform",`rotate(${-rot} 700 600)`);
dot2008.setAttribute("transform",`rotate(${-rot} 1100 480)`);
});
input{width:90vw;}
p{text-align:center;}
text{text-anchor:middle; font-family:'Playfair Display' serif; font-size:2em; font-weight:bold; fill:#9d9e9f;}

line{stroke:#000; stroke-width:1px; }

<input type="range" id="itr" min="-45" max="45" value="0" />

<svg viewBox="0 0 1400 900" style="outline:1px solid red;">
  <defs>
    <clipPath id="hexagonal-mask">
      <circle cx="700" cy="-40" r="705"></circle>
    </clipPath>

     <g id="cl">

      <circle r="15" fill="#fff"></circle>
      <line y2="180"></line>
      </g>
  </defs>

  <image clip-path="url(#hexagonal-mask)" height="100%" width="100%" xlink:href="https://assets.codepen.io/222579/castell.jpg"></image>
  <circle cx="700" cy="-40" r="655" stroke="#fff" stroke-width="1px" fill="transparent"></circle>

  <g id="theG" transform="rotate(0 700 -40)">

<g id="dot2007" transform="rotate(0 700 600)">

<svg x="668" y="600" width="64" height="224" viewBox="-32 -15 64 224" >
      <use xlink:href="#cl"/>
      <text y="200">2007</text>
    </svg>
    </g>

<g id="dot2006" transform="rotate(0 302 480)">

<svg x="270" y="465" width="64" height="224" viewBox="-32 -15 64 224">
      <use xlink:href="#cl"/>
      <text y="200">2006</text>
    </svg>
</g>

<g id="dot2008" transform="rotate(0 1100 480)">

<svg x="1068" y="465" width="64" height="224" viewBox="-32 -15 64 224">
      <use xlink:href="#cl"/>
      <text y="200">2008</text>
    </svg>
    </g>

  </g>
</svg>

Свободный перевод ответа Rotating a SVG circle with group element от участника  @enxaneta.


text:
Q: Proving that a particular CFG grammar generates language L $$L=\left\{w\in\{x,y\}^*\mid N(y)=2N(x)\right\}$$
and $G$ is
$$S\to yySx\mid ySxSy\mid xSyy\mid SS\mid\epsilon$$
I need to proof that the grammar generates this language.
I know that I need to use induction to prove it, but I can't follow through
so, could you show how to prove it?

A: There are two parts to this: you have to show that every word generated by $G$ is in $L$, and you have to show that every word in $L$ is generated by $G$. The first of these is straightforward. Suppose that $w$ is generated by $G$. Then it has a derivation
$$S=w_0\Rightarrow w_1\Rightarrow w_2\Rightarrow \ldots\Rightarrow w_{n-1}\Rightarrow w_n=w\,.$$
Clearly $|S|_x=|S|_y=0$, so $|S|_y=2|S|_x$. Now suppose that $0\le k<n$ and that $|w_k|_y=2|w_k|_x$, and verify that $|w_{k+1}|_y=2|w_{k+1}|_x$ no matter which production of $G$ is used to derive $w_{k+1}$ from $w_k$. Once you've done that, you can conclude by induction that $|w|_y=|w_n|_y=2|w_n|_x=2|w|_x$ and hence that $w\in L$.
The second part is a bit harder, but it can be done by induction on $|w|$. If $w\in L$ has length $0$, then $w=\epsilon$, which is generated by $G$. Now for the induction step let $n\in\Bbb Z^+$, suppose that every word of $L$ of length less than $n$ is generated by $G$, and let $w\in L$ be of length $n$; you need to show that $w$ is generated by $G$.
We'll need to break the argument into cases, and we'll use a technique that is useful but not obvious in order to do so. Say $w=u_1u_2\ldots u_n$, where each $u_k$ is either $x$ or $y$. Let $c_0=0$, and for $k=0,\ldots,n-1$ let
$$c_{k+1}=\begin{cases}
c_k+1,&\text{if }u_k=y\\
c_k-2,&\text{if }u_k=x\,.
\end{cases}$$
This is less complicated than it looks. Imagine reading $w$ from left to right, starting a counter at $0$, increasing it by $1$ each time you read a $y$, and decreasing it by $2$ each time you read an $x$; $c_k$ is the value of the counter after you've read $k$ letters of $w$. Because $w\in L$, it has twice as many $y$s as $x$s, so the counter must reach $0$ at the end of the word: $c_n=0$.

*

*Suppose first that $c_k=0$ for some $k$ with $0<k<n$. Let $w_1=u_1\ldots u_k$ and $w_2=u_{k+1}\ldots u_n$. Show that $w_1,w_2\in L$. Clearly $|w_1|,|w_2|<n$, so the induction hypothesis then ensures that $w_1$ and $w_2$ have derivations in $G$. Show that $w$ has a derivation in $G$ that starts $S\Rightarrow SS$.

Now suppose that $c_k\ne 0$ for $1\le k\le n-1$.

*

*If $u_1=x$, then $c_1=-2$. Suppose that $c_k>0$ for some $k>1$. Then there is a smallest $k$ such that $c_k>0$. When the counter increases, it always increases by $1$, so it must be that $c_k=1$ and $c_{k-1}=0$. But this is impossible (why?), so it must be that $c_k<0$ for $1\le k\le n-1$. Since $c_n=0$, this implies that $c_{n-1}=-1$ and $c_{n-2}=-2$ (why?) and hence that $u_{n-1}=u_n=y$. Thus, $w=xw_1yy$, where $w_1=u_2\ldots u_{n-2}$. Clearly $|w_1|<n$, so $w_1\in L$, and $w_1$ has a derivation in $G$. Show how to modify this derivation to get a derivation of $w$ in $G$.

Now suppose that $c_k\ne 0$ for $1\le k\le n-1$, and $u_1=y$, so that $c_1=1$. There are now two possibilities.

*

*Suppose that $u_n=x$, so that $c_{n-2}=2$. Argue as in the previous bullet point to show that if some $c_k<0$, then there must be an $\ell$ such that $k<\ell<n-1$ and $c_\ell=0$ and that this is impossible. Conclude that $c_k>0$ for $1\le k\le n-1$. In particular, $c_2>0$, so $u_2=y$ (why?). Thus, $w=yyw_1x$, where $w_1=u_3\ldots u_{n-1}$. Show that $w_1$ has a derivation in $G$, and show how to modify this derivation to get a derivation of $w$ in $G$.

*Finally, suppose that $u_n=y$. Then $c_1=1$, and $c_{n-1}=-1$ (why?), but there is no $k$ such that $1<k<n-1$ and $c_k=0$. This means that there must be a $k$ such that $c_k=1$ and $c_{k+1}=-1$; why? Clearly this means that $u_{k+1}=x$. Let $w_1=u_2\ldots u_k$ and $w_2=u_{k+2}\ldots u_{n-1}$. Show that $w_1,w_2\in L$; clearly $|w_1|,|w_2|<n$, so $w_1$ and $w_2$ have derivations in $G$. Show how to modify those derivations to get a derivation of $w$ in $G$.

Note that each of the four cases is based on one of the non-terminal productions in $G$.


text:
Q: vertx-http-service-factory not working in fat jar To deploy a verticle from HTTP, I added the plugin vertx-http-service-factory in pom.xml file:
<dependency>
    <groupId>io.vertx</groupId>
    <artifactId>vertx-http-service-factory</artifactId>
    <version>3.2.1</version>
</dependency>

Then I deploy the example verticle like this:
vertx.deployVerticle("https://bintray.com/artifact/download/vietj/testgenrepo/helloworld.zip::helloworld");

I works when I launch it from Eclipse, but when I start it from fat JAR, I have this error:
ava.lang.ClassNotFoundException: //bintray.com/artifact/download/vietj/testgenrepo/helloworld.zip::helloworld
   at java.net.URLClassLoader.findClass(Unknown Source)
   at java.lang.ClassLoader.loadClass(Unknown Source)
   at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
   at java.lang.ClassLoader.loadClass(Unknown Source)
   at io.vertx.core.impl.JavaVerticleFactory.createVerticle(JavaVerticleFactory.java:42)
   at io.vertx.core.impl.DeploymentManager.lambda$doDeployVerticle$163(DeploymentManager.java:142)
   at io.vertx.core.impl.FutureImpl.checkCallHandler(FutureImpl.java:135)
   at io.vertx.core.impl.FutureImpl.setHandler(FutureImpl.java:100)
   at io.vertx.core.impl.DeploymentManager.doDeployVerticle(DeploymentManager.java:131)
   at io.vertx.core.impl.DeploymentManager.doDeployVerticle(DeploymentManager.java:103)
   at io.vertx.core.impl.DeploymentManager.deployVerticle(DeploymentManager.java:91)
   at io.vertx.core.impl.VertxImpl.deployVerticle(VertxImpl.java:534)
   at io.vertx.core.impl.VertxImpl.deployVerticle(VertxImpl.java:521)
   at Scheduler.start(Scheduler.java:22)
   at io.vertx.core.AbstractVerticle.start(AbstractVerticle.java:111)
   at io.vertx.core.impl.DeploymentManager.lambda$doDeploy$169(DeploymentManager.java:407)
   at io.vertx.core.impl.ContextImpl.lambda$wrapTask$15(ContextImpl.java:314)
   at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:357)
   at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:357)
   at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:111)
   at java.lang.Thread.run(Unknown Source)

It seems that vertx-http-service-factory is not loaded in the fat jar.
There is probably something to modify in the pom.xml file, but I don't know what. Have a idea?

A: It works If I register HttpSecureServiceFactory :
vertx.registerVerticleFactory(new HttpSecureServiceFactory());

Then you can deploy a http verticle from a fat JAR:
vertx.deployVerticle("https://bintray.com/artifact/download/vietj/testgenrepo/helloworld.zip::helloworld");


text:
Q: How to use pattern recognition on graphs/charts? I can create time-series graphs from data (charts) as images in C#. One might be moving average of a measured value, say 100 pixels by 100 pixels, time on X, value on Y.
I only train with graphs of values that give a desired (or undesired) result. This means I have lots of 10k images of success that I can use for training a NN.
The idea is to look at a current graph and establish a % match against the training data (many successful images either compiled/summed, averaged, etc. A high % match is likely the same situation exists now as with previous successes.
But I cannot figure out:
Q: How to compare images, or more basically, how to load a current image to test against in a trained NN. Do I really need 10,000 input nodes?!
There has to be a better way.
Right now I'm trying to make Encog/C# work for the image recognition/matching. There seems to be a lot of research in OCR, where a hard yes/no is made on input data, but not much at all about a 'fuzzy' match to the training data...


text:
Q: My jupyter notebook doesn't warn to use the latest numpy version I am using a conda virtual env and i already upgraded numpy to 1.22. In my notebook it still uses 1.19.

why isn't it using 1.22?
Also when i open the venv in Python with a CLI:
>>> import numpy
>>> numpy.__version__
'1.22.4'

A: Are you running Jupyter from a base environment or from the new environment?  If you are launching Jupyter from a different environment, you need to switch kernels to the new environment.
There are several ways to check which kernel you are using, typically:
import sys
sys.executable

If the path is not in the correct environment, you can change by selecting the Kernel drop-menu > "Change Kernel..."
If the kernel you want to use does not appear there, you need to install ipykernel.
conda install --name <env name> ipykernel

How did you install the new version of numpy?  For a Conda environment, you should use Conda.  If you used PIP, it may be in an entirely different location/environment.
You can check the difference by running the following in Jupyter and the Python REPL:
import numpy as np
np.__file__


text:
Q: Calculating the percentage of a plane that is underneath a slope I am a bit stuck with this problem.  I have an NxN square and a line that passes through this square.  How can I calculate the percentage of the NxN square that falls above and beneath the line given an arbitrary slope?  I imagine I have to use the Pythagorean theorem on this one, I am just not sure how to apply it.  Any help is appreciated. (Not homework)

A: Basic idea: find the 0, 1 or 2 points where the line intersects the square. If there are 0 or 1 intersections, the square is entirely on one side of the line. If there are two, the square is bisected into two polygons (a triangle and a pentagon if the two intersections are on adjacent sides, or two quadrilaterals if the intersections are on opposite sides). Find the respective area of the two parts, and that will give you the percentages.


text:
Q: How to generate a content provider with GreenDao 3? In GreenDao 2.x., there was a method called Entity.addContentProvider() which generated a ContentProvider for an entity.
How to do the same in GreenDao 3.x?

A: With the same method Entity.addContentProvider() I am able to generate the content provider in GreenDao 3.


text:
Q: Inline function calling static inline function I'm not sure whether the following is a bug in the C standard, a bug in GCC, or some weird behavior I just misunderstand, but the following complains about an implicit declaration of foo:
static inline void foo(void);

inline void bar(void) {
    foo();
}

Any thoughts? Thanks.
Note: If you want the correct answer, search for mine rather than the other ones, regardless of votes.

A: Nevermind, I've found the correct answer.
Even though the code makes logical sense for the single translation unit case, the standard seems to explicitly forbid this corner case (it'd be bad practice anyway, since refactoring could lead to problems if foo and bar are moved to separate TUs---since foo wouldn't be bar's TU's scope).
C11's §6.7.4p3 says:

An inline definition of a function with external linkage shall not contain a definition of a modifiable object with static or thread storage duration, and shall not contain a reference to an identifier with internal linkage.

A: You are declaring foo, but never defining it. The error I get is inline function 'void foo()' used but never defined, which tells you exactly that.


text:
Q: Long lived thread doesn't call performSelectorOnMainThread I have a worker thread that I keep alive through a loop that's controlled by a flag. I need the thread to stay alive for the length of my application as it opens a permanent connection to a remote server.
I fire up that thread and call several methods on it with:
[worker performSelector:@selector(getBusy) onThread:worker withObject:nil waitUntilDone:NO];
This seems to work fine and the method is called. At some point in getBusy I try to call a method in the main thread with:
[delegate performSelectorOnMainThread:@selector(gotBusy) withObject:nil waitUntilDone:NO
where delegate is a reference to the class that starts the separate thread.
The problem is that gotBusy never gets called on the main thread. I've peppered it with NSLog() statements and I can't see them printed on the console.
What should I be looking for to debug this?

A: First, make sure delegate is not nil.   Secondly, make sure your main event loop is not blocked and not running in a modal mode.

A: Is it possible that you never assigned delegate, so you're calling performSelectorOnMainThread on a nil object? You could try setting waitUntilDone to YES so your worker thread will block and let the delegate do its work.


text:
Q: Reuse playbook and pass host from master playbook I have select.yml with prompts for IP and machine_id.yml which should be included from select.yml and should takes host from select.yml. I've tried many configurations without success.
How to reuse machine_id.yml and inject host into it?
select.yml
- hosts: localhost
  gather_facts: no
  vars_prompt:
  - name: target_host
    prompt: "[M] please enter the target host IP"
    private: no
  tasks:
    - add_host:
        name: "{{ target_host }}"
        groups: dynamic_hosts
    - import_playbook: machine_id.yml

machine_id.yml
- hosts: localhost
  gather_facts: no
  vars_prompt:
  - name: target_host
    prompt: please enter the target host IP
    private: no
  tasks:
    - add_host:
        name: "{{ target_host }}"
        groups: dynamic_hosts

- hosts: "{{ dynamic_hosts }}"
  vars:
    ansible_python_interpreter: /usr/bin/python3
  become: yes

  tasks:
    - name: Reset machine-id
      shell: rm /etc/machine-id && rm /var/lib/dbus/machine-id && dbus-uuidgen --ensure=/etc/machine-id && dbus-uuidgen --ensure
      args:
        warn: no

A: You were on the right way. - import_playbook: machine_id.yml must be on the level of - hosts:
Here is an example which worked for me:
select.yaml:
- hosts: localhost
  gather_facts: no
  vars_prompt:
  - name: target_host
    prompt: "[M] please enter the target host IP"
    private: no
  tasks:
    - add_host:
        name: "{{ target_host }}"
        groups: dynamic_hosts
    - debug: var=groups
- import_playbook: machine_id.yaml

machine_id.yaml:
- hosts: dynamic_hosts
  gather_facts: no
  tasks:
    - ping:

Can you give it a try? If it's not working, please let us know your error.


text:
Q: Force of an ideal spring Suppose you have an ideal spring (constant of the spring $k$) attached to a uniform disc of radius $R$ as in the picture below:

The force $F$ in red is from the spring.
My question is the following:
How should I decompose the force $F$ into its $x$ and $y$ components??
My intuition would tell me to multiply the module of the force by the sine and cosine of the angle between $F$ and the $x$ axis or something similar, however I noted in some exercises and exams, the solution simply states that $F_x = -kS(u_x)$ where $S$ is the distance from the y axis, $u_x$ the unit vector of the $x$ axis and $F_x$, of course, the $x$ component of $F$. What is the correct approach? I could not find anything useful on the internet so far...

A: If $S$ is de distance from $C$ to de $y$ axis, then $S=|r|\cos(\theta)$ where $r$ is the position of $C$ with respect to the origin and $\theta$ is the angle between the spring and the $x$ axis. However if you want to write $F_y$ then you would have $F_y=-k|r|\sin(\theta)u_y$. So you were correct in thinking in the decomposition of $F$ as a function of $\theta$ observer however that $S$ is not $|r|$ which is a crucial difference.

A: You have a correct answer, but I'm not sure if you have it for the right reason. Hooke's law states that
$$ \vec{F}_{\text{spring}} = -k\vec{r}$$
where $\mathbf{r}$ is the displacement of the spring from its equilibrium length (which you have not provided in the problem). If you take the equilibrium length to be 0, the spring force then has a magnitude
$$|\vec{F}_{\text{spring}}| = kR$$
where $R$ is the distance between the center of the disk and the origin.
Taking $\theta$ to be the angle between the angle the spring makes with the x axis, then,
$$\vec{F_x} = - kR \cos{\theta} \hat{u_x}$$
$$\vec{F_y} = - kR \sin{\theta} \hat{u_y}$$
High school trig tells you that $\cos{\theta} = \text{adjacent}/\text{hypotenuse}$ and $\sin{\theta} = \text{opposite}/\text{hypotenuse}$. In this case $\cos{\theta} = S/R$ and $\sin{\theta} = \sqrt{R^2-S^2}/R$. Therefore,
$$\vec{F_x} = - kR\Big(\frac{S}{R}\Big)\hat{u_x} = -kS\hat{u_x}$$
$$\vec{F_y} = - kR \Big( \frac{\sqrt{R^2-S^2}}{R} \Big) \hat{u_y} = -k\sqrt{R^2-S^2}\hat{u_y}$$


text:
Q: update angularjs model from jquery I want to update my Angular model based on text input which its value defined by Jquery script. How do I do that?
My Jquery
$("fire").click(function (e) {
      $("#modelChanger").val(1));
});

My DOM :
<input ng-model="data" type="text" id="modelChanger" ng-change="changeIt()"/>

My Angular controller:
$scope.data= 0; // I hope this one change to 1, but it wont
$scope.changeIt =  function(){
   $scope.data++;
}

I know ng-change always work for user directly change the value of any element. Is there  other angular directive to solve this one? Any advice guys?


text:
Q: disable href on content page from Master page in vb.net Just as the title says. I have code that disables all controls that runat=server. Its as follows
Dim c As Control
For Each c In pc
   If c.HasControls Then DisableAllControls(c.Controls)

   If c.GetType.ToString.ToLower.IndexOf("webcontrols.dropdownlist") > -1 Then
      DirectCast(c, DropDownList).Enabled = False
   ElseIf c.GetType.ToString.ToLower.IndexOf("webcontrols.textbox") > -1 Then
      DirectCast(c, TextBox).Enabled = False
   ElseIf c.GetType.ToString.ToLower.IndexOf("webcontrols.radiobuttonlist") > -1 Then
      DirectCast(c, RadioButtonList).Enabled = False
   ElseIf c.GetType.ToString.ToLower.IndexOf("webcontrols.radiobutton") > -1 Then
      DirectCast(c, RadioButton).Enabled = False
   ElseIf c.GetType.ToString.ToLower.IndexOf("webcontrols.button") > -1 Then
      DirectCast(c, Button).Enabled = False
   End If
 Next

But I have a couple of href's in there that i want to disable also. I know they dont runat server, so how can i catch these?

A: You can add runat="server":

It is the only way to maintain controls using server side code.

A: You can add runat="server" to HTML controls too. Without it you won't be able to access the control on the server side and you won't be able to disable it.

A: That code looks invalid (If c.HasControls Then DisableAllControls(c.Controls) has no matching End If) but perhaps VB.NET has added inline If syntax like that without me realising.
Anyway, as far as disabling all runat="server" controls, you should be able to just do this:
For Each c as WebControl In pc.OfType(Of WebControl)()
    ' Put your recursive call here as before
    c.Enabled = False
Next

Now, to "disable" those other elements, you can either add runat="server" to them (perhaps not even possible if you have generated HTML), or you can use some JavaScript. I'm going to assume by disable you mean hide in the case of  tags?
jQuery makes this easy, with a sample script being something like:
$(document).load(function() {
  $('a').hide();
});

or:
/* hides all a tags under an element with class="someClass" */
$(document).load(function() {
  $('.someClass a').hide();
});

You could then have your code render this script, using something like this in your Page:
Dim script as String = "" /* your javascript here */
Me.ClientScript.RegisterClientScriptBlock(Me.GetType(), "HideTagsScript", script)


text:
Q: Algorithm to not make randomly-placed objects overlap? Let's say I have a div and I insert other divs with randomly-generated location values (top, left).
I'd like an algorithm to not make the elements overlap. I could set the position to relative but the elements would overflow out of the container.
Here's an example fiddle.
for (var i = 0 ; i < 20 ; i++)
{
    var elem = $(document.createElement('div'));
    elem.attr('class', 'child').
    css
    ({
        'top': Math.floor(Math.random()*((height-50)-30+1)+30),
        'left': Math.floor(Math.random()*((width-50)-30+1)+30),
        'width' : 30,
        'height': 30
    });
    $('#wrapper').append(elem);
}

A: If you're not placing very many objects relative to your total area, you can just detect intersections and resample if you get an intersection. By the way though, if you want a uniform random sample from the ways to assign k non-overlapping objects in the area, then choosing the first object globally uniformly random and then keeping it fixed is not the right approach because the object locations could be biased in order to avoid overlap. You'd be better of placing the objects uniformly spaced from one another in some initial nonoverlapping assignment, and then keep choosing one of your objects and wiggling its location a bit, changing direction when you collide with another object. If you do this enough times you'll have essentially a random sample from what you really want to sample from.


text:
Q: (toad application) sql - cannot insert multiple records using f5 but f9 is working I was trying to insert multiple records in a table using TOAD SQL.
When pressing F9 it is working, but it only inserts one value at a time.
INSERT INTO TABLE VALUES ('VALUE1','VALUE2','VALUE3','VALUE4','VALUE5','VALUE6', null);

When pressing f5 it says it has inserted but when validating the table, it has not inserted the values I needed.
INSERT INTO TABLE VALUES ('VALUE1','VALUE2','VALUE3','VALUE4','VALUE5','VALUE6', null);

and
INSERT INTO TABLE VALUES ('VALUE1','VALUE2','VALUE3','VALUE4','VALUE5','VALUE6', null);
SELECT * FROM TABLE WHERE COLUMN IN ('VALUE1');

--no rows selected
Is this an application problem? Or grant access?
This is the same with all the DML.
Using SQL Developer Application, it has no problem, I can do multiple insert.
I want to continue using TOAD. Please help.
Thanks guys!


text:
Q: Joining two queries or a union /union all I have created a union all from the below code.  I am not sure this is what I want.  The top portion in is group down into smaller detail. It counts the number of  students, by school,grade, test scores by engProf and ethnic .  the second query gives a total conut of students broken down by student,school,grade and test taken. Returning the total number of second grade students at school x took the math test, and x students took the reading test. One will be a higher level summary of the other.  I want to join them together for one dataset to be used in a report.  Any suggestions.  I tried a union all not sure if that is the best solution.

SELECT
track,
schoolc,
schname AS[school],
grade,
subtestc AS[ELA/Math],
EngProf,
SUM(CASE WHEN (subtestc) IN ('ela','Math') AND tscrtypc ='A'THEN 1 ELSE 0 END) AS [total Students],
SUM(CASE WHEN (testscore)IN ('A','P') AND subtestc IN ('ela','Math') AND tscrtypc ='A'THEN 1 ELSE 0 END) AS [At/Above],
SUM(CASE WHEN (testscore)IN ('B','BB','FBB') AND subtestc IN ('ela','Math') AND tscrtypc ='A'THEN 1 ELSE 0 END) AS [Below],
SUM(CASE WHEN (subtestc) IN ('ela','Math') AND tscrtypc ='A' AND(ethnic)='White (not Hispanic)' THEN 1 ELSE 0 END) AS [Total White(not Hispanic)],
SUM(CASE WHEN (testscore)IN ('A','P') AND subtestc IN ('ela','Math') AND tscrtypc ='A' AND(ethnic)='White (not Hispanic)'THEN 1 ELSE 0 END) AS [White (Total not Hispanic) At/Above],
SUM(CASE WHEN (testscore)IN ('B','BB','FBB') AND subtestc IN ('ela','Math') AND tscrtypc ='A' AND(ethnic)='White (not Hispanic)'THEN 1 ELSE 0 END) AS [ Total White (not Hispanic)],
SUM(CASE WHEN (subtestc) IN ('ela','Math') AND tscrtypc ='A' AND(ethnic) <>'White (not Hispanic)' THEN 1 ELSE 0 END) AS [ Total Other Nonwhite students],
SUM(CASE WHEN (testscore)IN ('A','P') AND subtestc IN ('ela','Math') AND tscrtypc ='A' AND (ethnic)<>'White (not Hispanic)'THEN 1 ELSE 0 END) AS [TotalOther Non_White At/Above],
SUM(CASE WHEN (testscore)IN ('B','BB','FBB') AND subtestc IN ('ela','Math') AND tscrtypc ='A' AND (ethnic)<>'White (not Hispanic)'THEN 1 ELSE 0 END) AS [Total Other Non-White Below],
NULL AS [Grand total Students]

FROM [dbo].[qw_star_testing_detail]
WHERE subtestc IN('ela','Math')
AND tscrtypc ='A'
AND testscore NOT IN('9')
GROUP BY track,
schoolc,
schname,
track,
grade,
EngProf,
subtestc

UNION ALL

SELECT
track,--NULL AS [track],schoolc,
schoolc, ---NULL AS [schoolc],
schname AS[school],---NULL AS[school],
grade,---NULL AS [grade,],
subtestc AS[ELA/Math],--NULL AS[ELA/Math],
NULL AS[engProf],
null AS [total Students],
null AS [At/Above],
NULL AS [Below],
null AS [Total White(not Hispanic)],
NULL as [White (Total not Hispanic) At/Above],
null AS [ Total White (not Hispanic)],
NULL AS [ Total Other Nonwhite students],
null AS [TotalOther Non_White At/Above],
null AS [Total Other Non-White Below],
SUM(CASE WHEN (subtestc) IN ('ela','Math') AND tscrtypc ='A'THEN 1 ELSE 0 END) AS [Grand total Students]

FROM [dbo].[qw_star_testing_detail]
WHERE subtestc IN('ela','Math')
AND tscrtypc ='A'
AND testscore NOT IN('9')
GROUP BY track,
schoolc,
schname,
track,
grade,
--EngProf,
subtestc
--ethnic

A: Don't you just want to left outer join the 2?
Where the left table has the finer grain (more detail).
You could use a CTE.
With
Group1
AS
(SELECT
track,
schoolc,
schname AS[school],
grade,
subtestc AS[ELA/Math],
EngProf,
SUM(CASE WHEN (subtestc) IN ('ela','Math') AND tscrtypc ='A'THEN 1 ELSE 0 END) AS [total Students],
SUM(CASE WHEN (testscore)IN ('A','P') AND subtestc IN ('ela','Math') AND tscrtypc ='A'THEN 1 ELSE 0 END) AS [At/Above],
SUM(CASE WHEN (testscore)IN ('B','BB','FBB') AND subtestc IN ('ela','Math') AND tscrtypc ='A'THEN 1 ELSE 0 END) AS [Below],
SUM(CASE WHEN (subtestc) IN ('ela','Math') AND tscrtypc ='A' AND(ethnic)='White (not Hispanic)' THEN 1 ELSE 0 END) AS [Total White(not Hispanic)],
SUM(CASE WHEN (testscore)IN ('A','P') AND subtestc IN ('ela','Math') AND tscrtypc ='A' AND(ethnic)='White (not Hispanic)'THEN 1 ELSE 0 END) AS [White (Total not Hispanic) At/Above],
SUM(CASE WHEN (testscore)IN ('B','BB','FBB') AND subtestc IN ('ela','Math') AND tscrtypc ='A' AND(ethnic)='White (not Hispanic)'THEN 1 ELSE 0 END) AS [ Total White (not Hispanic)],
SUM(CASE WHEN (subtestc) IN ('ela','Math') AND tscrtypc ='A' AND(ethnic) <>'White (not Hispanic)' THEN 1 ELSE 0 END) AS [ Total Other Nonwhite students],
SUM(CASE WHEN (testscore)IN ('A','P') AND subtestc IN ('ela','Math') AND tscrtypc ='A' AND (ethnic)<>'White (not Hispanic)'THEN 1 ELSE 0 END) AS [TotalOther Non_White At/Above],
SUM(CASE WHEN (testscore)IN ('B','BB','FBB') AND subtestc IN ('ela','Math') AND tscrtypc ='A' AND (ethnic)<>'White (not Hispanic)'THEN 1 ELSE 0 END) AS [Total Other Non-White Below],
NULL AS [Grand total Students]

FROM [dbo].[qw_star_testing_detail]
WHERE subtestc IN('ela','Math')
AND tscrtypc ='A'
AND testscore NOT IN('9')
GROUP BY track,
schoolc,
schname,
track,
grade,
EngProf,
subtestc)
,
Group2
AS
(SELECT
track,--NULL AS [track],schoolc,
schoolc, ---NULL AS [schoolc],
schname AS[school],---NULL AS[school],
grade,---NULL AS [grade,],
subtestc AS[ELA/Math],--NULL AS[ELA/Math],
NULL AS[engProf],
null AS [total Students],
null AS [At/Above],
NULL AS [Below],
null AS [Total White(not Hispanic)],
NULL as [White (Total not Hispanic) At/Above],
null AS [ Total White (not Hispanic)],
NULL AS [ Total Other Nonwhite students],
null AS [TotalOther Non_White At/Above],
null AS [Total Other Non-White Below],
SUM(CASE WHEN (subtestc) IN ('ela','Math') AND tscrtypc ='A'THEN 1 ELSE 0 END) AS [Grand total Students]

FROM [dbo].[qw_star_testing_detail]
WHERE subtestc IN('ela','Math')
AND tscrtypc ='A'
AND testscore NOT IN('9')
GROUP BY track,
schoolc,
schname,
track,
grade,
--EngProf,
subtestc
--ethnic)

Select group1.track,
group1.schoolc, group1.[school]
,group2. whatever other fields you want
From Group1
Left outer join Group2
 ON Group1.track=group2.track
 AND Group1.schoolc=group2.schoolc
 and group1.school = group2.school
...

A: This is a fairly common practice with one trick... Add in an order or level column to get the results in the right order.  Don't have nulls for the items that you are grouping by because you can't order it right.  Here is a example where I am making a list of a class students and total count:
   SELECT class, student_name, count
   FROM
   (
     SELECT class, student_name, 0 as count, 1 as ord
     FROM classlist
     UNION ALL
     SELECT class, '' as student_name, count() as count, 2 as ord
     FROM classlist
     GROUP BY class
   ) T
   ORDER BY class, ord, student_name


text:
Q: How to get a mail in response, of the form submission by the User In Strapi I am new to Strapi and I want to create functionality, when a user submits form (from the frontend made in React js), in response to it the User will get a mail of form submission.

A: to send email in response of the type of request made


text:
Q: Multi Sub Array In Php i have a input elements as below
        <form method="post" >
1       <input type="text" name="passname[name]" />

2       <input type="text" name="passname[type]" />

3       <input type="text" name="passname[age]" />

1       <input type="text" name="passname[name]" />

2       <input type="text" name="passname[type]" />

3       <input type="text" name="passname[age]" />

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

    </form>

i want all the text box as array in php
like Below
Passenger Name : passname[name]
Passenger Type : passname[type]
Passenger Age : passname[age]

Is this possible with php
form code used in form
<input type="text" name="passname[name][]" />

<input type="text" name="passname[type][]" />

<input type="text" name="passname[age][]" />

<input type="text" name="passname[name][]" />

<input type="text" name="passname[type][]" />

<input type="text" name="passname[age][]" />

when i submit the form i get this type of array value
    array
  'passname' =>
        array
          'name' =>
            array
              0 => string '1' (length=1)
              1 => string '1' (length=1)
          'type' =>
            array
              0 => string '2' (length=1)
              1 => string '2' (length=1)
          'age' =>
            array
              0 => string '3' (length=1)
              1 => string '3' (length=1)
      'send' => string 'Submit' (length=6)

how can i do it in for each like blow
<?php
if(isset($_POST['aa']))
{
    $number = $_POST['1'];
    $text = $_POST['2'];
    foreach($number as $key=>$val)
    {
        echo $val."=".$text[$key]."
";
    }
}
?>
<formid="a"name="a"method="post">
<selectid="1[]"name="1[]">
<optionvalue="1">1</option>
<optionvalue="3">3</option>
<optionvalue="2">2</option>
</select>
<inputtype="text"value=""id="2[]"name="2[]"/>
<selectid="1[]"name="1[]">
<optionvalue="1">1</option>
<optionvalue="3">3</option>
<optionvalue="2">2</option>
</select>
<inputtype="text"value=""id="2[]"name="2[]"/>
<inputtype="submit"id="aa"name="aa"value="send now"/>
</form>

A: <input type="text" name="passname[name][]" />

<input type="text" name="passname[type][]" />

<input type="text" name="passname[age][]" />

A: <form method="post" >
       <input type="text" name="passname[name][]" />

       <input type="text" name="passname[type][]" />

       <input type="text" name="passname[age][]" />

       <input type="text" name="passname[name][]" />

      <input type="text" name="passname[type][]" />

       <input type="text" name="passname[age][]" />

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

    </form>

<?php
$_POST['passname']['name'];
$_POST['passname']['type'];
$_POST['passname']['age'];
?>

A: If you want to keep the passenger separated, you should build your form like this:
<form method="post" >
  <input type="text" name="passname[0][name]" />

  <input type="text" name="passname[0][type]" />

  <input type="text" name="passname[0][age]" />

  <input type="text" name="passname[1][name]" />

  <input type="text" name="passname[1][type]" />

  <input type="text" name="passname[1][age]" />

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

</form>

then, once submited, your $_POST array will look like this one:
$_POST == array(
  0 => array(
    'name' => 'XXX',
    'type' => 'XXX',
    'age' => 'XXX',
  ),
  1 => array(
    'name' => 'XXX',
    'type' => 'XXX',
    'age' => 'XXX',
  ),
  'send' => 'Submit',
);

where XXX represents the user input data.


text:
Q: ICLOUD_UNSUPPORTED_DEVICE when installing macOS Big Sur in VMware When I try to install macOS in VMware Workstation I get a popup error when I try to login with my Apple ID:
ICLOUD_UNSUPPORTED_DEVICE

That's all it says.
How do I make my VM appear as an iCloud supported device?

A: Shut down the VM gracefully, then add the following to the end of your virtual machine's .vmx file to make VMware believe it is running on Mac hardware:
board-id = "Mac-551B86E5744E2388"
hw.model.reflectHost = "FALSE"
hw.model = "MacBookPro14,3"
serialNumber.reflectHost = "FALSE"
serialNumber = "C02XXXXXX153"
smbios.reflectHost = "FALSE"
efi.nvram.var.ROM.reflectHost = "FALSE"
efi.nvram.var.MLB.reflectHost = "FALSE"
efi.nvram.var.ROM = "3c0754a2f9be"

Boot the VM.
Open iTunes, click Account menu, then Sign In.
Source for the above lines


text:
Q: Disabled button which is not embedded in the post
This is an editted question. Apologised for not stating it clearly.

I've a news page which will display list of product and a button accessible for user to click to take a look at the coupon available. I unsure on how to get it done.
 <button id="coupon_id" type="submit" value="Coupon" class="buttonlink"
                                onclick="parent.location='<?php echo 'receipt-singleview?id=' . $eachData["couponId"]; ?>'">Coupon</button>

i tried to code this but it was halfway cause i just testing it out.

A: It looks like you can use the $().html method to set the arrow that you want.
Fiddle: https://jsfiddle.net/x8oebpqf/
    if($this.hasClass('SeeMore2')){
        $this.html('&#9654');
    } else {
        $this.html('&#9660');
    }

A: Something like this?
https://jsfiddle.net/svq5scnm/

$('.SeeMore2').click(function(){
  var $this = $(this);
  $this.toggleClass('SeeMore2');
        $this.toggleClass('SeeLess2');

 });
.SeeMore2 .less{
    display:none;
}
.SeeLess2 .more{
    display:none;
}

<button class="SeeMore2">See More ►See Less ▲</button>


text:
Q: Harvest a THREDDS server correctly with GeoNetwork? I am trying to harvest datasets (NetCDF) from a THREDDS server using GeoNetwork 2.10.
People shall upload their NetCDF files to the THREDDS server and the CatalogScan element will list them. After the harvest task was run, new metadata harvested from the THREDDS catalog will be displayed on the GeoNetwork page.
By now, I do get data returned from harvesting. My problem is that the data is not displayed correctly and many items are missing. I've followed instructions from the GeoNetwork THREDDS harvesting tutorial.
The data returned looks like this:

As you can see there are many fields missing. The catalog.xml is configured like this:
<?xml version="1.0" encoding="UTF-8"?>
<catalog name="KüNO NetCDF TDS"
     xmlns="http://www.unidata.ucar.edu/namespaces/thredds/InvCatalog/v1.0"
     xmlns:xlink="http://www.w3.org/1999/xlink">
    <service name="all" base="" serviceType="compound">
        <service name="ncdods" serviceType="OpenDAP" base="/thredds/dodsC/"/>
        <service name="HTTPServer" serviceType="HTTPServer" base="/thredds/fileServer/"/>
        <service name="ncss" serviceType="NetcdfSubset" base="/thredds/ncss/grid/"/>
    </service>
    <datasetScan name="NetCDF Katalog" ID="netcdf_katalog" path="katalog" location="content/katalog" harvest="true">
        <metadata inherited="true">
        <serviceName>ncdods</serviceName>
        <dataType>Grid</dataType>
        <filter>
            <include wildcard="*.nc"/>
        </filter>
        <netcdf xmlns="http://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2">
            <attribute name="Conventions" value="CF-1.0"/>
        </netcdf>
        </metadata>
    </datasetScan>
</catalog>

And the GeoNetwork harvester is setup like this:


text:
Q: Android Don't calls onActivityResult with DialogFragment I've got a code that starts intent to take picture from camera
Intent pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(pictureActionIntent, PhotoUtility.CAMERA_PICTURE);

And after picture is taking back it should calls onActivityResult
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK)
        return;

    if (requestCode == PhotoUtility.CAMERA_PICTURE) {
        File f = PhotoUtility.saveFromCamera(data, picIV);
        imagePath = f.getAbsolutePath();
    } else if (requestCode == PhotoUtility.GALLERY_PICTURE) {
        File f = PhotoUtility.saveFromGallery(data, getActivity(), picIV);
        imagePath = f.getAbsolutePath();
    }
}

With simple Fragment it works fine, but if I use DialogFragment onActivityResult is not calling. How can solve this problem using DialogFragment?


text:
Q: Use token generated in the google API console to communicate with the google play apis I'm building a web game, and I'd like to make use of google's game services such as high scores. When I do this using the client_id of my api console project, it tells me that there is no app linked to this api consumer.
In the Google Play games publisher console, it says that my game is linked to my apis console project, but when I create a linked app, it still asked me to create a new oauth2 consumer id and secret. So I did it, entering the exact same name project name, and now I have 2 api console projects with the same name. I had the original proejct configured with other apis I use.
Do I need to just delete my original apis console project, and just configure the new project, the same way I had the original project configured? Or is there a way to use an existing apis console project and associate that with a linked app?
Also, if the game information in the game publishing console tells me that the game has been linked to the original project, why doesn't it just associate the linked app with that project, and the oauth credentials that it had obtained?

A: Really basic and you probably have, but have you enabled the Google Play Games Services API in API access?


text:
Q: How to remove dependency problem? I'm trying to install offline g++ software on Ubuntu 14.04:
$ sudo dpkg -i g++-4.4.4_4.4.3-4ubuntu5.1_i386.deb
[sudo] password for ecil:
dpkg: error processing archive g++-4.4.4_4.4.3-4ubuntu5.1_i386.deb (--install):
 cannot access archive: No such file or directory
Errors were encountered while processing:
 g++-4.4.4_4.4.3-4ubuntu5.1_i386.deb
ecil@ECIL-HP:~$ sudo dpkg -r g++-4.4
(Reading database ... 164836 files and directories currently installed.)
Removing g++-4.4 (4.4.3-4ubuntu5.1) ...
Processing triggers for man-db (2.6.7.1-1) ...
ecil@ECIL-HP:~$ sudo dpkg -i g++-4.4.4_4.4.3-4ubuntu5.1_i386.deb
ecil@ECIL-HP:~$ sudo dpkg -i g++-4.4.4_4.4.3-4ubuntu5.1_i386.deb
dpkg: error processing archive g++-4.4.4_4.4.3-4ubuntu5.1_i386.deb (--install):
 cannot access archive: No such file or directory
Errors were encountered while processing:
 g++-4.4.4_4.4.3-4ubuntu5.1_i386.deb
ecil@ECIL-HP:~$ sudo dpkg -r g++-4.4
dpkg: warning: ignoring request to remove g++-4.4 which isn't installed
ecil@ECIL-HP:~$ sudo dpkg -r g++-4.4
dpkg: warning: ignoring request to remove g++-4.4 which isn't installed
ecil@ECIL-HP:~$ sudo dpkg -r g++-4.4
dpkg: warning: ignoring request to remove g++-4.4 which isn't installed
ecil@ECIL-HP:~$ cd Desktop/
ecil@ECIL-HP:~/Desktop$ sudo dpkg -i g++-3.3_3.3.5-13_i386.deb
Selecting previously unselected package g++-3.3.
(Reading database ... 164820 files and directories currently installed.)
Preparing to unpack g++-3.3_3.3.5-13_i386.deb ...
Unpacking g++-3.3 (1:3.3.5-13) ...
dpkg: dependency problems prevent configuration of g++-3.3:
 g++-3.3 depends on gcc-3.3-base (>= 1:3.3.5-13); however:
  Package gcc-3.3-base is not installed.
 g++-3.3 depends on gcc-3.3 (>= 1:3.3.5-13); however:
  Package gcc-3.3 is not installed.
 g++-3.3 depends on gcc-3.3 (<< 1:3.3.6); however:
  Package gcc-3.3 is not installed.
 g++-3.3 depends on libstdc++5-3.3-dev (>= 1:3.3.5-13); however:
  Package libstdc++5-3.3-dev is not installed.

dpkg: error processing package g++-3.3 (--install):
 dependency problems - leaving unconfigured
Processing triggers for man-db (2.6.7.1-1) ...
Errors were encountered while processing:
 g++-3.3

A: Unless you show us any error message, only suggestion is to use gdebi or open the deb in Ubuntu Software Center instead of using dpkg.


text:
Q: Get memory addresses using IDAPython In my code, I am using idc.GetOpnd(ea,0) and idc.GetOpnd(ea,1) to get the 2 operands of an instruction. However, if its a call (or jmp) instruction, I am getting symbols like _perror and loc_8083BA9.
Using IDAPython, is it possible to remove all the symbols and deal only with memory locations.

A: Two options:

*

*Use LocByName to resolve names to addresses

*Use GetOperandValue instead of GetOpnd to get the value of the operand instead of its display string.


text:
Q: Ext.Net retrieve DateField with GetCmp I have a web page in ASP + Ext.Net in c# where I create some controls dynamically (text fields, comboboxes, datefields etc) based on an XML. When the user presses a button I have to read the values of those controls and do something with it, so I am using Ext.Net.X.GetCmp to do that. It works just fine for all controls, unless the control is a date control (T=DateField), and unless it has a custom date format (e.g. "dd MMM yyyy"). In that case, it returns a FormatException when I Try to retrieve the control.
A very short example to reproduce the problem:
ASPX:
<%@ Page Language="C#" CodeBehind="Sandbox.aspx.cs" Inherits="MyNamespace.Sandbox" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Multiple DateFields with DateRange Validation - Ext.NET Examples</title>
    <link href="/resources/css/examples.css" rel="stylesheet" />
</head>
<body>
    <form runat="server">
        <ext:ResourceManager runat="server" />

        <ext:Window
            runat="server"
            Width="350"
            Title="DateRange"
            Icon="Date"
            Closable="false"
            BodyPadding="5"
            Layout="Anchor"
            DefaultAnchor="100%">
            <Items>
                <ext:Button ID="MyTestButton" runat="server" Flex="1" Text="Test" ToolTip="Click here to crash" OnDirectClick="ButtonClicked" />
                <ext:FieldContainer
                    ID="MyFieldContainer"
                    runat="server"
                    >
                    <Items>
                        <%--HERE I CREATE A DATEFIELD IN CODE BEHIND--%>
                    </Items>
                </ext:FieldContainer>
            </Items>
        </ext:Window>
   </form>
</body>
</html>

Code behind (C#):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;

namespace MyNamespace {
    public partial class Sandbox : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {
            if (!this.Page.IsPostBack) {
                CreateDateField();
            }
        }

        protected void CreateDateField() {
            DateField date = new DateField() {
                ID = "MyDateField",
                //FieldLabel = "From",
                Format = "dd MMM yyyy",
                SubmitFormat = "dd/MM/yyyy",
                Value = "01 Jun 2014"
            };
            date.AddTo(MyFieldContainer);
        }

        [DirectMethod]
        public void ButtonClicked(object sender, DirectEventArgs e) {
            // Try to retrieve the control.
            // Spoiler alert: it will crash
            DateField date = Ext.Net.X.GetCmp<DateField>("MyDateField");
            // Change the date to see if it worked.
            date.Value = "02 Jun 2014";
        }
    }
}

The error I get is just a System.FormatException: String was not recognized as a valid DateTime. I have tried playing with the SubmitFormat property with no luck. Again, with the default date format it works just fine, but a requirement for the customer is to have their custom date format.
What am I doing wrong? Thank you very much for the help.

A: X.GetCmp reads a value from POST, but it has no idea about the Format, because it is absent in POST.
You have to specify the format manually. The same format that the DateField is created with.
X.GetCmp<DateField>("dfDate", new DateField.Config() { Format = "dd MMM yyyy"});

A bit more details about the X.GetCmp feature.


text:
Q: How to display a list obtained through web service using Xamarin Can I use an array to show the data obtained from a web service, and show them in a listview?
This is a snippet of my code:
class WSResult2
{
    public string url { get; set; }
    public string equipment { get; set; }
    public string serial { get; set; }
}

class WSResultList
{
    public List<WSResult2> items { get; set; }
}

Page4.xaml.cs:
private async Task wsvarAsync(Result result)
    {
        WSClient client = new WSClient();

        string wUrl = "--Here is the url of the web service--" + result.Text + "&option=2";

        var resultws = await client.Get<WSResultList>(wUrl);

        if (resultws != null)
        { //I want to know how to use an array here to get the complete list of each of the items captured by the web service.
            lblEquipment.Text = resultws.items[0].equipment;
            lblSerial.Text = resultws.items[0].serial;
            lblurl.Text = resultws.items[0].url;

        }
    }

Page4.xaml:
<ContentPage.Content>

    <StackLayout Padding="20">
        <StackLayout HorizontalOptions="Center">
        <Button x:Name="btnScan" Text="Read code" HorizontalOptions="FillAndExpand" VerticalOptions="EndAndExpand" BackgroundColor="LightBlue" TextColor="White" FontSize="Medium" CornerRadius="25" Clicked="btnScan_Clicked"/>
    </StackLayout>

    <Label x:Name="lblInfo" />

    <Label Text="Equipment: " TextColor="Red"/>
    <Label x:Name="lblEquipment" />

    <Label Text="Serial: " TextColor="Red"/>
    <Label x:Name="lblSerial" />
    <!-- I want to know how to use a Binding to show all the data captured from the web service. -->
    <Label IsVisible="False" Text="Report: " TextColor="Red"/>
    <Label IsVisible="False" x:Name="lblurl" />
    <Button x:Name="btnUrl" Text="See report"  Clicked="OnButtonClicked" CornerRadius="25" HorizontalOptions="Center" TextColor="White" FontSize="Medium" BackgroundColor="Red"/>

</StackLayout>

</ContentPage.Content>

WSClient.cs is the client to deserialize the JSON:
class WSClient
{
    public async Task<T> Get<T>(string url)
    {
        HttpClient client = new HttpClient();
        var response = await client.GetAsync(url);
        var json = await response.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<T>(json);
    }

    public async Task<T> Post<T>(string pUrl, T pData)
    {
        var wJsonData = JsonConvert.SerializeObject(pData);
        var wData = new StringContent(wJsonData, Encoding.UTF8, "application/json");
        HttpClient client = new HttpClient();
        var wResponse = await client.PostAsync(pUrl, wData);
        var json = await wResponse.Content.ReadAsStringAsync();
        return JsonConvert.DeserializeObject<T>(json);
    }
}

A: Page4.xaml
<ListView x:Name="ResultList">
<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell>
          <StackLayout>
               <Label Text="{Binding url }"/>
                </StackLayout>

        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate></ListView>

Page4.xaml.cs
private async Task wsvarAsync(Result result)
    {
        WSClient client = new WSClient();

        var json = await client.GetStringAsync(wUrl);
        var resultList = JsonConvert.DeserializeObject<List<WSResultList>>(json)

        //to view each item on debug
        for(var i = 0; i < resultList i++){
            Console.WriteLine(resultList[i].equipment);
        }

        //populate the list view to visualize your data
        ResulitList.ItemSource = resultList;
    }


text:
Q: Can't execute my SQL Data CREATE TABLE Vet
(
     VET_NUM CHAR(2) PRIMARY KEY,
     LAST_NAME CHAR(15),
     FIRST_NAME CHAR(15),
     STREET CHAR(15),
     CITY CHAR(15),
     STATE CHAR(3),
     POSTAL_CODE CHAR(5),
     SALARY DECIMAL(7,2),
     DEGREE CHAR(10),
     POSITION CHAR(15)
);

INSERT INTO Vet (VET_NUM, LAST_NAME, FIRST_NAME, STREET, CITY, STATE, POSTAL_CODE, SALARY, DEGREE, POSITION)
VALUES ('1', 'Skechley', 'Cristine', '24340 7th Plaza', 'Pittsburgh', 'PA', '15274', 88053.30, 'Masters', 'Vet'),
       ('2', 'Fishpoole', 'Sig', '06784 Anthes Point', 'Philadelphia', 'PA', '19184', 45525.56, 'Associates', 'Receptionist'),
       ('3', 'Stother', 'Rycca', '04304 Superior Hill', 'Allentown', 'PA', '18105', 90553.37, 'Masters', 'Vet'),
       ('4', 'Scandrite', 'Kerrill', '30320 Express Crossing', 'Harrisburg', 'PA', '17126', 102553.59, 'Doctorates', 'Vet'),
       ('5', 'Glassman', 'Rhett', '33418 Tomscot Trail', 'Mc Keesport', 'PA', '15134', 56052.24, 'Bachelor', 'Management'),
       ('6', 'Gioan', 'Rab', '1 Pennsylvania Street', 'Hatfield', 'PA', '19440', 35880.76, 'Student', 'Janitor');

The error I keep getting is

Msg 2627, Level 14, State 1, Line 35
  Violation of PRIMARY KEY constraint 'PK__Vet__7C53690AE94CBCDD'
  Cannot insert duplicate key in object 'dbo.Vet'. The duplicate key value is (1 ).
Msg 8152, Level 16, State 14, Line 38
  String or binary data would be truncated.
Msg 8152, Level 16, State 14, Line 41
  String or binary data would be truncated.
Msg 8152, Level 16, State 14, Line 44
  String or binary data would be truncated.

I don't know what I am doing wrong. Can anyone help me with this? I have looked on YouTube, and the video I watched said that the Data I have entered might not be good. I think my data is alright, but for some reason, I just can't get it to execute. I want to be able to see "Row has been effected"

A: try this
CREATE TABLE Vet
(VET_NUM CHAR(2) PRIMARY KEY,
LAST_NAME CHAR(20),
FIRST_NAME CHAR(20),
STREET CHAR(30),
CITY CHAR(20),
STATE CHAR(20),
POSTAL_CODE CHAR(20),
SALARY DECIMAL(8,2),
DEGREE CHAR(20),
POSITION CHAR(20));
    INSERT INTO Vet(VET_NUM,LAST_NAME,FIRST_NAME,STREET,CITY,STATE,POSTAL_CODE,SALARY,DEGREE,POSITION)
    VALUES
    ('1','Skechley','Cristine','24340 7th Plaza','Pittsburgh','PA','15274',88053.30,'Masters','Vet');
    INSERT INTO Vet
    VALUES
    ('2','Fishpoole','Sig','06784 Anthes Point','Philadelphia','PA','19184',45525.56,'Associates','Receptionist');
    INSERT INTO Vet
    VALUES
    ('3','Stother','Rycca','04304 Superior Hill','Allentown','PA','18105',90553.37,'Masters','Vet');
    INSERT INTO Vet
    VALUES
    ('4','Scandrite','Kerrill','30320 Express Crossing','Harrisburg','PA','17126',102553.59,'Doctorates','Vet');
    INSERT INTO Vet
    VALUES
    ('5','Glassman','Rhett','33418 Tomscot Trail','Mc Keesport','PA','15134',56052.24,'Bachelor','Management');
    INSERT INTO Vet
    VALUES
    ('6','Gioan','Rab','1 Pennsylvania Street' ,'Hatfield','PA','19440',35880.76,'Student','Janitor');

column length  is low


text:
Q: Unexpectedly found nil while unwrapping an Optional value Probably I don't understand clearly Optional values:
class func albumsWithJSON(allResults: NSArray) -> [Album] {
    var albums = [Album]()
    if allResults.count>0 {
        for result in allResults {
            var name = result["trackName"] as? String
            if name == nil {
                name = result["collectionName"] as? String
            }

            var price = result["formattedPrice"] as? String
            if price == nil {
                price = result["collectionPrice"] as? String
                if price == nil {
                    var priceFloat: Float? = result["collectionPrice"] as? Float
                    var nf: NSNumberFormatter = NSNumberFormatter()
                    nf.maximumFractionDigits = 2;
                    if priceFloat != nil {
                        price = "$"+nf.stringFromNumber(priceFloat)
                    }
                }
            }

            let thumbnailURL = result["artworkUrl60"] as String
            let imageURL = result["artworkUrl100"] as String
            let artistURL = result["artistViewUrl"] as? String

            var itemURL = result["collectionViewUrl"] as? String
            if itemURL == nil {
                itemURL = result["trackViewUrl"] as? String
            }

            var newAlbum = Album(name: name!, price: price!, thumbnailImageURL: thumbnailURL, largeImageURL: imageURL, itemURL: itemURL!, artistURL: artistURL!)
            albums.append(newAlbum)
        }
    }
}

At this line I get "unexpectedly found nil while unwrapping an Optional value" error:
var newAlbum = Album(name: name!, price: price!, thumbnailImageURL: thumbnailURL, largeImageURL: imageURL, itemURL: itemURL!, artistURL: artistURL!)

Obviously some informations are missing from JSON, but how can I handle a missing value?

A: All that error means is that one of the values that you're passing into that function is nil. When you put the ! at the end of those values, it unwraps it. If the value is nil while unwrapping, it throws an exception.
The way to fix this is dependent on how important the values being nil is. If you cannot live with any one of those being nil, then you'll have to check for nil and do something. If you can have them be nil, then you'll want to make sure that the function accepts nil values.
To better understand optionals, you should read the docs: https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_483


text:
Q: Laravel 8 - 2 database connection - leftjoin I've got 2 different databases and need a leftjoin to the second one.
It's on Laravel 8. It's a MariaDB and the sql_erp it's on MSSQL.
Who can help me?
My received fault-message is:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'sql_erp.artikel_stamm' doesn't exist (SQL: select * from `aa_bom` left join `sql_erp`.`ARTIKEL_STAMM` on `bom`.`art_nr` = `Artikel_Stamm`.`ARTNR` where `_x_zu_aa_doc_steps` = 1 order by `pos` asc limit 99)

in my controller:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Arbeitsanw\aa_doc_steps;
use App\Models\Arbeitsanw\aa_doc_header;
use App\Models\Arbeitsanw\aa_bom;
use App\Models\Arbeitsanw\ERP\Artikel_Stamm;
use Illuminate\Support\Facades\DB;

    public function loadstep($id)
    {
        $aa_doc_steps = aa_doc_steps::find($id);

        //Stkl laden
        $aa_doc_step_id=$id;
        $aa_stkl_artikels = aa_bom::where('_x_zu_aa_doc_steps', '=', $aa_doc_step_id)
                                        ->leftJoin('sql_erp.ARTIKEL_STAMM', 'bom.art_nr', '=', 'Artikel_Stamm.ARTNR')
                                        ->orderBy('pos', 'asc')
                                        ->take(99)
                                        ->get();

        return view('aa_edit_arbeitsschritt', compact('aa_doc_steps', 'aa_stkl_artikels'));
    }

my model
<?php

namespace App\Models\Arbeitsanw\ERP;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Http\Controllers\aa_stkl_form_controller;

class Artikel_Stamm extends Model
{
    use HasFactory;
    protected $connection = 'sql_erp';
    protected $table = 'ARTIKEL_STAMM';
}

A: You can use the Laravel Eloquent Left join structure as an example
$ c = Customer :: leftJoin ('orders', function ($ join) (
      $ join-> on ('customers.id', '=', 'orders.customer_id');
    })
    -> whereNull ('orders.customer_id')
    -> first ();

You can look at this code structure. Also, you need to define $ fillable = ['table_column', 'table_column'] in the Model file.


text:
Q: Trying to send data with serial port communication I am trying to use serial port communication to send data via xBee, but it is not working and I don't know why. It is not running, it is saying that is unable to start the program and "The System cannot find the file specified". I would appreciate it if someone could help me.
Here is the code that I am using to test it:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <commdlg.h>
#include <windows.h>

int main()
{
    DCB dcb;
    HANDLE hCom;
    BOOL fSuccess;
    COMMTIMEOUTS timeouts;
    char *buffWrite;
    DWORD dwBytesWritten = 0;

    hCom = CreateFile( L"COM9",
                    GENERIC_WRITE,
                    0,    // must be opened with exclusive-access
                    NULL, // no security attributes
                    OPEN_EXISTING, // must use OPEN_EXISTING
                    FILE_ATTRIBUTE_NORMAL,    // not overlapped I/O
                    NULL  // hTemplate must be NULL for comm devices
                    );

    if (hCom == INVALID_HANDLE_VALUE)
    {
        // Handle the error.
        printf ("CreateFile failed with error %d.\n", GetLastError());
        return (1);
    }

    // Build on the current configuration, and skip setting the size
    // of the input and output buffers with SetupComm.

    fSuccess = GetCommState(hCom, &dcb);

    if (!fSuccess)
    {
        // Handle the error.
        printf ("GetCommState failed with error %d.\n", GetLastError());
        return (2);
    }

    // Fill in DCB: 9,600 bps, 8 data bits, no parity, and 1 stop bit.

    dcb.BaudRate = CBR_9600;     // set the baud rate
    dcb.ByteSize = 8;             // data size, xmit, and rcv
    dcb.Parity = NOPARITY;        // no parity bit
    dcb.StopBits = ONESTOPBIT;    // one stop bit

    fSuccess = SetCommState(hCom, &dcb);

    if (!fSuccess)
    {
        // Handle the error.
        printf ("SetCommState failed with error %d.\n", GetLastError());
        return (3);
    }

    GetCommTimeouts(hCom,&timeouts);
    //COMMTIMEOUTS timeouts = {0};

    timeouts.ReadIntervalTimeout = MAXDWORD;
    timeouts.ReadTotalTimeoutConstant = 0;
    timeouts.ReadTotalTimeoutMultiplier = 0;
    timeouts.WriteTotalTimeoutConstant = 1000;
    timeouts.WriteTotalTimeoutMultiplier= 10;

    if(!SetCommTimeouts(hCom, &timeouts))
    {
        printf("error setting port state \n");
    }

    buffWrite = "Testing Serial Port!";

    if (WriteFile(hCom,   // handle to file to write to
                buffWrite,              // pointer to data to write to file
                sizeof(buffWrite),              // number of bytes to write
                &dwBytesWritten,NULL) == 0)      // pointer to number of bytes written
            {
                printf("Reading of serial communication has problem.");
                return FALSE;
            }

    CloseHandle(hCom);
}

Thank You.
Jack.

A: I am going to assume for a moment that the question posted by @rm5248 is on the mark and that you are talking about the program compiled from the code you posted is failing with CreateFile failed with error The system cannot find file specified.
The most likely cause is therefore that the COM Port you are opening does not exist.  If you are using Windows then use a command prompt and the MODE | MORE which will list for you available Com Ports on your system. Note that com ports are not shown in this list if being used.
Once you know of what ports you have available change the line in you code hCom = CreateFile( L"COM1",


text:
Q: Oracle : Rows to columns based on column value where value is not fixed
I have the below sample data in the Oracle table where the records for VALUE can be increased or decreased for LOCATION and LINE. For LINE BLOCK and LOACTION OP-40-BLOCK the VALUE can appear n number of times.:

 I want the below output data :

I have tried the below query :

SELECT OP,VAL3,VAL1,VAL2,(VAL1+VAL2+VAL3) TOTAL FROM(
SELECT LOCATION OP, REGEXP_SUBSTR(VALUE, '[^,]+', 1, 1) AS VAL1,
REGEXP_SUBSTR(VALUE, '[^,]+', 1, 2) AS VAL2,
REGEXP_SUBSTR(VALUE, '[^,]+', 1, 3) AS VAL3
FROM
(SELECT LOCATION,LISTAGG(VALUE,',') WITHIN GROUP (ORDER BY LOCATION) VALUE
FROM t_rk WHERE LINE='BLOCK'
GROUP BY LOCATION));

 but I am not getting the desired result. Please help.

A: First, number your rows per location, so to define which the first, second and third value is. Then aggregate by location.
select
  location,
  max(case when rn = 1 then value end) as value_1,
  max(case when rn = 2 then value end) as value_2,
  max(case when rn = 3 then value end) as value_3,
  sum(value) as total
from
(
  select
    location,
    value,
    row_number() over (partition by location order by value) as rn
  from t_rk
  where line = 'BLOCK'
) numbered
where rn <= 3
group by location
order by location;


text:
Q: How to use $pristine property on AngularJS form correctly When my form loads initially the $pristine property is always false.  It was my understanding that as long as there's no user interaction with the form that the $pristine property will be true until the user changes the model via some kind of interaction.  Is there anything else that I need to be aware that could set the $pristine property to false without the user manually changing the model?   I'm trying to alert the user that there are unsaved changes before they close the form if it's not pristine.

A: The problem ended up being the use of the Select2 angularjs directive.  There's a known bug that causes the form to be dirty on initialization.  There's currently an open issue on github that covers this problem.  Issue Here


text:
Q: Google Maps and Fusion tables - Loading error I trying to do the map base on geocodezip example http://www.geocodezip.com/geoxml3_test/v3_FusionTables_CountryBrowser.html , but I have always have message on my map "Data may still be loading".
I reduce my map to only 10 polygons but I have same message over and over.
Inside left sidebar; name of the polygons are properly displayed, and when I click "show" map guide me to the exact place of the polygon, but the polygons are not displayed on the map. Does anyone have any suggestions?
My code is below.
<!DOCTYPE html>

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Fusion Tables Natural Earth Data Country Browser</title>

Google Maps JavaScript API v3 Example: Fusion Tables Natural Earth Data Country Browser

A: With the new encrypted ids, you need to use the new query syntax:
layer.setQuery({select:'geometry',from:FT_TableID,where:"'name_0' = '"+CountryName+"'"});

layer.setQuery({select:'geometry',from:FT_TableID,where:"'name_0' = '"+CountryName+"' AND 'name' = '"+gpolygons[id].name+"'"});

and most important (if you only want the selected polygons to show):
layer = new google.maps.FusionTablesLayer(FT_Options);

The old "string" queries only seem to work with the numeric IDs.
working example
updated original example with new syntax

A: See answer above, it works for me. Thanks to geocodezip
Non numric fields should be enclosed in single quotes under double quotes, ex: " SELECT 'DATE' <= '2013-11-11'  "
 For complete example, you can have a look here.


text:
Q: Connection error when using pycharm and pyramid web framework I am using pycharm (v4.5.3) and the pyramid web framework (v1.5.7).
I created a simple project, but I got an error when I tried to access the welcome page (that is in my case 0.0.0.0:6543).
Here are the steps I followed:

*

*Installed python 3.4.3 and pycharm 4.5.3 (professional edition)

*Created a project with pycharm (without creating an env because of the pro edition)

*Selected scaffold "starter" and no template language because I read that could cause an error

*Using pycharm GUI I ran "setup.py develop".  The server starts at 0.0.0.0:6543 but the connection does not work. According to a video I watched on Youtube, a welcome page should appear. Indeed it appears only if I type "localhost:6543"; however my server is listening on 0.0.0.0:6543.

Can anyone help me?

A: 0.0.0.0 is a "meta address" which tells the server to listen on all available local interfaces. This address is non-routable, so you can't access the server by specifying this address - you need a real IP of one of your machine's network interfaces


text:
Q: CollectionAssert.Contains() as a replacement for NUnit's Assert.Contains() I'm replacing NUnit with TestManager in my Visual Studio project.  NUnit has the following Asserts:

*

*Assert.Contains(string, collection)

*Assert.That(collection, Has.No.Member(string))
I'm using the following for TestManager:

*

*CollectionAssert.Contains(collection, string)

*CollectionAssert.DoesNotContain(collection, string)
I'm looking for a way to replace
Assert.IsEmpty(collection) and Assert.IsNotEmpty(collection)
I could use CollectionAssert.DoesNotContain(collection, new List<string>())  But would rather have something more solid reflecting on collection.

A: LINQ usually is good for checking collections.
 Assert.IsFalse(collection.Any()); //      Assert.IsEmpty(collection)
 Assert.IsTrue(collection.Any()); //      Assert.IsNotEmpty(collection)

If you are looking for more fluent interface - consider FluentAssertions NuGet.
collection.Should().BeEmpty("because there are no doors");