Running a function in Wordpress when publishing a custom post type

Question: I am trying to run the following function anytime a wordpress "Jobs" custom post is published. The code works (lines 2-7) when it is placed in my theme template, but it only runs when the post is viewed. I want the code to run when the post is published, and so I have tried adding the code in a function inside my functions.php, but nothing is happening when each custom post is published. Any suggestions?
function indeedgeo(){
    $indeedgeo = get_post_meta($post>ID, indeedgeo, true);
    $indeedgeos=explode(' ',$indeedgeo);
    $_jr_geo_latitude = $indeedgeos[0];
    $_jr_geo_longitude = $indeedgeos[1];
    update_post_meta($post->ID, _jr_geo_latitude, $_jr_geo_latitude);
    update_post_meta($post->ID, _jr_geo_longitude, $_jr_geo_longitude);
    }
add_action('publish_Jobs', 'indeedgeo');

Answer: You should hook into one of the three actions;
do_action('edit_post', $post_id, $post);
do_action('save_post', $post_id, $post);
do_action('wp_insert_post', $post_id, $post);

that are run when a post is either saved, or has its status updated. Something like the following should do the trick.
function se_10441543_save_post($post_id, $post){
    //determine post type
    if(get_post_type( $post_id ) == 'your_post_type'){
        //run your code
        $indeedgeo = get_post_meta($post_id, indeedgeo, true);
        $indeedgeos=explode(' ',$indeedgeo);
        $_jr_geo_latitude = $indeedgeos[0];
        $_jr_geo_longitude = $indeedgeos[1];
        update_post_meta($post_id, _jr_geo_latitude, $_jr_geo_latitude);
        update_post_meta($post_id, _jr_geo_longitude, $_jr_geo_longitude);
    }
}

add_action('save_post', 'se_10441543_save_post', 10, 2);

