text:
Q: Having Trouble Converting Function to Extension I'd like to make the following an extension of NSURL instead of a function but I'm getting errors that I can't use the variables. How would I fix this?
The function gets the query string of a url and returns a dictionary with key value pairs of the parameters in the query.
func getKeyVals(url:NSURL) -> Dictionary<String, String>{
    var results = [String:String]()
    var keyValues = url.query?.componentsSeparatedByString("&")
    if keyValues?.count > 0 {
        for pair in keyValues! {
            let kv = pair.componentsSeparatedByString("=")
            if kv.count > 1 {
                results.updateValue(kv[1], forKey: kv[0])
            }
        }

    }
    return results
}

A: extension NSURL {
    func getKeyVals() -> Dictionary<String, String> {
        var results = [String:String]()
        let keyValues = query?.componentsSeparatedByString("&")
        if keyValues?.count > 0 {
            for pair in keyValues! {
                let kv = pair.componentsSeparatedByString("=")
                if kv.count > 1 {
                    results.updateValue(kv[1], forKey: kv[0])
                }
            }

        }
        return results
    }
}

if let checkedUrl = NSURL(string: "http://www.domain.com/index.php?device=iPad&capacity=128GB&color=white"){
    let keyVals = checkedUrl.getKeyVals()   // ["color": "white", "device": "iPad", "capacity": "128GB"]
}


text:
Q: Bazel: submodule in project does not use bazel , pushing to git doesnt include locally added BUILD file in submodule, how do i build? I am just starting to learn how to use bazel following this tutorial
One thing I am unsure how to do is how to use a submodule, from my own repo for example. where I do not use bazel. The repo just has some c/h files that I need to pull in. To make things work locally I added a BUILD file in folder pulled in from submodules. However after I commit and push my changes the BUILD file is obviously not there. How do I add the c/h files from the submodule folder to my build. Bazel seems to be looking for a BUILD folder in that directory and there will be none, if for example someone else clones this repo.
currently my "main" Directory has this build file:
cc_library(
  name = "uCShell-main",
  srcs = ["main.c"],
  deps = ["//uCShell:uCShell-lib" ],
)

cc_binary(
   name = "uCShell-bin",
   deps = [":uCShell-main" , "//uCShell:uCShell-lib" ]
)

and the folder with the pulled in submodule has this locally added BUILD file:
cc_library(
    name = "uCShell-lib",
    srcs = glob(["*.c"]),
    hdrs = glob(["*.h"]),
    visibility = ["//visibility:public"],
)

This works and compiles just fine. However do correct any issues or misuse of Bazel you see here, I'd like to learn.
Ultimately to reiterate the issue, when I push this project the locally added BUILD file will not be in the project because it is not in the original submodule. So how can I inlcude the c/h files in that submodule in order to build my main. And I would like to leave it as a submodule. Ultimately I can just add a BUILD file for the submodule's repo, but would like to find a better way, for example what if this was not my repo where I can just add a BUILD file.

A: If you use new_local_repository with a relative path to import the submodule, you can set build_file or build_file_content to add the BUILD file. You should be able to use that same  BUILD file as-is.
Because it will be in a different external repository, you'll need to access it via the corresponding label.
For example, if you put the BUILD file at build/BUILD.my_lib.bazel and this in WORKSPACE:
new_local_repository(
    name = "my_lib",
    path = "submodules/my_lib",
    build_file = "@//build:BUILD.my_lib.bazel",
)

then you can put @my_lib//:uCShell-lib in deps of any other target and it will all work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: pass extra value manually using chagePage how to pass a hash value manually to a next page in jquery mobile and receive it in a pagecreate / pageshow
i tried following when a button gets clicked on page1
   $.mobile.changePage('#page2?val=1', {
                transition: 'slideup'
            }

           );

HTML Page Code

<title>jQuery Mobile Test</title>

Page 1

            Place content here
            // i tried this too but didnt receive at the pagecreate of pge 1
            Send Value

Footer

Page 2

            Place content here

Footer

A: Ok, it looks like jqm does not support this:

jQuery Mobile does not support query parameter passing to
  internal/embedded pages.

However, their documentation offers to plugins that may help you:

There are two plugins that you can add to your project if query
  parameters are needed between pages. There is a lightweight page
  params plugin and a more fully featured jQuery Mobile router plugin
  for use with backbone.js or spine.js.

Found in the section called "Passing parameters between pages" here: http://jquerymobile.com/test/docs/pages/page-scripting.html


text:
Q: Null value and whitespace in Regex I have the following Regex:
^(?P<port_name>[\w\d\/]+)[^\S\r\n]+(?P<description>[\S]+ ?[\S]+)\s+(?P<duplex>[\w]+)\s+

That I use on the following data:
>show interfaces status
Port      Description     Duplex Speed   Neg  Link   Flow  M  VLAN
                                              State  Ctrl
--------- --------------- ------ ------- ---- ------ ----- -- -------------------
Te1/0/1   CVH10 Mgt+Clstr Full   10000   Off  Up     On    T  (1),161-163
Te1/0/2   CVH10 VM 1      Full   10000   Off  Up     On    T  (1),11,101,110,
                                                              120,130,140,150,
                                                              160,170,180,190,
                                                              200,210,230,240,
                                                              250,666,999
Fo2/1/1                   N/A    N/A     N/A  Detach N/A
Te2/0/8                   Full   10000   Off  Down   Off   A  1

