Router in react js

Question: I've been learning React for a few days. Everything has been going fine, but today I got this error.
Error in ./~/@remix-run/router/dist/router.cjs.js
Module parse failed: /home/sunny/Desktop/react-tut/reactjourney/node_modules/@remix-run/router/dist/router.cjs.js Unexpected token (1307:8)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1307:8)
@ ./~/react-router-dom/dist/umd/react-router-dom.development.js 12:125-153

and my App.jsx will look like this

import './App.css';

import React from 'react';

import { BrowserRouter, Route, Router } from 'react-router-dom';

function App(){

  return(

hello react router  6

      <BrowserRouter>

        <Routes>

          <Route path='/home' element={
 hey this is home
} />
        </Routes>

      </BrowserRouter>

  )
}

export default App;

I'm learning router in react js, but got an error and I find the solution for that!
Comment: You've a typo. The imported `Router` component should be the `Routes` component. Voting to close as "not reproducible or was caused by typo". Cheers.
Answer: A visible issue that I see in the code is that the inside <BrowserRouter> component should be the <Routes> component not <Router>. This could cause the error you are facing.
This code is working for me just fine:
import "./App.css";

import React from "react";

import { BrowserRouter, Route, Routes } from "react-router-dom";

function App() {
  return (

 hello react router 6

      <BrowserRouter>
        <Routes>
          <Route path="/home" element={
 hey this is home
} />
        </Routes>
      </BrowserRouter>

  );
}

export default App;

Here is the Sandbox Link:
Comment: Buddy my error didn't solve ??
Comment: Sorry to hear that the issue is still persisting. I think it's related to your environment, as your code is working perfectly after fixing the typo in the sandbox. Can you provide some additional information about your environment, like your package.json file, so that we can understand the issue better?

Router in react js


count records in web api?

Question: i want to ask how to get total count with data in web api. i have tried use if clause to count total record, but it only shows the total count and the data didn't show in xml format.
Are there anyway to do without If clause?
example from json format:
{
  Count: 2
   [
    {
     "userid": 1,
     "name": "emily",
     "mobile": "98724954",
     "Age": 24,
     "Date": 2020-10-04T21:05:00
     },
     "userid": 2,
     "name": "peter",
     "mobile": "42896592",
     "Age": 35,
     "Date": 2021-05-25T11:20:00
     }
    ]

How to make the count like the example in the xml format?
Questions: How to Count data or response and show data together with xml format in web api?
my code:

        [HttpGet]
        public IHttpActionResult Get()
        {
            List<TestClass> draft = new List<TestClass>();
            string mainconn = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
            SqlConnection sqlconn = new SqlConnection(mainconn);
            string sqlquery = "SELECT UserID, Name, Mobile, Age, Date From tbluser";
            sqlconn.Open();
            SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
            SqlDataReader sdr = sqlcomm.ExecuteReader();
            while (sdr.Read())
                {
                    draft.Add(new TestClass()
                    {
                        UserId = sdr.GetString(0),
                        Name = sdr.GetString(1),
                        Mobile = sdr.GetString(2),
                        Age = sdr.GetInt32(3),
                        Date = sdr.GetDateTime(4)
                    });
                }
            return Ok(draft);
        }
        if(test.Count>0)
        {
             return Ok(test.Count());
        }
        else
        {
             return Ok("None");
        };

results:
<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">10</int>

class:
public class TestClass
    {

        public string UserId { get; set; }

        public string Name { get; set; }

        public string Mobile { get; set; }

        public int Age { get; set; }

        public DateTime Date { get; set; }
    }

UPDATE
    [HttpGet]
    public IHttpActionResult Get()
    {
        List<TestClass> draft = new List<TestClass>();
        string mainconn = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
        SqlConnection sqlconn = new SqlConnection(mainconn);
        string sqlquery = "SELECT UserID, Name, Mobile, Age, Date From tbluser";
        sqlconn.Open();
        SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn);
        SqlDataReader sdr = sqlcomm.ExecuteReader();
        while (sdr.Read())
            {
                draft.Add(new TestClass()
                {
                    UserId = sdr.GetString(0),
                    Name = sdr.GetString(1),
                    Mobile = sdr.GetString(2),
                    Age = sdr.GetInt32(3),
                    Date = sdr.GetDateTime(4)
                });
            }
        var apiResult = new ApiResult
        {
            Count = api.Length,
            Data = api
        };
        var result= Ok(apiResult);
    }