http://codex.wordpress.org/Plugin_API/Action_Reference
Comment: This makes sense but doesn't do anything when the custom post is published/updated. The code has been added to functions.php and the only thing that I changed was to input the custom post type name. The //run your code section works fine when inserted into my theme template.
Comment: if you add in a wp_die(print_r($post)); before the if test for your posttype, what does it say when you then try to publish your post? That will at least indicate that the action is getting called.
Comment: Thanks for your response. With the line added I get the following when trying to bulk import posts from a rss feed (as is the usual method):
`stdClass Object ( [ID] => 3952 [post_author] => 1 [post_date] => 2012-05-04 17:35:43 [post_date_gmt] => 2012-05-04 17:35:43 [post_content] =>`
Comment: If I try to add a custom post manually I get the following:
`stdClass Object ( [ID] => 3953 [post_author] => 1 [post_date] => 2012-05-04 21:33:54 [post_date_gmt] => 0000-00-00 00:00:00 [post_content] => [post_title] => Auto Draft [post_excerpt] => [post_status] => auto-draft [comment_status] => open [ping_status] => open [post_password] => [post_name] => [to_ping] => [pinged] => [post_modified] => 2012-05-04 21:33:54 [post_modified_gmt] => 0000-00-00 00:00:00 [post_content_filtered] => [post_parent] => 0 [guid] => [menu_order] => 0 [post_type] => job_listing [[[Cut off due to comment length]]]
Comment: here's the rest: `[post_type] => job_listing [post_mime_type] => [comment_count] => 0 [ancestors] => Array ( ) [filter] => raw ) 1` I'm guessing this is showing all the functions that are running? I don't see my function there so it appears it's not running?
Comment: Ok so the issue is with the save_post/edit_post/wp_insert_post. When I use edit_post and I manually edit a post, the function works. So the issue must be that the method I am importing posts with (Autoblogged plugin which imports posts from RSS feeds) bypasses these actions.
Comment: I think the plugin is importing posts using the `xmlrpc_methods` hook
Comment: Thanks very much for your help. I am moving this to a new question: http://stackoverflow.com/questions/10457257/wordpress-function-not-running-when-importing-posts-via-rss
Comment: Ahh OK, if you are not using the standard post insertion methods, then I guess those actions wont run.
Answer: Not exactly sure how your "publish_jobs" hook is working but right off the bat, if you are placing this function in your functions.php, you will need to give it context. Replace $post>ID with the post number (an integer). If this applies to many post you will probably want to use another method of querying post data: http://codex.wordpress.org/Class_Reference/WP_Query. Let me know if this helps.
Comment: publish_jobs hook info taken from http://www.wpmods.com/custom-post-type-publish-action-hook/


What size breaker and wire do I need for my garage wall heater?

Question: I am planning on installing a Garage ceiling heater, which has a fan, and 240 volt coil electric heater. This unit is 26 amps, and 6000 watts, and will be installed in my garage, 60 feet from my main panel. Can you tell me what size wire, and breaker I need to feed this heater?
Comment: Does the installation instructions say anything about what wire size to use?  As things are now, it looks like you'll need 8 AWG because you are 1 amp over the limits for 10 AWG.  However the instructions could override that (under UL's watchful eye, as the instructions are approved as part of the UL approval for the machine).
Comment: I'm just surprised a builder would make a machine 25A when they could make it 24A and allow you to use smaller wire... Unless they had gone to UL and gotten UL to grant them a variance?... Hence my interest in the instructions.
Comment: @fixer1234 depends how it's insulated. 6kw of heat isn't that much.  It's a lot of power, but it's not a lot of heat.
Comment: Are you *sure* it's 26 amps? What does the installation instructions say? I ask because 6000 watts is *right on the cusp*... Also do you need any other electrical service in that garage?
Comment: The literature with heater says it is 26 amps.. I do not need any other electrical service in this garage
Comment: Im sorry this heater is 25 amps
Comment: A 6KW heater seems like extreme overkill for a garage, unless you are turning it into a sauna in the arctic.  Just sayin'.
Answer: For a 26A nameplate load, Code will require #8 wire and a 40A circuit breaker. There really isn't any legal way around it.
Not what you asked, but by code you also must have 8 ft. from the bottom of the heater to the garage floor, because you have to avoid igniting any potential gas leaks from your car (remember, technically a "garage" is for a car, although few of use use them for that). If your garage has an 8 ft. ceiling, that isn't going to fit.
Answer: Google finds plenty of links. For example:
https://www.thespruce.com/matching-wire-size-to-circuit-amperage-1152865
AWG 10 would seem to do. Once you pick the gauge, you must use the appropriate breaker for the wire. There might be, in your code some extra you must factor in. @harper points out, this is NEC 424.3b and adds 25%. This increases it to 8 AWG.
You can calculate the voltage drop at sites like http://www.calculator.net/voltage-drop-calculator.html
If I got your situation correct, that would only be a 3-volt drop. Looks acceptable.
Comment: Jeffrey code is the minimum requirement so that is the not Too dangerous level we go to. If the mtg states that the heater can be installed with #10 that would be legal and not TOO dangerous, however if no instructions are provided on the branch circuit size 125% of continuous loads is a requirement, fixed heating as defined by code are a continuous load.
Comment: Except this is a continuous load. NEC 424.3b.  See, this is a classic example of what happens when people learn electrical by asking questions on Google... How would you *even know* to ask the "continuous load" question? You wouldn't.
Comment: @Harper you are totally right on the perils of learning by asking on the internet. Personnaly, I know stuff from the theoretical side and had no idea about code. Thanks for sorting that out. Also, I can only guess what the reasons would be for someone to want this kind of heating power in a garage while not wanting to ask a professional. There's probably a reson. Anyway, with the edit, the OP should be able to make something not TOO dangerous.


C programming suites/IDEs

Question: I know that asking for something like Visual Studio is too much but something that will let me write, debug and compile in a GUI instead of the command line is good enough for me. (Not that I'm lazy, but I don't have time to learn the necessary commands...)
Answer: Code::Blocks
sudo apt install codeblocks

Wikipedia: Code::Blocks
Answer: Geany
Geany is a text editor using the GTK2 toolkit with basic features of an integrated development environment. It was developed to provide a small and fast IDE, which has only a few dependencies from other packages. It supports many filetypes and has some nice features.
To install geany in all currently supported versions of Ubuntu open the terminal and type:
sudo apt install geany

Comment: I like geany mostly because its the only free editor that feels most like my favorite non-free editor, SlickEdit.  Searching is a big deal to me, SlickEdit does it best, Geany's not too bad.
Answer: Eclipse
Eclipse with Eclipse IDE for C/C++ Developers.
This package includes:

C/C++ Development Tools
Git integration for Eclipse

Regardless of your operating system, you will need to install some Java virtual machine (JVM). You may either install a Java Runtime Environment (JRE), or a Java Development Kit (JDK), depending on what you want to do with Eclipse. If you intend to use Eclipse for Java development, then you should install a JDK. If you aren't planning to use Eclipse for Java development and want to save some disk space, install a JRE.
If you are using Linux, read this.
Answer: MonoDevelop
If you like Visual Studio, you will certainly like MonoDevelop. You can find it in the Software Center. You can even write .NET apps with it if you want to (like C# as you can see in the screenshot), but I suggest you don't.
To install MonoDevelop in Ubuntu 14.04-16.04 open the terminal and type:
sudo apt install monodevelop

]2
Comment: If you are able to write an application in native code, like C or C++, I think it is always better to do so. Using a framework like .NET always has a small impact on performance, so it might be better to avoid it.
Mono is great to make it easier for porting Windows apps to Linux, but when developing native applications for Linux I personally would rather use open-source technologies.
Comment: Why do you suggest not to write C# apps ?
Comment: leave mono debate out of this please. Mono is Open Source.
Answer: CodeLite
CodeLite is a powerful and lightweight IDE specializing in C, C++, PHP and JavaScript. Its features include:

Generic support for compilers
Built-in GDB support
Database-based Code Completion mechanism
Syntax highlighting for C/C++, Java, Perl, XML, Makefile, Lua, Diff files,
PHP, JavaScript, Python, HTML, and ASP
Text Folding
Bookmarks
Find and Replace
doxygen comment generator

To install CodeLite in all currently supported versions of Ubuntu open the terminal and type:
sudo apt install codelite

CodeLite screenshot gallery
For me CodeLite is the best replacement for Visual Studio.
Answer: NetBeans
Apache NetBeans IDE lets you quickly and easily develop Java desktop, Java EE, and web applications, as well as HTML5 applications with HTML, JavaScript, and CSS. The IDE also provides a great set of tools for PHP and C/C++ developers. To install NetBeans in all currently supported versions of Ubuntu open the terminal and type:
sudo snap install netbeans --classic

Comment: Netbeans font is ugly on Ubuntu and that screenshot is from windows ;)
Answer: vim
Vim is also a good choice for writing C programs.
Comment: Vim without any plugin might not be a good choice for IDE. But with few plugins , it can become a powerful IDE.  I use Ultisnip+clang_complete+supertab+delimate to turn vim into a C/C++ IDE.
Answer: Anjuta
Anjuta is a versatile software development studio featuring a number of advanced programming facilities including project management, application wizard, interactive debugger, source editor, version control, GUI designer, profiler and many more tools. It focuses on providing simple and usable user interface, yet powerful for efficient development.
To install Anjuta in all currently supported versions of Ubuntu open the terminal and type:
sudo apt install anjuta

Answer: Emacs
Install emacs-gtk for the version which supports good readable freetype fonts, gtk and other visual goodies.
Emacs allows you to compile and debug inside the GUI. With CEDET package, it has got nice code completion for C and C++ projects. Color theme will give nice themes and syntax coloring for the source code. Emacs can be customized heavily using the e-lisp.
Emacs running with CEDET and color theme showing code completion.
Also refer to Ubuntu Community Help Wiki for EmacsHowto.
Comment: Also, unlike many IDEs that specialize in one or a few languages, Emacs provides good editing support for [almost anything that has a text format](http://www.emacswiki.org/emacs/CategoryModes), so you can use it for easier integrated editing all the files that comprise a program distribution.
Comment: [ECB](http://ecb.sf.net/) is an Emacs package that provides the browsing features and side panes that other IDEs have -- check out the [sample screenshots](http://ecb.sourceforge.net/screenshots/) for a visual explanation.
Answer: KDevelop
I very highly recommend KDevelop. It's a KDE program, but it will work under GNOME. It's like a color explosion. Pretty much every single variable, class, method, language construct, etc. has a different color. Not just local variables one color, global, etc. Every local variable will have a different color from each other one.
It also integrates with cmake extremely well and is generally a great IDE to work with. I really wish there was a Java and/or Python plugin for it.
To install KDevelop in all currently supported versions of Ubuntu open the terminal and type:
sudo apt install kdevelop

Answer: qtcreator
QT Creator is the best C/C++ IDE available for Ubuntu.

Qt Creator is a cross-platform C++ integrated development environment which is part of the Qt SDK[2]. It includes a visual debugger and an integrated GUI layout and forms designer. The editor's features includes syntax highlighting and autocompletion, but not tabs. Qt Creator uses the C++ compiler from the GNU Compiler Collection on Linux and FreeBSD. On Windows it can use MinGW or MSVC with the default install and can also use cdb when compiled from source.
Answer: Sublime Text 2
I recommend Sublime Text 2. It is not free but worth every cent.

Sublime Text 2 may be downloaded and evaluated for free, however a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.

It features a plethora of useful features and is highly extensible.
Answer: Eclipse
Just for completeness I suggest you take a look at Eclipse. To install Eclipse in all currently supported versions of Ubuntu open the terminal and type:
sudo snap install eclipse --classic

Eclipse can handle just about any language you like with the right plugin, but in my opinion better options have already been mentioned in this list.
Answer: Anjuta DevStudio
Anjuta IDE for C/C++ and GNOME/Gtk+ applications has features that enable easy debugging, management of code and GUI design by providing a simple and usable user interface. It also integrates with version control systems like CVS, Git or Subversion.
To install Anjuta in all currently supported versions of Ubuntu open the terminal and type:
sudo apt install anjuta

Answer: One more good editor and awarded is Komodo Edit. You can use it with a lot languagies c, c++, python and more. Is free and croos platform.
There is a Komodo IDE but it is commercial and non-free. You can try it with a trial version.

C programming suites/IDEs


Divide the results of two select queries

Question: I have two SQL count queries that on their own work fine, they are:
SELECT count(*) AS TOTAL_PROGRESS_BY_LINE_
FROM dbo.PID_Components_PROCESS_LINES
WHERE ISOGEN_LINE_PROGRESS_ = 'C'

RESULT: TOTAL_PROGRESS_BY_LINE_ = 26

SELECT count(*) AS TOTAL_LINES_BY_PROJECT_
FROM dbo.PID_Components_PROCESS_LINES
WHERE PROJECT_NUMBER_ = 'PJ001234'

RESULT: TOTAL_LINES_BY_PROJECT_ = 130

Now how to do I add to the query to get the percentage of 26/130??
I have a new query to go along with how to get percentages.
Here it is:
SELECT ISOGEN_LINE_PROGRESS_, PROJECT_NUMBER_,
CASE
    WHEN ISOGEN_LINE_PROGRESS_ = 'A' THEN 'NOT IN MODEL'
    WHEN ISOGEN_LINE_PROGRESS_ = 'B' THEN 'ROUGHED IN'
    WHEN ISOGEN_LINE_PROGRESS_ = 'C' THEN 'PARTIAL CHECK'
    WHEN ISOGEN_LINE_PROGRESS_ = 'D' THEN 'READY FOR FINAL CHECK'
    WHEN ISOGEN_LINE_PROGRESS_ = 'E' THEN '100% COMPLETE'
    WHEN ISOGEN_LINE_PROGRESS_ = '0' THEN 'ISSUE FOR CONSTRUCTION'
END AS PROGRESS_PER_LINE_
FROM PID_Components_PROCESS_LINES
WHERE PROJECT_NUMBER_ = 'PJ001234'
ORDER BY ISOGEN_LINE_PROGRESS_

this brings back results below:
ISOGEN_LINE_PROGRESS_   PROJECT_NUMBER_ PROGRESS_PER_LINE_
A                       PJ001234        NOT IN MODEL
B                       PJ001234        ROUGHED IN
C                       PJ001234        PARTIAL CHECK
D                       PJ001234        READY FOR FINAL CHECK

If I remove the Distinct from my query there are obviously multiple rows for each level of progress.  How do I add to the above distinct query to have a column at the end with the rate or percent of each level of progress compared to the overall number of lines?
Comment: The values you are dividing are integers. Do you want an integer result, i.e. `0`, the percentage as an integer, i.e. `20`, or something else (`0.2000`, `20.00`, `'Not much.'`)?
Comment: Please put new questions in  _new questions_. The title, comments and answers won't make any sense if you change the initial question and it's all quite confusing if you try to wedge another question into the first one.
Comment: I would like  the result to be 20.00. I apologize I'm new to what I consider "more advanced" queries.
Comment: The columns I'm doing the count on are varchar data type if that makes a difference?
Answer: Select them as a subquery.
By default the result will be an integer because count(*) returns an int. For a decimal result convert to a decimal.
SELECT (
    SELECT CONVERT(decimal(9,2),COUNT(*)) AS TOTAL_PROGRESS_BY_LINE_
    FROM dbo.PID_Components_PROCESS_LINES
    WHERE ISOGEN_LINE_PROGRESS_ = 'C'
) / (
    SELECT CONVERT(decimal(9,2),COUNT(*)) AS TOTAL_LINES_BY_PROJECT_
    FROM dbo.PID_Components_PROCESS_LINES
    WHERE PROJECT_NUMBER_ = 'PJ001234'
)

Comment: @Drafter-SQL thats because when you divide an int by an int in SQL Server the result is always an int. So convert to decimal as I have shown. If you had shown your desired results in your question this would have been addressed.
Answer: You may use conditional aggregation and simple division in one query:
select
  100.0 *
  count(
    case when ISOGEN_LINE_PROGRESS_ = 'C'
    then 1
    end
  )
  /
  nullif(count(
    case when PROJECT_NUMBER_ = 'PJ001234'
    then 1
    end
  ), 0) as rate_
FROM dbo.PID_Components_PROCESS_LINES
WHERE ISOGEN_LINE_PROGRESS_ = 'C'
  or PROJECT_NUMBER_ = 'PJ001234'

Comment: This also came back as 0 for rate.  The columns I'm doing the count on are varchar data type if that makes a difference?
Comment: @Drafter-SQL I've updated the code with implicit conversion to decimal and your desired scale to 100
Comment: That did the trick, the result came back as 20.000. I appreciate all the help and apologize for not providing some sample data.  I have a follow up question and will put together some sample data to provide with the question this time.
Comment: @Drafter-SQL You're welcome. If you think some answer fits well with your needs and provides good enough solution you may [accept it or upvote](https://stackoverflow.com/tour) to indicate it as useful.
Answer: DECLARE @firstone INT;
DECLARE @secondone INT;
SELECT @firstone = count(*)
FROM dbo.PID_Components_PROCESS_LINES
WHERE ISOGEN_LINE_PROGRESS_ = 'C';

SELECT @secondone = count(*)
FROM dbo.PID_Components_PROCESS_LINES
WHERE PROJECT_NUMBER_ = 'PJ001234';

SELECT @firstone / @secondone AS resultthing

SELECT @firstone /CAST(@secondone AS DECIMAL (9,2))

Comment: You may have to CAST the result but that was not specified
Comment: I appreciate the fast responses but that returns 0???
Answer: You could use a common table expression to get the counts and then select the desired results in one swell foop:
with Counts as (
  select
    ( select Count(*) from Sys.Tables ) as NumberOfTables,
    ( select Count(*) from Sys.Columns ) as NumberOfColumns
  )
  select NumberOfTables, NumberOfColumns,
    NumberOfColumns / NumberOfTables as ColumnsPerTable,
    ( 100 * NumberOfColumns ) / NumberOfTables as IntegerPercentColumnsPerTable,
    ( 100.0 * NumberOfColumns ) / NumberOfTables as NumericPercentColumnsPerTable
    from Counts;

I used existing tables since you chose not to supply DDL and sample data. So it goes.


Why is System.Drawing.Color.Green (0, 128,0)?

Question: I thought it should be (0,255,0). Anyone know why?
Answer: Because the .NET framework uses the W3C version of the X11 color names. There's apparently two different "Green" colors, the X11 one which is (0, 255, 0), and the W3C one which is (0, 128, 0).
It is apparently not known why the W3C (or anybody) adopted this particular list of colors as standard, although I speculate that it's because it's the only real extensive list of "easy-to-use, human-readable" names for some RGB values (I personally can't imagine what the color <code>#6495ED</code> looks like until I look it up).
There are differences between the W3C and X11 list (like "Gray" and "Purple" having different RGB values between W3C and X11). Also, the .NET framework defines "DarkSeaGreen" as (143, 188, 139) instead of (143, 188, 143). I wouldn't be surprised if the rationale for these different values was "it looked more Green/Gray/Purple/etc."
Comment: @Ives: This is still RGB, the only point of contention is what RGB value creates the color associated with each English color word.  One system claims (0,1,0) is green (and this seems to make obvious sense), where the other system uses (0,.5,0) (which I'm guessing produces a green more similar to what a normal person would call "green".
Comment: Nice, I was not aware of that.
Comment: I didn't know about that. Very interesting this was the choice over RGB.
Comment: from the page you refer to green is defined in X11 as (0%, 100%, 0%) but in W3C as (0%, 50%, 0%) which is what the op says the value is the W3C one and not the X11 one
Comment: @Dan D: Right. I made sure to mention that there was two different versions of the color list.


flex checkbox group

Question: I need to use checkbox as radiobutton.
In my case I'd like to define a checkbox group but I don't know why.
If I select one checkbox, I'd like that other checkbox are deselecting
Could you help me ?
Thanks
Comment: @LondonDrugs_MediaServices Suggestion would definitely be the easiest solution. However, I think this is a very bad idea from a user experience point of view. Users expect these round buttons with bullets and these square buttons with ckeckmarks to behave a certain way. If you turn that around, you will confuse them.
Comment: @RIAstar - I agree, but that's essentially the question at hand, how to make my radio buttons look like checkboxes. (or how to make my checkboxes work like radio buttons).
Comment: Maybe you need to use a RadioButton / RadioButtonGroup instead of Checkboxes?
Comment: Why don't you just re-skin the radio button to look like a checkbox?
Comment: indeed re-skin radiobutton may be a solution, I try to do that
Comment: @Flex60460 is there any reasons why you would like to have a checkbox act as a radio button? I hope next time you will not want a button which can be used instead of scroll bar... :))
Answer: If there is a static amount of radio buttons you need, you could use Spark States.
<s:states>
    <s:State name="check1"/>
    <s:Stage name="check2"/>
</s:States>

<s:CheckBox selected="false" selected.check1="true" click="currentState='check1'"/>
<s:CheckBox selected="false" selected.check2="true" click="currentState='check2'"/>

When you click the first one, it triggers the "check1" state in which the first check box is selected and the other is unselected. Clicking the second one does the opposite. Obviously, this is not as flexible as some would hope. But if it's for an interface element (such as an options menu), it's perfect.
States are incredibly useful if you understand how and when to use them. This past weekend, I created an all-Flex slideshow using them and it is a great example of how powerful that simple little array can be.
EDIT: I just threw together a simple app to test this, and it doesn't look like it will work using click. I'm sure you could tinker with another event to get it to work, though. Sorry this didn't work.
Answer: I'd use RadioButtons, but if you really wanted to do it, I'd take LondonDrugs_MediaServices approach.
CheckBox and RadioButton both extend from ToggleButtonBase.
Create your own CheckBoxRadioButtonSkin. Copy the CheckBoxSkin to it and rename the hostComponent.
Then use this skin on your radioButton to make it appear to be checkbox.
Answer: I have had a requirement like this before and I used a Datagrid with Checkbox inside as itemRenderer.
I subclassed the Checkbox, overrode data getter so that each time it is clicked all the items of Datagrid are unselected, unchecked except for him. This method acquired some advantages:

Flexible to add number of options programmaticcally.
Display title of option group or not.
Enable to use scrollbar if there is a limit of space.

Hope the solution is what you are looking for.

flex checkbox group


complex numbers for quadratic equation

Question: Find the quadratic equation whose roots are $2+i$ and $3-i$.
$$\frac{-b\pm\sqrt{b^2-4ac}}{2a}$$
Comment: $(x-(2+i))(x-(3-i))$ will give you the equation
Answer: In general, if you want a polynomial $p(x)$ over $\mathbb{C}$ of degree $n$ with roots $a_1,...,a_n$ we have $p(x)=(x-a_1)\cdots(x-a_n)$ (where $a_i$ are not necessarily distinct - corresponding to roots of multiplicity). It is clear that each $a_i$ is in fact a root because $p(a_i)=(a_i-a_1)\cdots(a_i-a_i)\cdots(a_i-a_n)=0$.
Answer: If $a, b$ are roots of a quadratic equation, then the quadratic equation can be written as
$$(x-a)(x-b) = 0$$
This is intuitively true because substituting in either of the roots $a,b$ will cause LHS to yield $0$.
If you want a more rigorous proof, this result is known as the Weierstrass factorization theorem, which states that any entire function can be represented by a product involving its zeroes.
In your case, this is just
$$(x-(2+i))(x-(3-i)) = 0$$
You can expand it out if you want it in the form $ax^2 + bx + c = 0$.
A shortcut to the expansion would be to notice that $(x-a)(x-b) = x^2 - (a + b)x + ab$. The coefficient of $x$ is negative of the sum of the roots, while the term independent of $x$ is the product of the roots. This concept is further generalized to higher degree polynomials with Vieta's Formulas.
Comment: but how do you know (x-a)(x-b)=0?
Comment: @harry That is the definition of a root
Comment: Substitute in $a$ into LHS. Then it becomes $(a-a)(a-b) = 0\cdot(a-b) = 0$.
Comment: Thanks~ so root can be (x-a)(x-b)~
Comment: wait, but why (x+a) (x+b) = 0 ?
Comment: If you took $(x+a)(x+b) = 0$, then the roots would be $x=-a$ and $x=-b$ instead. This is because if you substitute (either of ) these two values in, you will observe that the LHS really resolves into $0$.
Comment: but it will become
x^2 - 5x + 7 + i = 0
Comment: Then that will be the quadratic equation you were looking for. :)
Comment: really? i thought the answer is
x^2 + (-5+i)x + 8 - i = 0
(but maybe the answer sheet is wrong)
Comment: You might want to try expanding it out again. Hold on, I'll improve my answer to show you a shortcut.
Comment: I believe the answer sheet is incorrect. WolframAlpha verifies : http://www.wolframalpha.com/input/?i=x%5E2+-+5x+%2B+7+%2B+i
Comment: Glad I could help!
Comment: http://www.wolframalpha.com/input/?i=x%5E2+%2B%28-5%2Bi%29x%2B8-i%3D0

erm i think the answer sheet is correct for some reason
Comment: There was a typo in your question - The second root should be $3-2i$
Comment: Oh Okie :D thank you, sorry for the trouble
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/13496/discussion-between-harry-and-yiyuan-lee)

complex numbers for quadratic equation


git repo in Dropbox, syncing on Linux and Windows, Whitespace issues

Question: I have a git repo in my Dropbox, that syncs between a Linux and a windows machine. I work on both machines on text files (.cpp on linux and win, .tex/.txt on win). So, my editors and programs both write CRLF (the win programs) and LF (the linux programs) files, all programs understand all variants on reading.
I would like to tell git to correct everything to LF (I like it that way best). On both platforms.
Alas with all my tries of core.autocrlf=true/false/input and core.eol=lf I get all kinds of messages. "Will convert from LF to CRLF", "all files have changed" and so on. Currently I have
core.eol=lf
core.autocrlf=input

and I am on my windows machine.
When tomorrow everything is synced to my Linux machine, what will I see?

Will there be LFs (as I currently have here)?
Will I see that all files have changed?

I hope I finally understood everything, but I am really not sure. input? Sounds strange...
Answer: It used to be that you had to have autocrlf set to true and that would do it. Currently, you should have it set to input. Then depending whether you are in linux or windows you set the eol setting differently.
To double check your settings a diff will show crlfs in the repository.
Also, edit the files with vim -b, this will show the line endings too.
Hope this helps.
Comment: Nope, doesn't work. I have `input` now set for 2 weeks (and thus now several Dropbox syncs later). Yesterday I committed everything on the Win machine (gits note was: "changing CRLF to LF"), and today on the Linux machine `git status` says everything (!) has changed. Or maybe thats ok, because it now has to change *everything* once to LF? hmmm...


My right click is being odd with Minecraft?

Question: My right click is not placing blocks or opening stuff. It is acting like I'm holding down right click instead, until I do a different action e.g. open inventory/attack. I have tried restarting Minecraft, my computer and using different clients (I have also reset my controls).
This is only on Minecraft Java.
Answer: That really does sound like a hardware issue, where your mouse lags to fire the 'mouseup' event on your right click.
Here is the test for you: https://www.onlinemictest.com/mouse-test/ You should see your click turn blue the moment you click, and then become paler the moment you release. My guess is you will see it stay dark blue even after release.
If you do: Well, not much to do with that. You 1- Manually do a repair of your mouse or 2- change your mouse.


Where clause in R while joining dataframes

Question: I am new to R programming. I have a task to join the dataframes using where condition filer. I have 2 data frames below I would like to join df2$B_col2 to df1 by col1 but only if df1$A_col2=1.
I used below code it gives the result but I know the code is efficient. If there is any way to drop the records while joining the tables itself, please let me know.

Df1      col1      A_col2
1          b          1
2          a          1
3          a          0
4          c          0
5          d          1

Df2      col1      B_col2
1          a          10
2          b          20
3          c          30
4          d          40
5          e          50

code
df3 <- left_join(df1,df2, by = "col1")
df4 <- df3[df3$df1col2 == 1,]

Output
 col1 df1col2 df2col2
1    b       1      20
2    a       1      10
5    d       1      40

Comment: `left_join(df1[df1$A_col2 == 1,], df2, by = "col1")`?
Comment: Hi Roland, Yes this is what exactly I am looking for. Many thanks!!
Answer: If you ware with base R, you can try merge + subset like below
> subset(merge(df1, df2, all.x = TRUE), A_col2 > 0)
  col1 A_col2 B_col2
1    a      1     10
3    b      1     20
5    d      1     40

or match + subset
> subset(
+   transform(
+     df1,
+     B_col2 = df2$B_col2[match(col1, df2$col1)]
+   ),
+   A_col2 > 0
+ )
  col1 A_col2 B_col2
1    b      1     20
2    a      1     10
5    d      1     40

A data.table option
> setDT(df2)[setDT(df1), on = .(col1)][A_col2 > 0]
   col1 B_col2 A_col2
1:    b     20      1
2:    a     10      1
3:    d     40      1


SSRS adding a footer row to a table - CSV output

Question: I have a simple table in SSRS which I am using to create a CSV report.
The output looks like:
a,b,c
1,2,3
4,5,6

where a,b,c are the column headers.
Now my client requires a footer row saying how many records are in the file.
However if I add a row to my table with the required fields in, the output becomes:
a,b,c,records
1,2,3,2
4,5,6,2

instead of:
a,b,c
1,2,3
4,5,6
records,2

Does anyone know how I can achieve the desired effect?
Answer: In SSRS 2005, the table control has, by default, three rows.  The top one is for a header, the bottom one is for footer, and the middle one is for data.  Looking at your example, it appears you dragged the records value into a new column in the middle row, and it automatically added a header for you.
Instead, drag it into the bottom row. You can type "records" into the leftmost column of the footer, and whatever data set field you have for the records count into the 2nd column.
In SSRS 2008, you have the Tablix control.  It defaults to a Header row and a Data row.  Right-click on the data row, and select Insert Row -> Outside Group - Below.  Then you have a footer row that you can add to the same way was in SSRS 2005.
Comment: That's what I did (Insert Row -> Outside Group - Below) - everything appears correctly in the report preview.
It's when exporting to CSV that it appears differently.
Answer: The effect you're trying to achieve is not possible but you can get rid of that column.
Select the row you use as Footer, actually the textbox associated and set the DataElementOutput for that textbox to NoOutput. That row will not be exported in CSV.
This applies to any textboxes in a report.
Answer: In SSRS 2008 , Click on the Report Tab on the top menu . Then select "Add Page Footer"


ASP.NET MVC 5 Set values for dropdownlist

Question: I want to make a DropDownList with a numeric rating from 1-5. I have a rating model and I want to apply these dropdown values to WaitTime, Attentive and Outcome.
Can I just set these values in the view and use the model? If so how would i go about doing this?
My Model Class:
     public class Ratings
    {
        //Rating Id (PK)
        public int Id { get; set; }

        public string UserId { get; set; }

                     //Medical Practice (FK)
                    public int MpId { get; set; }
                     public MP MP { get; set; }

        //User ratings (non-key values)

        [Required] //Adding Validation Rule
        public int WaitTime { get; set; }

        [Required] //Adding Validation Rule
        public int Attentive { get; set; }

        [Required] //Adding Validation Rule
        public int Outcome { get; set; }

    }

My View:

        @Html.LabelFor(model => model.WaitTime, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.WaitTime, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.WaitTime, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Attentive, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Attentive, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Attentive, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Outcome, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Outcome, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Outcome, "", new { @class = "text-danger" })

Comment: Add a `SelectList` property to your model and populate it with 5 `SelectListItem` objects, the use `@Html.DropDowListFor()` in the view
Answer: Use this instead of EditorFor for each field:
@Html.DropDownListFor(model => model.Outcome, new SelectList(Enumerable.Range(1, 5)))

Comment: Thanks @ranquild! This was simple and easy. worked like a charm
Comment: Or use the following syntax for Create/Edit views (does anybody know if it is possible to let it use the syntax from the validation?):
Answer: Here is the working fiddle - https://dotnetfiddle.net/daB2DI
In short, lets say your model is -
public class SampleViewModel
{
    [Required] //Adding Validation Rule
    public int WaitTime { get; set; }

    [Required] //Adding Validation Rule
    public int Attentive { get; set; }

    [Required] //Adding Validation Rule
    public int Outcome { get; set; }
}

And your controller actions are -
[HttpGet]
public ActionResult Index()
{
    return View(new SampleViewModel());
}

[HttpPost]
public JsonResult PostData(SampleViewModel model)
{
    return Json(model);
}

Your Get CSHTML should be -
@model HelloWorldMvcApp.SampleViewModel

@{
    ViewBag.Title = "GetData";
}

GetData

@{
    var items = new List<SelectListItem>();
    for (int i = 1; i < 6; i++)
    {
        var selectlistItem = new SelectListItem();
        var code = 0;
        selectlistItem.Text = (code + i).ToString();
        selectlistItem.Value = (code + i).ToString();
        items.Add(selectlistItem);
    }
}

@using (Html.BeginForm("PostData","Home"))
{
    @Html.AntiForgeryToken()

SampleViewModel

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.WaitTime, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(model => model.WaitTime, items, "--Select--", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.WaitTime, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Attentive, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(model => model.Attentive, items, "--Select--", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Attentive, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Outcome, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(model => model.Outcome, items, "--Select--", new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Outcome, "", new { @class = "text-danger" })

                <input type="submit" value="Create" class="btn btn-default" />

}

When you run the code, you should see page like below -

And when you select some values and click on create, you should get those values in PostData action.
Answer: try to adapt this to your project
in your controller:
    ViewBag.ParentID = new SelectList(departmentsQuery, "NewsMID", "Title", selectedDepartment);
  return View(model);

in your view put this
  @Html.DropDownList("ParentID")


Should "expand" arrows point towards the expanding content or away from it?

Question: When using the official Github for Mac GUI client, I've seen that there's an icon which is used to open a hidden menu. It uses arrows to indicate that it moves something, but those arrows are pointing opposite as they move the content, as shown in these images:

I've seen this some other times, can't remember where. Is this a new practice? Why could be the reason of using them that way?
Comment: Asking the reason someone else decided to do something isn't really a question anyone here can answer, as they (probably) didn't create the screen.  Can you think of a different way to get an answer that would help you with your design decisions?
Answer: This is just another example of the famous state-action ambiguity problem, which is discussed in length on this UX.SE question.
The designer of the interface in question has chosen to show the state, rather than the action. Like you, I find it a bit awkward and unintuitive, but theory wise - there's nothing wrong with it, it can be either or, and neither will be conclusive.
Perhaps what's more disturbing is that in this specific case, the designer could have simply use a label 'Show merge view' and 'Hide merge view' and save us all having to cognate the semantics.
Comment: I agree with Izhaki and I would add that the continuing presence of the phrase "Merge View" might cause somebody to believe that something is yet to be explored when it already has been explored. Ideally, GUIs should be crystal clear to the user, creating very little possibility of confusion.


how can send multiple value by checkbox

Question: i have write code by ajax to sent name and roles by ajax, the name send success, but checkbox not send when choose more than 2 roles.
ajax code
   var HttPRequest = false;

   function doCallAjax(Mode,Page,ID) {
      HttPRequest = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         HttPRequest = new XMLHttpRequest();
         if (HttPRequest.overrideMimeType) {
            HttPRequest.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }

      if (!HttPRequest) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }

      var url = 'AjaxRolesPermRecord.php';
      var pmeters = "troles_Name=" + encodeURI( document.getElementById("roles_Name").value) +
                    "&tper=" + encodeURI( document.getElementById("per").value) +
                    '&myPage='+Page +
                    "&tID=" + ID +
                    "&tMode=" + Mode;

        HttPRequest.open('POST',url,true);

        HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        HttPRequest.setRequestHeader("Content-length", pmeters.length);
        HttPRequest.setRequestHeader("Connection", "close");
        HttPRequest.send(pmeters);

        HttPRequest.onreadystatechange = function()
        {

             if(HttPRequest.readyState == 3)  // Loading Request
              {
               document.getElementById("mySpan").innerHTML = "load ...";
              }

             if(HttPRequest.readyState == 4) // Return Request
              {
               document.getElementById("mySpan").innerHTML = HttPRequest.responseText;
              }

        }

   }

and i get it on other page like this
foreach($selected as $key=>$val)
{
    $SqlInsertIntotable = mysql_query("INSERT INTO permissions_roles (id,permission_id,role_id)
                                       value ('','".$val."','".$RoleID."')");
}

the problem is
Invalid argument supplied for foreach()

Comment: $selected is missing or empty..can't find it anywhere else in your code?
Comment: @Oli i get it on php page like this `$selected = $_POST["tper"]; `
Comment: add an alert(pmeters) after the 'var pmeters' and check if all data is filled in
Comment: its like this `troles_Name=admin&tper=1&myPage=1&tID=&tMode=ADD` but tper we must take more than one value
Comment: on my code here `"&tper=" + encodeURI( document.getElementById("per").value) +` we must get more than one value how can do that
Answer: Are the checkboxs defined like an array?
For example:
 <input type="checkbox" name="selected[]">

Comment: how can i defined it by array on my code and get it on php page
Comment: ` `
Comment:
Comment: i will defined ` ` and get same problem
Comment: If you do it without ajax, but with a classic form, it works?
Comment: You can get only the selected checkboxes and sent it one for param to the server
Answer: Pass all checkboxes values as an array in Javascript
This deals with your problem of selecting values and passing them to 'tper'

how can send multiple value by checkbox


Jquery RegEx Validation

Question: I am wanting to check if an input field has the attribute "pattern" and if so, preform a regex check aganst said pattern.I know this is already done by HTML5, but I am wanting to handle the event myself. I am receiving this error: Uncaught TypeError: Object a-zA-Z has no method 'test'
 ///Check Perform Reg///////////////////////////////////////////////////////
         if ($(this).attr("pattern")) {
             var reg = $(this).attr("pattern");
             var currentValue = $(this).val();

             if (reg.test(currentValue)) {
                 $(this).after($error.clone().text("Invalid Input.Try Again."));
                 $(".error:hidden").fadeIn("slow");
                 hasError = true;
                 return false;
             }

             }
        ///////////////////////////////////////////////////////////////////////////

Still no luck,
also here is my html:

    <input class="formInput" name="First Name" pattern="^[A-Za-z_-][A-Za-z0-9_-]*$" type="text"  id="frmFirst" min="2" maxlength="30"  required="required"/>
    First Name

Comment: This is not a good solution set the pattern in the HTML part because anyone can bypass that without any check. So, you should to check if the pattern match directly in the js.
Answer: Normally regular expression with javascript / jquery handle like
var reg = /pattern/;
if (reg.test($(this).val())) {
    // perform some task
}

Comment: It appears to be the same thing my code already does. except the pattern is passed from a variabel
Comment: yea it look like same, for regular expression you need to enclose pattern within /[pattern]/ e.g /test/ for matching with value test.
Answer: As already mentioned by others you need to use an object instead of the string returned by the jQuery attr() method. You can see the difference between the two here.
Will return "string":
var reg = $(this).attr("pattern");
console.log(typeof reg)

Will return with "object":
var reg = new RegExp($(this).attr("pattern"));
console.log(typeof reg);

So if you replace:
var reg = $(this).attr("pattern");

With:
var reg = new RegExp($(this).attr("pattern"));

The Uncaught TypeError: Object a-zA-Z has no method 'test' error will disappear
...but your validation still won't work very well.  Your conditional logic says if the regex test returns TRUE then handle an error:
if (reg.test(currentValue)) {
    //error handling
}

Instead it should handle an error if the test returns FALSE:
if (!reg.test(currentValue)) {
    //error handling
}

This should work for you.
Answer: You can try something like this. It will alert "var2 failed".
var var1 = "1";
var var2 = "A";
var myRegEx = new RegExp('[0-9]+'); //make sure the var is a number

if (var1 != myRegEx.exec(var1)) {
    alert("var1 failed");
}

if (var2 != myRegEx.exec(var2)) {
    alert("var2 failed");
}

Answer: A string is not a RegExp object.
You could use something like:
var reg = new RegExp($(this).attr("pattern"));

Answer: Below is the proper way to validate a text-box based on a regular Expression using Jquery in MVC. Please note that this expression is made to validate multi email addresses in one string:
      var emailReg = new RegExp(/^([A-Z0-9.%+-]+@@[A-Z0-9.-]+.[A-Z]{2,6})*([,;][\s]*([A-Z0-9.%+-]+@@[A-Z0-9.-]+.[A-Z]{2,6}))*$/i);
      var emailText = $('#email').val();

      if (!emailReg.test(emailText)) {
          alert('Wrong Email Address\Addresses format! Please reEnter correct format');
            return false;
        }
    }

Comment: Jquery is the same anywhere.

You just need to apply it to a text-box or input field where you like to validate against this jquery expression.

Jquery RegEx Validation


MacOS Can't install headonly on homebrew (brew tap homebrew/headonly)

Question: This is what the terminal says after I put in this command brew tap homebrew/headonly
haven't tried anything to solve it yet, any suggestions please?
==> Tapping homebrew/headonly Cloning into '/usr/local/Homebrew/Library/Taps/homebrew/homebrew-headonly'...
remote: Repository not found. fatal: repository 'https://github.com/Homebrew/homebrew-headonly/' not found Error:
Failure while executing; `git clone https://github.com/Homebrew/homebrew-headonly /usr/local/Homebrew/Library/Taps/homebrew/homebrew-headonly --depth=1`
exited with 128