Which gives me this result (https://regex101.com):

I can't seem to figure out:

*

*How to match the description without also matching the duplex value of Full, because of it's spaces.

*How to match a value of null when there is no discription avalible as seen in the last two lines.

I'm starting to learn Regex and hope someone can help me out.

A: You can not assume that the columns are divided by at least 2 whitespace chars, so in that case you can make the pattern a bit more specific.
Note that \w also matches \d.
^(?P<port_name>[\w\/]+)[^\S\r\n]+(?P<description>(?!Full\b|N\/A\b)\S+(?:[^\S\r\n]+\S+)*?[^\S\r\n]+)?(?P<duplex>Full|N\/A)[^\S\r\n]+(?P<speed>\d+|N\/A)\b

*

*^ Start of string

*(?P<port_name>[\w\/]+)[^\S\r\n]+ port_name match 1+ word chars or -

*(?P<description> description

*

*(?!Full\b|N\/A\b) Negative lookahead, assert not Full or N/A directly to the right

*\S+(?:[^\S\r\n]+\S+)*? Match 1+ non whitespace chars and optionally repeat 1+ spaces and 1+ non whitespace chars, as least as possible

*[^\S\r\n]+ Match 1+ spaces (whitespace chars without a newline)

*)? Close the group and make it optional

*(?P<duplex>Full|N\/A)[^\S\r\n]+ duplex Match either Full or N/A

*(?P<speed>\d+|N\/A)\b speed Match either 1+ digits or N/A

See a regex 101 demo.
To match all values including optional fields:
^(?P<port_name>[\w\/]+)[^\S\r\n]+(?P<description>(?!Full\b|N\/A\b)\S+(?:[^\S\r\n]+\S+)*?)?\s+(?P<duplex>Full|N\/A)\b\s+(?P<speed>[\d\w\/]+)\s+(?P<neg>[\w\/]+)\s+(?P<link_state>[\w]+)\s+(?P<flow_control>[\w\/]+)(?:(?P<mode>[^\S\r\n]+\w+)(?:[^\S\r\n]+(?P<vlans>[\d(),-]+(?:\r?\n[^\S\r\n]+[\d(),-]+)*))?)?

See another regex 101 demo.


text:
Q: How to scrape dynamic javascript content on a website in python? I need to scrape this website in python (https://www.winamax.fr/paris-sportifs/live) to get and save in a csv file the latest odds but it's a javascript dynamically updated content (AJAX? not so familiar with js...). I've tried with selenium and nothing worked.
I've found the js script handling all the data at this adress (https://static.winamax.fr/betting/client/1.31.1/12.main.js) which uses the webpackJsonp module so I guess the data is in json format (correct me if I'm wrong, again I'm not very familiar with javascript).
That displays all the infos but it's really messy and I can only read the titles (like "events live", "events to come", "favorites" etc) not the actual data from matchs, here is the raw version (a big one line code, that's why it more digestable to read with the link provided above)
(window.webpackJsonp=window.webpackJsonp||[]).push([[12],{696:function(t,e,n){"use strict";var r=n(55),o=n.n(r),a=n(52),i=n(3),u=n(4),c=n.n(u),s=n(10),f=n(275);function l(t){return function(t){if(Array.isArray(t)){for(var e=0,n=new Array(t.length);e<t.length;e++)n[e]=t[e];return n}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function p(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}var m=f.a.STANDARD,h=f.a.LIVE,v=f.a.FAVORITES,y=Object(a.createSelectorCreator)(a.defaultMemoize,s.j),d=[],E=function(t){return Object(a.createSelector)([function(t,e){return e.location.pathname},function(t,e){return e.match.params.sportId},function(t,e){return e.match.params.categoryId},function(t,e){return e.match.params.tournamentId},function(t,e){return e.match.params.hour}],function(e,n,r,o,a){return function(t){return function(e,n,r,o,a){return function(n){if("home"===t){if("live"===n)return{text:c()("EVENTS_LIVE"),type:h};if("edito"===n)return{text:c()("NEW_TITLE"),type:m};if("to_come"===n)return{text:c()("EVENTS_TO_COME"),type:m}}else if("live"===t){if("live"===n)return e.match(/favorites/)?{text:c()("CURRENT_FAVORITES"),type:v}:{text:c()("EVENTS_LIVE"),type:m};if("prematch"===n)return e.match(/favorites/)?{text:c()("TOCOME_FAVORITES"),type:v}:{text:c()("EVENTS_TO_LIVE"),type:m}}else if("tv"===t){if("live"===n)return e.match(/favorites/)?{text:c()("CURRENT_FAVORITES"),type:v}:{text:c()("EVENTS_LIVE"),type:h};if("prematch"===n)return e.match(/favorites/)?{text:c()("TOCOME_FAVORITES"),type:v}:{text:c()("EVENTS_TO_COME"),type:m}}else if("favorites"===t){if("live"===n)return{text:c()("CURRENT_FAVORITES"),type:v};if("prematch"===n)return{text:c()("TOCOME_FAVORITES"),type:v}}else if("catalog"===t){if("live"===n)return{text:c()("EVENTS_LIVE"),type:m};if("prematch"===n)return{text:c()("EVENTS_TO_COME"),type:m}}else if("calendar"===t)return{text:c()("NEXT_HOURS",{count:s.h.castNumber(a)}),type:m};return{text:void 0,type:m}}}}(t)(e,n,r,o,a)})},O=function(t){return Object(a.createSelector)([function(t,e){return e.match.params.sportId},function(t,e){return e.match.params.categoryId},function(t,e){return e.match.params.tournamentId}],function(e,n,r){return function(t){return function(e,n,r){return function(o){return"home"===t?"live"===o.hlType?"live":"highlight":["tv","favorites"].indexOf(t)>-1?"LIVE"===o.status?"live":"highlight":"live"===t?"LIVE"===o.status?"live":"prematch":"catalog"===t?(void 0!==r?a="tournament":void 0!==n?a="category":void 0!==e&&(a="sport"),"LIVE"===o.status?"live":a):"highlight";var a}}}(t)(e,n,r)})},b=function(t){return Object(a.createSelector)([function(t){return t.entities},function(t,e){return e.match.params.sportId},function(t,e){return e.match.params.categoryId},function(t,e){return e.match.params.tournamentId},function(t,e){return e.match.params.hour},function(t,e){return e.location.pathname}],function(e,n,r,o,a,i){var u,c=t;return["live","tv","catalog"].indexOf(t)>-1?i.indexOf("favorites")>-1?c="favorites":void 0!==o?(c="tournaments",u=o):void 0!==r?(c="categories",u=r):void 0!==n&&(c="sports",u=n):"calendar"===t&&(c="calendar",u=a),u?e[c][u]:e[c]})},g=function(t){return Object(a.createSelector)([function(t,e){return e.match.params.sportId},function(t,e){return e.match.params.categoryId},function(t,e){return e.match.params.tournamentId},function(t,e){return e.location.pathname}],function(e,n,r,o){var a="matches";return"live"===t?o.indexOf("favorites")>-1?a="liveMatches":void 0===r&&void 0===n&&void 0===e||(a="liveMatches"):"tv"===t&&(o.indexOf("favorites")>-1?a="tvMatches":void 0===r&&void 0===n&&void 0===e||(a="tvMatches")),a})},T=function(t){return Object(a.createSelector)([b(t),g(t),function(t){return t.entities.matches}],function(t,e,n){var r=t&&t[e]||d;return Object(i.map)(r,function(t){return n[t]})})},I=function(t){return y([T(t),function(t){return t.entities.sports},function(t){return t.entities.categories},function(t){return t.entities.tournaments}],function(t,e,n,r){return Object(i.reduce)(t,function(t,o){if(void 0!==o&&null!==o){var a=o.sportId,i=o.tournamentId,u=o.categoryId;if(99999!==a){var c,f=e[a];if(o.tvChannels&&(c=s.f.convertToLowerCase(o.tvChannels)),void 0!==f&&null!==f){var l=n[u];if(void 0!==l&&null!==l){var m=r[i];void 0!==m&&null!==m&&t.push(function(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{},r=Object.keys(n);"function"===typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter(function(t){return Object.getOwnPropertyDescriptor(n,t).enumerable}))),r.forEach(function(e){p(t,e,n[e])})}return t}({},o,{tvChannels:c,sportName:f.sportName,categoryName:l.categoryName,tournamentName:m.tournamentName}))}}}}return t},[])})},S=function(t){return Object(a.createSelector)([b(t),g(t),I(t)],function(t,e,n){return{isLoading:void 0===t||t&&void 0===t[e],isNull:null===t||t&&null===t[e]||!1,matches:n}})};e.a=function(t){return function(){return y([S(t),O(t),E(t),function(t){return t.entities.grids}],function(e,n,r,a){var u=e.matches,s=e.isLoading,f=e.isNull;if(s||f)return{list:d,isEmpty:0===u.length,isLoading:s,isNull:f};var p={default:function(){return!0}};"home"===t?p={live:["hlType","live"],edito:["hlType","edito"],to_come:function(t){return t&&"live"!==t.hlType&&"edito"!==t.hlType}}:"live"!==t&&"tv"!==t&&"catalog"!==t&&"favorites"!==t||(p={live:["status","LIVE"],prematch:["status","PREMATCH"]});var h=Object(i.reduce)(p,function(e,s,f){var p=Object(i.filter)(u,s);return p.length>0?("catalog"===t&&"prematch"===f||e.push({type:"separator",payload:{item:r(f)}}),p.forEach(function(r,a,i){if("catalog"===t){var u,s,f=i[a-1],l=o.a.unix(r.matchStart).format("l"),p=r.isOutright;a>0&&(u=o.a.unix(f.matchStart).format("l"),s=f.isOutright),"LIVE"!==r.status&&(r.isOutright?s!==p&&e.push({type:"separator",payload:{item:{text:c()("BETS_OUTRIGHTS"),type:m}}}):u!==l&&e.push({type:"separator",payload:{item:{text:o.a.unix(r.matchStart).format(c()("formats.dateShort")),type:m}}}))}e.push({type:n(r),payload:{item:r}})}),"home"===t&&"edito"===f&&a&&a.length&&e.push.apply(e,l(Object(i.map)(a,function(t){return{type:"grid",payload:{item:t}}})))):"home"===t&&0===p.length&&"edito"===f&&a&&a.length&&(e.push({type:"separator",payload:{item:{text:c()("NEW_TITLE"),type:m}}}),e.push.apply(e,l(Object(i.map)(a,function(t){return{type:"grid",payload:{item:t}}})))),e},[]);return{list:h,isEmpty:0===h.length,isLoading:s,isNull:f}})}}},837:function(t,e,n){"use strict";n.r(e);n(6);var r=n(0),o=n.n(r),a=n(12),i=n(4),u=n.n(i),c=n(277),s=n.n(c),f=n(274),l=n(111),p=n(35),m=n(696),h=n(712),v=n(171),y=n(698),d=n(694);function E(t){return(E="function"===typeof Symbol&&"symbol"===typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"===typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function O(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}function b(t,e){return!e||"object"!==E(e)&&"function"!==typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function g(t){return(g=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function T(t,e){return(T=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}var I=function(t){function e(){return function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}(this,e),b(this,g(e).apply(this,arguments))}var n,a,i;return function(t,e){if("function"!==typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&T(t,e)}(e,r["Component"]),n=e,(a=[{key:"componentWillMount",value:function(){var t=this.props,e=t.location,n=t.match;this.dispatchRoute(n.params,e.pathname)}},{key:"componentWillReceiveProps",value:function(t){var e=t.match.params,n=t.location.pathname;this.props.location.pathname!==n&&this.dispatchRoute(e,n)}},{key:"dispatchRoute",value:function(t,e){var n=l.a.LIVE,r=t.sportId,o=t.categoryId,a=t.tournamentId;e.indexOf("favorites")>-1?n+=":favorites":void 0!==a?n+=":tournament:".concat(a):void 0!==o?n+=":category:".concat(o):void 0!==r&&(n+=":sport:".concat(r)),this.props.askRoute(n)}},{key:"render",value:function(){var t=this.props,e=t.isLoading,n=t.isNull,r=t.isEmpty,a=t.list;return e?o.a.createElement(s.a,{title:u()("DOCUMENT_TITLE.LIVE")},o.a.createElement(v.a,{loading:!0})):o.a.createElement(s.a,{title:u()("DOCUMENT_TITLE.LIVE")},o.a.createElement("section",{className:"event-list"},!n&&!r&&o.a.createElement(h.a,{items:a}),(n||r)&&o.a.createElement("p",{className:"no-results centered-message-betting"},u()("EVENTS_NO"))))}}])&&O(n.prototype,a),i&&O(n,i),e}();e.default=Object(f.a)(d.a,y.a,Object(a.connect)(function(){var t=Object(m.a)("live")();return function(e,n){return t(e,n)}},function(t){return{askRoute:function(e){t(p.a.send({route:e}))}}}))(I)}}]);

So I simply need to scrape this data and return it to pretty much the same format of the website (from the most global to the most refined data):

*

*Total number of live games (all sports included) with all their infos, bets and odds available. Within this list I can select any game individually and see its infos, odds and bets available.

*total number of live games by each sport (ex: football (8), basketball (6) ect..) with all their infos, bets and odds available.

*A list of all live tournaments/leagues by each sport (ex: if footaball is selected, return british premier league, spanish liga, french ligue 1 ect ect) with all their infos, bets and odds available.

*When a specific tournament/league is selected in a sport (ex: british premier league in football), display the list all of its live games with all their infos, bets and odds available.

*Lastly, within this list of point 4/, I need like in point 1/ to be able to select any live game individually to see its infos, odds and bets available.

Any help, suggestions & ideas will be greatly appreciated.
j.d

A: The website https://www.winamax.fr/paris-sportifs/live gets 'fresh' data periodically using WebSocket  .
Navigate to the WS tab (under Network tab) and see the frames of data coming from the server to the client.
Try to use a WebSocket client like https://pypi.org/project/websocket_client/ and point it to the site you try to scrape.


text:
Q: How do you know if an equation of spring motion is overdamped? Looking at an equation, how can you know if if it overdamped, critically damped, or under-damped?
For example:

How can you tell that the equation $c_1e^{2x} + c_2e^{-2x}$ is overdamped?
How can you tell that the equation $e^{-x}(c_1+c_2x)$ is critically damped?
How can you tell that the equation $e^{-t}(c_1\cos(3t) +c_2\sin(3t))$ is underdamped?

A: The shape of these is the key.  An overdamped system will be pure exponentials (though they are usually all decreasing).  Critically damped has a term in $xe^x$.  And underdamped have oscillatory solutions, like yours with cosine and sine waves.

A: Hint:
Just look at how your equations are set up.

*

*$e^{-x}(c_1+c_2x)$ means you have repeated roots.

*$c_1e^{2x} + c_2e^{-2x}$ means you have distinct roots.

*$e^{-t}(c_1cos(3t) +c_2sin(3t))$ means you have complex conjugates roots.

The roots will tell you whether it is critically damped, overdamped, or underdamped.


text:
Q: How to fix urllib.error.HTTPError: HTTP Error 406: Not Acceptable I'm using ipwhois PyPI, the code works to check the IP and gives the output but occasionally get an error:
  raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 406: Not Acceptable"

During handling of the above exception, another exception occurred:

socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

I am using Sublime Text Editor for coding
import requests
import os,sys
from bs4 import BeautifulSoup
import pandas as pd
from ipwhois import IPWhois

class IPCheck():
    ip = input ("Enter Source IP Address: ")

    def __init__(self):
        pass
    def whoip(self):
        obj = IPWhois(self.ip)
        results = obj.lookup_rws()
        print("\nSource IP Details and Analysis: \n\nWHOIS IP Lookup Results: \n------------------------\nOrg Name: {}".format(results['nets'][0]['description']))
        print("Range: {}".format(results['nets'][0]['range']))
        print("Handle: {}".format(results['nets'][0]['handle']))
        print("Registration Date: {}".format(results['nets'][0]['created']))
        print("Address: {}".format(results['nets'][0]['address']))
        print("City: {}".format(results['nets'][0]['city']))
        print("State/Province: {}".format(results['nets'][0]['state']))
        print("Country: {}".format(results['nets'][0]['country']))
        print("Postal Code: {}".format(results['nets'][0]['postal_code']))

IPC=IPCheck()
IPC.whoip()

This is the error traceback:
Traceback (most recent call last):
  File "C:\Users\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 649, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 406: Not Acceptable                         During handling of the above exception, another exception occurred:                \AppData\Local\Programs\Python\Python37-32\lib\site-packages\ipwhois\ipwhois.py", line 701, in get_rws
    url)
ipwhois.ipwhois.WhoisLookupError: Whois RWS lookup failed for 'http://rdap.lacnic.net/rdap/ip/201.220.29.49'.


text:
Q: Create File shortcut with Symfony2 FileSystem Anyone know how to use the Filesystem component Symfony2 to create shortcut files? Or another way to create a file shortcut?

A: $filesystem = new Symfony\Component\Filesystem\Filesystem;

$filesystem->symlink($originDir, $targetDir, $copyOnWindows = false);

Reason to use Symfony Filesystem over the native PHP symlink would be because this method will prepare the directory for you, converts triggered errors into exceptions, and manages compatibility on Windows which doesn't support symlinks, so creates a copy instead.
Source: https://github.com/symfony/symfony/blob/2.7/src/Symfony/Component/Filesystem/Filesystem.php#L289


text:
Q: Tkinter progress bar not working properly I am trying to add a progress bar to my window until some work is being done. But it is not working properly. I want it to keep moving until the work is done but it just moves rapidly and then stops. Also if I try to minimize or close the progress window it just hangs and stops responding.
Can anyone help me how can I do it properly? Here is my code.
import time
from tkinter import ttk
from tkinter import *

numbers = []

def main():
    main_window = Tk()
    app = info(main_window)
    main_window.mainloop()

class info:
    def __init__(self, root):
        # start = timer()
        self.error_str = ''
        self.root1 = root
        self.root1.title('LOADING......')
        self.root1.geometry("380x200")

        self.root1.eval('tk::PlaceWindow . center')
        self.root1.resizable(width=False, height=False)
        self.root1.configure(background='white')

        progress = ttk.Progressbar(self.root1, orient=HORIZONTAL,
                                   length=380, mode='determinate')
        progress.place(x=0, y=100)
        i = 20

        for x in range(1, 50):
            numbers.append(x * 2)
            print(numbers)

            progress['value'] = i
            self.root1.update_idletasks()
            time.sleep(0.1)
            i = i + 40

        self.root = root
        self.root.title('Second window')

        self.root.geometry('1350x800+0+0')

        frame1 = Frame(self.root, bg='#7877a5')
        frame1.place(x=0, y=0, width=1350, height=150)
        title = Label(frame1, text="Second Window", font=("Times New Roman", 40, "bold", "italic"),
                      bg='#7877a5',
                      fg='white')
        title.place(x=380, y=45)

if __name__ == '__main__':
    main()

A: Generally speaking you shouldn't call time.sleep() in a tkinter application because it interferes with the GUI's mainloop() and will make your program hang or freeze. Use the universal widget method after() instead.
Lastly you need to specify a maximum value for the Progressbar so its indicator scales properly relatively to the values of i you are setting its value to. The default for maximum is only 100, which your code was greatly exceeding in the for x loop.
Here's the code that needs to change in info.__init__(). The two lines changed have # ALL CAPS comments:
        progress = ttk.Progressbar(self.root1, orient=HORIZONTAL,
                                   length=380, mode='determinate',
                                   maximum=(48*40)+20)  # ADDED ARGUMENT.
        progress.place(x=0, y=100)
        i = 20

        for x in range(1, 50):
            numbers.append(x * 2)
            print(numbers)

            progress['value'] = i
            self.root1.update_idletasks()
            self.root1.after(100)  # Delay in millisecs.  # REPLACED TIME.SLEEP() CALL.
            i = i + 40


text:
Q: Go examples and idioms There's not a lot of Go code to learn the language from, and I'm sure I'm not the only one experimenting with it. So, if you found out something interesting about the language, please post an example here.
I'm also looking for

*

*idiomatic ways to do things in Go,

*C/C++ style of thinking "ported" to Go,

*common pitfalls about the syntax,

*anything interesting, really.

A: There is a make system set up that you can use in $GOROOT/src
Set up your makefile with
TARG=foobar           # Name of package to compile
GOFILES=foo.go bar.go # Go sources
CGOFILES=bang.cgo     # Sources to run cgo on
OFILES=a_c_file.$O    # Sources compiled with $Oc
                      # $O is the arch number (6 for x86_64)

include $(GOROOT)/src/Make.$(GOARCH)
include $(GOROOT)/src/Make.pkg

You can then use the automated testing tools by running make test, or add the package and shared objects from cgo to your $GOROOT with make install.

A: This is an implementation of a stack. It illustrates adding methods onto a type.
I wanted to make the stack part of it into a slice and use the slice's properties, but although I got that to work without the type, I couldn't see the syntax for defining a slice with a type.
package main

import "fmt"
import "os"

const stack_max = 100

type Stack2 struct {
    stack [stack_max]string
    size  int
}

func (s *Stack2) push(pushed_string string) {
    n := s.size
    if n >= stack_max-1 {
        fmt.Print("Oh noes\n")
        os.Exit(1)
    }
    s.size++
    s.stack[n] = pushed_string
}

func (s *Stack2) pop() string {
    n := s.size
    if n == 0 {
        fmt.Print("Underflow\n")
        os.Exit(1)
    }
    top := s.stack[n-1]
    s.size--
    return top
}

func (s *Stack2) print_all() {
    n := s.size
    fmt.Printf("Stack size is %d\n", n)
    for i := 0; i < n; i++ {
        fmt.Printf("%d:\t%s\n", i, s.stack[i])
    }
}

func main() {
    stack := new(Stack2)
    stack.print_all()
    stack.push("boo")
    stack.print_all()
    popped := stack.pop()
    fmt.Printf("Stack top is %s\n", popped)
    stack.print_all()
    stack.push("moo")
    stack.push("zoo")
    stack.print_all()
    popped2 := stack.pop()
    fmt.Printf("Stack top is %s\n", popped2)
    stack.print_all()
}

A: Another interesting thing in Go is that godoc. You can run it as a web server on your computer using
godoc -http=:8080

where 8080 is the port number, and the entire website at golang.org is then available at localhost:8080.

A: Calling c code from go
It's possible to access the lower level of go by using the c runtime.
C functions are in the form
void package·function(...)

(note the dot seperator is a unicode character) where the arguments may be basic go types, slices, strings etc. To return a value
call
FLUSH(&ret)

(you can return more than one value)
For instance, to create a function
package foo
bar( a int32, b string )(c float32 ){
    c = 1.3 + float32(a - int32(len(b))
}

in C you use
#include "runtime.h"
void foo·bar(int32 a, String b, float32 c){
    c = 1.3 + a - b.len;
    FLUSH(&c);
}

Note that you still should declare the function in a go file, and that you'll have to take care of memory yourself. I'm not sure if it's possible to call external libraries using this, it may be better to use cgo.
Look at $GOROOT/src/pkg/runtime for examples used in the runtime.
See also this answer for linking c++ code with go.

A: Here is a go example using the sqlite3 package.
http://github.com/bikal/gosqlite-example

A: Defer statements

A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns.
DeferStmt = "defer" Expression .
The expression must be a function or method call. Each time the "defer" statement executes, the parameters to the function call are evaluated and saved anew but the function is not invoked. Deferred function calls are executed in LIFO order immediately before the surrounding function returns, but after the return values, if any, have been evaluated.

lock(l);
defer unlock(l);  // unlocking happens before surrounding function returns

// prints 3 2 1 0 before surrounding function returns
for i := 0; i <= 3; i++ {
    defer fmt.Print(i);
}

Update:
defer is now also the idiomatic way to handle panic in an exception-like manner:
package main

import "fmt"

func main() {
    f()
    fmt.Println("Returned normally from f.")
}

func f() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in f", r)
        }
    }()
    fmt.Println("Calling g.")
    g(0)
    fmt.Println("Returned normally from g.")
}

func g(i int) {
    if i > 3 {
        fmt.Println("Panicking!")
        panic(fmt.Sprintf("%v", i))
    }
    defer fmt.Println("Defer in g", i)
    fmt.Println("Printing in g", i)
    g(i+1)
}

A: const ever = true

for ever {
    // infinite loop
}

A: A stack based on the other answer, but using slice appending to have no size limit.
package main

import "fmt"
import "os"

type Stack2 struct {
        // initial storage space for the stack
        stack [10]string
        cur   []string
}

func (s *Stack2) push(pushed_string string) {
        s.cur = append(s.cur, pushed_string)
}

func (s *Stack2) pop() (popped string) {
        if len(s.cur) == 0 {
                fmt.Print("Underflow\n")
                os.Exit(1)
        }
        popped = s.cur[len(s.cur)-1]
        s.cur = s.cur[0 : len(s.cur)-1]
        return
}

func (s *Stack2) print_all() {
        fmt.Printf("Stack size is %d\n", len(s.cur))
        for i, s := range s.cur {
                fmt.Printf("%d:\t%s\n", i, s)
        }
}

func NewStack() (stack *Stack2) {
        stack = new(Stack2)
        // init the slice to an empty slice of the underlying storage
        stack.cur = stack.stack[0:0]
        return
}

func main() {
        stack := NewStack()
        stack.print_all()
        stack.push("boo")
        stack.print_all()
        popped := stack.pop()
        fmt.Printf("Stack top is %s\n", popped)
        stack.print_all()
        stack.push("moo")
        stack.push("zoo")
        stack.print_all()
        popped2 := stack.pop()
        fmt.Printf("Stack top is %s\n", popped2)
        stack.print_all()
}

A: Go object files actually include a cleartext header:
jurily@jurily ~/workspace/go/euler31 $ 6g euler31.go
jurily@jurily ~/workspace/go/euler31 $ cat euler31.6
amd64
  exports automatically generated from
  euler31.go in package "main"
    import

$$  // exports
  package main
    var main.coin [9]int
    func main.howmany (amount int, max int) (? int)
    func main.main ()
    var main.initdone· uint8
    func main.init ()

$$  // local types
  type main.dsigddd_1·1 struct { ? int }

$$

!
<binary segment>

A: I have seen a couple of people complaining about the for-loop, along the lines of "why should we have to say i = 0; i < len; i++ in this day and age?".
I disagree, I like the for construct. You can use the long version if you wish, but the idiomatic Go is
var a = []int{1, 2, 3}
for i, v := range a {
    fmt.Println(i, v)
}

The for .. range construct loops over all the elements and supplies two values - the index i and the value v.
range also works on maps and channels.
Still, if you dislike for in any form, you can define each, map etc. in a few lines:
type IntArr []int

// 'each' takes a function argument.
// The function must accept two ints, the index and value,
// and will be called on each element in turn.
func (a IntArr) each(fn func(index, value int)) {
    for i, v := range a {
        fn(i, v)
    }
}

func main() {
    var a = IntArr([]int{2, 0, 0, 9}) // create int slice and cast to IntArr
    var fnPrint = func(i, v int) {
        fmt.Println(i, ":", v)
    } // create a function

    a.each(fnPrint) // call on each element
}

prints
0 : 2
1 : 0
2 : 0
3 : 9

I'm starting to like Go a lot :)

A: There are a lot of small programs in test in the main directory. Examples:

*

*peano.go prints factorials.

*hilbert.go has some matrix multiplication.

*iota.go has examples of the weird iota thing.

A: Here's a nice example of iota from Kinopiko's post:
type ByteSize float64
const (
    _ = iota;   // ignore first value by assigning to blank identifier
    KB ByteSize = 1<<(10*iota)
    MB
    GB
    TB
    PB
    YB
)

// This implicitly repeats to fill in all the values (!)

A: Go and get your stackoverflow reputation
This is a translation of this answer.
package main

import (
    "json"
    "fmt"
    "http"
    "os"
    "strings"
)

func die(message string) {
    fmt.Printf("%s.\n", message);
    os.Exit(1);
}

func main() {
    kinopiko_flair := "https://stackoverflow.com/users/flair/181548.json"
    response, _, err := http.Get(kinopiko_flair)
    if err != nil {
        die(fmt.Sprintf("Error getting %s", kinopiko_flair))
    }

    var nr int
    const buf_size = 0x1000
    buf := make([]byte, buf_size)

    nr, err = response.Body.Read(buf)
    if err != nil && error != os.EOF {
        die(fmt.Sprintf("Error reading response: %s", err.String()))
    }
    if nr >= buf_size { die ("Buffer overrun") }
    response.Body.Close()

    json_text := strings.Split(string(buf), "\000", 2)
    parsed, ok, errtok := json.StringToJson(json_text[0])
    if ! ok {
        die(fmt.Sprintf("Error parsing JSON %s at %s", json_text, errtok))
    }

    fmt.Printf("Your stackoverflow.com reputation is %s\n", parsed.Get ("reputation"))
}

Thanks to Scott Wales for help with .Read ().
This looks fairly clunky still, with the two strings and two buffers, so if any Go experts have advice, let me know.

A: Here's an idiom from the Effective Go page
switch {
case '0' <= c && c <= '9':
    return c - '0'
case 'a' <= c && c <= 'f':
    return c - 'a' + 10
case 'A' <= c && c <= 'F':
    return c - 'A' + 10
}
return 0

The switch statement switches on true when no expression is given. So this is equivalent to
if '0' <= c && c <= '9' {
    return c - '0'
} else if 'a' <= c && c <= 'f' {
    return c - 'a' + 10
} else if 'A' <= c && c <= 'F' {
    return c - 'A' + 10
}
return 0

At the moment, the switch version looks a little cleaner to me.

A: You can swap variables by parallel assignment:
x, y = y, x

// or in an array
a[j], a[i] = a[i], a[j]

simple but effective.

A: Type switches:
switch i := x.(type) {
case nil:
    printString("x is nil");
case int:
    printInt(i);  // i is an int
case float:
    printFloat(i);  // i is a float
case func(int) float:
    printFunction(i);  // i is a function
case bool, string:
    printString("type is bool or string");  // i is an interface{}
default:
    printString("don't know the type");
}

A: When importing packages, you can redefine the name to anything you want:
package main

import f "fmt"

func main() {
    f.Printf("Hello World\n")
}

A: From James Antill's answer:
foo := <-ch     // This blocks.
foo, ok := <-ch // This returns immediately.

Also, a potential pitfall: the subtle difference between the receive and send operators:
a <- ch // sends ch to channel a
<-ch    // reads from channel ch

A: Named result parameters

The return or result "parameters" of a
  Go function can be given names and
  used as regular variables, just like
  the incoming parameters. When named,
  they are initialized to the zero
  values for their types when the
  function begins; if the function
  executes a return statement with no
  arguments, the current values of the
  result parameters are used as the
  returned values.
The names are not mandatory but they
  can make code shorter and clearer:
  they're documentation. If we name the
  results of nextInt it becomes obvious
  which returned int is which.

func nextInt(b []byte, pos int) (value, nextPos int) {

Because named results are initialized and tied to an unadorned return, they can simplify as well as clarify. Here's a version of io.ReadFull that uses them well:

func ReadFull(r Reader, buf []byte) (n int, err os.Error) {
    for len(buf) > 0 && err == nil {
        var nr int;
        nr, err = r.Read(buf);
        n += nr;
        buf = buf[nr:len(buf)];
    }
    return;
}

A: /*
 * How many different ways can £2 be made using any number of coins?
 * Now with 100% less semicolons!
 */

package main
import "fmt"

/* This line took me over 10 minutes to figure out.
 *  "[...]" means "figure out the size yourself"
 * If you only specify "[]", it will try to create a slice, which is a reference to an existing array.
 * Also, ":=" doesn't work here.
 */
var coin = [...]int{0, 1, 2, 5, 10, 20, 50, 100, 200}

func howmany(amount int, max int) int {
    if amount == 0 { return 1 }
    if amount < 0 { return 0 }
    if max <= 0 && amount >= 1 { return 0 }

    // recursion works as expected
    return howmany(amount, max-1) + howmany(amount-coin[max], max)
}

func main() {
    fmt.Println(howmany(200, len(coin)-1))
}

A: I like that you can redefine types, including primitives like int, as many times as you like and attach different methods. Like defining a RomanNumeral type:
package main

import (
    "fmt"
    "strings"
)

var numText = "zero one two three four five six seven eight nine ten"
var numRoman = "- I II III IV V VI VII IX X"
var aText = strings.Split(numText, " ")
var aRoman = strings.Split(numRoman, " ")

type TextNumber int
type RomanNumber int

func (n TextNumber) String() string {
    return aText[n]
}

func (n RomanNumber) String() string {
    return aRoman[n]
}

func main() {
    var i = 5
    fmt.Println("Number: ", i, TextNumber(i), RomanNumber(i))
}

Which prints out
Number:  5 five V

The RomanNumber() call is essentially a cast, it redefines the int type as a more specific type of int. And Println() calls String() behind the scenes.

A: Returning a channel
This is a true idiom that is quite important: how to feed data into a channel and close it afterwards. With this you can make simple iterators (since range will accept a channel) or filters.
// return a channel that doubles the values in the input channel
func DoublingIterator(input chan int) chan int {
    outch := make(chan int);
    // start a goroutine to feed the channel (asynchronously)
    go func() {
        for x := range input {
            outch <- 2*x;
        }
        // close the channel we created and control
        close(outch);
    }();
    return outch;
}

A: for {
    v := <-ch
    if closed(ch) {
        break
    }
    fmt.Println(v)
}

Since range automatically checks for a closed channel, we can shorten to this:
for v := range ch {
    fmt.Println(v)
}

A: Timeout for channel reads:
ticker := time.NewTicker(ns);
select {
    case v := <- chan_target:
        do_something_with_v;
    case <- ticker.C:
        handle_timeout;
}

Stolen from Davies Liu.


text:
Q: Javascript: Losing object reference while reading array items How to read object from array, or what I'm doing wrong?
Here is my array map with object as key:
var nj = new RegExp("nj","g");
var replaceMap = {nj:"ň"};

But while looping the array I can't get valid object reference.
for (var replaceValue in replaceMap) {
   text = text.replace(replaceValue, replaceMap[replaceValue]);
}

When replace is performing then it replaces only one instance of search text - RegExp object modifier for global match ("g") is ignored. I suppose, that I didn't get a valid object reference in replaceValue. When I used nj variable replace operation then it works fine.
Thanks in advance.

A: Reason:
When you refer something like for(var x in o){...}, then x is a javascript string, and not an object.
So in your case it is "nj" and not RegExp object nj
hence only the first match gets replaced.
You can test it like this:
var a=new RegExp("kk","g");
var mymap={a:"jjj"};

for(var k in mymap){
console.log(k+"  "+typeof k);
}

The console output will give you the typeof the key

A: text = text.replace(/nj/g, 'ň');

This should perform the same thing

A: Check this in your browser console (press F12 in Chrome of Firefox):
>var aa="hello";
undefined
>var replaceMap={aa: "Hello2"}
undefined
>replaceMap
Object {aa: "Hello2"}

This is the equivalent code:
var aa="hello";
var replaceMap={};
replaceMap.aa="Hello2";

replace.aa has nothing to do with variable aa
But you can fix it interchanging keys and values in your map:
var replaceMap = {"ň": nj};
for (var replaceValue in replaceMap) {
   text = text.replace(replaceMap[replaceValue], replaceValue);
}


text:
Q: Which Mobius Transforms Preserve Convexity For A Set Of Points Say a set of points is convex position if no point is contained in the convex hull of the others. I am trying to grasp which Mobius Transforms will modify this property.
For simplicity I considered transforms of the form: $f(z) = \frac{1}{z-d}$
So I wrote a program that would take a set of points that were not convex and marked in green the values of $d$ which changed this:

And I wrote a program that would take a set of points that were convex in and mark in green the values of $d$ that changed this.

It seems like the values of $d$ which are contained in an odd number of cicumcircles changes the orientation. Is there an easy way of analytically verifying this? Is there a more general phenomena of which this is an instance?


text:
Q: Interlinking GUI in some other language and Python I have done coding for mathematical simulation of Theory of Computation concepts in Python such as grammar checking and other stuff. My Problem is that I have to build a decent looking GUI for it .
I have looked at PyQt4 and the lack of documentation is really a big deterrent. I have looked at other graphical libraries in Python and they are not helping me so is there a way that I can write the GUI stuff in some other language and integrate python in it.
The problem is that I want mathematical stuff like circles, epsilon on runtime which have drag and drop events available on them. So simply creating an image is not an option.
I am sorry for being a little non specific here but the problem is that I am looking for things that can help here. I have asked a question before too for GUI and unfortunately I could'nt find the right answers for it.
Is there a way I can get around this problem.
Thanks a lot....

A: I'd look again at PyQT4 if you want something decent looking.  PyQt has an an example directory in the source code. KDE uses QT and they have a lot examples too. You have to understand that it is a binding against QT4. When I use it with python I usually just have the QT docs open. Its pretty easy to translate.
You could look at PyGTK also, but again, it is a binding against GTK.

A: Most python guis I recommend tkinter but drag 'n drop isn't built into tkinter yet and I'm not a huge fan of the other libraries.
Have you thought about IronPython in .Net and WPF? You'll need to learn the xaml syntax but it's not much harder than html (technically, it's stricter and simpler but you need to learn some library controls it will instantiate). There are free versions of visual studio for all of this.
Another simple way would be to expose a command line or webservice interface to your python routines.


text:
Q: Не видит TAG в xml Ругается на этот код. Что я делаю не так?
code:
 Fragment fragment = getSupportFragmentManager().findFragmentByTag("Chat");
                if(!fragment.isVisible()){
                    //Log.i(TAG,dataSnapshot.getKey());
                    push(dataSnapshot.getKey());
                }

xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="by.ittech.test_chat.Chat.Chat"
    android:tag="Chat">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
>
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/chat_input_mess"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_toLeftOf="@+id/chat_send"
            android:layout_toStartOf="@+id/chat_send" />

        <Button
            android:text="@string/chat_send"
            android:textSize="11dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/chat_send"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <ListView
            android:id="@+id/chat_list"
            android:divider="@android:color/transparent"
            android:dividerHeight="6dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:stackFromBottom="true"
            android:transcriptMode="alwaysScroll"
            android:layout_above="@+id/chat_input_mess" />
    </RelativeLayout>

</FrameLayout>

Ошибки:
FATAL EXCEPTION: main
    Process: by.ittech.test_chat, PID: 22231
    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v4.app.Fragment.isVisible()' on a null object reference

A: tag View и tag фрагмента - разные вещи. Фрагмент не будет найден по тегу, назначенному для какого то View, ему нужно присваивать собственный тэг через метод FragmentManager, например:
fragmentManager.beginTransaction().replace(R.id.fragment_container, mFragment, TAG);

При выводе фрагмента на экран присваивайте ему тэг, как в методе выше. А проверку на видимость делайте после проверки на NULL:
if(fragment!=null && !fragment.isVisible()){
                //Log.i(TAG,dataSnapshot.getKey());
                push(dataSnapshot.getKey());
            }


text:
Q: BootstrapValidator + PHP : edit data in modal from table I am a lit a bit lost because I didn't find an example to guide me to solve my problem.
I display some data in a tab (contact) with a button (edit) at each line with PHP code.
When I click the button, I open the modal and display the information from the selected line.
Now I would like to validate the form with bootstrapvalidator but the validation doesn't see my modal because the modal is identified with the id of the contact like this : id="myModal<?php echo $contact['id'];?>".
In my jquery script, I don't know how to identify the modal from this id.
Example with a reset password function modal:

            <a class="btn btn-warning btn-sm" data-toggle="modal" data-target="#myModalR<?php echo $user['login']; ?>">
            <a id="del" class="btn btn-danger btn-sm"  onclick="deleteAccount('<?php echo $user['login']; ?>')" >

            <div class="modal fade" id="myModalR<?php echo $user['login']; ?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel<?php echo $user['login']; ?>" aria-hidden="true">

                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
                            <h4 class="modal-title" id="myModalLabel<?php echo $user['login']; ?>">Login : <?php echo $user['login']; ?>

                            <form id="resetPwd" method="post" class="form-horizontal">

                                    Mot de passe*

                                        <input type="password" class="form-control" name="pwd" id="pwd1"
                                            data-bv-identical="true"
                                            data-bv-identical-field="confirmPwd"
                                            data-bv-identical-message="Les mots de passe ne sont pas identiques">

                                    Confirmer le mot de passe*

                                        <input type="password" class="form-control" name="confirmPwd" id="pwd2"
                                            data-bv-identical="true"
                                            data-bv-identical-field="pwd"
                                            data-bv-identical-message="Les mots de passe ne sont pas identiques">

                                (*) champs obligatoires

                                    <button type="button" class="btn btn-default" data-dismiss="modal">Sortir</button>
                                    <button type="submit" class="btn btn-primary">Enregistrer</button>

                            </form>

Javascript :
$(function() {
    $('#resetPwd').bootstrapValidator({
        message: 'Cette valeur n\'est pas valide',
        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },fields: {
            pwd: {
                validators: {
                    notEmpty: {
                        message: 'Champ requis'
                    }
                }
            },confirmPwd: {
                validators: {
                    notEmpty: {
                        message: 'Champ requis'
                    }
                }
            }
        }
    }).on('success.form.bv', function(e){
        e.preventDefault();

        $('#myModalR').modal('hide');


text:
Q: Is the inverse of an invertible circulant matrix also circulant? The circulant matrices in $M_n(F)$ ($F$ field) form a subspace $\mathcal C_n$ spanned by $I,J,J^2,\cdots,J^{n-1}$ where
$$J=\begin{bmatrix} O & I_{n-1}\\1 &  O\end{bmatrix}$$
This subspace $\mathcal C_n$ is also closed under multiplication, which makes it a subring of $M_n(F)$.
Now my question is, if $A\in \mathcal C_n$ and $A$ is non-singular, can we assert that $A^{-1}\in\mathcal C_n$ too?
I'm in particular encouraged to make this guess by observing  these examples:
$$\begin{bmatrix}0 & 1 & 1 & \cdots & 1\\ 1 & 0 & 1 & \cdots & 1 \\ 1 & 1 & 0 & \cdots & 1\\ \vdots & \vdots & \vdots & & \vdots \\ 1 & 1 & 1 & \cdots & 0 \end{bmatrix}^{-1}=\frac{1}{n-1}\begin{bmatrix} 2-n & 1 & 1 & \cdots & 1\\ 1 & 2-n & 1 & \cdots & 1 \\ 1 & 1 & 2-n & \cdots & 1\\ \vdots & \vdots & \vdots & & \vdots \\ 1 & 1 & 1 & \cdots & 2-n \end{bmatrix}$$
and
$$
\begin{bmatrix}
   1 & 2 & 3 & \cdots & n-1 & n \\
   n & 1 & 2 & \cdots & n-2 & n-1\\
   n-1 & n & 1 & \cdots & n-3 & n-2 \\
   \vdots & \vdots & \vdots & & \vdots & \vdots \\
   2 & 3 & 4 & \cdots & n & 1
\end{bmatrix}^{-1}=
\frac1{ns}
\begin{bmatrix}
  1-s & 1+s & 1 & \cdots & 1 & 1\\
  1 & 1-s & 1+s & \cdots & 1 & 1 \\
  1 & 1 & 1-s & \cdots & 1 & 1\\
  \vdots & \vdots & \vdots & & \vdots & \vdots \\
  1+s & 1 & 1 & \cdots & 1 & 1-s
\end{bmatrix}
$$
in which $s:=1+2+\cdots+n$.

A: By Cayley-Hamilton theorem, the inverse of every nonsingular matrix $A$ can be expressed as a polynomial in $A$ of degree $\le n-1$. Therefore, if $A$ is in the linear span of $I,J,\ldots,J^{n-1}$, then $A^{-1}$ is a polynomial in $J$ of degree $\le (n-1)^2$. Since $J^n=I$, it follows that $A^{-1}$ lies inside the linear span of $I,J,\ldots,J^{n-1}$. Hence it is circulant.


text:
Q: Interactive PositionalAudio component in react-three-fiber drei Im making a 3D website and just tried to place audio using PositionalAudio by using react-three-fiber drei. But it's not working due to google new autoplay policy. So I needed to play my website music using the PositionalAudio component and with a play/stop button, which plays and stops the music with the user's command. So is there any way to do an interactive audio player by using the PositionalAudio component in react-three-fiber drei?

A: You have to set some trigger for it. I fixed mine by conditionally rendering it with state.
<Suspense>
    <mesh position={[0, 0, 0]}>
      <boxBufferGeometry attach="geometry" args={[0.1, 0.1, 0.1]} />
      <meshStandardMaterial color="red" />
      {musicZoom && (
        <PositionalAudio autoplay loop = {false} url="/discoSite.mp3" distance={3} />
      )}
    </mesh>
  </Suspense>


text:
Q: Calling ajax function from ajax The following code called when clicked a button and call the insert
_all function that is an ajax function. In success I put an alert but not working the json call liquidations_a_insert_all.jsp is working fine.
$(document).ready(function() {
 $('#click1').click(function(event) {
     var auditorid = $('input:hidden[id=Wauditorid]').val();
     $.ajax({
         type: 'GET',
         url: 'groupauditors.jsp',
         data: {
             Woauditorid: auditorid
         },
         dataType: 'json',
         success: function(data) {
             $.each(data, function(index, element) {
                    var currRow = $("#tr0").clone().appendTo($('#items')).attr('id','tr' + (index + 1));
                    currRow.find('td:eq(0)').html(index + 1);
                    currRow.find('.subgroupid').html(element.subgroupid);
                    currRow.find('.auditorid').html(element.auditorid);

                    insert_all(element.auditorid, "", "");
             });
         }
        });
    });
});

that call the  insert_all(element.auditorid, "", "");
function insert_all(auditorid, onSuccess, onFail) {
 $.ajax({
         type: 'GET',
         url: 'liquidations_a_insert_all.jsp',
         data: {
             Wauditorid: auditorid
         },
         dataType: 'json',
         success: function(data) {
                    alert("insert_all");
//$( 'table tbody tr td:last-child').html(data.inserted);
                    }
     });
 }

Any idea?

A: I hope Using  async:false, in Both ajax Function
$(document).ready(function() {
 $('#click1').click(function(event) {
     var auditorid = $('input:hidden[id=Wauditorid]').val();
     $.ajax({
         type: 'GET',
         url: 'groupauditors.jsp',
         data: {
             Woauditorid: auditorid
         },
         async:false,
         dataType: 'json',
         success: function(data) {
             $.each(data, function(index, element) {
                    var currRow = $("#tr0").clone().appendTo($('#items')).attr('id','tr' + (index + 1));
                    currRow.find('td:eq(0)').html(index + 1);
                    currRow.find('.subgroupid').html(element.subgroupid);
                    currRow.find('.auditorid').html(element.auditorid);

                    insert_all(element.auditorid, "", "");
             });
         }
        });
    });
});

function insert_all(auditorid, onSuccess, onFail) {
 $.ajax({
         type: 'GET',
         url: 'liquidations_a_insert_all.jsp',
         data: {
             Wauditorid: auditorid
         },
         async:false,
         dataType: 'json',
         success: function(data) {
                    alert("insert_all");
//$( 'table tbody tr td:last-child').html(data.inserted);
                    }
     });
 }


text:
Q: Scrapy on AWS EC2 : where to write the items? I have a working spider on my local machine, which writes items to a local postgres database.
I am now trying to run the same spider through scrapyd on an EC2 instance. This obviously won't work, because the code (models, pipelines, settings files) refers to a database on my local machine.
Which adaptations should I implement to make this work ?

A: Found it, answer was easier than i thought. In the settings.py file, delete the settings for ITEM_PIPELINES and DATABASE. After deletion, deploy the project through scrapyd on EC2.
By default, items will now be written as JSON-lines. This can be overridden with FEED_FORMAT and FEED_URI :
sudo curl http:/xxxxxxxxx.us-west-2.compute.amazonaws.com:6800/schedule.json -d project=xxxxxxxxxx -d spider=xxxxxxxxx -d setting=FEED_URI=/var/lib/scrapyd/items/xxxxxxxxxx.csv -d setting=FEED_FORMAT=csv


text:
Q: JAXB marshall elements with comments So I have a class like
@XmlAccessorType(value = XmlAccessType.FIELD)
public class Item {

@XmlAttribute
private String idA;

private String nameA;

@XmlAttribute
private String idB;

private String nameB;

@XmlAttribute
private String idC;

private String nameC;

public Item() {
}

public Item(String idA, String nameA, String idB, String nameB, String idC, String nameC) {
    this.idA = idA;
    this.nameA = nameA;
    this.idB = idB;
    this.nameB = nameB;
    this.idC = idC;
    this.nameC = nameC;
}

@Override
public String toString() {
    return "Item [nameA = " + nameA + ", nameB = " + nameB + ", nameC = " + nameC + "]";
}
}

And its container:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Items {

private List<Item> items;

public Items() {
}

public Items(List<Item> items) {
    this.items = items;
}
}

And I'm using this listener to write comments after each item:
public class AddCommentsListener extends Marshaller.Listener {

private XMLStreamWriter xsw;

public AddCommentsListener(XMLStreamWriter xsw) {
    this.xsw = xsw;
}

@Override
public void beforeMarshal(Object source) {
}

@Override
public void afterMarshal(Object source) {
    if (source instanceof Item) {
        try {
            xsw.writeComment(source.toString());
        } catch (XMLStreamException e) {
        }
    }

}
}

Finally my test class is:
public class Test {
public static <T> void saveToXml(T entity, OutputStream stream) {
    try {
        JAXBContext jc = JAXBContext.newInstance(entity.getClass());
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setListener(new AddCommentsListener(XMLOutputFactory.newFactory().createXMLStreamWriter(stream)));
        marshaller.marshal(entity, stream);
    } catch (JAXBException | XMLStreamException e) {
        System.out.println(e);
    }
}

public static void main(String[] args) throws FileNotFoundException {
    List<Item> items = new ArrayList<>();
    for (int i =0 ;i < 100; i++) {
        String idA = String.format("idA %s", i);
        String nameA = String.format("locationA %s", i);
        String idB = String.format("idB %s", i);
        String nameB = String.format("locationB %s", i);
        String idC = String.format("idC %s", i);
        String nameC = String.format("locationC %s", i);
        items.add(new Item(idA, nameA, idB, nameB, idC, nameC));
    }
    Path path = Paths.get("out.txt");
    saveToXml(new Items(items), new FileOutputStream(path.toFile()));
}
}

And the output:
<items idA="idA 17" idB="idB 17" idC="idC 17">
    <nameA>locationA 17</nameA>
    <nameB>locationB 17</nameB>
    <nameC>locationC 17<!--Item [nameA = locationA 17, nameB = locationB 17, nameC = locationC 17]--><!--Item [nameA = locationA 18, nameB = locationB 18, nameC = locationC 18]--><!--Item [nameA = locationA 19, nameB = locationB 19, nameC = locationC 19]--><!--Item [nameA = locationA 20, nameB = locationB 20, nameC = locationC 20]--><!--Item [nameA = locationA 21, nameB = locationB 21, nameC = locationC 21]--><!--Item [nameA = locationA 22, nameB = locationB 22, nameC = locationC 22]--></nameC>
</items>

But the comment is inside of the element, combined, and only sometimes, any ideas how to have comments after every item, and of course after the element?


text:
Q: Turn on autocompletion in macros I would love to have autocomplete in macros like for example,
#ifdef DEBUG
static void print_debug_info(object obj) {
...
}
#endif

Using a near-default configuration of AppCode, it doesn't appear this is enabled. Is there anyway to enable it?


text:
Q: Typescript (Angular2): Passing objects to functions -> possible memory leaks? I have read that when passing objects as parameters in javascript (also inherited in Typescript) it is passed by reference.
Could that possibly cause memory leaks?
Let's assume a scenario where:

*

*The following component, executes the saveCustomerInfo function

*The function then pushes the object in an array.

*The component gets destroyed.

@Component({
    selector: "customer-details",
    templateUrl: "../html/customerDetails.template.html"
})
export class CustomerDetailsComponent {
  customerData: Customer;

  constructor(private customerService: CustomerService): void {}

  saveCustomerInfo(): void {
    this.customerService.saveCustomer(this.customerData);
  }
}

Wouldn't that cause a memory leak, as the service now has a saved reference of a Component's attribute not allowing the Component to be garbage collected?
In any case, what is the best practice on such calls? Should we only pass temporary objects declared inside the functions via "let" or pass clones created by Object.create()?
Thank you very much in advance,
Dimitris

A: @Component({
    selector: "customer-details",
    templateUrl: "../html/customerDetails.template.html"
})
export class CustomerDetailsComponent {
  customerData: Customer;

  constructor(private customerService: CustomerService): void {}

  saveCustomerInfo(): void {
    this.customerService.saveCustomer(this.customerData);
  }
}

In your example code, based on what you described in the rest of your question, I assume that the customerService.saveCustomer(customerData) call ends up putting its parameter (customerData) into an internal array.
This correctly means that the customerData object won't be garbage collected because now your customerService object has a reference to it. However, although the customerData object can't be garbage collected, the rest of the CustomerDetailsComponent can be garbage collected without an issue - the fact that someone else has a reference to one of its internal properties means that specific property won't be marked for garbage collection, but the rest of the object is still ready for garbage collection (assuming no one else is holding a reference to the component itself).

A: "When Angular sees a component is no longer needed in the DOM, it will destroy the component."
Basically, when the component isn't needed, ngDestroy() is called.
In this isntance, you can actually test to see if the component gets destroyed by implementing the lifecycle hook on the component, making the call to as you do above and then moving to a new view where the component isn't in the DOM.
The component should be destroyed just fine.


text:
Q: How to activate an Excel file without knowing the full name? I am downloading an Excel file which changes name every day with random numbers at the end.
I am taking the data and copying it in my masterfile. I've got the copy/paste.
Is there a way to code it other than Activesheet. I don't want the specific Excel file open and selected when I run my macro as we usually have multiple Excel files open.
Is there a way to select the Excel file without knowing the full name?
Here is the whole code I have:
'*******************************************************************************
' Purpose:    Updates ...
' Change PartialWorkbookName and the value of cStrPartial (the string).
'*******************************************************************************
Sub PartialWorkbookName()
  Const cStrPartial As String = "Task_States_(Pivot)"
  Dim objWb As Workbook
  For Each objWb In Workbooks
    If Left(objWb.Name, Len(cStrPartial)) = cStrPartial Then Exit For
  Next
  If objWb Is Nothing Then GoTo NotFound
  With objWb
'*******************************************************************************
' Code in here

.ActiveSheet.Columns("A:A").Select
'going from horasphere data status+date, making it readable by converting it with the comma and pasting it into your masterfile table.
'have to find a way to have the macro find the file without a name as the name will always change.

    Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
        Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1 _
        ), Array(14, 1), Array(15, 1), Array(16, 1)), TrailingMinusNumbers:=True
    'this top part is to make the data readable by going into Data - Text to columns - etc

    'To copy paste the readable data into the masterfile to run the 1st macro
    Rows("1:1").Select
    Selection.Delete Shift:=xlUp
    'Selects all dirty cell in the worksheet that is currently opened only, may need to tweak this later on
    ActiveSheet.UsedRange.Select
    Selection.Copy

    'pastes it into the blank sheet
    Windows("macro").Activate
    Sheets(3).Select
    Range("A1").Select
    ActiveSheet.Paste

    'deletes the table (have to eventually put that at the beginning of my macro)
    Sheets(1).Select
    Rows("3:3").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Delete Shift:=xlUp

    Sheets(3).Select
    Rows("1:1").Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy
    Sheets(1).Select
    Range("A2").Select
    ActiveSheet.Paste
    Sheets(3).Select
    Cells.Select
    Selection.ClearContents
    Sheets(1).Select

'*******************************************************************************
  End With
  Set objWb = Nothing
Exit Sub
NotFound:
  MsgBox "Workbook not found."
End Sub
'*******************************************************************************

A: Partial Workbook Name
'*******************************************************************************
' Purpose:    Updates ...
' Change PartialWorkbookName and the value of cStrPartial (the string).
'*******************************************************************************
Sub PartialWorkbookName()
  Const cStrPartial As String = "Book_20"
  Dim objWb As Workbook
  For Each objWb In Workbooks
    If Left(objWb.Name, Len(cStrPartial)) = cStrPartial Then Exit For
  Next
  If objWb Is Nothing Then GoTo NotFound
  With objWb
'*******************************************************************************
' Code in here

'*******************************************************************************
  End With
  Set objWb = Nothing
Exit Sub
NotFound:
  MsgBox "Workbook not found."
End Sub
'*******************************************************************************

You can reduce it (not recommended) to this:
'*******************************************************************************
' Purpose:    Updates ...
' Change PartialWorkbookNameReduced and the value of cStrPartial (the string).
'*******************************************************************************
Sub PartialWorkbookNameReduced(): Const cStrPartial As String = "Book_20"
  Dim objWb As Workbook: For Each objWb In Workbooks
      If Left(objWb.Name, Len(cStrPartial)) = cStrPartial Then Exit For
    Next: If objWb Is Nothing Then GoTo NotFound
  With objWb
'*******************************************************************************
' Code in here

'*******************************************************************************
  End With: Set objWb = Nothing: Exit Sub
NotFound: MsgBox "Workbook not found."
End Sub
'*******************************************************************************

Additionally you can put the Dim line in the first line but it exceeds the 80 char limit, so I didn't do it.
EDIT:

*

*In TextToColumns I have removed all arguments with default parameters.

*If you compare this code with your code you can see the logic how    this was done. So if an error occurs you can easily revert the part
  where the error occurred.

*Whatever is happening in the downloaded file is happening on a sheet    named "Sheet1", between the following two lines:

With objWb.Worksheets("Sheet1")

End With

*

*And what's happening in the workbook where this code resides is    happening between the following two lines:

With ThisWorkbook

End With

'*******************************************************************************
' Purpose:    Updates ...
' Change PartialWorkbookName and the value of cStrPartial (the string).
'*******************************************************************************
Sub PartialWorkbookNamedsf()
  Const cStrPartial As String = "Task_States_(Pivot)"
  Dim objWb As Workbook
  For Each objWb In Workbooks
    If Left(objWb.Name, Len(cStrPartial)) = cStrPartial Then Exit For
  Next
  If objWb Is Nothing Then GoTo NotFound
'*******************************************************************************
  With objWb.Worksheets("Sheet1")
    ' going from horasphere data status+date, making it readable by converting
    ' it with the comma and pasting it into your masterfile table.
    ' have to find a way to have the macro find the file without a name as
    ' the name will always change.
    .Columns("A:A").TextToColumns Destination:=.Range("A1"), _
        Tab:=True, Comma:=True, TrailingMinusNumbers:=True, FieldInfo:= _
        Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), _
        Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), Array(9, 1), _
        Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), _
        Array(14, 1), Array(15, 1), Array(16, 1))
    ' this top part is to make the data readable by going into
    ' Data - Text to columns - etc

    ' To copy paste the readable data into the masterfile to run
    ' the 1st macro
    .Rows(1).Delete Shift:=xlUp

    ' Selects all dirty cell in the worksheet that is currently opened only,
    ' may need to tweak this later on
    .UsedRange.Copy

  End With

  With ThisWorkbook

    ' pastes it into the blank sheet
    .Sheets(3).Range("A1").Paste
    ' deletes the table (eventually put this at the beginning of my macro)
    .Sheets(1).Rows(3).End(xlDown).Delete Shift:=xlUp
    .Sheets(3).Rows(1).End(xlDown).Copy Destination:=.Sheets(1).Range("A2")
    .Sheets(3).Cells.ClearContents
    .Sheets(1).Select

  End With
'*******************************************************************************
  Set objWb = Nothing
Exit Sub
NotFound:
  MsgBox "Workbook not found."
End Sub
'*******************************************************************************


text:
Q: argument 2 to map() must support iteration Hi i'm making a basic raycast engine so i think it would be nice to start with the minimap but the problem is that my class map ask for a mapGrid in the constructor and when i pass it python give me this error argument 2 to map() must support iteration
This is the code:
Main part
import pygame
def map(object):
    def __init__(self,grid,scale):
        self.grid= grid
        self.mapWidth= len(grid[0]) #Number of map blocks
        self.mapHeight= len(grid)
        self.miniMapScale= scale #How many pixels to draw a map block
        self.miniWidth= self.mapWidth * self.miniMapScale #Size of the minimap
        self.miniHeight= self.mapHeight * self.miniMapScale

        self.rectGrid= grid

        for y in range(self.mapHeight):
            for x in range(self.mapWidth):
                self.rectGrid[y][x]= pygame.Rect(x,y,self.miniWidth,self.miniHeight)

    def blitMiniMap():
        pass

Data file
mapGrid= [
    [1,1,1,1],
    [1,0,0,1],
    [1,0,0,1],
    [1,1,1,1]
]

size = [640, 480]

map class
import pygame
def map(object):
    def __init__(self,grid,scale):
        self.grid= grid
        self.mapWidth= len(grid[0]) #Number of map blocks
        self.mapHeight= len(grid)
        self.miniMapScale= scale #How many pixels to draw a map block
        self.miniWidth= self.mapWidth * self.miniMapScale #Size of the minimap
        self.miniHeight= self.mapHeight * self.miniMapScale

        self.rectGrid= grid

        for y in range(self.mapHeight):
            for x in range(self.mapWidth):
                self.rectGrid[y][x]= pygame.Rect(x,y,self.miniWidth,self.miniHeight)

    def blitMiniMap():
        pass

Thanks.

A: map is a python built-in function. Using map as a function name thus leads to confusion, so you should consider renaming your map function to something different.
Also, what you call "map class" only defines a function, not a class. Did you perhaps confuse def with class in the class definition?


text:
Q: Datatrigger on empty string How can a DataTrigger change the visibility of stackpanel, based on a binded string?
I have the following Xaml
<StackPanel HorizontalAlignment="Right"
            Orientation="Horizontal"
            Grid.Column="1"
            Background="#FF7a7a7a">
    <StackPanel.Style>
        <Style TargetType="{x:Type StackPanel}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding SearchText}" Value="">
                    <Setter Property="Visibility" Value="Hidden"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>
    Content....
   </StackPanel>

I Know that SearchText gets updates and binds properly outside the StackPanel
Could somebody point me in the right direction?

A: This:
<DataTrigger Binding="{Binding SearchText}" Value="">
   <Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>

will work for empty string (""), however it will not work for null.
Add another DataTrigger for the null case:
<DataTrigger Binding="{Binding SearchText}" Value="{x:Null}">
   <Setter Property="Visibility" Value="Hidden"/>
</DataTrigger>

A: Correct using String.Empty in XAML:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
...
<DataTrigger Binding="{Binding SearchText}" Value="{x:Static sys:String.Empty}">

A: Weird as it might sound, the code below works for me:
<StackPanel Background="#FF7a7a7a">
    <StackPanel.Style>
        <Style TargetType="{x:Type StackPanel}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Text, ElementName=textBlock}" Value="">
                    <Setter Property="Visibility" Value="Hidden"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>
    <TextBox x:Name="textBlock" Text="" Width="100" Height="30"></TextBox>
</StackPanel>

Can you tell the value your Property is sending?

A: Try this
<StackPanel.Style>
                                        <Style TargetType="StackPanel">
                                            <Setter Property="Visibility" Value="Collapsed"/>
                                            <Style.Triggers>
                                                <DataTrigger Binding="{Binding YourBoundPropertyName}" Value="True">
                                                    <Setter Property="Visibility" Value="Visible"/>

                                                </DataTrigger>
                                            </Style.Triggers>
                                        </Style>
                                    </StackPanel.Style>


text:
Q: Issue with a Form Submission on Return Key I am fumbling for reasons for why I can't get this script to work when a "return" key is pressed. The form works when I try to submit via clicking the "GO" button yet not when the "Return" key is pressed via keyboard. I'm a bit outside my comfort zone on this project but about have it working.
https://jsfiddle.net/jbrewlet/9rjhzox5/

Are you in our delivery area?

<form action="action_page.php" method="GET">
    <input type="text" id="zipCode">
   <input type="button" onClick="checkZipcode()" value="GO"></input>
</form>

<p1 id="resultText"></p1>

Thanks for any help you can provide.

A: You can assign an onsubmit event on the form which will run when the form attempts to submit which will include hitting enter when inside the form.  Here is the altered code with changes in comments:

Are you in our delivery area?

<form action="action_page.php" method="GET" id="zipCodeForm">
    <input type="text" id="zipCode">
   <input type="button" onClick="checkZipcode()" value="GO"></input>
</form>

<p1 id="resultText"></p1>

A: Try this.

Are you in our delivery area?

<form action="action_page.php" method="GET">
 <input type="text" id="zipCode">
 <input type="button" onClick="checkZipcode()" value="GO"></input>
</form>

<p1 id="resultText"></p1>


text:
Q: Show that the matrix of T relative to the basis ${1, x, x^2}$ is T is the application defined by $T(a_0 + a_1x + a_2x^2)$ = $a_1x$
Show that the matrix of T relative to the basis ${1, x, x^2}$ is:
$\left[
    \begin{array}{cc}
0 & 0 & 0 \\
0 & 1 & 0 \\
 0 & 0 & 0
    \end{array}
\right]$

A: Every linear transformation can be written in matrix form. Just start with the most general case, i.e.
$$\pmatrix{t_{11} & t_{12} & t_{13} \\ t_{21} & t_{22} & t_{23} \\ t_{31} & t_{32} & t_{33}}$$
with $t_{ij} \in\mathbb R$. Then,
$$T(a_0 + a_1 x + a_2x^2) = (a_0 t_{11} + a_1 t_{12} + a_2 t_{13}) + (a_0 t_{21} + a_1 t_{22} + a_2 t_{23}) \cdot x + (a_0 t_{31} + a_1 t_{32} + a_2 t_{33}) \cdot x^2$$
but we want it to be $T(a_0 + a_1 x + a_2 x^2) = a_1x$. Two polynomials are equal if and only if their coefficients are equal. Hence, we get
$$a_0 t_{11} + a_1 t_{12} + a_2 t_{13} = 0$$
$$a_0 t_{21} + a_1 t_{22} + a_2 t_{23} = a_1$$
$$a_0 t_{31} + a_1 t_{32} + a_2 t_{33} = 0$$
for all $a_0,a_1,a_2 \in \mathbb R$. It follows that all $t_{ij} = 0$ except $t_{22} = 1$. Thus, the matrix of $T$ is
$$\pmatrix{0 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & 0}$$

A: In the basis $\{ 1,x,x^2\}$, the vector $v=a_0+a_1x+a_2x^2$ is represented by the components:
$$v=
\begin{bmatrix}
a_0\\a_1\\a_2
\end{bmatrix}
$$
and
$$u=a_1x=
\begin{bmatrix}
0\\a_1\\0
\end{bmatrix}
$$
So you want a matrix $M$ such that:
$$
\begin{bmatrix}
m_{11}&m_{12}&m_{13}\\m_{21}&m_{22}&m_{23}\\m_{31}&m_{32}&m_{33}
\end{bmatrix}
\begin{bmatrix}
a_0\\a_1\\a_2
\end{bmatrix}=
\begin{bmatrix}
0\\a_1\\0
\end{bmatrix} \quad \forall a_1,a_2,a_3
$$
a simple inspection shows the result.


text:
Q: Ubuntu pl2303 usbserial overflow? I am connecting a currentcost electricity monitor to my ubuntu server and am using the method to connect as described here ...
putting your watts on the web
#!/bin/sh

/opt/bin/head /dev/ttyUSB0 -n1 | /bin/grep '<ch1><watts>' | /bin/sed -e s/\<ch1\>\<watts\>/\ / | /opt/bin/cut -d' ' -f2 | /opt/bin/cut -c1-5

Now, I am also having the same problem as described here ... putting your watts on the web, part 2
The data hangs where the head command pulls the data. It works for a while then randomly stops.
Firstly, I would like to know whether I can virtually unplug and reinsert the USB device /dev/ttyUSB0, so I can at least fix the problem remotely when it happens.
Secondly, what would be the best method of investigating the cause? Alternatively, should I be looking at writing a C program to do this instead? I know very little C, so this would be a challenge.

A: For a C snippet that (purportedly) equals an unplug/replug cycle, see here.

A: Could it be a file permissions issue?  It was for me: PL2303 on Ubuntu 16.04 Default Permission for /dev/ttyUSB0: crw-rw---- I had to run chmod 777 /dev/ttyUSB0 so that my serial terminal (Cutecom) could access the device. If the device is automatically broadcasting data,    connecting it to Cutecom is a good smoke test.


text:
Q: PHP Submit form only if checkbox is ticked I have a problem with a wordpress widget that I developed.
It 's just a form with an email field, a button and a checkbox.
When the user click on submit, I want to verify if the checkbox is ticked and IF YES submit the form...
My problem is that the form is submitted even tough the checkbox is not ticked. The page is reloaded.
Here is a short version of my code :
<?php if(isset($_POST['rules']) && $_POST['rules'] == 'Yes')
{
        echo 'The checkbox was selected';
} else {
        echo 'The checkbox wasn\'t selected';
} ?>

<form id="form-invite" method="post" action="">
    Your friend(s) email :

    <small style="text-transform:uppercase;font-family:Arial;font-size:9px;color:#333;"Multiple emails separated by comma.
    <input class="kolom" type="text" name="email" id="email"/>
    <input class="button-primary classic-button" type="submit" name="send-them" value="Send Invitation"/>
    <input type="checkbox" name="rules" value="Yes" /> I read the Privacy Policy

</form>

A: Add a simple onsubmit handler to the form, e.g.:

Demo: http://jsfiddle.net/vqVEF/


text:
Q: How to typeset a frame with the title across the boundary? How could I typeset a frame like:

?
I've always used mdframed or tcolorbox to typeset frames but I cannot find mention of such functionality.
Is there a simple way of achieving this effect with one of the above-mentioned packages?
If not can we obtain that output with a tcolorbox's skin via tikz?
If not how else could we get that box?

A: Remarks
This solution using tcolorbox was heavily inspired by the "FancyTitle" example in the tcolorbox documentation on page 45.
Implementation
\documentclass{article}
\pagestyle{empty}
\usepackage{tcolorbox,lipsum}
% Inspired by FancyTitle in the tcolorbox-doc page 45
\tcbuselibrary{skins}
\newtcolorbox{mycolorbox}[2][]{%
    enhanced,
    colback=white,colframe=black,
    arc=0pt,outer arc=0pt,
    enlarge top by=\baselineskip/2+1mm,
    overlay unbroken and first={%
        \node[
            rectangle,fill=white,
            inner sep=1mm,anchor=west
        ] at ([xshift=4.5mm]frame.north west) {\strut\textbf{#2}};
    },
    #1%
}
\begin{document}
\lipsum[1]
\begin{mycolorbox}{Variables}
    \[ \frac{}{x_1 : A_1,\ldots,x_n : A_n \vdash x_i : A_i} i \in \{ 1,\ldots,n \} \]
\end{mycolorbox}
\lipsum[1]
\end{document}

Output

A: You could use TikZ for the task:
Code
\documentclass[parskip]{scrartcl}
\usepackage[margin=15mm]{geometry}
\usepackage{tikz}
\usetikzlibrary{calc}

\usepackage{lipsum}

\newcommand{\mybox}[3][black]% [options] title, content
{   \par
    \begin{tikzpicture}
        \node[draw,minimum width=\textwidth,inner sep=5mm,align=center,#1] (tempnode) {#3};
        \node[right,#1,fill=white] at ($(tempnode.north)!0.9!(tempnode.north west)$) {#2};
    \end{tikzpicture}
    \par
}

\begin{document}

\lipsum[1]

\mybox{Test 1}{$\int\limits_{e}^{\pi}\log_2 x\ dx$}

\lipsum[2]

\mybox[very thick,red]{Test 2}{$\int\limits_{e}^{\pi}\log_2 x\ dx$}

\lipsum[3]

\mybox[line width=1mm,densely dashed,cyan!50!lime,text=black]{Test 3}{$\int\limits_{e}^{\pi}\log_2 x\ dx$}

\lipsum[4]

\end{document}

Output

Edit 1:
As the very wide boxes cause overfull hbox warnings, I used \rlap from the mathtools package to reduce their width to zero. This is probably okay for thin frames, but very thick frames might extrude into the margin. Also, now you can influence the text and title separately (and hence go nuts if you like):
Code
\documentclass[parskip]{scrartcl}
\usepackage[margin=15mm]{geometry}
\usepackage{tikz}
\usetikzlibrary{calc}
\usepackage{mathtools}

\usepackage{lipsum}

\newcommand{\mybox}[4]% title, content, options, title options
{   \par
    \vspace{3mm}
    \rlap{%
    \begin{tikzpicture}
        \node[draw,minimum width=\textwidth,inner sep=5mm,align=center,outer sep=0pt,#3] (tempnode) {#2};
        \node[fill=white,right,#4] at ($(tempnode.north)!0.9!(tempnode.north west)$) {#1};
    \end{tikzpicture}}
    \par
}

\begin{document}

\lipsum[1]

\mybox{Test 1}{$\int\limits_{e}^{\pi}\log_2 x\ dx$}{}{}

\lipsum[2]

\mybox{Test 2}{$\int\limits_{e}^{\pi}\log_2 x\ dx$}{red,densely dotted,ultra thick,fill=yellow!30}{text=red,rounded corners=3mm,font=\Huge,circle}

\lipsum[3]

\mybox{Test 3}{$\int\limits_{e}^{\pi}\log_2 x\ dx$}{text=yellow,inner color=blue,outer color=red,rounded corners=10mm}{left color=orange,right color=yellow,rounded corners=3mm,draw}

\lipsum[4]

\end{document}

Output


text:
Q: Flutter google maps fix marker top center map
I need to center the marker in the visible part of the map (Map's actual area fills the whole screen, bottom sheet is above it). AnimateCamera does not help, because it centers the marker within the entire map, and as a result the marker slides downwards and disappears behind the bottom sheet.
Is there a way I could center within the visible part of the map? I don't want to resize the map itself and then center with animateCamera, this seems to create some rendering issues for me.
I searched stackoverflow for similar problems, tried to work out the problem my self but to no avail.


text:
Q: I can change tint colour on UIButton but not UIImage I am playing around with tint colours on a UIImage and a UIButton.
On the UIButton (when the button type is set to System), I am able to set the tint colour of the  UIButton in Xcode by going to Attributes Inspector -> View -> Tint
On UIImageView, I have set the same image, but when I go to the Attributes Inspector -> View -> Tint, the colour of the image does not change.
Why is the behaviour like this ? and how do I fix it ?
I am using iOS 7 and Xcode 5.1.1

A: Your image's rendering mode needs to be set to template and not original. To do this, you can call the -[UIImage imageWithRenderingMode:] method on your image and pass in UIImageRenderingModeAlwaysTemplate, then set your image view's image to the resulting image:
yourImageView.image = [yourImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

Or, in Swift:
yourImageView.image = yourImage.imageWithRenderingMode(.AlwaysTemplate)


text:
Q: Iterating multiple rounds when i don t know how many rounds there are going to be I have researched the different posts and it seems that it is really not recommended to define variable dynamically in python.
i am faced with an issue, I want to analyse multiple rounds (the number of rounds can varry)
I found a way to do it but I find it a little brutal (it involves copy pasting 50 times the same code):
def ProcessRound(Input1,Input2,Input3,Source1):
    #the function process the Source and assign the result to Inputs with the right name
    return Input1,Input2,Input3

StopProcess = 0

Source1 = "Text I want to analyse that may exist or not if doesnt exist it is False"

if Source1 != False:
    Input1Rnd1 = []
    Input2Rnd1 = []
    ProcessRound(Input1Rnd1,Input2Rnd1,Source1)
else:
    StopProcess = 1
    #if this step not valid there are no more steps so want to avoid continuing

if StopProcess !=1:
    Source2 = "Text2"
    if Source2 != False:
        Input1Rnd2 = []
        Input2Rnd2 = []
        ProcessRound(Input1Rnd2,Input2Rnd2,Source2)
    else:
        StopProcess = 1

#there can be many rounds up to 50 but trying to keep question clear

so if I copy and adapt those pargraphs 50 times it works (tested it on the first 5 rounds) but it sounds a bit brute force to me?
Ideally I would much prefer to do something like:
def ProcessRound(i,Sourcei):
    #the function process the Source
    return Input1rndi,Input2rndi,Input3rndi
#here the main difference is the the return variable would be named based on the round number:i

StopProcess = 0
i= 0

while StopProcess != 1:
    Sourcei = "Text I want to analyse where i in the name would change"
    if Sourcei != False:
       LastRoundReached = i
       StopProcess = 1
    else:
       ProcessRound(i,Sourcei)

If i do this I would get all the variable I need to use (input1rnd1, input2rnd1, input1rnd2...) but don t have to copy paste my code 50 times
it is one of my first question on this site and I am trying to follow proper guidelines but don't hesitate to comment if you think this was not appropriate

A: It is still a little unclear exactly what you want to do here.  It seems that the main issue you have is in writing a data-driven solution where the processing code can be written once, and then any number of "rounds" can be processed by defining a data structure containing the input for each round.
I gather that in your example, the input for each round is a single string.  That input is processed, and three resulting values are produced by the process.
Here is an example code that illustrates a clean way of addressing the problem defined above:
sources = [
    "Text I want to analyse that may exist or not if doesnt exist it is False",
    "Text I want to analyse where i in the name would change",
    "Text2"
]

results = []

def ProcessRound(i, source):
    # the function processes the provided source, resulting in three output values
    result1 = f"<result data for round {i}>"
    result2 = f"<more result data for round {i}>"
    result3 = f"<even more result data for round {i}>"
    return result1, result2, result3

# Process each source in turn...
# "enumerate" gives us an index value for each iteration over our list so
# that we don't have to manage an index variable ourself.
for i, source in enumerate(sources):

    # Process the next source value and store the results in our 'results' list
    results.append((source, ProcessRound(i, source)))

# ... later on, process the results.  If you wanted to do this processing
# at another time, you could store the results in a database instead of an
# in-memory list.  That is left as an exercise for the OP :)
for i, result in enumerate(results):

    # Break out the stored result
    source, (result1, result2, result3) = result

    # Here you would process the results of the round however you want.  As an example,
    # here we just print all of the information we have about the round, including the result
    print(f"Result of round {i}:")
    print("   Input:", source)
    print("   Output:", result1, result2, result3)

Result:
Result of round 0:
   Input: Text I want to analyse that may exist or not if doesnt exist it is False
   Output: <result data for round 0> <more result data for round 0> <even more result data for round 0>
Result of round 1:
   Input: Text I want to analyse where i in the name would change
   Output: <result data for round 1> <more result data for round 1> <even more result data for round 1>
Result of round 2:
   Input: Text2
   Output: <result data for round 2> <more result data for round 2> <even more result data for round 2>

UPDATE: I updated my answer per the OPs desire to store the processing results and then utilize the results later on.  Note that I store the original source in each result record so that the exact same processing code as in my original answer can be run later on with no change.  The result is therefore identical.

A: It is a little hard to follow what you are intending (for example, you indicate you would like to return something from the function but you don't use it?) but it should follow three design components:

*Processing Logic
This is the logic you are using against each round of input. I assume this is what your function is for.

    Input1, Input2, Input3 = ProcessRecord(Source)

*Looping Logic
This is where you determine what condition your loop stops with. This is the most confusing part where if Source != False: with contents assigned to Source means it is always true?

Either you are looking for a particular terminating Source:
    if Source == 'terminating':
      break # end loop
    # Processing Logic

or you want to stop when there simply is no more input:
for Source in [Source1, Source2, Source3, ...]:
  # Processing Logic

alternatively you can also record how many:
for LastRoundReached, Source in enumerate([Source1, Source2, Source3, ...]):
  # Processing Logic
# LastRoundReached remains as a variable with the value of the last iteration

*

*Data
The data you are feeding into your loop. Aka, where is your Source coming from? This is also confusing.

If your Source is a line in a file:
with open('filename', mode='rt') as file:
  lines = file.readlines()

for Source in lines:
  # Processing Logic

If your Source is user input:
Source = input('prompt (Enter to exit)>')
while Source:
  # Processing Logic
  Source = input('prompt (Enter to exit)>')

If your Source is hard-coded:
AllSource = [
  `Source1`,
  `Source2`,
  `Source3`,
  ...
]

for Source in AllSource:
  # Processing Logic

I assume, based on your posted code, that you are entirely dealing with strings, but these ways could work otherwise.
To note: I might assume that you want the return of the ProcessRecord to be accumulated so you would want something like:
Input1Accumulated = []
Input2Accumulated = []
Input3Accumulated = []

for Source in ...:
  Input1, Input2, Input3 = ProcessRecord(Source)
  Input1Accumulated.append(Input1)
  Input2Accumulated.append(Input2)
  Input3Accumulated.append(Input3)

A: Not much of an improvment, but you can use exec with f-strings to avoid copy-pasting the code 50 times:
for i in range(1, 51):
    exec(f"if StopProcess !=1:\n"
         f"    Source{i} = 'Text{i}'\n"
         f"    if Source{i} != False:\n"
         f"        Input1Rnd{i} = []\n"
         f"        Input2Rnd{i} = []\n"
         f"        ProcessRound(Input1Rnd{i},Input2Rnd{i},Source{i})\n"
         f"    else:\n"
         f"        StopProcess = 1")


text:
Q: Can you redeploy an Android application via Intellij 9 Ultimate's Android support? I know that eclipse can do this, can Intellij via the new Android support do this?

A: Sure, just Run the application (Shift+F10), IDEA issues pm install -r device shell command and automatically restarts the application. It's the only action you need in order to test the new version of your application because Make is invoked automatically before Run by default.
If you have more than one Run configuration for different emulators (when you want to test under different resolutions and locales), then it's handy to use Alt+Shift+F10 to quickly select the desired configuration from the pop-up before Run.
Emulator is never restarted, just the application is redeployed, so it's really fast.
Note that the Run panel will have only the most recently invoked configuration output, if you want to keep multiple configurations, just Pin the tab in the Run panel. Logcat panel allows to choose the Device from the drop-down menu.


text:
Q: Flutter: Scanned 'Path' On Null I'm trying to upload an image taken using the image picker package to my localhost server using a PHP API.
When the picture is taken, a message in the debug console appears saying "scanned (some path) to null" and the image path isn't saved.
I'd be very grateful if anyone who knows anything about this fills me in on how I can fix it. thank you in advance!
Here's my Relevant code:
-(PHP Backend)inserting an image to the database:

include_once "../../api/patients/create_image.php";
if (
    isset($_POST["id"])
) {

    if (!empty($_FILES["file"]['name']) )
    {
    $image = uploadImage("file", '../images/', 200,600);

    $img_image = $image["image"];

    }
    else{
        $img_image = "";
    }
    $id = $_POST["id"];
    $insertArray = array();

    array_push($insertArray, htmlspecialchars(strip_tags($img_image)));
    array_push($insertArray, htmlspecialchars(strip_tags($id)));

    $sql = "insert into patient_images (image, file_id) values (?,?)";
    $result = dbExec($sql, $insertArray);

    $resJson = array("result" => "success", "code" => 200, "body" => $insertArray);
    echo json_encode($resJson, JSON_UNESCAPED_UNICODE);
} else {
    //bad request
    $resJson = array("result" => "fail", "code" => "400");
    echo json_encode($resJson, JSON_UNESCAPED_UNICODE);
}

unction uploadImage($inputName, $uploadDir  , $thumbnail_width , $image_width)
{
    $image = $_FILES[$inputName];
    //echo "error " . $image['name'] . $image['tmp_name'] . "end;";
    $imagePath = '';
    $thumbnailPath = '';
//  echo "before";
    // if a file is given
    if (trim($image['tmp_name']) != '') {
        $ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];

        // generate a random new file name to avoid name conflict
        $imagePath = md5(rand() * time()) . ".$ext";

        list($width, $height, $type, $attr) = getimagesize($image['tmp_name']);

        // make sure the image width does not exceed the
        // maximum allowed width

        if ($width > $image_width) {
//                  echo "after";
            $result    = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, $image_width);
            $imagePath = $result;
        } else {
            $result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
        }

        if ($result) {
            // create thumbnail
            $thumbnailPath =  md5(rand() * time()) . ".$ext";
            $result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, $thumbnail_width);

            // create thumbnail failed, delete the image
            if (!$result) {
                unlink($uploadDir . $imagePath);
                $imagePath = $thumbnailPath = '';
            } else {
                $thumbnailPath = $result;
            }
        } else {
            // the product cannot be upload / resized
            $imagePath = $thumbnailPath = '';
        }

    }

    return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
}

*

*(Front-end):
 Future<bool> uploadFile(File imageFile, String id) async {
    var stream = http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    var length = await imageFile.length();
    var uri = Uri.parse(path_api + 'patients/insertImage.php');
    print(uri.path);
    var request = http.MultipartRequest('POST', uri);
    var multiPartFile = http.MultipartFile('file', stream, length,
        filename: basename(imageFile.path));
    request.fields['id'] = id;
    request.files.add(multiPartFile);
    var response = await request.send();
    if (response.statusCode == 200) {
      print('ok');
    } else {
      print('nope');
    }
  }

  Future getImageCamera() async {
      var image = await picker.pickImage(source: ImageSource.camera);
      setState(
        () {
          if (image != null) {
            _image = File(image.path);
          } else {
            print('no image selected');
          }
        },
      );
    }