Comment: Thank you for the help, i know more things about coding
Comment: The JSON snippet you've posted is not valid JSON. There are multiple syntax errors in it. Please correct it and post the actual JSON structure you're working with. Also, please post an example of the XML you are looking for.
Comment: what i want to do is to count the total record when i search in web api it show the total records on the top and it also with the data too
Comment: @Xerillio i have edited now, your answer is similar to what i want, but how to do it with sql connection, sorry for the late reply
Comment: Could you elaborate what you think is missing from my answer? It's not clear what's wrong
Comment: @Xerillio i have updated the code and the `.Length` got red line and `Data = api` *api* got red line too.
Comment: it said the Length does not contain for definition, and api cannot implicitly convert type
Comment: I've updated my answer. You simply need to change `.Length` to `.Count` since you're using a `List`. Also change the type of `Data` like I did in my answer.
Comment: @Xerillio put all in the test api result class?
Comment: i don't think ```var apiResult = new ApiResult
        {
            Count = api.Length,
            Data = api
        };
        var result= Ok(apiResult);``` put it in the class too, it should be in the controller
Comment: I've update the answer now with all of the changes you need in the controller action.
Answer: You haven't given an example of what you expect as output, so it's a little difficult to know exactly how you want the XML to look. Also note, that your (invalid) JSON example does not match your TestClass, so I've assumed your TestClass is correct.
First, add a wrapper class so you can serialize the Count to XML as well:
public class TestApiResult
{
    public int Count { get; set; }
    public List<TestClass> Data { get; set; }
}

Update your controller action to put your data into an instance of this class:
[HttpGet]
public IHttpActionResult Get()
{
    string mainconn = ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
    using var sqlconn = new SqlConnection(mainconn);
    string sqlquery = "SELECT UserID, Name, Mobile, Age, Date From tbluser";
    sqlconn.Open();
    using var sqlcomm = new SqlCommand(sqlquery, sqlconn);
    using var sdr = sqlcomm.ExecuteReader();

    var data = new List<TestClass>();
    while (sdr.Read())
    {
        data.Add(new TestClass()
        {
            UserId = sdr.GetString(0),
            Name = sdr.GetString(1),
            Mobile = sdr.GetString(2),
            Age = sdr.GetInt32(3),
            Date = sdr.GetDateTime(4)
        });
    }

    // The important bit:
    var apiResult = new ApiResult
    {
        Count = data.Count,
        Data = data
    };
    var result= Ok(apiResult);
}

This will as an example result in the following XML:
<?xml version="1.0" encoding="utf-8"?>
<TestApiResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Count>3</Count>
  <Data>
    <TestClass>
      <UserId>fooID</UserId>
      <Name>fooName</Name>
      <Mobile>fooMobile</Mobile>
      <Access>1</Access>
      <Date>2022-08-11T00:00:00+00:00</Date>
    </TestClass>
    <TestClass>
      <UserId>barID</UserId>
      <Name>barName</Name>
      <Mobile>barMobile</Mobile>
      <Access>2</Access>
      <Date>2022-08-12T00:00:00+00:00</Date>
    </TestClass>
    <TestClass>
      <UserId>bazID</UserId>
      <Name>bazName</Name>
      <Mobile>bazMobile</Mobile>
      <Access>3</Access>
      <Date>2022-08-13T00:00:00+00:00</Date>
    </TestClass>
  </Data>
</TestApiResult>

Note: I've added some using statements to your code. It's important to remember, so that application resources are properly disposed when you're not using the object anymore. See the documentation for using to get more information.
Check this fiddle for a test.

count records in web api?


How to convert this .htaccess for LIGHTTPD?

Question: I have this .htaccess
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

How can I convert it to run my website through Lighttpd ?
Thank you so much!
Comment: I think it's not possible without mod-magnet. But maybe someone can prove me wrong. Anyway, this is more for serverfault or superuser.
Answer: You should be able to use:
url.rewrite-if-not-file => ( ".*" => "/index.php" )

Make sure to enable mod_rewrite in lighttpd.conf and reload lighty.

url.rewrite-[repeat-]if-not-file New:
  For the 1.4.x branch as of 1.4.24 or
  r2647 from svn:
Rewrites a set of URLs internally in
  the webserver BEFORE they are handled
  and checks that files do not exist.
Take examples from above, this is to
  mimic Apache´s "!-f" RewriteRule.
  Please note this does not work for
  directories, pipes, sockets or alike.
Where do I want to use this? Maybe
  with e.g. Drupal backend, where
  mod_magnet (has an Apache´s -f and -d
  solution) might not be handy or simply
  "too much" for just this kind of
  rewrites.


Aside,main and footer had issued when using float after nav used pseudo element after with clear both

Question: My navigation menu bar looks good (1st time building). After finish building the navigation menu bar and when I started to add my aside, main and footer elements inside the " div " I had some problem.
I tried to float aside and main side by side and footer at the bottom but whenever my mouse hover over to the " nav #Menu .MenuList " that had a sub menu ; the aside, main and footer elements got messed up. All of them seems like got " clear : both " It is fine when my mouse doesn't hover over to the " nav #Menu .MenuList ".
I think is because of the " clear:both " at pseudo elements " nav #Menu::after { ...... } ". I think it " clear : both " for EVERYTHING AFTER the " nav #Menu ".
I didn't want to messed up my navigation, so I tried using " display : inline/inline-table/inline-block " at " nav #Menu .MenuList " instead of using " float : left " and remove the pseudo elements " nav #Menu::after { ...... } " . For this , when my mouse hover over to the " nav #Menu .MenuList " , the background at " nav #Menu { ...... } " then got messed up. The height keeps on changes/The background completely gone.
For your information, I also used CSS reset from HTML5 doctor. (In my honest opinion, I think is good to use the GENERAL CSS reset for BEGINNERS like me to have a better idea in dealing CSS)
HTML5 is here:

                blabla

                blabla

                blabla

                        blabla

                                blabla

                        blabla

                                blabla

                blabla

                        blabla

                                blabla

                                        blabla

                                blabla

                                        blabla

                                blabla

                                        blabla

                        blabla

                                blabla

CSS is here:
div
{
    width : 980px ; height : auto ; margin-left : auto ; margin-right : auto ;
}

    header
    {
        background-color : #FFFFFF ; width : 100% ; height : 200px ; margin-left : auto ; margin-right : auto ;
    }

    nav
    {
        background-color : #FFFFFF ; font-family : "Comic Sans MS" , cursive , sans-serif ; font-size : 1em ; width : 100% ; height : auto ;
        margin-left : auto ; margin-right : auto ;
    }

        nav #Menu
        {
            line-height : 35px ; background : linear-gradient( #00FFFF , #4D70DB ) ; border-style : solid ; border-color : #999999 ;
            border-radius : 5px ;
        }

        nav #Menu .MenuList
        {
            float : left ; width : 7em ; text-align : center ; position : relative ;
        }

        nav #Menu::after
        {
            content : '.' ; visibility : hidden ; clear : both ;
        }

        nav #Menu .MenuList > a
        {
            font-weight : 550 ; text-decoration : none ; color : #000000 ; cursor : default ;
        }

        nav #Menu .MenuList:hover
        {
            background : linear-gradient( #A3A3A3 , #5C5C5C ) ;  border-style : solid ; border-color : #999999 ; border-radius : 5px ;
        }

        nav #Menu .MenuList:hover > a
        {
            color : #FFFFFF ;
        }

            nav #Menu .MenuList .SubMenu
            {
                display : none ;
            }

            nav #Menu .MenuList:hover .SubMenu
            {
                display : block ; position : relative ; top : 100% ; box-shadow : 0.7px 0.7px 1px #777777 ; background-color : #FFFFFF ;
                border-width : 1px ; border-radius : 5px ; border-style : solid ; border-color : #d8d9da ;
            }

            nav #Menu .MenuList:hover .SubMenu .SubMenuList
            {
                width : 7em ; text-align : center ; position : relative ;
            }

            nav #Menu .MenuList:hover .SubMenu .SubMenuList > a
            {
                text-decoration : none ; color : #000000 ; cursor : default ;
            }

            nav #Menu .MenuList:hover .SubMenu .SubMenuList:hover > a
            {
                color : #7FFFD4 ;
            }

                nav #Menu .MenuList .SubMenu .SubMenuList .Drop
                {
                    display : none ;
                }

                nav #Menu .MenuList .SubMenu .SubMenuList:hover .Drop
                {
                    display : block ; position : absolute ; top : 0 ; left : 100% ; box-shadow : 0.7px 0.7px 1px #777777 ;
                    background-color : #FFFFFF ; border-width : 1px ; border-radius : 5px ; border-style : solid ; border-color : #d8d9da ;
                }

                nav #Menu .MenuList .SubMenu .SubMenuList:hover .Drop .DropList
                {
                    width : 7em ; text-align : center ; position : relative ;
                }

                nav #Menu .MenuList .SubMenu .SubMenuList:hover .Drop .DropList > a
                {
                    text-decoration : none ; color : #000000 ; cursor : default ;
                }

                nav #Menu .MenuList .SubMenu .SubMenuList:hover .Drop .DropList:hover > a
                {
                    color : #7FFFD4 ;
                }

                    nav #Menu .MenuList .SubMenu .SubMenuList .Drop .DropList .SubDrop
                    {
                        display : none ;
                    }

                    nav #Menu .MenuList .SubMenu .SubMenuList .Drop .DropList:hover .SubDrop
                    {
                        display : block ; position : absolute ; top : 0 ; left : 101.5% ; box-shadow : 0.7px 0.7px 1px #777777 ;
                        background-color : #FFFFFF ; border-width : 1px ; border-radius : 5px ; border-style : solid ; border-color : #d8d9da ;
                    }

                    nav #Menu .MenuList .SubMenu .SubMenuList .Drop .DropList:hover .SubDrop .SubDropList
                    {
                        width : 7em ; text-align : center ; position : relative ;
                    }

                    nav #Menu .MenuList .SubMenu .SubMenuList .Drop .DropList:hover .SubDrop .SubDropList > a
                    {
                        text-decoration : none ; color : #000000 ; cursor : default ;
                    }

                    nav #Menu .MenuList .SubMenu .SubMenuList .Drop .DropList:hover .SubDrop .SubDropList:hover > a
                    {
                        color : #7FFFD4 ;
                    }

    aside
    {
        background-color : #FFFFFF ; width : 22.5% ; height : 500px ; float : left ;
    }

    main
    {
        background-color : #000000 ; width : 77.5% ; height : 500px ; float : right ;
    }

    footer
    {
        background-color : red ; width : 100% ; height : 200px ; clear : both ;
    }

Answer: You have messed up a lot of css. But still this is what I did to get it working.
Actually you have floated aside and main, what you should do is float aside to left, and do not float main, just give it a property of overflow hidden.
Plus the dropdown menu was an issue. It should be positioned absolute, so to make it stick above everything. And the border you applied to menu after hover, increased the height of the the menu which was why all the layout messed up
Here,s the working code
HTML:

                blabla

                blabla

                blabla

                        blabla

                                blabla

                        blabla

                                blabla

                blabla

                        blabla

                                blabla

                                        blabla

                                blabla

                                        blabla

                                blabla

                                        blabla

                        blabla

                                blabla

CSS:
*{list-style:none;padding:0;margin:0;}
div
{
    width : 980px ; height : auto ; margin-left : auto ; margin-right : auto ;
}

    header
    {
        background-color : #FFFFFF ; width : 100% ; height : 200px ; margin-left : auto ; margin-right : auto ;
    }

    nav
    {
        background-color : #FFFFFF ; font-family : "Comic Sans MS" , cursive , sans-serif ; font-size : 1em ; width : 100% ; height : auto ;
        margin-left : auto ; margin-right : auto ;
    }

        nav #Menu
        {
            line-height : 35px ; background : linear-gradient( #00FFFF , #4D70DB ) ; border-style : solid ; border-color : #999999 ;
            border-radius : 5px ;
        }

        nav #Menu .MenuList
        {
            float : left ; width : 7em ; text-align : center ; position : relative ;
        }

        nav #Menu::after
        {
            content : '.' ; visibility : hidden ; clear : both ;
        }

        nav #Menu .MenuList > a
        {
            font-weight : 550 ; text-decoration : none ; color : #000000 ; cursor : default ;
        }

        nav #Menu .MenuList:hover
        {
            background : linear-gradient( #A3A3A3 , #5C5C5C );
        }

        nav #Menu .MenuList:hover > a
        {
            color : #FFFFFF ;
        }

            nav #Menu .MenuList .SubMenu
            {
                display : none ;position:absolute;
            }

            nav #Menu .MenuList:hover .SubMenu
            {
                display : block ;box-shadow : 0.7px 0.7px 1px #777777 ; background-color : #FFFFFF ;
                border-width : 1px ; border-radius : 5px ; border-style : solid ; border-color : #d8d9da ;position:absolute;
            }

            nav #Menu .MenuList:hover .SubMenu .SubMenuList
            {
                width : 7em ; text-align : center ; position : relative ;
            }

            nav #Menu .MenuList:hover .SubMenu .SubMenuList > a
            {
                text-decoration : none ; color : #000000 ; cursor : default ;
            }

            nav #Menu .MenuList:hover .SubMenu .SubMenuList:hover > a
            {
                color : #7FFFD4 ;
            }

                nav #Menu .MenuList .SubMenu .SubMenuList .Drop
                {
                    display : none ;
                }

                nav #Menu .MenuList .SubMenu .SubMenuList:hover .Drop
                {
                    display : block ; position : absolute ; top : 0 ; left : 100% ; box-shadow : 0.7px 0.7px 1px #777777 ;
                    background-color : #FFFFFF ; border-width : 1px ; border-radius : 5px ; border-style : solid ; border-color : #d8d9da ;
                }

                nav #Menu .MenuList .SubMenu .SubMenuList:hover .Drop .DropList
                {
                    width : 7em ; text-align : center ; position : relative ;
                }

                nav #Menu .MenuList .SubMenu .SubMenuList:hover .Drop .DropList > a
                {
                    text-decoration : none ; color : #000000 ; cursor : default ;
                }

                nav #Menu .MenuList .SubMenu .SubMenuList:hover .Drop .DropList:hover > a
                {
                    color : #7FFFD4 ;
                }

                    nav #Menu .MenuList .SubMenu .SubMenuList .Drop .DropList .SubDrop
                    {
                        display : none ;
                    }

                    nav #Menu .MenuList .SubMenu .SubMenuList .Drop .DropList:hover .SubDrop
                    {
                        display : block ; position : absolute ; top : 0 ; left : 101.5% ; box-shadow : 0.7px 0.7px 1px #777777 ;
                        background-color : #FFFFFF ; border-width : 1px ; border-radius : 5px ; border-style : solid ; border-color : #d8d9da ;
                    }

                    nav #Menu .MenuList .SubMenu .SubMenuList .Drop .DropList:hover .SubDrop .SubDropList
                    {
                        width : 7em ; text-align : center ; position : relative ;
                    }

                    nav #Menu .MenuList .SubMenu .SubMenuList .Drop .DropList:hover .SubDrop .SubDropList > a
                    {
                        text-decoration : none ; color : #000000 ; cursor : default ;
                    }

                    nav #Menu .MenuList .SubMenu .SubMenuList .Drop .DropList:hover .SubDrop .SubDropList:hover > a
                    {
                        color : #7FFFD4 ;
                    }

    aside
    {
        background-color : #FFFFFF ; width : 22.5% ; height : 500px ; float : left ;
    }

    main
    {
        background-color : #000000 ; width : 77.5% ; height : 500px ;overflow:hidden;
    }

    footer
    {
        background-color : red ; width : 100% ; height : 200px ;
    }

Comment: Hi awesometvi , TY for your prompt reply , it's my 1st time self-learning HTML CSS JS PHP and MYSQL so I'm sorry abouting messing up the CSS ( I know some pro coders can make the navigation bar perfectly with very few lines however I just can't follow them properly ) . You are absolutely correct . The real problem is at " nav #Menu .MenuList .SubMenu " which the " position " should be " absolute " and not " relative " , thanks for pointing out my mistake so quickly and accurately . Everything works OK for now :) .
Comment: Yes, it could have been less code than this, but you'll learn this in time. If you need any help, do buzz me.
Comment: Alright , thanks for your kind offer , I will :) . Is my 1st time using this forum though so I'm still not quite familiar , but I mostly visit here to study the problems other posted here .


Guitar chords for samba

Question: I'd like to learn some standard samba chords for guitar. I understand this usually involves jazz chords like 9, 11, 13 and a few others.
I can construct these chords myself, but:

It's tedious.
Most of the variations don't sound "samba-ish enough". Often they are either too low or high or miss some important note and I am quite sure there is a bunch of basic riffs one should be familiar with.

So, while samba chord theory is welcome, I'd appreciate if you could provide concrete variations. Better still, I'd like to see some database of these chords. I am sure there must be some but, alas, I was unable to find them; at least disregarding some weird pages.
Answer: First of all:
I've tried to learn these by means of books, but it didn't quite work (at least for me).
Much more effective way to start (at least for me) was to go with youtube lessons. There are tons of them and some of them are quite good. For your purpose I'd like to recommend this one http://www.youtube.com/watch?v=Rl8J2AcwngA.
Second is about the "database" question you've asked:
When you get into the area of "colored chords" be prepared to get overwhelmed -- there are virtually infinite possibilities. To get the idea -- check the "Chord chemistry" book by Ted Greene (...I know that you'll never fail recommending this guy...).
Comment: I'll try the video lessons but I feel this isn't the right way for me... Books should work better, so thanks for that recommendation.
Answer: For the "sambaish" sound the most important thing is the rhythm of the right hand.  The thumb plays bass notes, usually on beats 1 and 3, with bassline usually alternating on I and V of the chord, and the index+middle+ring fingers stab the top of the chord in a highly syncopated way.  They almost always use 4-note chords.
However, like you have seen, a lot of the sound is also in the voicings.  For samba, I have had pleasing results with the similar kind of voicings as used in other brasilian music such as choro, bossa-nova:
Minor voicings:

Am7  [5x555x]
Dm7  [x5756x]
Dm9  [x5355x]
Dm6  [x5x465]
Am11 [5x553x]

Major voicings:

AM7  [5x665x]
A6   [5x465x]
A69 [5x445x]
DM7  [x5767x]
D69  [x5445x]

Dominant voicings:

A7    [5456xx]
A13   [5x567x]
A13b9 [6x567x]
A7#5  [5x566x]
D9    [x5455x]
D+    [x5433x]

Some "sambaish" 2-5-1 examples off the top of my head:

Em7b5 [x7878x] -> A+7  [5x566x] -> Dm9 [x5355x]
Em7   [x7578x] -> A13  [5x567x] -> DM9 [x5465x]
Bm7   [7x777x] -> E9   [x7677x] -> AM7 [5x665x]
Bm7b5 [7x776x] -> E7b5 [6x675x] -> Am6 [5x455x]
Em11  [5x543x] -> A7b9 [5x532x] -> D69 [x5445x]
Answer: If you are looking for a book "The Brazilian Guitar Book
by Nelson Faria" is pretty much the de-facto authoritative text as far as I'm aware, but I haven't checked out any of the competition in the last ten years; regardless, it's invaluable in my opinion even if there are other qualified sources now as well.

Guitar chords for samba


Modeling an SQLite on iOS

Question: I'm thinking about making an iOS app but I can't seem to find a good solution for the DB.
Without entering too much into details, think that I need to store in my DB all the date/time a user will have to do a task.
All I know is the starting date/time, how many tasks the user will do and the time interval between tasks.
The easiest way to do this, of course, is to enter one record for each date/time the user will do a task.
This way I could face the insertion of thousands of records, since the user can choose to repeat the daily tasks up to 5 years.
Each time the user opens up the app, he will see the daily tasks, so I'll have to fetch it from the DB.
I thought about inserting just one record for each task, indicating the starting and ending date/time, but it's not possible because the first and last day might be different.
Example:
Users choose 4 tasks per day at 6h interval, starting at 10AM:
First day:
task1: 10 AM
task2: 4 PM
task3: 10 PM
From second day on:
task1: 4 AM
task2: 10 AM
task3: 4 PM
task4: 10 PM
Last day:
task1: 4 AM
task2: 10 AM
I hope I've been clear enough and that someone will have some good ideas.
Thanks.
Comment: `The easiest way to do this, of course, is to enter one record for each date/time the user will do a task.` -- Yep.
Comment: `but it's not possible because the first and last day might be different.` -- So?  Why is that a problem?
Comment: No, you don't store a record for every possible repetition of an event. a repeated event with no end has theoretically an infinite number of occurences. You store ONE copy of the event, then have some method of storing repeat rules for it, so you can trivially compute if the event occurs in a date/time range.
Comment: This question is probably better suited for programmers.stachexchange.com.
Comment: @MarcB This is exactly what I thought, but I can't come up with a good solution. Any idea for this case?
Comment: @RobertHarvey Because I don't know how to do it. I don't know how many events will exist in a day, so I thought about creating another table (in a to-many relationship with the first one) that will hold all the date/time records. But at the end this last table will hold one record for each date/time and I don't think this is the right way to do it.
Answer: Based on the following assumptions: 1) A project may consist of 1 or more Task(s). 2) A user may have 1 or more Project(s). 3) A task cannot be assigned to more than 1 project. 4) A Project cannot be assigned to more than 1 user.
I would model this as follows:

By the way, in iOS coredata you don't deal with 'records' you deal with 'objects'.
Comment: Let's take out the user table (this will be a single user app for now). Change Project with Task and Task with Time. This way it will be (more or less) what I have to do. The problem is, that if the user have 4 tasks per day, every day, for 3 years, the Time table will end up holding about 4320 records and I'd rather find a way (if it exists) to write just one (or a little more) record(s) for each task. For now I'm using SQLite directly because I don't know CoreData yet. Do you think CoreData is better/faster than SQLite?
Comment: My point is that if you organize it like I did above it makes more sense. You want to "group" a set of tasks together and wrap them in a time constraint. I call that a "project". A project has a time constraint and may have a number of tasks to complete. If you just assign a bunch of tasks to a user then you will have the problem you outlined. I would add timeStart and timeEnd fields to the task entity as well.
Comment: Change project to calendar if you want. Either way, you need a way to group your tasks
Comment: Note, you need to think about what you plan to do with 'tasks' in your code. Most likely, you will be creating task objects and using them. If this is the case then create task objects in coredata. When you fetch from coredata, you are ready to rock and roll. Last thing you want to do is convert some overly simplified (demarshalled) version of an object into an object in ios if you don't have to. Coredata is an object model not a relational model. You deal with objects not records.
Comment: I'm sorry but I think I didn't understand you correctly. If you'd have to get the records (objects if you wish) for the second and last day in my example, how would you do it? Of course I need the logic, not the code.
Comment: Sorry, maybe I'm missing it... I would create a Project or Calendar or Day (whatever entity you want to use to group tasks). I would assign the tasks to the Day. When you want to get the tasks for the last day you would grab the Day representing the last day and then all the tasks associated with it (i.e the group). Please clarify your example if I'm missing your point. I don't know what 'last day' means in your example so it's hard to be more specific.
Comment: The idea of assigning the tasks to a day seems more logic to me, so thank you for pointing me that way. Still, the Day table (if we talk in DB terms), will hold a record for each day from the first to the last, and that could mean tens of thousands of records. Now if this is inevitable, I'm interested about the performances of both SQLite and CoreData. Which would be faster in writing let's say 20000 records and in fetching the record for the current day?

Modeling an SQLite on iOS


Copy a temporary structure using malloc and a void pointer

Question: I have the following function which is being called as the start to a module for a program on an embedded AVR clock. I want to get the value from the clock object which will return a date_time structure and copy it into the space I am allocating from the heap.
void time_set_mode_start(Display *display, volatile Controls *controls,
                         volatile TimeKeeper *clock, void *data) {

    DEBUG_LED_PORT |= _BV(DEBUG_LED);
    data = malloc(sizeof(date_time));
}

What is the best way to get data the value returned from clock->getTime() into the data pointer?
Comment: There isn't [enough information](http://tinyurl.com/so-hints). [Sample code](http://sscce.org/) should be complete and concise. What's the interface spec for `TimeKeeper::getTime`?
Answer: One way is to use memcpy. Specifically, you would probably want memcpy(data, clock->getTime(), sizeof(date_time)).
Another way — probably better, now that I think about it — is to use ordinary assignment:
*((date_time*)data) = *(clock->getTime());

This treats data as a date_time *, and assigns a value to the date_time object that it points to.
(Note: in both of the above code-snippets, I'm assuming that clock->getTime() returns a date_time *. Is that correct?)
By the way, I should point out that data = malloc(sizeof(date_time)); will completely replace the original void * data that was passed in. Your caller will never see the memory location that data now points to, because the pointer is being passed by value.
Comment: In this case would need to modify getTime() to return a pointer vs the actually struct? I tried doing something similar by creating a temporary structure and then passing it's address to memcpy. All I got was garbage data and I believe I got a segfault however I can't tell on this embedded system..
Comment: @secretformula: As you were posting your question, I was completely rewriting my answer. What I originally wrote was pretty facile, sorry.
Comment: Thank you this looks like it would work. I will create a separate method that returns a `date_time*`. I do intend to completely replace what ever is in there. It will have been freed by another module's end method. I will accept in 4 mins when I am able
Comment: @secretformula: Maybe it's just that you trimmed the code-snippet so much that some relevant code is missing, but -- why are you even passing in a `data` pointer? Your current code-snippet never writes to the pointer that was passed in; it just writes to new space that the caller never sees. Jonathan Leffler's answer below suggests (as one possibility) that your prototype should have `void ** pdata` instead of `void * data`, and I think he's right that that's what you have in mind.
Comment: Whats happening is the program is modular. The clock has multiple functions i.e. Time, Time set... I wanted to be able to easily add and remove these fuctions. So i have a 2d array of function pointers. Each modual has 3 functions: start, update, end. Each of the 3 fuctions has the prototype above. This function posted above is the start function which i want to allocate space on the temp pointer it is passed. It will then work with this space in the update method, then free it in the end method. Please tell me if there is a better way./ Is the a better place to discourse this?
Comment: @secretformula: The problem is that you're *not* allocating space on the temp pointer it is passed. You're allocating space, and setting `data` to point to that space; but the temp pointer that was passed is still pointing to wherever it was pointing before. (It's like if your function accepted an `int i`, and then had `i = 3;`. That would change `i`, but it wouldn't change the integer that was passed. The caller wouldn't see the 3. This is the same thing, only the value is a `void *` instead of an `int`.)
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/5219/discussion-between-secretformula-and-ruakh)
Answer: Either the calling code needs to allocate the space for the value and pass that into the function shown as the data parameter, or the function prototype needs to have void **data so that the function can pass the value back.  As it stands, your code overwrites the local copy of data with a newly allocated value, which then leaks memory on return.
Assuming the prototype of date_time TimeKeeper::getTime():
void time_set_mode_start(Display *display, volatile Controls *controls,
                         volatile TimeKeeper *clock, void **pdata)
{
    DEBUG_LED_PORT |= _BV(DEBUG_LED);
    *data = malloc(sizeof(date_time));
    *(date_time *)(*data) = clock->getTime();
}

If the prototype is date_time *TimeKeeper::getTime(), then the assignment is:
    *(date_time *)(*data) = *clock->getTime();

If it is something else, you need to tell us.


Two linearly independent vectors perpendicular to vector $u$

Question: I'm having trouble with these types of questions. I have the following vector $u = (4, 7, -9)$ and it wants me to find 2 vectors that are perpendicular to this one.
I know that $(4,7,-9)\cdot (x,y,z) = 0$.
The dot product of two vectors must equal to zero in order for them to be perpendicular.
But that doesn't tell me much at this point. Any inputs?
Comment: What does the equation $4x + 7y -9z = 0$ mean? It certainly means any point satisfying that equation is perpendicular to your vector. What does it mean graphically?
Answer: You are correct that your first vector needs to have dot product zero with $(4,7,-9)$.  Just pick any $x,y$ you like and solve for $z$.  I will pick $x=9,y=0$ and find $z=4$ works, so we have $(9,0,4)$  Now you can either do the same with dot products with both vectors, or you can take the cross product, which is guaranteed to be perpendicular to both.  So take $(4,7,-9) \times (9,0,4)$ getting $(28, -97, -63)$.  I admit, I used Alpha do do the work.
Comment: @Dimitri Topaloglou:   If you don't need the two vectors to be perpendicular to each other, you can repeat my construction of the first vector to get, for example, $(4,-7,0)$ or $(0,7,9)$ more easily.
Answer: Basically you can choose any two vectors that will satisfy that equation. For example, a=<0,0,0> or b=<9,9,11>.
Comment: Just remember that the two vectors you choose need to be linearly independent from each other as well!
Comment: And $(0,0,0)$ is linearly dependent with every vector.
Answer: Take vector $n = (x,y,z)$. As you said by yourself, dot product should vanish. So
$$
(4,7,-9) \cdot (x,y,z) = 4x+7y-9z = 0
$$
As you might see, all points that lie on the plane $4x+7y-9z = 0$ satisfy the condition of perpendicularity. If you want two linear independent vectors, just pick two different points. So, pick any two different triples $n_1 = (x_1, y_1, (4x_1+7y_1)/9)$ and $n_2 = (x_2, y_2, (4x_2+7y_2)/9)$ where $(x_1, y_1) \ne (x_2, y_2)$, and you're done.
Answer: of course it depend how you define your inner product!but with ordinary product(oghlidusi).
i am agree with Kaster it will be all of points on the plain $4x+7y-9z = 0$
Comment: oghlidusi ro be "Euclidean" taghir bede. ;-)