.
Comment: Why do you want to tap homebrew/headonly for?
Answer: It's normal: homebrew/headonly has been deprecated a long time ago, the repository doesn't exist anymore. It was hard to maintain and so it didn't really make sense to keep having it since anyone can create their own tap.


Can I use DOCSIS 3.0 to connect to my LAN over coax?

Question: Let me describe the bizarre situation here in simple terms.

I need to get an Ethernet connection from the network closet to the garage TV.
My main router is an OpenWRT Linksys wrt32x which has 5 gigabit Ethernet ports (1 WAN, 4 LAN; although this can be reconfigured for 2 WANs if we want for whatever reason), a USB 2.0 port, and a USB 3.0/eSATA port, both of which I can do whatever USB shenanigans I want (I own a rare USB-A male to USB-A male data link cable, and I've heard of running PPP over serial? if that's at all relevant).
There is a single data line (CATV over Coax) that runs directly from the closet to the garage. This coax line is marked "DIRECTV RJ-6 75 Ohm High-Performance 3.0 GHz," which is kind of weird because we've never used DIRECTV on this line notwithstanding.
The CATV signal isn't that important so replacing it with a data-only line is A-OK (but my ISP runs both on the same wire so I assume it's possible to do that myself as well).
I have a DOCSIS 3.0 cable modem/router combo, the Cisco DPC3825, that as of now is being used just as a 4-port gigabit Ethernet switch. It has 4 gigabit Ethernet, 1 coax, and 1 USB port. This one doesn't have OpenWRT support unfortunately.
The most obvious solution, wireless, is not usable because it's what we already have-- it hasn't been working at all. Given how terrible the speeds on even 802.11ac with the device 15 yards away have been I think there's some sort of interference in the garage due to some electrical equipment, but I'm no expert. It could also be that the access point is shitty, but regardless I prefer static wired setups to wireless ones if possible.
I want to run a DOCSIS signal on this coax wire, over which the LAN (Link layer Ethernet/PPP/etc bridge OR network layer IP tunnel are both good) connection will run, that can be modem'd by the DPC3825. Essentially I want to be both the "customer" (garage) and the "ISP" (closet) at the same time.
The topology of the link I'd like to achieve is this:

<code>|_______Accessible_________|_Inaccessible_|_____________________________Accessible____________________________|
|                          |              |                                                                   |
Router <--Ethernet--> [???] <--Coaxial-Line--> DOCSIS 3.1 Modem <--Ethernet--> Switch <--Ethernet--> Garage TV
</code>
Basically all I'm looking for is the <code>[???]</code> listed above. I've spent a while trying to find documentation on using DOCSIS for a LAN but nothing's turned up. It's not typical to run what's typically used an ISP's protocol WAN-LAN connection as a LAN-LAN connection, but I've actually done this kind of thing before, only with DSL/PPPoE instead, and it worked despite being super weird (all I did then was use OpenWRT as a PPPoE server and attached an old DSL modem). I want to take advantage of the modem I already own-- yes, MoCA/G.hn could solve this problem easy, but devices for them're quite expensive. Is it practical to emulate the PPPoATMoDOCSIS that my ISP uses?
I've no preference as to whether it's a solution involving layer 2 (Ethernet/PPP/etc) over DOCSIS or layer 3 (IP) over DOCSIS: just as long as I can get to my local subnet from both ends, it'll work; and since I've not been able to find anything about a sort of system like this, I'll try to try out what I can just for future reference if nothing else.
Comment: Two issues here:  First of all, this is likely off-topic for Home Improvement.  Second of all, DOCSIS is not designed for your intended use and you don't have the correct equipment to implement what you need to make it work.  Your cable modem is a DOCSIS client box only. There is no server side and that means you don't have a working DOCSIS system.  See this link: https://www.thegeekstuff.com/2012/05/docsis-introduction/
Comment: It's also really difficult for me to figure out what root issue you're trying to solve. Perhaps if you simplified your question, leaving out everything superfluous and describe the situation it would help.
Comment: All right, what I'm trying to say is "I want to get my garage Apple TV connected, and the only wire to it is coax from the network. Can I run a connection over that?" I've tried using wireless but for whatever reason what's been really terrible at holding a connection, so this (and powerline Ethernet I guess) were what I came up with.
Comment: Bottom line is that your RG-6 is 75 Ohm coax which is NOT what is used for the old Ethernet Coax solution which uses 50 Ohm coax.  For a short run you could possibly get away with it but I'd expect issues.  What you need are TWO RJ-45 (i.e. 10Base-T) to 10Base-2 transceivers that would convert from your wired LAN to the coax and then from the coax to wired LAN.  Then you could plug in your Apple TV or add a WiFi AP if needed there.  You'll be spending a lot of money for all this and you're probably better off just running some CAT6 to the garage.
Comment: Ahh, so it's literally a different cable. I'll stick to using coax for basic cable since running cat5e or even cat6 to the garage wouldn't be very expensive given my circumstances; thanks for the information.
Comment: This question does not appear to be about home improvement within the scope defined in the help center.
Answer: An alternative approach is to use Multimedia over Coax (MoCA) which is a popular solution in the United States however you can utilize this approach in any country.
At a minimum you need two MoCA devices that have a coax and ethernet input. This will provide a network over a single line of coax. If your coax goes into splitter, then the MoCA devices can talk to each other and route network traffic as if the splitter was acting as a network switch. So using MoCA you can connect multiple devices.
MoCA will also allow TV signals to co-exist over the coax, however, you must make sure you put a filter on the coax leading into your house from an aerial otherwise your MoCA signal will leak and interfere with the reception of your neighbours.
The latest version of MoCA can reach speeds of 2.5 gigabits/second full duplex.
Answer: You need an ethernet-over-coax device for RG-6 cable.
A slightly surprising source of these is CCTV suppliers, as there is a lot of analogue CCTV wiring out there, and people want to upgrade to higher resolution IP CCTV, without running new cable. Therefore, converters to run Ethernet over Coax are available.
Example