git: best strategy to merge secondary branch

Question: Sometimes, when I am developing a big feature, I create a secondary branch (out of my original feature branch) to make it easier for my colleagues (and for myself sometimes) to visualize differences between parts of the same feature. It should look like this:
main      --o--o--o---------
                \
feature          o--o--o--o--o
                        \
secondary                o--o--o

When I need to merge everything, I usually merge secondary on feature and then to main, which works just fine. The problem is that sometimes I need to "merge by steps", meaning that I cannot merge secondary into *feature, but I have to merge feature into main, first. In that case, when I update secondary with everything new in main, it messes it up a bit, like having conflict in most files modified on both feature and secondary.
What should be the best approach to not mess this up?
P.D.: this may be a common question, but searching I couldn't put it to words to find a similar question :(
Comment: Are `feature` and `secondary` alternative implementations of the same feature, or is `secondary` an independent development that happens to share some commits with `feature` because it is convenient?
Answer: You should rebase the secondary branch in your then-feature-merged main branch.
In that way you will be kept with only modifications done on you secondary branch which are not already in the feature or main branches.
You could still have conflict, but only on modifications done specifically in your secondary branch so it should be easy to fix.
Summary:

git switch main
git merge feature
git switch secondary
git rebase main + any commands to solve conflit and ends rebase
git switch main
git merge secondary (add --no-ff if you want to keep a merge commit)


Implicit Function Theorem, an application

Question:
Let $f: \mathbb{R}^{k+n} \to\mathbb{R}^n$ be of class $C^1$; suppose that $f(\mathbf{a})=0$ and that $Df(\mathbf{a})$ has rank n. Show that if $\mathbf{c}$ is a point of $\mathbb{R}^n$ sufficiently close to $\mathbf{0}$, then the equation $f(\mathbf{x}) = \mathbf{c}$ has solution.

So this sounds almost like a reinstatement of the theorem. Here I will recite it for this question
Let $\mathbf{a} = (a_1,a_2, \dots, a_n) \in \mathbb{R}^{n + k}$; I somehow have to show that  $$\det \frac{\partial f}{\partial \mathbf{x}} (\mathbf{a}) \neq 0$$
All I know is that the derivative matrix is invertible, so does this also imply $\det Df(\mathbf{a}) \neq 0$?
Comment: Note that $Df(a)$ is not square. So it does not have a determinant.
Comment: You need to 'split' the variable $a$ into $a_1,a_2$ such that $\frac{\partial f ((a_1, a_2))} {\partial a_1}$ consists of the $n$ linearly independent columns of $Df(a)$.
Comment: @copper.hat, would that Jacobian give me a 1 x n matrix? Still not square
Answer: The main complication here is rearranging the indices of the function argument.
Since $\operatorname{rk} Df(a)=n$, there exists indices $i_1,...,i_n$ such that the columns $\{ Df(a) e_{i_j} \}_{j=1}^n$ are linearly independent ($e_j$ is the $j$th unit vector in $\mathbb{R}^{n+k}$). Let $\pi$ be a permutation of $\{1,...,n+k\}$ such that $\pi_j = i_j$ for $j=1,...,n$, and let $\Pi=\begin{bmatrix} e_{\pi_1} \cdots e_{\pi_{n+k}} \end{bmatrix}$ be the corresponding permutation matrix.
Let $\binom{\hat{x}}{\hat{y}} = \ \Pi^{-1} a$, where $\hat{x} \in \mathbb{R}^n$, $\hat{y} \in \mathbb{R}^k$. Define $\phi:\mathbb{R}^n \times \mathbb{R}^n \to \mathbb{R}^n$ by $\phi(x,c) = f(\Pi \binom{x}{\hat{y}}) -c$ (note that $\hat{y}$ is 'fixed'), note that $\phi$ is $C^1$ and $\phi(\hat{x},0) = 0$. Furthermore, $\frac{\partial \phi(\hat{x},0)}{\partial x}= \begin{bmatrix} Df(a)e_{\pi_1} \cdots Df(a)e_{\pi_{n}} \end{bmatrix}$, and so is invertible. Hence by the implicit function theorem, there exists neighborhoods $V$ of $\hat{x}$, $U$ of $0$ and a function $\eta:U \to V$ such that $\phi(\eta(c),c) = 0$ for $c \in U$.
Hence $f(\Pi \binom{\eta(c)}{\hat{y}}) =c$, for $c \in U$.


As a beginner, what should I look for when buying my first synthesizer?