VHW-HW    HIGHWIRE Ethernet over coax converter (2 required per link)
  100BaseT up to 350m (1150ft) full-rate over RG-6

https://www.veracityglobal.com/products/ethernet-over-coax-devices/highwire.aspx
One supplier
http://www.eaccu-tech.com/by-vendor/vhw-hw-veracity/
There is also a possible hack solution - connect wifi antennae connectors directly to the co-ax cable.

There are some problems with this plan. WiFi is 50 Ohms, TV coax cable
  is 75 Ohms. Only one MIMO channel will be available meaning the
  maximum theoretical bandwidth will be 433 Mbps. WiFi is also at much
  higher frequencies than what coax is designed for.
With two WiFi antenna to coax adapters, [Tobias] simply connected the
  coax directly to a router set up to bridge Ethernet over WiFi. The
  entire thing worked, although testing showed it was only getting about
  60 Mbps of throughput.

https://hackaday.com/2018/10/19/wired-wireless-over-coax/
Comment: That "use the coax for a wifi antenna" hack is pure win.  a 10Base2-10BaseT adapter.
Comment: Sounds all right; I was just curious if there was a different potential solution that might be less expensive lol. I'll have to try out the wifi antenna straight to coax thing though, worth a shot.


How to pass jwt token from one route to another?

Question: I am new to coding. I have set up a login function within Flask using flask-JWT. Thus far, I am able to login (on "/login") and a token is generated using jwt.
However,  I have other routes which are also protected using a wrapper (@token_required). I would like to make it such that once users have logged in, the token will be passed to the other protected pages which they will then be able to access.
These are my codes:
wrapper to protect page
def token_required(f):                      #wrapper for token auth
    @wraps(f)
    def decorated(*args, **kwargs):
        token = request.args.get('token')

        if 'x-access-token' in request.headers:
            token = request.headers['x-access-token']

        if not token:
            return jsonify({'message': 'Token is missing!'}), 401

        try:
            data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
            current_u = User.query.filter_by(username=data['user']).first()
            #identify user, otherwise, return error

        except:
            return jsonify({'message': 'Token is invalid!'}), 401

        return f(current_u, *args, **kwargs)   #previously return f(*args, **kwargs)

    return decorated

login route
@app.route('/login', methods=['GET', 'POST'])        #login route
def login():
    auth = request.authorization

    if not auth or not auth.username or not auth.password:
        return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm = "Login Required!"'})

    user = User.query.filter_by(username=auth.username).first()

    if not user:
            return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm = "Login Required!"'})

    if user.check_password(auth.password):
        token = jwt.encode({'user': auth.username, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=2)}, app.config['SECRET_KEY'])

        return jsonify({'message': 'hello ' + user.username}, {'token': token})

    return make_response('Could not verify', 401, {'WWW-Authenticate': 'Basic realm = "Login Required!"'})

protected route using wrapper
@app.route('/protected')           #protected routes
@token_required
def protected(current_u):
    return jsonify({'message' : 'This is only for people with valid tokens'})

I am just stuck at this point in time as I can't quite find tutorials specifically for this / maybe its also an issue with not knowing what to search for. Could anyone help me out please?
Answer: on further thougt I dont think using session is necessary as the authentication is encoded in the jwt token. I think you bug is in the decorator
try:
        data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=["HS256"])
    except:
        return jsonify({'message': 'Token is invalid!'}), 401

This is except clause is to broad, what exceptions need to be handled here?
Comment: thanks for this! i was hoping if you may provide me a little more help.. where should i include these codes - within the wrapper? :) i tried it in the routes.py as a standalone function, within the wrapper, and also within the routes but none seemed to work :/
Comment: thanks! i missed out a line, which was to identify the user logged in as current_user, before throwing out the exception that all unidentified users will get the "token is invalid!" message. i have added that before the "except:" line. i also added that as an argument in the wrapper, as well as in the routes (e.g. def protected(current_u):). however, i'm still not getting the tokens passed automatically :/ what else could go wrong?
Comment: ^ to clarify, i meant to say i added it in the code in my main post! :)
Comment: are you passing the 'x-access-token' header in your client code?
Comment: could you explain what that entails please? the protected page simply returns a json message for now. (i was trying to set up something similar to this tutorial: https://www.youtube.com/watch?v=WxGBoY5iNXY&t=1335s).
Comment: do we have to use API testing tools like Postman app (as with the tutorial) before we can pass the 'x-access-token' header, or are we able to do that in the script?
Comment: you need to pass the x-access-token header, you can use tools like postman for this or when you want to stay in python there is also the requests library


Are there 3-way dimmer switches that do not need travelers between them?

Question: I put a few three-way switches in a house I did years ago that both dimmed but remember it requiring travelers.    Wondering if this has come along where we can retrofit existing 3-way switches (not dimmable)?
Comment: take look in to smart switches
Comment: Most in-wall smart switches I've seen that are designed as 2-way dimmers seem to require a traveller, though they may use it for signalling rather than as an alternate power path. The simpler but less responsive solution is to link the two switches/dimmers through software, with one actually being wired to the light and the other just a remote control sender
Comment: @keshlam - yea it seems the traveller is used to communicate the lighting level set on the other switch.     I set up a bunch of these like 10 years ago.   Figured with smart tech that they could "radio" this now without using some remote smart software.    I have a kitchen where I moved an island which had two lights with 2 2-way switches... both lights being moved and would really like them on dimmers.    I am going to be very surprised if no one figured out how to get two switches within range talking to each other in the past 10 years.
Comment: It can certainly be done. But companies don't seem interested in selling a hubless solution; they want you to buy into their ecosystem so you'll order the next device from them too
Comment: I don't think "2-way" is standard terminology for these multi-station switches.
Comment: @kreemoweet it is in Europe.  OP is referring to what Americans call "3-way".
Comment: @kreemoweet - sorry I am in europe half the time...   and I call it a culture-slip and I do it all the time... I know the term in the US, meant to use it but brain must have been thinking about something in europe at the time!
Answer: I would look at something like Lutron Caseta that has wireless remote control switches. You can use it with a hub, but you can also pair remotes to switches directly, without a hub.
In this setup, you would install the "real" switch that's actually wired into the circuit at one of the locations. At the other location, install the remote control switch (which isn't hooked up to any wires) and just put a wirenut on the existing wiring to maintain continuity. I've done this several places throughout my house.
Comment: having remotes for light switches seem excessive but I will look into it.


I get ORA-00905: missing keyword

Question: I write this query and when I run it I get

ORA-00905: missing keyword

I check with many online SQL query checker and all of them answered it is correct can any body help me what's the problem
select *
from T_TimelineItem ti
where ti.C_HIDE = 0
  and ti.F_RELATED_BUSINESS = 4335
  and exists(select *
             from T_Business b
                      inner join MM_BIZ_GUILDS g on b.C_ID = g.ID1
             where b.C_ID = ti.F_RELATED_BUSINESS
               and g.ID2 in (49))
  and (CASE ti.C_TYPE
           WHEN 1 then ti.C_ID in (select po.C_TIMELINEID
                                   from T_PRODUCT pr
                                            inner join T_POST po on po.C_ID = pr.F_POST
                                   where po.F_BUSINESS = ti.F_RELATED_BUSINESS
                                     and pr.F_GUILD in (49))
           WHEN 8 THEN ti.C_ID in (select po.C_TIMELINEID
                                   from T_COMPETITION com
                                            inner join T_POST po on po.C_ID = com.F_POST
                                   where po.F_BUSINESS = ti.F_RELATED_BUSINESS
                                     and com.F_GUILD in (49)) END);

Comment: What line does the error mention?
Answer: Don't use case in where clauses
and (ti.C_TYPE = 1 and ti.C_ID in (select po.C_TIMELINEID
                               from T_PRODUCT pr
                                        inner join T_POST po on po.C_ID = pr.F_POST
                               where po.F_BUSINESS = ti.F_RELATED_BUSINESS
                                 and pr.F_GUILD in (49)))

or (ti.C_TYPE = 8 and ti.C_ID in (select po.C_TIMELINEID
                               from T_COMPETITION com
                                        inner join T_POST po on po.C_ID = com.F_POST
                               where po.F_BUSINESS = ti.F_RELATED_BUSINESS
                                 and com.F_GUILD in (49)) END))