Question: There are countless options out there and it is very easy for a beginner to feel overwhelmed. Which features should I be looking for? Which are the most important characteristics? How can the options be classified?
Comment: What would you like to do with it? The most important characteristics are situational. You might want portability over sound quality, or sound quality over a broad palate. Maybe you want to be able to recreate an orchestra, or maybe you just want classic 70s or 80s synth sounds. As it stands, this seems really too broad. It's like asking what to look for in a guitar without specifying acoustic, electric, classical, or genre.
Comment: Many beginning musicians may confuse the term synthesizer with or use it synonymously with keyboard instruments that can serve various functions similar to a true synthesizer - such as Sampler Keyboard, MIDI Controller Keyboard, Workstation Keyboard, Arranger Keyboard, Portable Digital Keyboard, Digital Piano and others. Should the answer deal only with true synthesizers or should a discussion of the other type keyboard instruments/input devices be a part of the answer?  Should the answer be limited to keyboard controlled synthesizers or should all types of input devices be explored?
Comment: I did the search. The entire first page of results are all far more specific than your question. All of them state some combination of intended use, price range, specific category, etc. The word "synthesizer" itself is so broad it could include a complicated tape machine, software plugin, capictively coupled oscillator, wave table module, doctored Commodore 64 computer, and so on. The possibilities are manifold.
Comment: have you thought of downloading some softsynths? There are lots of free and shareware/trialware ones. These would give you some idea of what to look for.
Comment: @ToddWilcox I'm not looking for product recommendations, but an overview for a beginner. You could carve the first part of your comment as a very interesting section of an answer. Similar questions have been asked before with very good reception and ended up being very useful. Search for "what to look for first" to see some examples. I'm asking this one specifically because I saw the other, more specific, question getting closed and wanted a similar one that is on scope.
Comment: @ToddWilcox What would make this specific enough? What to look for when buying my first analog subtractive synthesizer? A separate question should be asked for every synthesis type? For every genre? I think this question can be easily answered in its current form and you might be exaggerating a little bit on the broadness. It's just meant to be an overview for the beginner that asks this very common question. "There are many types of synths, the most common are this, and that, and so on".
Comment: What about what are the most popular types of synthesis? Or what to look for if I want to learn how to use synthesizers? Or why are the most famous synthesizers so popular?
Comment: @ToddWilcox But those questions have nothing to do with this one. This is supposed to aid a beginner looking to buy a synth. You are over thinking it. There are countless types of electric guitars but the question on this site had good answers regardless because you don't have to focus on every single little variable, an overview of the most popular and common is more than enough. I know there's a lot more variety in synths (that's why it is so easy to feel overwhelmed in the first place), but the same principle applies.
Comment: @ToddWilcox And that's probably how the answer should be carved as: "if you are a beginner you should focus on the simpler and most common stuff like subtractive, fm, wavetable, your options are these and these because..." The beginner part is what makes the scope much more smaller than you think it is.
Comment: First thing I thought of was modular, subtractive, analogue synths. But you mention FM, wavetable and additive which are very different sounds and (I guess) techniques.  So the beginner should have some idea on the sound differences, at least.
Comment: I don't think this is off topic; we have had similar questions before. Like 'what to look out for when buying a used piano' etc. I think it's a good question
Comment: I'd go with Dave's suggestion - it's a _helluva_ lot less expensive, and you get to find out what does what without too much strain, just, perhaps, the cost of an inexpensive MIDI controller (which you can continue using as you buy hardware). Consider also programmes like PureData and Csound.
Answer: With little experience and without clear vision of requirements, this probably will not be the last synthesizer you ever buy. In other words, you are buying the exploration device.
For such a device, I would suggest to set the budget limit and select the synthesizer that has as many various features available as possible. Then you will be able to try all of them and be much more sure about your requirements later.
The quality probably does not matter as much, as after exploration (and discovering you really like) you can buy a long-term model that is strong in features you like the most.


PHP Variable in SQL LIKE

Question: I want to place a PHP variable in SQL LIKE, I tried many ways but no change.
e.g. today $adate is 2012-08-12%
<code>$adate =  date("Y-m-d") . '%';
$tvisit = db_result(db_query("SELECT `counter_id` FROM counter_today WHERE `counter_date` LIKE '{$adate}' ORDER BY `counter_id` DESC LIMIT 1"));
</code>
How can I do that ?
Comment: If you are serious about the theming tag, if you are putting a SQL query into your theme then you should throw away everything you did so far and read a book or two on Drupal and come back. Sorry.
Comment: Pro Drupal Development by John K. VanDyk is by far the best one out there in my opinion.  But, what I think @chx was getting at is this should be in a module, where content is created, not in a theme, where that content is styled.  Much like HTML and CSS and their division of labor.
Comment: That one is for D6.   The Definitive Guide to Drupal 7 is my goto for D7.
Comment: Can you suggest some books?, Thanks
Comment: Thanks Jimajamma, which version of drupal this book covers ?
Answer: The syntax would be along the lines of:
<code>$adate =  date('Y-m-d');
$tvisit = db_result(db_query("SELECT counter_id FROM {counter_today} WHERE counter_date LIKE '%s%%' ORDER BY counter_id DESC LIMIT 1", $adate));
</code>
The changes from your original:

Put {}'s around table name so if you are on a shared database, drupal can put a prefix on automagically.
Put LIKE's % in the sql itself, not in the variable.  You need to put in %% since % itself is drupal's way of starting a variable (kinda like \\ to put in a \)
Put %s in in front of that for the variable, which is a string.  Remove the {}'s since they are for table names.  Granted, php will find $adate in there since it's all wrapped in ""'s but then you open up yourself to sql injection etc (however remote it would be in this specific example).
Put the $adate variable in the function call as an argument.
Take out the ``'s surrounding the field/column names.

PHP Variable in SQL LIKE


Prove field extension is a field

Question: I have a field extension $\mathbb Q (2^{1/3}) = a + b2^{1/3} + c2^{2/3}$ where $a,b,c\in \mathbb Q$. I want an elementary proof it indeed is a field. How to go about proving it contains its inverse $(\forall x \in \mathbb Q(2^{1/3}))(x^{-1} \in \mathbb Q(2^{1/3}))$?
Thank you very much!
Answer: Write the system of equations corresponding to $(a+br+cr^2)(x+yr+zr^2)=1$, where $r=\sqrt[3]{2}$:
\begin{cases}
ax+2cy+2bz=1\\
bx+ay+2cz=0\\
cx+by+az=0
\end{cases}
The determinant of the system is $a^3+2b^3+4c^3-6abc$, which is non zero provided at least one of the coefficients is non zero.
How to see this? We can assume $a$, $b$ and $c$ are integers, because if we're able to find the inverse of $a+br+cr^2$ in this case, then also the inverse of
$$
\frac{a}{d}+\frac{b}{d}r+\frac{c}{d}r^2
$$
can easily be found, multiplying by a rational number. We can also assume that $a$, $b$ and $c$ have no common prime factor, for a similar reason.
So, suppose $a^3+2b^3+4c^3=6abc$.
Note that $a$ must be even, so we can write $a=2A$; therefore
$$
8A^3+2b^3+4c^3=12Abc
$$
and dividing by $2$ we get $4A^3+b^3+2c^3=6Abc$, which means $b$ is even; write $b=2B$ so that
$$
4A^3+8B^3+2c^3=12ABc
$$
which, like before, has the consequence that $c$ is even. Contradiction.
By Cramer's theorem, the above system has a solution for every non zero number of the form $a+br+cr^2$.
Comment: Yep this is the method I was in the process of typing up. Note that this method easily generalizes to radicals of primes.
Comment: @user21820 Of course, the proof with vector spaces is *much* better.
Comment: Yes, for any base field contained in $\mathbb{C}$, that is.
Answer: I'm not sure what you mean by an elementary proof.
Note that $p(x)=x^3-2$ is irreducible over $\mathbb Q[x]$ (e.g. by Eisenstein).
Hence given any polynomial $q(x)$ either $q(x)=r(x)p(x)$ for some polynomial r(x), or we have $$q(x)r(x)+p(x)s(x)=1$$ for some polynomials $r(x)$ and $s(x)$ which can be determined using the Euclidean algorithm.
If we then substitute $x=\sqrt[3] 2$ we get $p(\sqrt[3] 2)=0$ and therefore $q(\sqrt[3] 2)r(\sqrt[3] 2)=1$

Note that in the first case $q(\sqrt[3] 2)=0$ and we are only looking for inverses for non-zero elements.
Answer: Let $K=\mathbb{Q}[\sqrt[3]{2}]$. Take $\alpha \in K$, $\alpha\ne0$ and consider $\phi: K \to K$ given by $\phi(x)=\alpha x$. Then $\phi$ is an injective $\mathbb{Q}$-linear transformation because $K\subset \mathbb R$, which has no zero divisors. Since $K$ is a finite-dimensional vector space over $\mathbb{Q}$, the injectivity of $\phi$ implies its surjectivity. In particular, $1$ is in the image of $\phi$, which proves that $\alpha$ is invertible in $K$.
Comment: Hmm the injectivity part you didn't prove is no easier than the original question...
Comment: Indeed. Is there another way?
Comment: There is a completely 'elementary' but messy way that I found prior to being taught Galois theory. I'll sketch both in my answer.
Comment: Yes the matrix form was the way I found, but unfortunately it's not so easy to prove that the determinant is non-zero!
Comment: Yes, indeed. Nice! However it now depends on the association with the structure of $\mathbb{R}$, which of course won't generalize to other base fields.
Answer: Your statement of the existence of inverse is incorrect, because the notation $x^{-1}$ already assumes the existence of an inverse in the field already. Rather it should be:
$\forall x \in \mathbb{Q}(2^{\frac{1}{3}}) \left( \exists y \in \mathbb{Q}(2^{\frac{1}{3}}) \left( xy=1 \right) \right)$
The simplest way is to show that this set corresponds to the set of polynomials over $\mathbb{Q}$ modulo the irreducible $(x^3-2)$, which gives a field. In a Galois theory course it is usually derived as a consequence of the theorem that the quotient ring of a unital commutative ring over a maximal ideal is a field. But without using any ring theory at all, it can be seen by observing that we can define $\gcd$ for polynomials over $\mathbb{Q}$ using the Euclidean algorithm, and so irreducibility automatically implies that any non-multiple has an inverse modulo it.
Answer: Here is another answer.
Let $K=\mathbb{Q}[\sqrt[3]{2}]$. Take $\alpha \in K$, $\alpha\ne0$.
Because $K$ has dimension $3$ over $\mathbb{Q}$, the four numbers $1$, $\alpha$, $\alpha^2$, $\alpha^3$ must be linearly dependent and so there are $a_3$, $a_2$, $a_1$, $a_0$ in $\mathbb Q$, not all zero, such that $a_3 \alpha^3 + a_2 \alpha^2 + a_1 \alpha + a_0=0$.
If $a_0\ne0$, then $(-\frac{a_3}{a_0}\alpha^2-\frac{a_2}{a_0}\alpha-\frac{a_1}{a_0})\alpha=1$ and you have found the inverse of $\alpha$.
If $a_0=0$, then cancel one $\alpha$ and repeat.
Answer: Take the Ring $R=\Bbb Q[X]$ ,prove that $x^3-3$ is irreducible in $R$ . So $\langle x^3-3\rangle$ is a maximal ideal in $R$ . Hence the quotient ring $\Bbb Q[x]/\langle x^3-3\rangle$ is a field . Prove an isomorphism between this field and $\Bbb Q[2^{1/3}]$.

Prove field extension is a field


Amend foreach loop to output  based on variable of IDs

Question: I am trying to modify the way a category list is drawn on the front end of a Magento website (simple idea). I have a list of categories that I want to seperate and use with jquery accordiation, so for EG. I want a header "2010 and older" under which sit categories with IDs 1 to 10. Then I want a heading "2011" under which live categories with IDs 11 to 20.
The default category code below just loops through the IDs and echos out the category list in a
 - but I want to customise the
:
<?php $collection = $this->_getCollection(); ?>
<?php if (count($collection) > 0) : ?>

    <?php foreach ($collection as $_category ) : ?>

                    <a href="<?php echo $this->getUrl('gallery/category/view/', array('id' => $_category->getId())); ?>"><?php echo $this->htmlEscape($_category->getName()) ?>

    <?php endforeach ?>

<?php endif; ?>

I can't see the wood for the trees! - I figured to pull the IDs into an array and draw the new structure based on IF statements, but no luck in building the array.
Can anyone see a quick way that I can break the loop to say, if IDs are 1 to 10 then list in
, then move on for IDs 11 to 20 in
  for eg.?
Many Thanks
Comment: If you use `id` HTML attributes, I think you need nested lists otherwise you would have duplicate id's.
Comment: Hi,I can use class IDs - no problem
Answer: Try to check for category id's you don't want to display and use continue; to get the next:
<?php foreach ($collection as $_category ): ?>
<?php if ($_category->getId() == 10) { continue; } ?>

        <a href="<?php echo $this->getUrl('igallery/category/view/', array('id' => $_category->getId())); ?>"><?php echo $this->htmlEscape($_category->getName()) ?>

<?php endforeach ?>

Answer: You should divide your problem. One part is the output, which can be represented with a function:
<?php

$htmlLi= function($class, $url, $name) {
?>
                <li class="<?php echo $class; ?>">
                    <a href="<?php echo $url; ?>"><?php echo $name; ?>

<?php
}

Then you have the logic to decide about the classname based on some id:
$classById = function($id) {
    $class = $id < 11 ? '2010' : '2011';
    return $class;
}

And you finally want to put this together:
<?php $collection = $this->_getCollection(); ?>
<?php if (count($collection) > 0) : ?>

    <?php foreach ($collection as $_category) {
        $id    = $_category->getId());
        $class = $classById($id);
        $url   = $this->getUrl('gallery/category/view/', array('id' => $id);
        $name  = $this->htmlEscape($_category->getName());
        $htmlLi($class, $url, $name);
    } ?>

<?php endif; ?>

This also demonstrates, that your own function _getCollection() does not already returns the data in the format you need it. It's probably better it would return the fields you really need for the loop:
$class, $url and $name


jquery and jquery.ui work in all browsers except IE 7 - Why?

Question: I have written a small jquery application that allows a person to slide a handle 200 px to the right.
The application uses jQuery 1.2.6 and jquery UI 1.5.3
My script works flawlessly in all browsers except ie 7 (ie 6 untested, don't care).  It even works in ie 8.
to see the code app in action and the code via view source, please check out http://iomobile.dev.devsu.com.
iphone-unlock.js is the jquery code, which uses style.css specifically for the graphic elements. Sorry it's very slow - caching is turned off while I debug.
Also, there are no errors for debugging.  Any thoughts on why this is happening are greatly appreciated.
I thought it may be helpful to add the code in an edit:
$(document).ready(function()
{
<code>var unlock = function()
{

    $.openPopupLayer({
        name: "iPhoneInteract",
        url: "/sites/all/themes/tao/templates/iphone.html",

        afterClose: function () {
            $("#unlock-handle").animate({"left" : "-1"} );
            $("#slide-to-unlock").animate({opacity: 1}, 200 );
        top.location.href = 'http://iomobile.dev.devsu.com/?device=desktop';
        }
    });

}

$("#unlock-slider").slider({
    handle: "#unlock-handle",
    animate:true,
    slide: function(e,ui)
    {
        $("#slide-to-unlock").css("opacity", 1-(parseInt($("#unlock-handle").css("left"))/120));
    },
    stop: function(e,ui)
    {
        if($("#unlock-handle").position().left == 210)
        {
            unlock();
        }
        else
        {
            $("#unlock-handle").animate({left: 0}, 200 );
            $("#slide-to-unlock").animate({opacity: 1}, 200 );
        }
    }
    }
);
</code>
});
    enter code here
Comment: If this is the only code you've written so far, **start using the latest versions.** jQuery 1.2.6 is ancient, almost 3 years old at this point.
Answer: IE7 has a problem with animation if two conditions are true:

A containing DIV has position: relative, AND
The property being animated is not set (in this case "left")

Looking at the style.css, it appears you are setting a value for "left," but #unlock-bottom does have position:relative so it's unclear if the IE7-specific issue applies. It might be helpful to debug with the animated elements in a container that does not have position:relative to see if the problem goes away.
See http://www.electrictoolbox.com/jquery-animation-issues-ie7-position-relative/
Comment: Thank you! After reading the article you sent, I made adjustments to the position elements.  Although I'm still working on the issue, at least now the animate behavior is erratic instead of simply nothing at all. Thanks for the direction!
Answer: First, try using the latest versions of both (jQuery 1.5.1 / UI 1.8.9). There's no reason to rely on outdated code, there are hundreds of bugs fixed between rele
Comment: Unfortunately, you're right, but switching to such drastically different versions of jQuery will likely break parts of the existing code (if there are any).
Comment: It's true that I wrote this code a while back. Specifically, it was written for the content management system Drupal, which still uses 1.2.6.  i did try to upgrade but I did encounter more bugs than normal, so I figured easier to stick with what works.


passing variable from one script to another in shell scripting

Question: I have a script suppose script.sh
it has two scripts to run parallaly inside
sh script1.sh &
sh script2.sh &
wait;
echo $var1
echo $var2

i want to get these two variable(var1,var2) printed while running script.sh
cat script1.sh

var1=1;
export $var1

cat script2.sh

var1=1;
export $var1

Comment: Is it strictly defined on which shell interpreter/operating system should it run or solution should be portable?
Comment: unix bash shell@mpasko256
Comment: Is'nt it some kind of duplicate of
https://stackoverflow.com/questions/42067435/how-to-return-a-variable-from-one-shell-script-to-another-script?rq=1
question?
Comment: that method is not working as i am running script1 and script2 with &, both will run in background
Comment: "UNIX" doesn't say anything useful. There's a big difference between something that only runs on Linux, or something that only runs on Linux and MacOS, vs something that also needs to run on Solaris and HPUX and IRIX and AIX.
Comment: Possible duplicate of [bash background process modify global variable](https://stackoverflow.com/questions/13207292/bash-background-process-modify-global-variable)
Answer: This can be done with coprocesses in bash 4.x, if your script1 and script2 write their variables to stdout:
#!/usr/bin/env bash
#              ^^^- Must be bash, not /bin/sh; must NOT start this script with "sh name".

start_seconds=$SECONDS
run_script1() { sleep 5; echo "one"; }  # replace these with your script1 or script2
run_script2() { sleep 5; echo "two"; }

coproc coproc_script1 { run_script1; }
coproc coproc_script2 { run_script2; }

read -u "${coproc_script1[0]}" var1
read -u "${coproc_script2[0]}" var2
echo "End time: $(( SECONDS - start_seconds )); var1=$var1; var2=$var2"

If the values weren't running in parallel, your End time would be 10 or more. Instead, it should in practice be 5 or 6 with the above code.
Answer: Things that come to mind:

If you use bash, you can run a script using dot:

.script1.sh

It will run script in the same environment, so you can modify environment variables of the "invoker" script.
If it is a single output data, you can just print into a standard output of the inner script and intercept in the outer script:

inner_result=`script1.sh`

If it is a numeric value, you can return it as a exit code of the script (but I do not recommend this method as it is a bad practice in script development)

Edit:

Use temporary file to store result and then remove it (but depending on operating system, named queues could be best dedicated solution)
Comment: both script1.sh and script2.sh returns single output data. but both has to be triggered together and val1 and val2 should get printed after wait call
Comment: I missed requirement that scripts need to be runned in parallel, so then added fourth solution
Comment: If you only need bash 4.x support, I'd actually suggest coprocesses. BTW, since 1-2 don't address the question *at all* and 3 would need to pass individual PIDs to `wait` to tie exit status back to them, I'd suggest heavy revision for this answer.


Changing DNS records when Moving a site

Question: I'm building a new Magento website on a Amazon ec2 instance and will need to point domain of their old OSCommerce site to the new ec2 instance's elastic IP address.
Normally I would have though this a simple task of updating the A record of their domain, but when I logged into the account with their register I see they have 90 records set up already, mostly CNAME & A records.
They have no IT guy to ask, but I'm almost 100% sure what I need to do but as I normally work with web dev stuff like php and javascript etc I just want to make sure I have it right.
To give you a sample of their DNS records they have set up:
Type    Host                            Data                        TTL      Kind    State    In Synch
A       intweb1.their-domain.com        19?.??.???.OLD              3600     Manual  Active     yes
CNAME   intweb.their-domain.com         intweb1.their-domain.com    3600     Manual  Active     yes
CNAME   www.their-domain.com            intweb1.their-domain.com    3600     Manual  Active     yes
A       fs.their-domain.com             19?.??.???.OLD              3600     Manual  Active     yes
CNAME   fileserver.their-domain.com     fs.their-domain.com         3600     Manual  Active     yes

I believe I only need to REMOVE:
A       intweb1.their-domain.com        19?.??.???.OLD              3600     Manual  Active     yes

AND CHANGE:
CNAME   www.their-domain.com            intweb1.their-domain.com    3600     Manual  Active     yes

TO:
A       www.their-domain.com            19?.??.???.NEW              3600     Manual  Active     yes

AND ADD ANOTHER RECORD:
CNAME   their-domain.com                www.their-domain.com        3600     Manual  Active     yes

Is this correct?
Answer: The best practice would be:
Set a reasonably small ttl so if something goes wrong, you don't have to wait 1 hour to rollback (ttl is in seconds) So you avoid data written on different versions of the db depending on the clients in one site or the other (if the old site allows you to do so, you can force there a redirection to the new server to avoid this too)

Reduce ttl to a desired amount of time for a smother change
Change the A records to reflect the right servers IP addresses.
Change the CNAMEs if needed to reflect the right names (if needed depending on the situation, the you exemplified should be changed, maybe you have some more)

If you are not changing the mail server nor the dns provider, just don't change MX, SOA or any related.
When you see everything is working as expected with resolution, grow the ttl to a reasonable number.
keep in mind TTL is the most important there, if you have some nasty resolution, in your current scenario, a change will take an hour to reflect, so move it to a small number while approaching the migration date but to a logic amount (I'm facing a migration today, and I'll set a 10' ttl for the most critical stuff, that I can face 10' for rollback, it depends on your application -have in mind that the ttl is spreaded around other dns that fwd, so you can't control resolution beyond this number-)
Comment: Well, half an hour is better than an hour. In general, DNS providers limit the lowest limit if they offer dns for free (and if it's not, a low ttl generates much more requests, so you pay for that) if 1800 is the lowest you can have, is your best option. Then, the number you are putting there depends on the amount of visit and the risk to have a "split brain" between you old an new db.
Before you change your dns, copy the current values, so if for any reason you have to roll back, you avoid the time asking your old provider support about them ;)
Comment: hadn't considered TTL.   I believe this is at the registrars default setting but I can edit it.  Although it seems to be low enogh `Min TTL 1800`, does that look ok to you?

Changing DNS records when Moving a site


Understanding input_shape parameter in LSTM with Keras

Question: I'm trying to use the example described in the Keras documentation named "Stacked LSTM for sequence classification" (see code below) and can't figure out the input_shape parameter in the context of my data.
I have as input a matrix of sequences of 25 possible characters encoded in integers to a padded sequence of maximum length 31. As a result, my x_train has the shape (1085420, 31) meaning (n_observations, sequence_length).
from keras.models import Sequential
from keras.layers import LSTM, Dense
import numpy as np

data_dim = 16
timesteps = 8
num_classes = 10

# expected input data shape: (batch_size, timesteps, data_dim)
model = Sequential()
model.add(LSTM(32, return_sequences=True,
               input_shape=(timesteps, data_dim)))  # returns a sequence of vectors of dimension 32
model.add(LSTM(32, return_sequences=True))  # returns a sequence of vectors of dimension 32
model.add(LSTM(32))  # return a single vector of dimension 32
model.add(Dense(10, activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'])

# Generate dummy training data
x_train = np.random.random((1000, timesteps, data_dim))
y_train = np.random.random((1000, num_classes))

# Generate dummy validation data
x_val = np.random.random((100, timesteps, data_dim))
y_val = np.random.random((100, num_classes))

model.fit(x_train, y_train,
          batch_size=64, epochs=5,
          validation_data=(x_val, y_val))

In this code x_train has the shape (1000, 8, 16), as for an array of 1000 arrays of 8 arrays of 16 elements. There I get completely lost on what is what and how my data can reach this shape.
Looking at Keras doc and various tutorials and Q&A, it seems I'm missing something obvious. Can someone give me a hint of what to look for ?
Thanks for your help !
Answer: LSTM shapes are tough so don't feel bad, I had to spend a couple days battling them myself:
If you will be feeding data 1 character at a time your input shape should be (31,1) since your input has 31 timesteps, 1 character each. You will need to reshape your x_train from (1085420, 31) to (1085420, 31,1) which is easily done with this command :
 x_train=x_train.reshape(x_train.shape[0],x_train.shape[1],1))

Answer: Check this git repository LSTM Keras summary diagram and i believe you should get everything crystal clear.
This git repo includes a Keras LSTM summary diagram that shows:

the use of parameters like return_sequences, batch_size, time_step...
the real structure of lstm layers
the concept of these layers in keras
how to manipulate your input and output data to match your model requirements  how to stack LSTM's layers

And more
Comment: @gung i really appreciate the way you are managing to review these answers to keep on standards, but i think that i can't elaborate even more about these parameters where there is many technical details concerning it. I just think that my answer could be helpful for developers facing similar issues with keras inputs and not necessarily this particular issue. Thanks
Comment: Thank you for that, @MohammadFneish. This looks like it would be more helpful now.  However, it isn't clear that this is quite an *answer to the question*, as opposed to a helpful suggestion. Be aware that [stats.SE] is strictly a Q&A site, not a forum. Can you add [still more] information to explain the input shape parameter?
Answer: I know it is not direct answer to your question. This is a simplified example with just one LSTM cell, helping me understand the reshape operation for the input data.
from keras.models import Model
from keras.layers import Input
from keras.layers import LSTM
import numpy as np

# define model
inputs1 = Input(shape=(2, 3))
lstm1, state_h, state_c = LSTM(1, return_sequences=True, return_state=True)(inputs1)
model = Model(inputs=inputs1, outputs=[lstm1, state_h, state_c])

# define input data
data = np.random.rand(2, 3)
data = data.reshape((1,2,3))

# make and show prediction
print(model.predict(data))

This would be an example of the LSTM network with just a single LSTM cell and with the input data of specific shape.
As it turns out, we are just predicting in here, training is not present for simplicity, but look how we needed to reshape the data (to add additional dimension) before the predict method.


Use of induction in a proof of the Five Colour Theorem

Question: I am having trouble understanding how the inductive hypothesis is being used in a proof of the five colour theorem in Matousek & Nesetril's 'Invitation to Discrete Mathematics'. Since it is the beginning of the proof, I will just quote it quickly (emphasis mine),

We proceed by induction on the number of vertices of the graph $G=(V,E)$. For $|V|\leq5$, the statement holds trivially.
By the results of section 5.3 we know that any planar graph has a vertex $v$ of degree at most 5. If we even have $\deg_G(v)<5$ then consider the graph $G-v$, and apply the inductive hypothesis on it. Assuming that the graph $G-v$ is coloured by colours 1,2,...,5, then we colour the vertex $v$ by some colour $i\in\{1,2,...,5\}$ not occurring among the (at most 4) colours used on the neighbours of $v$. In this way, we get a colouring of $G$ by 5 colours.

I don't understand how the inductive hypothesis is being used. It seems to me that they are saying that by the inductive hypothesis, the graph $G-v$ is 5-colourable. But I don't see how our induction gives us that conclusion.
I am trying to elaborate on my misunderstanding of this proof, but I am finding that I cannot even articulate what it is that I don't understand. So perhaps my real question is could somebody rephrase this part of the proof so as to give me another perspective on what is being said?
Answer: The induction is on $|V|$, the number of vertices of the graph $G$ in question. The induction hypothesis is, given any planar graph $G$ with $n$ vertices, then $G$ is $5$-colourable.
As part of the induction step, we assume some planar $G'$ has $n + 1$ vertices. We know we can find a vertex $v$ in $G'$ with $4$ or fewer neighbours, and so we let $G$ be $G'$ with the vertex $v$ (and adjacent edges) removed. Note that $G$ now has $n$ vertices, and is still planar.
By the induction hypothesis, $G = G' - v$ must be colourable with $5$ colours. The rest of the argument follows simply from there. Since $G'$ is a completely arbitrary planar graph on $n + 1$ vertices, we have therefore shown that any planar graph on $n + 1$ vertices is $5$-colourable, which is what we're trying to prove in the induction step.
That's what completes the induction proof. We can do this step multiple times to prove it for planar graphs with $n + 2, n + 3,$ etc. The argument allows us to prove the next case from the current one.


How to install mysql server using ansible playbook?

Question: I am trying to install mysql server on centos using ansible playbook. My yml file looks like above.
<code>---
- name: Install MySQL database server
  hosts: test
  become: yes
  become_method: sudo
  gather_facts: true
  tags: [database]
  tasks:
        - name: Update the software package repository
          yum:
                update_cache: yes

        - name: Install MySQL
          package:
                name: "{{ item }}"
                state: latest

          with_items:
              - mysql-server
              - mysql-client
              - python-mysqldb
</code>
But it getting error.
<code>failed: [192.168.94.151] (item=mysql-server) => {"changed": false, "item": "mysql-server", "msg": "No package matching 'mysql-server' found available, installed or updated", "rc": 126, "results": ["No package matching 'mysql-server' found available, installed or updated"]}
</code>
How can i fix this issue?
Comment: Use the correct package names.
Comment: To obtain valid package names, SSH into your server and do `yum search mysql`.
Comment: Yes, they are wrong.
Comment: Is this wrong? `- mysql-server - mysql-client`
Answer: I had to download and add the repository and then update.
<code>   - name: Download sources
      get_url:
        url: http://repo.mysql.com/mysql-community-release-el7-5.noarch.rpm
        dest: /opt/mysql

   - name: Install package
     yum:
       name: /opt/mysql/mysql-community-release-el7-5.noarch.rpm
       state: present

   - name: Install MySQL
     yum: name=mysql-server state=installed
</code>
Comment: You don't have to `get_url` first. You can just provide the URL directly to `yum`.


Página de erro 404 no IIS

Question: Boa tarde, eu desenvolvi um sistema e tenho uma lógica que não permite que perfis que não tem autorização acessem partes do sistema que não é permitido para ele. O que acontece é que, quando se tenta acessar uma área que não é permitida, o IIS dá uma página de erro 404(Not Found) em resposta a tentativa frustrada. O que eu queria saber é: Tem como eu colocar uma página de erro personalizada no IIS, pra que quando aconteça essa situação, mostre a minha página de erro personalizada ? Pois fico com medo em relação a segurança da minha aplicação.
Se alguém puder ajudar, ficaria grato !
Comment: Está usando MVC?
Comment: Exatamente, MVC mesmo.
Comment: Na minha aplicação eu customizei uma classe para fazer esse tipo de redirecionamento. Criei uma classe herdando a classe DefaultControllerFactory, depois sobrescrevi esse método: GetControllerInstance
Comment: É porque o meu problema é que, eu até tenho uma biblioteca que quando se tenta acessar uma página que não existe ele, redireciona pra uma página customizada. Ai tem um detalhe: Sem publicar no IIS, rodando pelo VS mesmo, quando eu tento acessar uma área não permitida por um perfil que não tem acesso, ele redireciona pra página de login de novo, ou seja, dá logout. Mas no IIS não, ele dá a página de 404. E eu não queria isso, queria uma página igual a que eu fiz, mas no IIS.
Answer: Tem.
No seu arquivo Web.config, adicione o seguinte:
<system.web>
    <customErrors mode="On" >
        <error statusCode="404" redirect="~/SeuControllerDe404" />
    </customErrors>
</system.web>

Controller:
public class SeuControllerDe404 : Controller
{
    [AllowAnonymous]
    public ActionResult Index()
    {
        return View();
    }
}

View:

Oops! Este endereço não existe.

Comment: Teria como colocar um exemplo de como criar ? Digo: o Controller e a View ?
Comment: @ÉrikThiago Veja agora.
Comment: Agooora entendi ! Valeeu Cigano !
Answer: Olá, tudo bem?
Sei que esta pergunta já foi respondida mas tem muito mais sobre isso já que, desse modo, você não vai conseguir retornar o erro 404 de maneira satisfatória.
O jeito mais seguro de fazer seria usando <httpErrors> dentro do <system.webServer>, como no exemplo abaixo:
<httpErrors errorMode="Custom">
    <remove statusCode="404"/>
    <error statusCode="404" path="/erro404.html" responseMode="File"/>
<httpErrors>

Desse modo você vai retornar tanto o HTTP status 404 quanto conserver a url original da página.
Você pode ver essa solução mais explicada neste artigo: http://davidsonsousa.net/pt/post/criando-paginas-de-erro-404-personalizadas-no-aspnet-mvc
Comment: Cara, parabéns. Seu post e sua resposta são excelentes ! Eu estou usando um pacote do nuget pra fazer esse redirecionamento. Mas dessa forma ai ta ótima ! E valeeu !

Página de erro 404 no IIS


How can I create a view on a profile page that shows content related to the user we are viewing

Question: I have a specific "sport user id" that the user provides in order to grab sports results about that user. I want to display their results, which I keep updated and organized programmatically in a cron job, on their profile. The way I would like to link the content would be by keeping the "sport user id" as a field in the result content type and also as a field in the user.
How do I go about creating a filter to do this?
Answer: Check out the EVA (Entity Views Attachment) module. This allows you to create views, which you can use as a field on any entity (node, profile, user or whatever) you like.
After you created the view, go to "Manage Display" of your content type and move the field in the right position.
Answer: This is a simple way to show content of a user on their profile page:

create a view of the content with a contextual filter (called argument in D6) "userid from URL"
assign the view to a block
assign that block to show on the user profile (user/uid)


What is the helper function for "lowercase" when writing an Angular schematic template?

Question: I'm working on building a simple angular schematic template following a tutorial here. All going well. This tutorial uses a helper function (dasherize) to convert the file name from AwesomeWrap to hello-awesome-wrap.
hello-__name@dasherize__

I want to change this functionality in my own implementation to simply ensure file names are lower case, so AwesomeWrap should be awesomewrap.
This functionality doesn't seem well documented though (or not that I can find) and I can't find a list of available functions for this. I tried creating a file view-__name@lowercase__.ts but lowercase didn't seem an available function.
When I run schematics .:sensor --name=test, I get the error message:

Error: Pipe "lowercase" is not defined.

So what is the correct syntax for this? Is there a list of available transforms that can be performed in this way?
Answer: There is currently no lowercase in the Angular Schematics Devkit package.
You can see all the supported functions here: https://github.com/angular/angular-cli/blob/master/packages/angular_devkit/core/src/utils/strings.ts
If you need a lowercase function you can open a Pull Request for this file and add it.
Answer: I can only image that they transform dasherize__ to require('dasherize')(__). Where __ is obviously the name of the file. Soo, I guess we need to find a package which does lowercase for you:
npm install lower-case

And I guess you can then use this as:
view-__name@lower-case__.ts

Comment: @Liam Aw, unfortunately! Was worth a shot :D. There should be a way though, to extend the angular devkit. Otherwise I believe it's quite limited
Comment: Added the error message if that's any help. It seems to be looking for a pipe but lowercase is the correct pipe so I'm not sure what I'm missing
Comment: Yeah again, makes good sense. I might just submit a PR, it's seems an obvious piece of missing functionality and really simple to implement
Answer: Sorry for late answer.
In your template file(example: ./files/__name@dasherize__.component.ts)file just use string.toLowerCase()
import { Component } from '@angular/core';

@Component({
  selector: "<%= name.toLowerCase() %>",
  template: `
  `,
})
export class <%= classify(name)%>Component {

}

If you want to use it like dasherize, go to index.ts
export function mySchematics(_options: Schema): Rule {
  return (tree: Tree, _context: SchematicContext) => {
    const sourceTemplates = url('./files');

    const sourceParametrizedTemplates = apply(sourceTemplates, [
      template({
        ..._options,
        ...strings,
        tolowercase
      })
    ]);

    return mergeWith(sourceParametrizedTemplates)(tree, _context);
  };
}

export function tolowercase(value: string): string {
  return value.toLowerCase();
}

Then you can use like in folder or file name:
__name@tolowercase__component.ts
also use in template like this
import { Component } from '@angular/core';

@Component({
  selector: "<%= tolowercase(name) %>",
  template: `
  `,
})
export class <%= classify(name)%>Component {

}


Plot a perfect sphere with equal axes by parametric plot in Sympy

Question: I would like to know how using plot3d_parametric_surface in Sympy we can plot a perfect sphere. By perfect I mean with equal axes. The result with this function has an oval shape!
from sympy import *
from sympy.plotting.plot import plot3d_parametric_surface
from sympy.abc import theta , phi
plot3d_parametric_surface(sin(phi)*cos(theta) , sin(phi)*sin(theta), cos(phi), (phi,0,pi),(theta,0,2*pi))

I tried to implement the answers in the matplotlib (equal unit length): with 'equal' aspect ratio z-axis is not equal to x- and y- but I didn't have any success.
Answer: One of the main problems is that ax.set_aspect('equal') is not implemented yet in matplotlib. The current versions of matplotlib (3.1) raise an explicit error as soon as set_aspect('equal') is called. Older versions gave a quite wrong projection, although often the user was not aware of the error. Other StackOverflow answers about setting the equal aspect ratio in 3D just set the xyz limits equal, which gets you closer to the desired result, but without being a fully equal projection.
A workaround is to manually set the figure axis until the sphere has the desired aspect ratio. This is cumbersome, because the plot dimensions include space for the axes labels and for padding.
For example, setting the figsize to 6, 5.6 seems to go well
from sympy import sin, cos, pi
from sympy.plotting.plot import plot3d_parametric_surface
from sympy.abc import theta, phi
import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = 6, 5.6
plot3d_parametric_surface(sin(phi) * cos(theta), sin(phi) * sin(theta), cos(phi),
                          (phi, 0, pi), (theta, 0, 2 * pi))

Inserting an invisible box (in case you're not drawing a sphere), could be achieved with just a diagonal line:
from sympy import sin, cos, pi
from sympy.plotting.plot import plot3d_parametric_surface, plot3d_parametric_line
from sympy.abc import theta, phi, t
import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = 6, 5.6

p1 = plot3d_parametric_surface(sin(phi) * cos(theta), sin(phi) * sin(theta), cos(phi),
                               (phi, 0, pi), (theta, 0, 2 * pi), show=False)
p2 = plot3d_parametric_line(t, t, t, (t, -1, 1), line_color='none', show=False)
p1.append(p2[0])

#p1.backend(p1).ax[0].set_aspect('equal')  # this raises a NotImplementedError
p1.show()


imagem de background de tela android

Question: Boa tarde !
   Estou tentando colocar uma imagem de background ma tela de login do meu aplicativo, essa imagem foi baixada do site unsplash, e quando coloco ela na propriedade de background do meu layout o seguinte erro é apresentado:
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ramattecgmail.rafah.herdeirosapp/com.ramattecgmail.rafah.herdeirosapp.Activitys.LoginActivity}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class <unknown>

segue código XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg"
tools:context="com.ramattecgmail.rafah.herdeirosapp.Activitys.LoginActivity">

   <Button
    android:id="@+id/bt_login_face"
    android:layout_width="@dimen/bt_login_width"
    android:layout_height="@dimen/bt_login_height"
    android:paddingTop="@dimen/bt_login_pad_vertical"
    android:paddingBottom="@dimen/bt_login_pad_vertical"
    android:paddingLeft="@dimen/bt_login_pad_horizontal"
    android:layout_marginBottom="@dimen/bt_login_face_mrg_bot"
    android:layout_gravity="center_horizontal|bottom"
    android:stateListAnimator="@null"
    android:elevation="12dp"
    android:background="@drawable/face_button_login"
    android:drawableLeft="@drawable/face_btn2"
    android:text="@string/login_face"
    android:textSize="@dimen/bt_login_txts"
    android:textAlignment="center"
    android:textColor="@color/primaryTextColor" />

<Button
    android:id="@+id/bt_login_google"
    android:layout_width="@dimen/bt_login_width"
    android:layout_height="@dimen/bt_login_height"
    android:paddingLeft="@dimen/bt_login_pad_horizontal"
    android:paddingBottom="@dimen/bt_login_pad_vertical"
    android:paddingTop="@dimen/bt_login_pad_vertical"
    android:layout_marginBottom="@dimen/bt_login_google_mrg_bot"
    android:layout_gravity="center_horizontal|bottom"
    android:stateListAnimator="@null"
    android:elevation="12dp"
    android:background="@drawable/google_button_login"
    android:drawableLeft="@drawable/google_btn"
    android:text="@string/login_google"
    android:textSize="@dimen/bt_login_txts"
    android:textAlignment="center"
    android:textColor="@color/red" />

 </FrameLayout>

Abaixo segue o código da activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mAuth = FirebaseAuth.getInstance();

    /*************** TESTE DE LOGIN COM BOTÃO CUSTOMIZADO ***********/
    FacebookSdk.sdkInitialize(getApplicationContext());

    btFaceLogin = findViewById(R.id.bt_login_face);
    btGoogleLogin = findViewById(R.id.bt_login_google);

    //EVENTOS
    btGoogleLogin.setOnClickListener(this);
    btFaceLogin.setOnClickListener(this);

    callbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.d(TAG, "Sucesso linha 82");
            AccessToken token  = AccessToken.getCurrentAccessToken();
            handleFacebookAccessToken(token);
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {

        }
    });

    /*************** TESTE DE LOGIN COM BOTÃO CUSTOMIZADO ***********/

    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    // Build a GoogleApiClient with access to the Google Sign-In API and the
    // options specified by gso.
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

}

No setConentView o erro já é apresentado, a imagem está no formato png.
Ao rodar o app dessa forma ele nem abre.
Comment: cadê o botão do face no XML?
Comment: pode postar o código de activity ? só o onCreate
Comment: Desculpa galera, nem vi que estava sem o botão do face
Answer: Esse erro ocorre geralmente quando seu android:background é muito grande. Faça o teste de diminuir a imagem.
Comment: Era isso mesmo, a imagem que eu baixei era exageradamente grande, muito obrigado pela dica !
Answer: Tente colocar isso no seu xml:
<Button
   android:id="@+id/bt_login_face"
   android:layout_width="wrap_content"
   android:layout_height="@dimen/bt_login_height" />

Comment: Valeu pela tentativa Felipe, mas não é a falta do botão, apenas tinha esquecido de deixar ele no código de exemplo que postei
Comment: beleza! tenta refazer teu código que pode dar certo.

imagem de background de tela android


Create a class of Colors

Question: In my app, I have for example 5 available colors for different Task that user can choose between them anytime. I thought it would be good to have a class of color and I declare few colors inside the class that in any controller I can access to those colors as an Array. For example when I want to show the colors to pickup, I want them as an array. But I don't know how to do that? I create a class but in the init part, I don't know how to add colors
final class Colors {
    var color : [UIColor]

    init(color: [UIColor]) {

    }
}

Your help will be appreciated.
Comment: Consider to use Assets
Answer: Extend UIColor, make your colors static properties, and make your array a computed static property.
Answer: Option 1 - You can extend UIColor to list all of your colors and create an array:
extension UIColor {
    struct GoTimeThemes {
        static let firstColor = UIColor(red: 48.0/255.0, green: 35.0/255.0, blue: 174.0/255.0, alpha: 1.0)
        static let secondColor = UIColor(red: 83.0/255.0, green: 160.0/255.0, blue: 263.0/255.0, alpha: 1.0)
        static let thirdColor = UIColor(red: 146.0/255.0, green: 80.0/255.0, blue: 156.0/255.0, alpha: 1.0)

        static var allColors: [UIColor] {
        let colors = [firstColor, secondColor, thirdColor]
        return colors
        }
    }
}

And call your array like so
let colors = UIColor.GoTimeThemes.allColors

Option 2 - You can put your colors in an Enum that conforms to CaseIterable:
enum ThemeColors: CaseIterable {
    case firstTheme, secondTheme, thirdTheme

    var color: UIColor {
        switch self {
        case .firstTheme:
            return UIColor(red: 48.0/255.0, green: 35.0/255.0, blue: 174.0/255.0, alpha: 1.0)
        case .secondTheme:
            return UIColor(red: 83.0/255.0, green: 160.0/255.0, blue: 263.0/255.0, alpha: 1.0)
        case .thirdTheme:
            return UIColor(red: 146.0/255.0, green: 80.0/255.0, blue: 156.0/255.0, alpha: 1.0)
        }
    }
}

And call it with allCases to get a Collection:
ThemeColors.allcases //→ [firstTheme, secondTheme, thirdTheme]

Answer:
I thought it would be good to have a class of color and I declare few colors inside the class that in any controller I can access to those colors as an Array.

An enumeration would work well for this. The set of colors is fixed, right? It sounds like you won't need distinct instances of the set of colors, and it'd probably be nice to be able to access the colors without needing to create an object or bother with sharing an object. An enumeration gives you a set of discrete values, and it can have methods associated with it. For example, you could have a darkGreen value, and then methods like uiColor() and cgColor() that return UIColor and CGColor objects that correspond to that value.
Comment: I thought about enum, but how can I convert that enum anytime to array? Thanks for your help
Comment: conform the enum to the `CaseIterable` protocol and then you can access the `.allCases` property which will be an array of all possible values.

Create a class of Colors


Commerce Kickstart: How To Add Sort Fields To Search API?

Question: I've been playing with the Search API and I can add new Facet Displays and filters, but no matter what I try I can't get any fields other than Price, Latest and Title to appear as Sort options. What's the 'trick'?
Answer: For other travelers, the answer is that it's a bug with a patch that has not been made part of the official distribution as of 26 Sep 2014. See #6 for the patch.
https://www.drupal.org/node/2202093


Reset Password with RSA Keys

Question:
I wrote a module to reset your password using RSA keys.
The code will send an email to the user with a link to reset his
password.
The user then will click on the link, that will send him back to the
MVC web site.
The link is composed of 3 parts: URL / ID / Public RSA Key
I am using MVC with routes

Issue 1: RSA Keys have slashes "/", therefore I had to URL Encode they key.
Issue 2: When the Key is encoded and the user clicks on it, MVC gives me the following error
The request filtering module is configured to deny a request that contains a double escape sequence
Does anyone know how to deal with RSA keys inside MVC using routes?
Of course without opening the door to HTML injection......
Comment: `` however this does expose security vulnerabilities to your application. see http://stackoverflow.com/a/7742208/426894
Comment: That will open the door for HTML Injection....
Comment: You might want to take a look at http://stackoverflow.com/questions/7739233/double-escape-sequence-inside-a-url-the-request-filtering-module-is-configured. Also, does "MVC" mean something different in ASP.net? I only know of it in the meaning of the Model-View-Controller design pattern, which can't exactly do any error-throwing of its own.
Comment: @JAB "MVC" is a generic reference to ASP.net MVC Framework.  Many people don't actually realize the framework is named after a design pattern, and use the shorthand.
Answer: I would recommend you passing this information as query string parameters. Scott Hanselman explains in details in this blog post.
Quote from his conclusion:

After ALL this effort to get crazy stuff in the Request Path, it's
  worth mentioning that simply keeping the values as a part of the Query
  String (remember WAY back at the beginning of this post?) is easier,
  cleaner, more flexible, and more secure.
Answer: You can enable that feature with the following code in the web.config.  Please note, however, this may be a security risk, as it allows someone to append javascript double escaped elements to a page url, as many others have commented.
<system.webserver>
    <modules runallmanagedmodulesforallrequests="true">
        <security>
            <requestfiltering allowdoubleescaping="true">
            </requestfiltering>
        </security>
    </modules>
</system.webserver>

your better option by far is to have your link go to a form which asks for the RSA to be pasted in and submitted back.  A small bit more work for your end users, but drastically more secure.

Reset Password with RSA Keys