Comment: thanks it worked. I didn't know we cant use case in where clause.
Comment: You can use `case` sometimes but it is always better to use simple boolean logic instead.
Answer: I have removed multiple in cause you can use equal easily for single value comparison and you don't need to select all the column inside exists
select *
from T_TimelineItem ti
where ti.C_HIDE = 0
  and ti.F_RELATED_BUSINESS = 4335
  and exists(select 1
             from T_Business b
                      inner join MM_BIZ_GUILDS g on b.C_ID = g.ID1
             where b.C_ID = ti.F_RELATED_BUSINESS
               and g.ID2 = 49
             )
  and (ti.C_TYPE=1
           and ti.C_ID in (select po.C_TIMELINEID
                                   from T_PRODUCT pr
                                            inner join T_POST po
                                  on po.C_ID = pr.F_POST
                                   where po.F_BUSINESS = ti.F_RELATED_BUSINESS
                                     and pr.F_GUILD =49
                             )
           or ( ti.C_TYPE=8 and
                            ti.C_ID in (select po.C_TIMELINEID
                            from T_COMPETITION com
                            inner join T_POST po on po.C_ID = com.F_POST
                            where po.F_BUSINESS = ti.F_RELATED_BUSINESS
                            and com.F_GUILD =49
                      )

Comment: I wanted to check some hql cause I  use "in (49)". list of ids will be write instead of 49

I get ORA-00905: missing keyword


Use arrow keys when switching applications with super + tab

Question: When you switch Applications with Super + tab you can cycle forwards by holding down super and pressing tab. And you can cycle backwards by holding super + shift and pressing tab.
But is there a way to configure it so that you can use the arrow keys (left and right) while holding super to cycle backwards and forwards through the applications?
Mac OS has this feature and I can't stop doing it! It's quite quite handy :)
Answer: You can add Super+Right and Super+Left as keybindings to switch through the Alt+Tab task switcher with following commands:
gsettings set org.gnome.desktop.wm.keybindings switch-applications "['<Super>Tab', '<Alt>Tab', '<Super>Right']"
gsettings set org.gnome.desktop.wm.keybindings switch-applications-backward "['<Shift><Super>Tab', '<Shift><Alt>Tab', '<Super>Left']"

These keybindings are by default assigned to tiling the windows left and right, so you may want to change these keybindings, or at least disable them:
gsettings set org.gnome.mutter.keybindings toggle-tiled-left "['']"
gsettings set org.gnome.mutter.keybindings toggle-tiled-right "['']"

To reset to defaults, replace "set" by "reset" and leave the final argument off in the above commands.
Answer: I don't really have a way to perform this exactly as you describe but if you place separate applications on different desktops, you can use super+page up and super+page down to change between desktops, and effectively between apps.


What do the angle bracketed symbols at the end of a class name mean?

Question: For example look at this:
ArrayList<String> arrayList = new ArrayList<String>();

Could I use the <>s with a custom class? How do I use them?
Comment: ArrayList s = new ArrayList() ?
Comment: you can use like this `ArrayList s= new ArrayList();` and add object of any class you want
Comment: Do you understand my question? Like this: MyClass class;
Comment: Declare your class as: `class MyClass {}`
Answer: You can put any class in the <> as long as it fulfills the generic class's constraints:
ArrayList<MyClass> arrayList = new ArrayList<MyClass>();

You can define your own class to use the <> simply:
class MyGenericClass<E> {
    E e;
    MyGenericClass(E e) { this.e = e; }

    E getE() { return e; }
    void setE(E e) { this.e = e; }
}

Now you can make your own:
MyGenericClass<String> stuff = new MyGenericClass<String>("Foo");
System.out.println(stuff.getE());

Answer: The tutorial Generics gives you all the information needed. The section Generic types shows how to declare and implement custom classes.
class MyClass<T> {
    ...
}


How to reference this id in py file

Question: How can I reference id: output in the main.py file to print a message on the label ?
I tried
self.root.ids.screen_manager.get_screen("Caesar_Screen").ids.output.text =""

but I always get this error
C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\Scripts\python.exe

C:\Users\Samoo\PycharmProjects\CryptoMD2\main.py
[INFO   ] [Logger      ] Record log in C:\Users\Samoo\.kivy\logs\kivy_21-05-03_57.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.gstreamer" 0.3.2
[INFO   ] [deps        ] Successfully imported "kivy_deps.angle" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.3.0
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.3.1
[INFO   ] [Kivy        ] v2.0.0
[INFO   ] [Kivy        ] Installed at "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)]
[INFO   ] [Python      ] Interpreter at "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\Scripts\python.exe"
[INFO   ] [KivyMD      ] v0.104.1
[INFO   ] [Factory     ] 186 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil (img_ffpyplayer ignored)
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] GLEW initialization succeeded
[INFO   ] [GL          ] Backend used <glew>
[INFO   ] [GL          ] OpenGL version
[INFO   ] [GL          ] OpenGL vendor
[INFO   ] [GL          ] OpenGL renderer
[INFO   ] [GL          ] OpenGL parsed version: 4, 3
[INFO   ] [GL          ] Shading version
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <32>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [GL          ] NPOT texture support is available
[INFO   ] [Base        ] Start application main loop
B
[INFO   ] [Base        ] Leaving application in progress...
 Traceback (most recent call last):
   File "kivy\properties.pyx", line 861, in kivy.properties.ObservableDict.__getattr__
 KeyError: 'screen_manager'

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\main.py", line 46, in <module>
     CryptoMD().run()
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\app.py", line 950, in run
     runTouchApp()
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\base.py", line 582, in runTouchApp
     EventLoop.mainloop()
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\base.py", line 347, in mainloop
     self.idle()
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\base.py", line 391, in idle
     self.dispatch_input()
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\base.py", line 342, in dispatch_input
     post_dispatch_input(*pop(0))
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\base.py", line 248, in post_dispatch_input
     listener.dispatch('on_motion', etype, me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\core\window\__init__.py", line 1412, in on_motion
     self.dispatch('on_touch_down', me)
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\core\window\__init__.py", line 1428, in on_touch_down
     if w.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\uix\screenmanager.py", line 1198, in on_touch_down
     return super(ScreenManager, self).on_touch_down(touch)
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\uix\relativelayout.py", line 297, in on_touch_down
     ret = super(RelativeLayout, self).on_touch_down(touch)
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\uix\behaviors\button.py", line 138, in on_touch_down
     if super(ButtonBehavior, self).on_touch_down(touch):
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\uix\widget.py", line 545, in on_touch_down
     if child.dispatch('on_touch_down', touch):
   File "kivy\_event.pyx", line 709, in kivy._event.EventDispatcher.dispatch
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivymd\uix\behaviors\ripplebehavior.py", line 231, in on_touch_down
     return super().on_touch_down(touch)
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivymd\uix\button.py", line 961, in on_touch_down
     return super().on_touch_down(touch)
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
     self.dispatch('on_press')
   File "kivy\_event.pyx", line 705, in kivy._event.EventDispatcher.dispatch
   File "kivy\_event.pyx", line 1248, in kivy._event.EventObservers.dispatch
   File "kivy\_event.pyx", line 1132, in kivy._event.EventObservers._dispatch
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\venv\lib\site-packages\kivy\lang\builder.py", line 57, in custom_callback
     exec(__kvlang__.co_value, idmap)
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\cryptomd.kv", line 100, in <module>
     app.out_encrypt(Text.text, key.text) if key.text != "" else None
   File "C:\Users\Samoo\PycharmProjects\CryptoMD2\main.py", line 34, in out_encrypt
     self.root.ids.screen_manager.get_screen("Caesar_Screen").ids.output.text = out_encrypted
   File "kivy\properties.pyx", line 864, in kivy.properties.ObservableDict.__getattr__
 AttributeError: 'super' object has no attribute '__getattr__'

in the terminal where it says [INFO  ]..
the letter B before Leaving the application is the message I want to display on the Label. the the error message starts with
 KeyError: 'screen_manager'
 During handling of the above exception, another exception occurred:

.py
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
# from funcs import Encrypt
import string

alphabet = string.ascii_lowercase

class Caesar_Screen(Screen):
    pass

class Aes_Screen(Screen):
    pass

sm = ScreenManager()
sm.add_widget(Caesar_Screen(name='Caesar'))
sm.add_widget(Aes_Screen(name='Aes'))

class CryptoMD(MDApp):

    def __init__(self, **kwargs):
        self.Encrypt = Encrypt()
        self.title = 'Crypto'
        self.theme_cls.primary_palette = "Purple"
        super().__init__(**kwargs)

    def out_encrypt(self, Text, key):
        obj = Encrypt()
        Text = Text.lower()
        key = key
        Key = int(key)
        out_encrypted = obj.encrypt(Text, key)
        self.root.ids.screen_manager.get_screen("Caesar_Screen").ids.output.text = out_encrypted

    def out_decrypt(self, Text, key):
        obj = Encrypt()
        Text = Text.lower()
        key = key
        Key = int(key)
        out_decrypted = obj.decrypt(Text, key)
        self.root.ids.screen_manager.get_screen("Caesar_Screen").ids.output.text = out_encrypted

class Encrypt():
    def encrypt(self, Text, key):
        Text = Text.lower()
        key = key
        Key = int(key)
        encrypted_message = ""

        for c in Text:
            if c in alphabet:
                position = alphabet.find(c)
                new_position = (position + Key) % 26
                new_character = alphabet[new_position]
                encrypted_message += new_character
            else:
                encrypted_message += c
        message = str(encrypted_message)
        print(message.upper())
        return message.upper()

    def decrypt(self, Text, key):
        Text = Text.lower()
        key = key
        Key = int(key)
        encrypted_message = ""

        for c in Text:
            if c in alphabet:
                position = alphabet.find(c)
                new_position = (position - Key) % 26
                new_character = alphabet[new_position]
                encrypted_message += new_character
            else:
                encrypted_message += c
        message = str(encrypted_message)
        print(message.upper())
        return message.upper()

if __name__ == '__main__':
    CryptoMD().run()

#:kivy 1.11.1
#:import rgba kivy.utils.rgba

ScreenManager:
    id: screen_manager

    Caesar_Screen:
    Aes_Screen:

<Caesar_Screen>:
    name: "Caesar_Screen"

    BoxLayout:
        orientation: 'vertical'

        BoxLayout:
            id: bx
            orientation: 'vertical'
            size_hint_y: 0.2
            padding: [20, 10, 10, 20]
            canvas.before:
                Color:
                    rgba: rgba('#8A2BE2')
                RoundedRectangle:
                    pos: self.pos
                    size: self.size
                    radius: [0, 0, 90, 90]

        BoxLayout:
            MDCard:
                id: card
                orientation: 'vertical'
                size_hint: [0.35, 1]
                pos_hint: {'center_x': 0.5, 'center_y': 0.65}
                padding: [30, 10, 25, 10]
                spacing: 7

                BoxLayout:
                    orientation: 'horizontal'
                    MDLabel:
                        text: "[color=000000] Caesar Cipher [/color]"
                        text_size: self.size
                        font_size: 28
                        bold: True
                        markup: True
                        halign: "left"
                        valign: "top"

                    MDFillRoundFlatButton:
                        text: 'AES'
                        size: self.size
                        pos_hint: {'center_x': 0.9, 'center_y': 0.77}
                        on_press: root.manager.current = 'Aes_Screen'

                MDLabel:
                    id: output
                    text: "[color=000000] Output [/color]"
                    text_size: self.size
                    font_size: 27
                    bold: False
                    markup: True
                    halign: "center"
                    valign: "top"

                BoxLayout:
                    padding: [0, 0, 50, 0]
                    orientation: 'vertical'

                    MDTextField:
                        id: Text
                        text: "a"
                        auto_indent: True
                        allow_copy: True
                        multiline: False
                        helper_text: "Enter Text..."
                        helper_text_mode: "persistent"
                        max_text_length: 100
                        required: True
                        allow_copy: True

                    MDTextField:
                        id: key
                        text: "1"
                        input_filter: "int"
                        helper_text: "Enter Key..."
                        helper_text_mode: "persistent"
                        required: True
                        allow_copy: True
                BoxLayout:
                    padding: [0, 0, 0, 0]
                    spacing: 3
                    orientation: 'vertical'

                    MDRoundFlatButton:
                        id: encrypt_bt
                        text: "Encrypt"
                        size: self.size
                        pos_hint: {'center_x': 0.5}
                        on_press:
                            app.out_encrypt(Text.text, key.text) if key.text != "" else None

                    MDRoundFlatButton:
                        id: decrypt_bt
                        text: "Decrypt"
                        size: self.size
                        pos_hint: {'center_x': 0.5}
                        on_press:
                            app.out_decrypt(Text.text, key.text) if key.text != "" else None

        BoxLayout:
            orientation: 'horizontal'
            padding: [30, 10, 30, 20]
            spacing: 20
            size_hint_y: 0.25
            pos: self.pos

            Widget:
                canvas.before:
                    Color:
                        rgba: rgba('#bfff00')
                    Ellipse:
                        pos: self.pos
                        size: self.size
            Widget:
                canvas.before:
                    Color:
                        rgba: rgba('#8A2BE2')
                    Ellipse:
                        pos: self.pos
                        size: self.size
            Widget:

                canvas.before:
                    Color:
                        rgba: rgba('#00ffff')
                    Ellipse:
                        pos: self.pos
                        size: self.size

<Aes_Screen>:
    name: "Aes_Screen"
    BoxLayout:
        orientation: 'vertical'

Comment: always put full error message (starting at word "Traceback") in question (not comment) as text (not screenshot, not link to external portal). There are other useful information.
Comment: works for me: `self.root.get_screen("Caesar_Screen").ids.output.text` without `.ids.screen_manager`
Comment: BTW: code works also without `sm = ScreenManager()` and `sm.add_widget(...)` because it creates second screen manager which is never used. And if I use `sm.get_screen("Caesar_Screen").ids` then I get empty `{}`
Comment: What class contains the line: `self.root.ids.screen_manager.get_screen("Caesar_Screen").ids.output.text = out_encrypted`?
Comment: show more code. In which place do you run it? As I remeber Kivy classse may load `kv` after running `__init___` so code in `__init__` may not work - and it may need to use scheduler to run code with small delay.
Comment: @JohnAnderson this one `class CryptoMD(MDApp):`
Comment: @furas I use Pycharm on windows 10 , full code is now included, can u check again please.
Comment: @furas uhh now I see ! Thanks for the clarification
Answer: Frankly, sometimes I don't understand why ids works or not.
In your code works
 self.root.get_screen("Caesar_Screen").ids.output.text

without .ids.screen_manager

BTW:
You don't need sm = ScreenManager() and sm.add_widget(...) because it creates second screen manager which is never used. And if I use sm.get_screen("Caesar_Screen").ids then I gives empty {}
If you created self.Encrypt = Encrypt() then you don't have to create obj = Encrypt() - you can use self.Encrypt.encrypt(Text, key) instead of obj.encrypt(Text, key)
There is other suggestion: use lower_case_names for variables (ie. self.encrypt isntead of self.Encrypt or text instead of Text) and CamelCaseNames only for classes because it helps to recognize classes in code. Some IDEs may even use special color for CamelCaseNames to even simpler recognize classes in code.
See more in PEP 8 -- Style Guide for Python Code
Functions encrypt and decrypt are almost the same - the only difference is +key and -key - so you could create one function and run it with +key or -key

from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen, ScreenManager
import string

alphabet = string.ascii_lowercase

class Caesar_Screen(Screen):
    pass

class Aes_Screen(Screen):
    pass

class CryptoMD(MDApp):

    def __init__(self, **kwargs):
        self.encrypt = Encrypt()   # PEP8: `CamelCaseNames` for classes, but `loser_case_names` for variables
        self.title = 'Crypto'
        self.theme_cls.primary_palette = "Purple"
        super().__init__(**kwargs)

    def out_encrypt(self, text, key):
        out_encrypted = self.encrypt.encrypt(text, key)
        self.root.get_screen("Caesar_Screen").ids.output.text = out_encrypted

    def out_decrypt(self, text, key):
        out_encrypted = self.encrypt.decrypt(text, key)
        self.root.get_screen("Caesar_Screen").ids.output.text = out_encrypted

class Encrypt():

    def encrypt(self, text, key):
        return self.convert(text,  int(key))

    def decrypt(self, text, key):  # PEP8: `lower_case_names` for variables
        return self.convert(text, -int(key))

    def convert(self, text, key):
        text = text.lower()
        key = int(key)

        encrypted_message = ""

        for char in text:
            if char in alphabet:
                position = alphabet.find(char)
                new_position = (position + key) % 26
                new_character = alphabet[new_position]
                encrypted_message += new_character
            else:
                encrypted_message += char

        print(encrypted_message.upper())

        return encrypted_message.upper()

if __name__ == '__main__':
    CryptoMD().run()

How to reference this id in py file


What is the code for the martianbuddy.com cabinet in Doom 3 BFG Edition?

Question: In Doom 3 BFG there are the same two cabinets as in the original Doom 3 which can only be opened by a code from martianbuddy.com. This website just redirects to bethesda now and the code cannot be obtained.
What is the code for those cabinets?
Answer: Both cabinets are opened by the code 0508. The one in Administration will contain a Chaingun and the one in Delta Labs 2B will contain the BFG 9000.
Comment: Incidentally, this code is in the subject of the email sent to Jonathan A. Moses telling him that he won.


iPhone view with pop up animation?

Question: I'm new to iPhone development, its going OK so far, I've managed to get to grips with the Tab bar, navigation bar and tableviews.
However I want to be able to copy what the settings app does on the device when a user wants to change language.
In Settings, General, International when a user clicks on Language a new screen animates over the previous screen with a navigation bar that has a cancel and done button and a table view showing the languages available for selection.
I cant seem to find how to do this via Google so I was wondering if someone could point me in the right direction of a tutorial or what I should be searching for? Is it type of view or a certain way to animate a view?
Answer: This is done via a method available on UIViewController (and thus all of its derivatives as well) called - presentModalViewController:animated:. You simply need to create a new view controller that you want to display and pass it into that.
See the link to the UIViewController docs above for more info and the complementary method - dismissModalViewControllerAnimated: to close the view. The docs have links to example code on how to use them as well.
Answer: in iPhone, it's done through modal view controller. Refer  this tutorial.

iPhone view with pop up animation?


Show that $\int_{-a}^{a} f(x) \ dx = \int_{0}^{a} [f(-x)+f(x)] \ dx$

Question: Question :
Given a constant $a>0$, show that $\int_{-a}^{a} f(x) \ dx = \int_{0}^{a} [f(-x)+f(x)] \ dx$ and hence, evaluate $\int_{-1}^{1} ln(x+\sqrt{1+x^2}) \ dx$.

I just follow the definite integrateion rules and tried the following.

Why is there a negative sign (-) in front of $f(-x)$?
Thank you for your help. =]
Comment: If you change the order of integration period, then the sign of the  integral changes.
Comment: Notice your integral is equal to $$\int_{-1}^{1} \ln(x + \sqrt{1+x^2} )dx = \int_{-1}^{1} \sinh^{-1}(x) dx = 0$$
Comment: Try doing a $y = -x$ substitution at the step where you made the big box.  You'll get $dy = -dx$.  Your statement $ = \int_{a}^0 f(-x) dx + ... $ doesn't take into account the sign change on the differential $dx$.  You should get $ = \int_{a}^0 f(-y) \cdot -dy + ...$
Answer: you are using $$\int_a^bf(x)dx = - \int_b^af(x)dx$$


Schlage Locks - What is "Less Full Sized Core" vs Full Size?

Question: I am buying a Schlage commercial lock set, and there is a $120 price delta between:
FSIC Full Size Inter-changeable Cores
And
Less Full Sized Core
What does this mean?
Answer: "Less" here means "without". You can purchase the lock set either including the core, or with a hole where you can add a core you already have or one you purchase separately.
Comment: "Less" as in "minus". A bit awkward in this instance, but not entirely uncommon in modern English usage. "Your total, less the 10% 'friend' discount is...".
Comment: Got it. If it said "Less Core" I would track it better. "Less Full Size Core" confused me. Thanks all!


Using mod_rewrite for subdomains

Question: I wan't people to be able to register their own sections within my site, and have those sections be their own subdomain of my site. so someone can register 'test' and have 'test.example.com' refer to their site which would be at say /site.php?id=1 So how would i go about writing a mod_rewrite rule for this?
Answer: mod_rewrite might not be the best tool for this. RewriteRules are great for mapping a file to something else, but it was not really meant for domain matching.
The best you can do using mod_rewrite is the following:
RewriteEngine On
# Skip www.domain.com
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com
RewriteRule ^/(.*)$  site.php?domain=%1&file=$1 [L]

Which is not really useful. What I would recommend to do instead if programmatically check the value of HTTP_HOST as such:
function get_subdomain() {
  if(preg_match('/^([^.]+)\.domain\.com/i', $_SERVER['HTTP_HOST'], $matches))
    return $matches[1];
}

Answer: You can configure apache to claim the "special" domains in the apache configuration (e.g. www.mydomain.com, etc), in your virtual host containers and have the others default to your first virtual host.  You can then rewrite the base url to a dispatch application that inspects the URL and sends the user off to their correct area.
From Apache 2.0 docs:

Almost any Apache directive may go
  into a VirtualHost container. The
  first VirtualHost section is used for
  requests without a known server name.

Put the code to handle *.mydomain.com in the first virtual host:
<VirtualHost *:80>
  Servername custom.mydomain.com
  DocumentRoot /var/www/html/custom
  RewriteEngine on
  RewriteRule ^/$ /var/www/cgi-bin/dispatch.cgi [R]
  # more configs here
</VirtualHost>

<VirtualHost *:80>
  Servername www.mydomain.com
  DocumentRoot /var/www/html/homepage
  # more configs here
</VirtualHost>

In dispatch.cgi, inspect the calling url to determine where the user should go.  Make sure you set up your DNS to accept all subdomains.
Hope that helps!
Answer: Actually, we've been using this technique without much problem for the past year. Our mod_rewrite config looks like:
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !www.mydomain.com
RewriteCond %{HTTP_HOST} ^([^.]+)\.mydomain\.com
RewriteCond %{REQUEST_URI} !admin
RewriteRule (.*) /admin/ [R=301,L]
RewriteRule ^admin(.*)$ hosted/admin/$1 [QSA,L]

What happens, is that users are directed to theiraccount.mydomain.com/admin.
We then use PHP to identify the account portion of the domain name. Using something like $_SERVER['SERVER_NAME'] or some method of getting the domain name and parsing it works very well.
Keep these configs in the httpd.conf though, this will become a cpu problem in higher traffic sites if it's kept as .htaccess.

Using mod_rewrite for subdomains


Single AWS IOT rule for all thing shadow updates

Question: Hi I am new to AWS IOT rules and I have a use case where I need to process all the successful updates to multiple thing shadows in a lambda. The rule triggers the lambda.
Currently my iot rule is something like this:
SELECT * FROM '$aws/things/testThing/shadow/update/accepted'
But instead of 'testThing' i want to use something like
SELECT * FROM '$aws/things/#/shadow/update/accepted'
which will trigger the same lambda for any thing shadow update.
But I am unable to come up with such a rule. Currently I am creating multiple rules(one for each shadow) which I don't think is the right thing to do.
I might use something like
SELECT * FROM '$aws/things/#'
which will give lot of unwanted data and unwanted triggers, I am trying to avoid doing such a thing.
Answer: Found that I need to use + instead of *,#
SELECT * FROM '$aws/things/+/shadow/update/accepted'


How do I control exports?

Question: In the first scenario, I accepted an assignment from one of the factions to export some Tobacco.  Everything I find and click gives me an option to import stuff, but how do I export?  Is that managed automatically?
Answer: Yes, as long as you have a tobacco farm, when the tobacco is harvested and there's no cigar factory, it will automatically be hauled to the dock.
Comment: Keep in mind that it takes a while for crops to grow, so don't get concerned if your exports aren't starting to count up right away.
Comment: "A while" being two years for all crops except corn, which takes about one year.

How do I control exports?


How to load HSQLDB script with Hibernate

Question: I created simple DB with LibreOffice Base and exported it with SCRIPT command. It has only one table Tag with "id" and name. I created corresponding class named Tag, with annotation @Entity, and for id @Id.
I load data with following code:
<code>public static void main(String[] args){

    Configuration configuration=new Configuration();
    configuration.configure();
    serviceRegistry=new ServiceRegistryBuilder().applySettings(
    configuration.getProperties()).buildServiceRegistry();
    sessionFactory=configuration.buildSessionFactory(serviceRegistry);
    session=sessionFactory.openSession();
    session.beginTransaction();

    tag=(Tag) session.get(Tag.class, 1);
    session.close();
    System.out.println(tag.getName());
}
</code>
Running this i get follwing lines:
Hibernate: select tag0_.id as id0_0_, tag0_.name as name0_0_ from Tag tag0_ where tag0_.id=?
and NullPointerException.
in xml file i have specified the file to be used "jdbc:hsqldb:file:testdb", also added Tag as a mapping class.. What i am doing wrong??
Answer: If you use Hibernate+HSQLDB for testing you could set property "hibernate.hbm2ddl.auto" to
"create" - in that case hibernate will create required schema by itself

hibernate.hbm2ddl.auto Automatically validates or exports schema DDL
  to the database when the SessionFactory is created. With create-drop,
  the database schema will be dropped when the SessionFactory is closed
  explicitly.


Scout Helicopter maps in Obliteration mode

Question: I want to play Obliteration game mode with a scout helicopter.
In which maps can I play?
Comment: Note: With the recent patch I'm not sure that this question is relevant any more. I think helicopters have been removed from Obliteration, at least on PS4.
Comment: As one DICE employee confirmed, all obliteration servers were mistakenly set as 'infantry mode'. It is expected to be fixed soon.
Comment: Ah, I was unaware of that, thanks for letting me know! Obliteration was a lot less fun with just quads and RHIBs
Answer: You can play with a scout helicopter in these maps in Obliteration:

Zavod 311
Hainan Resort
Flood Zone
Paracel Storm

Tip #1: I would definitely recommend to start in Zavod 311 because after this map comes Hainan Resort and Flood Zone so you can play with a scout helicopter for three consecutive rounds.
Tip #2: Out of these four maps, only Zavod 311 has a mobile anti-air vehicle - your biggest nightmare - so be extra careful.
Tip #3: The map with most cover for a helicopter is Flood Zone. Then comes Zavod 311/Hainan Resort and lastly Paracel Storm, which have almost no cover. My advice on that is make sure you have an unselfish engineer in your helicopter to repair you and harass the enemy helicopter with anti-air rockets (Stinger and Igla).