IIS HTTP Error 400 (Invalid Verb) -- corrupted request?

Question: Looking for some help on this one. I'm somewhat limited on what I can share since the app is internal...
Scenario: Web app makes a POST request to /api/shortLink endpoint to get back a short link (think: URL shortening service) to a dashboard within our BI application. The shortlink saves parameter/filter values so the user can return to the same view using the short link.
The shortLink service returns a regular 200 status and the shortLink code. All is well, right? Not so.. The very next HTTP request (GET, POST, doesn't matter) from the page results in an HTTP 400 error (Invalid Verb).
The issue is only happening in Chrome (latest build).
Firefox, IE11, Vivaldi and Safari all work fine.
Initial post request to get a shortLink value (works fine, shortLink is generated and returned:
Request:
POST http://jaxbamaptst1:8000/api/shortlink/?sessionId=4ea65890-dbb2-4757-8f03-c0e3bf306cdf HTTP/1.1
Host: jaxbamaptst1:8000
Connection: keep-alive
Content-Length: 18192
Pragma: no-cache
Cache-Control: no-cache
Accept: */*
Origin: http://jaxbamaptst1:8000
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://jaxbamaptst1:8000/Dashboard/1e4ce64e-31e7-4f9e-96aa-8b9e546ba5c8
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: webapp_sessionid=4ea65890-dbb2-4757-8f03-c0e3bf306cdf; webapp_clientid=27271080-59a9-4c3c-aaef-d8c489414165

"/Dashboard/41c892a0-d83c-4d98-beaa-cee8c656c727?e=false&vo=viewonly&overrides=eyJfX2NsYXNzVHlwZSI6ImR1bmRhcy52aWV3LmNvbnRyb2xzLlZpZXdPdmVycmlkZXMiLCJ2aWV3UGFyYW1ldGVycyI6W10sImRlZmF1bHRWaWV3UGFyYW1ldGVyVmFsdWVzIjpbeyJ2aWV3UGFyYW1ldGVyTmFtZSI6InBhcmFtQ3VycmVudE9yZyIsInBhcmFtZXRlclZhbHVlIjp7Il9fY2xhc3NUeXBlIjoiZHVuZGFzLmRhdGEuQ29sbGVjdGlvbk1lbWJlclZhbHVlIiwidmFsdWVzIjpbeyJfX2NsYXNzVHlwZSI6ImR1bmRhcy5kYXRhLkhpZXJhcmNoeU1lbWJlciIsImNvbXBhdGlibGVVbmlxdWVOYW1lIjoiW0RpbSBFbXBsb3llZV0uW0N1cnJlbnQgT3JnLUNlbnRlci1VTS1UTS1BZ2VudF0uW0NlbnRlcl0uJltSXSZbQ01DXSZbS05YQ01DXSIsImhpZXJhcmNoeVVuaXF1ZU5hbWUiOiJbRGltIEVtcG<<snip rest of overrides. Very lengthy>>

The response is also normal and returns the desired shortLink:
HTTP/1.1 200 OK
Cache-Control: no-store, must-revalidate, no-cache, max-age=0
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: Mon, 01 Jan 1990 00:00:00 GMT
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
Date: Fri, 30 Sep 2016 02:44:21 GMT
Content-Length: 28

"saqecfh3x14wmygknpqnzxwt3w"

Now, no matter what the next call is from the page, the result will be an HTTP 400 - Invalid Verb
The request looks completely normal in Chrome. However, when you look at it in Fiddler, things get a little odd..
Here's a failing request:
JSZVVUAXF1ZU5HBWUIOIJBRGLTIEVTCGXVEWVLXS5BQ3VYCMVUDCBPCMCTQ2VUDGVYLVVNLVRNLUFNZW50XS5BT3JNYW5PEMF0AW9UXS4MW1JDJLTDTUNDIIWIAGLLCMFYY2H5VW5PCXVLTMFTZSI6ILTEAW0GRW1WBG95ZWVDLLTDDXJYZW50IE9YZY1DZW50ZXITVU0TVE0TQWDLBNRDIIWIY2FWDGLVBII6IKNNQYISIMXLDMVSV<<snipped for brevity>>SBGFWC2VKIJPMYWXZZSWIY2HPBGRJDGVTQ291BNQIOJASINVUAXF1ZU5HBWUIOIJBRGLTIGET http://jaxbamaptst1:8000/Link/?shortLink=saqecfh3x14wmygknpqnzxwt3w HTTP/1.1
Host: jaxbamaptst1:8000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: http://jaxbamaptst1:8000/Dashboard/1e4ce64e-31e7-4f9e-96aa-8b9e546ba5c8
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Cookie: webapp_sessionid=4ea65890-dbb2-4757-8f03-c0e3bf306cdf;      webapp_clientid=27271080-59a9-4c3c-aaef-d8c489414165

Note the encoded data (or garbled nothingness?) preceding the "GET" verb. Not surprising that IIS is returning the error 400.
Chrome looks like all was well (except for the 400 response):
Request URL:http://jaxbamaptst1:8000/Link/?shortLink=saqecfh3x14wmygknpqnzxwt3w
Request Method:GET
Status Code:400 Bad Request
Remote Address:127.0.0.1:8888  <<due to Fiddler proxy>>

Ever seen anything like this?
Also, as an aside -- We don't usually use SSL with this app since it is internal. However, I noticed that if I access it using SSL the error does not occur.
Comment: Looks like the second request tries to GET and NOT to POST the request to the API. Normally the endpoint will reject (for security reasons) any GET request.
Comment: Thanks Franco. GET is expected here. It is not an API endpoint. It is an attempt to navigate to the shortlink page.
Answer: Resolved: Finally figured out this morning that this issue was caused by McAfee DLP. Leaving this here in case anyone else runs into a similar situation.
Comment: Under what circumstances does McAfee's DLP do this?
Comment: I wish I knew exactly what aspect of these requests caused the issue. After we determined DLP was the source of the issue, we sent similar information as to what I posted above to McAfee. All we got back was a note with the next release of essentially "try it now."


Anyone know what this wire sticking out of my wall is?

Question: Moved into a new (but old) house recently and found this sticking out of my wall. Any idea what it is? Old telephone or radio wiring assembly?
Comment: First you drive your car into your new house, and then you plug that into the OBD-II port on the vehicle. ;)
Answer: That's the cable and connector used between Verizon FIOS ONTs (mounted outdoors typically) and their indoors-mounted AC-DC power supply and backup battery.
The larger wires carry DC power (from either the AC supply or the battery); the smaller wires communicate status (power failure, battery missing, etc.) between the two units.
Comment: I should have recognized it!


How do I get rid of these leftover flatpak files?

Question: I wanted to try out Tauon Music Box, so I installed the flatpak version, didn't quite like it so I removed it with the following: flatpak uninstall com.github.taiko2k.tauonmb
but when I search for it with: locate tauon I found these files:
/var/lib/flatpak/appstream/flathub/x86_64/7cbba18599d341ff2e031150b5ab4bec37c8dd2474b7d3421094c64f8f86fa1e/icons/128x128/com.github.taiko2k.tauonmb.png
/var/lib/flatpak/appstream/flathub/x86_64/7cbba18599d341ff2e031150b5ab4bec37c8dd2474b7d3421094c64f8f86fa1e/icons/64x64/com.github.taiko2k.tauonmb.png
/var/lib/flatpak/repo/refs/heads/deploy/app/com.github.taiko2k.tauonmb
/var/lib/flatpak/repo/refs/heads/deploy/app/com.github.taiko2k.tauonmb/x86_64
/var/lib/flatpak/repo/refs/heads/deploy/runtime/com.github.taiko2k.tauonmb.Locale
/var/lib/flatpak/repo/refs/heads/deploy/runtime/com.github.taiko2k.tauonmb.Locale/x86_64
/var/lib/flatpak/repo/refs/remotes/flathub/app/com.github.taiko2k.tauonmb
/var/lib/flatpak/repo/refs/remotes/flathub/app/com.github.taiko2k.tauonmb/x86_64
/var/lib/flatpak/repo/refs/remotes/flathub/runtime/com.github.taiko2k.tauonmb.Locale
/var/lib/flatpak/repo/refs/remotes/flathub/runtime/com.github.taiko2k.tauonmb.Locale/x86_64

How do I get rid of those?
Comment: How about deleting them?
Comment: I know, but is there a "fancy" command that would delete them automatically?
Answer: Clean your flatpak installation with:
flatpak uninstall --unused

Add the --delete-data option to also remove user data for which no flatpak is installed anymore.
That will remove unused libraries, etc.
You can also check and repair your installation using
flatpak repair

This will remove invalid objects and reinstall where needed.
Comment: The folder `/var/lib/flatpak/appstream/... ` contains icons for all flathub apps (seemingly all).  I think you can let this remain.  The files in `/varlib/flatpak/repo/.. ` that are not in use may be removed manually. I did that with lollypop music player and no problems yet.  I used  `uninstall --unused --delete-data` and `repair` before doing this.
Comment: I got rid of some other files this way, but the tauonmb still remain untouched
Comment: That is the best I can give you. If uninstall scripts do not otherwise remove remaining directories or files, you may risk to delete them manually. If you break something, the `flatpak repair` command likely will allow you to make the system consistent again. Accept the better answer if it still arrives, but if there is nothing better, then please accept this answer.
Comment: Appreciate the help! I guess I'll delete them manually then.


Combine multiple replace text

Question: I wanna translate English to Vietnamese via javascript:
var text = 'Name, Password and ConfirmPassword';
var _text = text.replace('Name', 'Tên đại diện')
                .replace(/Password|ConfirmPassword/g, 'Mật khẩu');

My question: Is there another way to compress 2 replace into 1?
Just like:
var text = 'Name, Password and ConfirmPassword';
var _text = text.replace(/(Name)|(/Password|Confirmpassword/g)/, ???);

Answer: Using a callback one can return different things depending on what part of the regex matched
var _text = text.replace(/Password|ConfirmPassword|Name/g, function(m) {
    if ( m === 'Name' ) return 'Tên đại diện';
    return 'Mật khẩu';
});

Answer: if you need a few languages or just want to simplify the code I would use json objects to hold the translations and just change the text of the elements with the translation, rather than deal with many regex replacements.

// language translations. this objects key is the element selector
var translations = {
  '#welcome' : {
    english: 'Hello',
    vietnamese: 'chào bạn',
    thai: 'สวัสดี',
    afrikaans: 'Goeie dag'
  },
  '#password' : {
    english: 'Please enter your password',
    vietnamese: 'Vui lòng nhập mật khẩu của bạn',
    thai: 'กรุณาใส่รหัสผ่านของคุณ',
    afrikaans: 'gee jy jou wagwoord'
  },
  '.submit': {
    english: 'Submit',
    vietnamese: 'đệ trình',
    thai: 'ส่ง',
    afrikaans: 'Indien'
  }
};

/**
 * translate a string based on the translations hash object
 *
 * this function will find an element based on the selector and change
 * it's text or placeholder to the selected language
 *
 * @param {string}    language    language to translate text to
 */
function translate( language ){
  return function( e ){
    for( var key in translations ){
      var el = document.querySelector( key ),
          translation = translations[ key ][ language ];

      if( el.placeholder ){
        el.placeholder = translation;
      }
      else if( el.value ){
        el.value = translation;
      }
      else {
        el.innerHTML = translation;
      }
    }
  }
}

// get all the required elements
var
  english    = document.querySelector('#translate-english'),
  vietnamese = document.querySelector('#translate-vietnamese'),
  thai       = document.querySelector('#translate-thai'),
  afrikaans  = document.querySelector('#translate-afrikaans');

// bind the events to the language buttons
      thai.addEventListener('click', translate('thai'), false);
   english.addEventListener('click', translate('english'), false);
 afrikaans.addEventListener('click', translate('afrikaans'), false);
vietnamese.addEventListener('click', translate('vietnamese'), false);
<button id="translate-english">english</button>
<button id="translate-vietnamese">Vietnamese</button>
<button id="translate-thai">Thai</button>
<button id="translate-afrikaans">afrikaans</button>

hello stackoverflow

<input type="password" id="password" placeholder="Please enter your password" />
<input type="submit" class="submit" value="Submit" />
Comment: Nice sample. Thank you!

Combine multiple replace text


Basic definition of orientation/preservation question

Question: I'm reading through do Carmo's book on Riemannian Geometry and reviewing a bit about orientation. He uses a definition of orientation preserving which I find difficult to verify in practice, but perhaps I'm missing something. He says a manifold is orientable if every change of coordinates function has a positive (determinant) Jacobian, and a choice of such a differentiable structure is a choice of orientation.
1) First, I wanted to verify that if $\varphi: M_1 \to M_2$ is a diffeomorphism, then $M_2$ gets an orientation from $M_1$. My argument was: if $y_\beta^{-1} \circ y_\alpha$ is a change of coordinate map on $M_2$, then $y_\beta^{-1} \circ y_\alpha = (x_\beta \varphi^{-1})^{-1} \circ (x_\alpha \varphi^{-1}) = \varphi (x_\beta^{-1} \circ x_\alpha) \varphi^{-1}$ for suitable coordinate maps $x_\alpha, x_\beta$ on $M_1$. Hence the determinant of the Jacobian for coordinate maps on $M_2$ are positive because the ones on $M_1$ are. Does this work?
2) Now how do I actually compare orientations under a map? For example, I want to do the classic exercise of showing the antipodal map $A: S^n \to S^n$ is orientation preserving iff $n$ is odd. I see that the determinant of the Jacobian of $A$ is $(-1)^{n+1}$ (I think Jacobians behave well under restriction?), but I don't see how to use this to compare the induced orientation on $A(S^n)$ using the above formulation.
I would prefer to try to solve this using this level of information, and not bringing anything fancier like differential forms into the picture yet. Thanks.
Comment: You don't need differential forms for orientation, but you do need tangent spaces.  To this end, I would look into Arnol'd's *Mathematical Methods of Classical Mechanics*.
Comment: I certainly can use tangent spaces. I thought that was implicit in the Jacobian language. But I don't want to build up some machinery about differential forms to do this. I'd like to use do Carmo's early definitions to work this out.
Comment: No need for differential forms, but you will need a volume form (the determinant), which requires exterior products.
Comment: Do you mind expanding your comments into an answer? I'd prefer avoiding volume forms as I'm trying to prove this from as close to the definitions as possible, but your solution might be the best that can be done with this somewhat awkward definition.
Answer: Actually, let's even forget about volume forms.
Start with the manifold ${\bf R}^{N}$, regard it as a vector space (in the future, as a tangent space at a point of a manifold), and choose a basis:
$$
{\bf E} = \{{\bf e}^{k} \; : \; k = 1, 2, \ldots, N\}
$$
(in the future, a frame on the manifold), with the qualification that the basis is ordered (say, by the indices $k$).  (For $N$, the order ${\bf e}^{1} = (1, 0), {\bf e}^{2} = (0, 1)$ corresponds to what we know colloquially as the counterclockwise orientation; to help the visual, traverse the points points: ${\bf 0} =  (0,0), {\bf e}^{1} = (1, 0), {\bf e}^{2} = (0, 1)$, in that order).
A linear transformation $A$ which transforms one basis (frame) to another will, therefore, be invertible, hence has a nonzero determinant.  The transformation with a positive determinant is said to $\textit{preserve orientation}$ with a negative determinant, to $\textit{change orientation}$.  (Test this on the 2-D example I gave above.)
Two frames have the same orientation if one is transformed into the other by a transformation with a positive determinant.  This establishes an equivalence relation on the set of frames, with two equivalence classes.  These classes are called orientations.
Hope this sheds light on it.
A source: Mathematical Analysis II, V.A. Zorich


getstatusoutput returning 'unsupported operand type(s)'

Question: I am trying to substitute the values of strings on commands.getstatusoutput, but it gives me the below error:
ping_out = commands.getstatusoutput("ssh %s 'ping -c 2 %s'") % (jmp, ip)

jmp and ip are my string variables.
When I call the above command, it gives me this error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'tuple' and 'tuple'
>>>

How can I fix this?
Comment: Do you mean `ping_out = commands.getstatusoutput("ssh %s 'ping -c 2 %s'" % (jmp, ip))` instead?
Answer: ("ssh %s 'ping -c 2 %s'") % (jmp, ip)

The parenthesis are wrong:
("ssh %s 'ping -c 2 %s'" % (jmp, ip))

The % (jmp, ip) belong to the "ssh %s 'ping -c 2 %s'" string


Is there a possible way to run two .xml files in testng.xml parallel?

Question: I currently have two different TestSuites (SUITE1.XML and SUITE2.xml) with different configurations (e.g browsers, Os)...
I call both SUITES inside testng.xml to run on saucelabs... and it runs fine... Only what I am concerned is, I want these suites to run parallel instead of sequential...
The output i get is

[TestNG] Running:
  /Users/muzamilabbasi/Automation/BaublebarTest/Suite1.xml

This is Browser String FIREFOX
This is Platform String WIN8
This is Version String 25
This is Browser String FIREFOX
This is Platform String WIN8
This is Version String 25
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
Page Title isGoogle
Page Title isGoogle

===============================================
mysuite1
Total tests run: 2, Failures: 0, Skips: 0
===============================================

[TestNG] Running:
  /Users/muzamilabbasi/Automation/BaublebarTest/Suite2.xml

This is Browser String FIREFOX
This is Platform String XP
This is Version String 7
This is Browser String FIREFOX
This is Platform String XP
This is Version String 7
Page Title isGoogle
Page Title isGoogle

I have searched alot of web and mostly answers I got is using ANT {PARALLEL} task I can achieve but how? I need an example.. Please help.
I am using macOS & TESTNG 6.8.6
Answer: Another option is to use a suite-of-suites.  I'll preface this by saying it's been a while since I've worked with this setup, but hopefully you'll find enough detail here to at least get started.
First, you'd define two (or more) suite XML files:
<suite name="Suite1">
    <test name="test1">
        <classes>
            <class name="fully.qualified.ClassName" />
        </classes>
        <methods>
            <include name="method1" />
        </methods>
    </test>
</suite>

and...
<suite name="Suite2">
    <test name="test2">
        <classes>
            <class name="fully.qualified.ClassName" />
        </classes>
        <methods>
            <include name="method2" />
        </methods>
    </test>
</suite>

Then, you'd define a suite-of-suites XML file:
<suite name="suite of suites">
    <suite-files>
        <suite-file path="Suite1.xml" />
        <suite-file path="Suite2.xml" />
    </suite-files>
</suite>

Do note, that the suite-file path value is the relative path from the current suite-of-suites XML file to the XML file you're calling.  If they're in the same directory, simply the file name will suffice.
Additionally, both XML types do support the <parameter> tag.  The standard suite XML will read both at <suite> and in the <test> levels, and I've found that <parameter> tags at the <suite> level on the suite-of-suites XML file will work as well.
Finally, on execution, you'd need only pass in the suite-of-suites XML file as your suite file argument.
EDIT:
Here's how I was able to make my two suites run in parallel.  The trick was setting up my main() method properly.
public class TestRunner
{
    public static void main(String[] args)
    {
        TestNG testng = new TestNG();
        TestListenerAdapter adapter = new TestListenerAdapter();
        List<String> suites = new ArrayList<String>();

        testng.addListener(adapter);
        suites.add(args[0]);
        testng.setTestSuites(suites);
        testng.setParallel("parallel");
        testng.setSuiteThreadPoolSize(5);
        testng.setOutputDirectory("path to output");
        testng.run();
    }
}

Then, on the command line:
java -jar ParallelSuiteDemo.jar SuiteOfSuites.xml

Note, my jar and all xml files were in the same directory with this configuration.  The command line args and <suite-file> entries would need to be configured properly if you wish you use a directory structure.
This yielded my two suite.xml files running in parallel on a Selenium Grid.
There may be better ways of doing this, to be honest.  This is just what worked for me when I was trying to do something similar.
Comment: Hi Tim, I actually tried this configuration with master & slave suites but the problem is, I am using sauce labs to execute my tests, so lets say I have suites called (SUITE1.xml having 20 test cases and SUite2.xml having 20 testcase) both for different configuration, I called them inside my MasterSUite.xml, what I don't get it its run the SUITE1.xml first after completion of SUITE1.xml it runs SUITE2.xml .... What I want is both (SUITE1.xml & SUITE2.xml) to run at the same time
Comment: I see what you're saying.  I'll need to go through some old code to find the specifics, but I did have this working just as you describe what you want to see.  The only difference, though, was I was running on an internal Grid as opposed to Sauce... though I would think Sauce would work with this sort of thing since the configuration is all in the code.  I'll need a few days, but I'll get this back in working order on my end and post my findings in hopes that you can attempt the same with Sauce and get the desired result.  I seem to recall that there was an obscure setting someplace for this.
Comment: I updated my answer to include some new information you may find helpful if you wish to pursue this approach.  With the new configurations, I was able to get two suites to run in parallel on my own Grid.  There may be other/better ways to do this than what I added above... it's just what worked for be back when I was working with suite-of-suite files.  Hopefully this will at least get you started and you can make improvements where you see fit.
Comment: The command should be: `java -jar TestRunner.jar SuiteOfSuites.xml`
Answer: You no need to run suits in parallel....instead you can write two tests in single testng.xml suit and can run it in parallel.
If you want to use two different configurations for different tests (browser/os etc) make that as a parameter in testng.xml and use selenium grid to redirect each threads to appropriate nodes
Have look at the below example
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="Test Suit" verbose="2" parallel="tests">

<test name="Regression Test">
    <parameter name="browser" value="firefox" />
    <parameter name="os" value="win7" />
    <classes>
        <class name="pakagename.classname" />
    </classes>
</test>

<test name="Smoke Test">
    <parameter name="browser" value="chrome" />
    <parameter name="os" value="mac" />
    <classes>
        <class name="pakagename.classname" />
    </classes>
</test>

Also may be you can run two testng.xml suits using ANT or MAVEN. But I prefer 1st one. Please add the below section in pom.xml of your MAVEN project
<build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.17</version>
            <configuration>
                <suiteXmlFiles>
                    <suiteXmlFile>testng1.xml</suiteXmlFile>
                    <suiteXmlFile>testng2.xml</suiteXmlFile>
                </suiteXmlFiles>
                <reportsDirectory>${basedir}/src/test/java/</reportsDirectory>
             <testFailureIgnore>true</testFailureIgnore>
            </configuration>
        </plugin>
      <plugins>
<build>

Comment: Bharat I haven't given it a shot, I am avoiding to use maven as we have ANT, so I will see if I can fit into ANT somewhere, if you could help will appreciate..
Comment: @Muzamil: I have not worked in ANT. You can try 'tim-slifer' solution, invoke it from ANT. To run slave xmls in parallel using master xml add '' in your master xml. Again I am not sure this will serve your purpose, just a hint.
Comment: Thanks Bharat, I will surely try it
Answer: Yes, you can do this by using "suitethreadpoolsize" attribute of testng
<suite-files suitethreadpoolsize="2">
    <suite-file path="suite1.xml" />
    <suite-file path="suite2.xml" />
</suite-files>

Refer the testng's official website for more details
http://testng.org/doc/documentation-main.html#parallel-running
Thanks!
Comment: Can you bit elaborate how did you exactly use the above xml tags? Getting error "Attribute "suitethreadpoolsize" must be declared for element type "suite-
 files"." and not allowing to run.


How does chain fishing work?

Question: How exactly do I chain fish in Pokemon X and Y? Do i have to talk to the super rod fisherman, or what. I fish every time after the last, but I have no way to know if it is working or not. I run at the end of every battle instead of KO'ing due to limited PP.
Comment: That's what the PP O-power is good for ;)
Answer: Simply pick a spot and use any rod.
These actions will cause the chain to break*:

Reeling it in too late/early
No fish biting (use a pokemon with Suction Cups / Sticky Hold ability in the first party slot to reduce the chance of this)
Loading/reloading a map

Entering a building
Using Fly

Ending the game / switching the 3DS off

These actions will not cause the chain to break*:

Running from battle
Catching/Fainting the pokemon
Fishing up a different pokemon
Using Potions / Repels / PP restore from menu
Using a different fishing rod
Equipping the Bicycle / Dowsing Machine / Skates
Moving to another spot on land (within the same map)

Encountering other Pokemon in grass.

Crossing a map boundary as long as it does not involve doors and/or loading a map. (e.g. it is okay to move along the coast of Cyllage City, Lower Route 8, Ambrette Town)
Using Surf and Waterfall

Moving from land to water using Surf
Moving on water
Encountering Water pokemon by moving on water

Using Rock Smash

Encountering pokemon from the Rock Smash

Saving the game (but this doesn't matter because the chain breaks if you switch off the game, so you can't load a save file that maintains the chain).
Closing the 3DS lid (sleep mode)
Pressing the home button (suspended game)

*A Summary on how this information was verified:

Started with a fishing record of 5 consecutive.
Fish 6 consecutive times
Perform the alleged action that will break the chain
Fish another 2 consecutive times
Check against the fisherman in the fishing shack on Route 16

If he reports 6 as the longest chain, then the action that was investigated breaks the consecutive chain. If he reports 8 as the longest chain, then that action does not break the chain.
Comment: Good and useful information, but didn't clearly answer the question.

How does chain fishing work?


How do I repair and block up a completely cut top plate?

Question: I removed some in-wall ducting coming from the attic that fed registers on both sides of the wall. I intend on patching up the drywall of course, but before I do I want to block up the hole in the top plate as seen in the photos, and make sure that it is structurally sound. Studs are 16" on center.
Two questions:

There is existing strapping for the top plate on both sides of the wall, it extends about six inches to either side of the hole in the top plate. Since I don't know the quality of the fastener used to affix the strapping to the top plate and the condition of the strap itself, should I add additional strapping for structural purposes?
Of the several locations that I removed this ducting, most don't have enough top plate exposed between studs to affix blocking to, so it would have to be stud-to-stud, or on top in the attic, but even there the ceiling joists don't provide much room to connect blocking to. Any recommendations for blocking the hole in the top plate?
Answer: The home was presumably built to be sound with the duct in place, so it's still sound with it gone. You don't have to build it better.
Just add blocking as needed to support the drywall. If you happen to have clearance to lay a plate through the entire area and screw it in, great. If not, don't sweat it.
One strategy is to add short legs to a plate before you put it in place, then screw the legs to the adjacent studs. You don't really need to double it, and you can position it at an arbitrary height that makes sense as drywall backing.
<code>ELEVATION (FRONT) VIEW
______                           ________
______|_ _____________________ _|________
______| |_____________________| |________
    | | |                     | | |
    | | |<-- screws --------->| | |
    | | |                     | | |
    | | |                     | | |
    | |_|                     |_| |
    | |                         | |
    | |                         | |
</code>
Comment: It's made it 60+ years, I would assume it's sufficient.
Comment: I was typing adding legs and then nail plates on top from attic but your answer is better, avoids working in attic.
Comment: Thanks for the excellent suggestion. The strategy for blocking seems so logical, I guess my brain just doesn't work quite like that yet. Much appreciated.

When it comes to the structure, I guess what made me question the tie strap adequacy was the fact that our rafters are undersized (2x4s) etc, so that put into question the engineering (or lack thereof) for the rest of the house.
Comment: What makes you say they're undersized? Modern engineered trusses are commonly built entirely with 2x4 even in my snowy climate.
Comment: It's a stick-built roof, no trusses. House was built in 1961.
Comment: @spuck That's what a number of people have told me and I'm starting to believe them :) However, the roof _is_ sagging (which is a problem for another day), so when I see stuff like that it makes me question the rest of the structure. Appreciate your input!
Comment: @isherwood, Should not the inserted horizontal piece be *on top* of the vertical "legs" (as in your first drawing - see edit history), instead of being *inside* them?
Comment: Why? Do you anticipate weight resting on it? It's better as I've drawn it because any actual force is more likely to be _upward_ (additional framing, drilling for wires, etc.), and the screws will hold better in shear.
Answer: There's an even easier solution here if you have a power screwdriver of some sort (better still an impact driver): pocket the screws. Cut your 2x4 to length and screw it into the surrounding top plates.
To put it another way, you take some 3" deck screws and drive them into your 2x4 at an angle about 1" from the ends. This avoids the need for any cleating (like isherwood suggested). I don't see any metal to get in your way.
Comment: Easy enough. Thanks for the suggestion!
Answer: The Building Code requires a lap at top plates of 16" and nailing of two 16d common, or three 3"x0.13" nails, or three 3"x14 gauge staples. (See Table 2304.9.1, item 13.)
This might be easier to install.
Comment: If I'm following you, in an ideal world I'd prefer to do this. However, the ceiling joists are in the way of attaching anything to the top, so any repair would require cutting out the top board of the double top plate and temporarily supporting the ceiling joists. Does that clarify things or am I way in the weeds?


How to use UIDatePicker (countdown timer) to select 0 hour 0 minute?

Question: As per my product specification, I have to let the user to select 0 hour and 0 minutes, I have  tried with date picker but its not allowing( default 1 minute got selected). What to do now? I googled and got to know its not allowed, Is there any other control I can use? If so will it behave like UIDatePicker (with countdown timer mode)? Thanx..
Answer: You can set date picker to 00 programmatically in viewDidLoad:
NSDateComponents * components = [cal components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
  [components setHour:0];
  [components setMinute:0];
  [comps setSecond:0];
  NSDate * date = [cal dateFromComponents:components];
  [self.datePicker setDate:date animated:TRUE];

Comment: Will it allow to select 0 minute 0 hour in GUI?
Comment: no this method does not work! Does not allow 0 to be selected under minutes
Answer: You can use a UIPicker. You can insert data like 0,5,10,15,etc minutes.
Answer: Just set the pickers mode...
[datePicker setDatePickerMode:UIDatePickerModeCountDownTimer];
Then have the desired behavior.
Comment: He's already using that mode. This doesn't solve the problem (setting 0 hours and 0 mins).


Is Rails 3 missing an error translation?

Question: In my en.yml I have this:

en:
  errors:
    format: "%{message}"
    messages:
      blank:        "%{attribute} can't be blank"
      invalid:      "%{attribute} is invalid"
      too_short:    "%{attribute} is too short"
      too_long:     "%{attribute} is too long"
      wrong_length: "%{attribute} is the wrong length"
      taken:        "%{attribute}, {value}, is already taken"

And here's my User model so far:

    validates_presence_of       :username
    validates_uniqueness_of     :username
    validates_length_of         :username,  :within => 4..15
    validates_format_of         :username,  :with => /^\w+$/i

    validates_presence_of       :password
    validates_length_of         :password,  :within => 6..20

When I test random data, all error messages work great, except for the validates_uniqueness_of, which returns the default 'has already been taken'
Thank you very much in advance.
Answer: shouldn't it be
taken:        "%{attribute}, %{value}, is already taken"
with percent sign for value?
I didn't know you could access value, but it makes sense, otherwise that could be username.
I see that taken is the right key, but I still would try without {value} to see if it works.
At last or temporary fix I think you can pass a message in you model validation, something like this should work:
validates_uniqueness_of     :username, :mesage => "#{self.username} is already taken"

but of course you loose a lot of benefits.
Comment: You're welcome, if this solved your problem you should consider to tick this answer as accepted, here on the left under the zero. have fun! - and BTW what solution helped you? the `%` sign?
Comment: Yep, that was it--sorry, I didn't realize the checkbox today, I will start using it.


Timezone in odoo 9

Question: After concatenate date and time field, and result put in new datetime field get 2 hours more than necessary
Example:
date = fields.Date(string = 'date', select=True)
time = fields.Many2one('period.time', string='Available time',select=True)
date_time = fields.Datetime(string='Datetime', compute="_compute")
description = fields.Char(string = 'Descroption', compute="_compute")

@api.onchange('date', 'time') #time is 08:00:00
def _compute(self):
    self.date_time = "%s %s:00" % (self.date,self.time.name)
    self.description = "%s %s:00" % (self.date,self.time.name)

date_time (Datetime) 2017-04-10 10:00:00  --> Wrong
description (Char) 2017-04-10 08:00:00   --> Correct
How fix this issue?
Comment: Time is which type of field in odoo ?
Comment: @EmiproTechnologiesPvt.Ltd. time is Many2one
Comment: Can you write full code of your fields ?
Comment: @EmiproTechnologiesPvt.Ltd. added i  post...
Comment: Can you write class definition of my.time class ?
Comment: @EmiproTechnologiesPvt.Ltd.  https://postimg.org/image/ajm1df46b/
Answer: This is not wrong from odoo side because odoo save date in UTC.When the user request a date odoo convert the date from the database to the timezone of the users.
so if you go to the database you will find that the field is stored date = 2017-04-10 08:00:00 but in the view the date is converted to timezone of the user in your case is converted to 2017-04-10 10:00:00
so before saving the date make sure that you convert the value to UTC datetime i mean don't save 2017-04-10 08:00:00 to date_time but save 2017-04-10 06:00:00
EDITS :
Try this i hope it work id didn't use it but i think it will work if there is any error just put it here:
# first import
from datetime import datetime
import pytz

class ...
    ...
    date = fields.Date(string = 'date', select=True)
    time = fields.Many2one('period.time', string='Available time',select=True)
    date_time = fields.Datetime(string='Datetime', compute="_compute")
    description = fields.Char(string = 'Descroption', compute="_compute")
    ...
    ...

    @api.onchange('date', 'time') #time is 08:00:00
    def _compute(self):
        # by default timezone = UTC
        user_time_zone = pytz.UTC

        if self.env.user.partner_id.tz :
            # change the timezone to the timezone of the user
            user_time_zone = pytz.timezone(self.env.user.partner_id.tz)

        # create time string
        concat_time = "%s %s:00" % (self.date,self.time.name)
        fmt = '%Y-%m-%d %H:%M:%S'

        # create a time object
        user_time = datetime.strptime(concat_time, fmt)

        # define the timezone of the time object
        # here i think the first line is enougth
        user_time = user_time_zone.localize(user_time)
        user_time.replace(tzinfo=user_time_zone)

        # you can get the time in UTC like this
        print "This is what you need to save in database %s ", user_time.astimezone(pytz.UTC).strftime(fmt)

        self.date_time = user_time.astimezone(pytz.UTC).strftime(fmt)

Comment: i used a lot of code you can make it more less see  openerp.fields.Datetime  class you can see how the convert happen
Answer: In the odoo class datetime you can find for the class Datetime the method,
def context_timestamp(record, timestamp):

You can use this method to convert you Datetime in UTC to the timestamp of the user like this.
You need import this 2 packages
import datetime as DT
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT as DF

and after do this.
date = fields.Date(string = 'date', select=True)
time = fields.Many2one('period.time', string='Available time',select=True)
date_time = fields.Datetime(string='Datetime', compute="_compute")
description = fields.Char(string = 'Descroption', compute="_compute")

@api.onchange('date', 'time') #time is 08:00:00
def _compute(self):
       date_utc = DT.datetime.strptime(self.date, DF)
       date_tz = fields.Datetime.context_timestamp(self, date_utc)
       self.description = date_tz.strftime(DF)

Timezone in odoo 9


Need help in Django 2x ,( FOREIGN KEY constraint failed )

Question: hi everyone i made a simple modeland my problem is when i try to make a FOREIGN KEY in my model it shows me this error message , it would be awesome if you can help
here is the code
Model.py:
from django.db import models
from django.utils import timezone

# Create your models here.
class category(models.Model):
    title=models.CharField(max_length=100,default='')
    def __str__(self):
        return self.title
class gigpost(models.Model):

    title=models.CharField(default='',max_length=100)
    Category=models.OneToOneField(category,on_delete=True,default='')
    published_at=models.DateTimeField(auto_now_add=True)
    description=models.TextField(default='',max_length=None)
    mainphoto=models.ImageField(default='')
    photo=models.FileField()
    def __str__(self):
        return self.title

Admin.py
from django.contrib import admin
from .models import gigpost , category

# Register your models here.
admin.site.register(gigpost)
admin.site.register(category)

the error message :
IntegrityError at /admin/gigpost/category/add/
FOREIGN KEY constraint failed
Request Method: POST
Request URL:    http://127.0.0.1:8000/admin/gigpost/category/add/
Django Version: 2.2.5
Exception Type: IntegrityError
Exception Value:
FOREIGN KEY constraint failed
Exception Location: C:\Users\Madara\Miniconda3\envs\myEv\lib\site-packages\django\db\backends\base\base.py in _commit, line 240
Python Executable:  C:\Users\Madara\Miniconda3\envs\myEv\python.exe
Python Version: 3.7.6
Python Path:
['C:\\Users\\Madara\\Desktop\\empliya\\empliya',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\python37.zip',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\DLLs',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\lib',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv',
 'C:\\Users\\Madara\\Miniconda3\\envs\\myEv\\lib\\site-packages']
Server time:    Tue, 18 Feb 2020 19:34:39 +0000

Answer: category=models.OneToOneField(Category, on_delete=models.PROTECT, default='')

instead of
Category=models.OneToOneField(category,on_delete=True,default='')

also class name should be in uppercase:
class Category(models.Model):
class Gigpost(models.Model):


Filtering overlapped rows in data frame based on majority count of labels

Question: How to filter duplicated rows with overlapped labels? I need a subset of Dataframe where duplicated rows are replaced with one row for which label count is max.
Consider a dataframe df:
df = pd.DataFrame({
 'X' : [1, -1, 1, 1, 3, -2, -1, -1],
 'Y' : [2, 3, 2, 2, 2, -1, 3, 3],
 'label' : [0, 1, 1, 0, 2, 1, 2, 2]
})

After filtering, the following subset df_output is expected
df_output = pd.DataFrame({
 'X' : [1, -1, 3, -2],
 'Y' : [2, 3, 2, -1],
 'label' : [0, 2, 2, 1]
})

Answer: I think you are looking for groupby mode i.e
df.groupby(['X','Y'])['label'].apply(lambda x : x.mode().values[0]).reset_index()

Output :

  X  Y  label
0 -2 -1      1
1 -1  3      2
2  1  2      0
3  3  2      2
Comment: Ohk you need mode I think. Hope my solution helps. Its better we clear this comment section,
Comment: Do vote when you get enough reputation. You can delete the comments now na. They are really lengthy


ListView loads images but wont scroll

Question: The following Container is inside a Columnd. I just added the following portion of code because I think it is the only relevant part for this issue (I hope so).
When the ListView is added, the images are loaded and shown. However, scrolling is not enabled and not all images can be rendered. I don't know if this problem is related to the way I am using ListView, or related to using it on a GetX Obx.
My flutter version is
[✓] Flutter (Channel stable, 2.5.0, on Ubuntu 20.04.3 LTS 5.11.0-34-generic, locale en_US.UTF-8)
Any ideas?
Container(
                    height: 180,
                    child: Row(
                      children: [
                        Expanded(
                          child: Obx(() {
                            if (editProductController.imgDataList.value != []) {
                              final imgWidgets =
                                  editProductController.imgDataList.value
                                      .map(
                                        (imgData) => Container(
                                          width: 180,
                                          child: Image.memory(
                                            imgData,
                                            fit: BoxFit.cover,
                                          ),
                                        ),
                                      )
                                      .toList();
                              return Container(
                                width: 100,
                                child: ListView.builder(
                                  padding: EdgeInsets.all(8),
                                  itemCount: imgWidgets.length,
                                  scrollDirection: Axis.horizontal,
                                  //physics: AlwaysScrollableScrollPhysics(),
                                  itemBuilder: (context, index) =>
                                      imgWidgets[index],
                                ),
                              );
                            } else {
                              return Center(
                                child: Image.asset(
                                  'assets/images/image_placeholder.jpg',
                                ),
                              );
                            }
                          }),
                          flex: 2,
                        ),
                        Expanded(
                          child: Container(
                            height: 60,
                            child: CustomButton(
                                text: product != null
                                    ? "Modificar Imagenes"
                                    : "Agregar Imagen",
                                onTap: () async {
                                  try {
                                    List<XFile>? pickedFiles =
                                        await ImagePicker().pickMultiImage();
                                    if (pickedFiles != null) {
                                      final imgDataList = <Uint8List>[];

                                      for (final pickedFile in pickedFiles) {
                                        final imgData =
                                            await pickedFile.readAsBytes();
                                        imgDataList.add(imgData);
                                      }

                                      editProductController.imgDataList.value =
                                          imgDataList;
                                    } else {
                                      throw Exception(
                                          'No se pudo cargar las imagenes');
                                    }
                                  } catch (e) {
                                    Get.snackbar(
                                      'Error cargando las imagenes',
                                      e.toString(),
                                    );
                                  }
                                }),
                          ),
                        ),
                      ],
                    ),
                  )

Answer: Flutter 2.5 update
Please add those codes for your horizontal scrolling
// Set ScrollBehavior for an entire application.
MaterialApp(
  scrollBehavior: MyCustomScrollBehavior(),
  // ...
);

class MyCustomScrollBehavior extends MaterialScrollBehavior {
  // Override behavior methods and getters like dragDevices
  @override
  Set<PointerDeviceKind> get dragDevices => {
        PointerDeviceKind.touch,
        PointerDeviceKind.mouse,
      };
}

Another approach
MaterialApp( scrollBehavior: MaterialScrollBehavior().copyWith( dragDevices: {PointerDeviceKind.mouse}, )

For more visit this link
Comment: Thank you! Corre solution.
Comment: your are welcome, happy coding!

ListView loads images but wont scroll


How can explode elements randomly?

Question: This is my code:
function get_random(){
    $filter_word     = '1,2,3,4,5,6,7,8,9';
    $array = explode(',', $filter_word);
    $randomKeys = array_rand($array, 2);
    $str = '';
    foreach($randomKeys as $key){
        $str = $array[$key];
    }

    return $str;
}

The problem that if I used array_rand i must know the number of elements to can add the number in array_rand and I can't know something like this (it's a data stored into the database) so if the elements are less than two it gives me an error:

Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array

Is there a better way to make this?
Comment: `shuffle($array)` then `array_pop($array)` for each random element you want.
Comment: `function get_random($arr) { return $arr[array_rand($arr)]; }`
Comment: @AlexHowansky  can you give me an example, please?
Answer: I suppose you are looking for something like this:
$randCount = rand(1, count($array));
$randomKeys = array_rand($array, $randCount);

Answer: you can use count() before using array_rand-
function get_random(){
    $filter_word     = '1,2,3,4,5,6,7,8,9';
    $array = explode(',', $filter_word);
    $str = '';
    if(count($array)>1){
       $randomKeys = array_rand($array, 2);

       foreach($randomKeys as $key){
           $str = $array[$key];
       }
    }
    else{
            $str = $filter_word;
     }
    return $str;
  }

Comment: The same thing if it's only one element it's give me a error: Warning: array_rand(): Second argument has to be between 1 and the number of elements in the array
Comment: Error changing to: Warning: Invalid argument supplied for foreach()
Comment: that means you have single data, may be you could try limiting divide by 2, see the updated answer
Comment: Yes, i know this and this is my problem I want if there is only one element then get and not print an error.
Comment: @John I have made your answer completely, make a try
Comment: Thank you but there's another error: Parse error: syntax error, unexpected '[', expecting '('
Comment: which line you having this problem??
Comment: $str = array[0]; and i think thats because my php is 5

How can explode elements randomly?


What is the relationship between Unity, Gnome, Gnome 3, Compiz, Metacity, and LightDM?

Question: I am learning about Graphical User Interfaces in Ubuntu and constantly come across different terms, which cause a lot of confusion for me. I have tried reading easy-to-understand tutorials about the relationship between the named packages, but I don't have a complete picture.
LightDM appears as a service on my installation and is a 'Window Manager', how is this related to Compiz, which is also a Window Manager but not a service? Is Metacity also a Window Manager?
Then there comes Gnome 3, Unity, Gnome Shell and Gnome - all of which seem to be different things. Please help me understand the relationship between all this terminology.
Answer: You only need to know 4 terms:

Display manager
Window Manager
Graphical User Interfaces (GUI)
Desktop Environments

Display manager
Examples are LightDM, GDM, KDM, and LXDM. They normally have display manager somewhere in their names.  These start the X server at boot and provide a login screen.  They often let you select a window manager and/or desktop environment as part of logging in.
Window Manager
Compiz, Metacity, Mutter, W9dk, fluxbox are window managers. There are too many to list.  If you want you can check all the packages that provide x-window-manager to get an incomplete list of the window managers in Ubuntu. These only are responsible of drawing the application borders, managing the position of the windows, themes and decorations.
Grapical User Interfaces (GUI)
Anything that the user interacts with in any graphical way, with icons and representations. Window Managers, Display Manager and Graphical shells, applications, etc. falls in this category. Whatever the user is using that is represented predominantly in a graphical way is a GUI.
Desktop Environments
In the Linux world, it's referred to as a set of applications, packages, services, etc. that provides a complete and balanced ecosystem for the user. Unlike Window Manager or Desktop Manager, Desktop Environments take care of everything. From the login screen through your mail application, the network manager, text editor, the system settings, image viewer, file manager, etc. There are 4 well known Desktop Environments in Linux and Ubuntu:

GNOME
KDE Desktop Environment
LXDE: Lightweight X11 Desktop Environment
XFCE Desktop Environment

These all have a complete set of applications, settings, services, desktop/file/window managers, internet browser, etc.

So, to address your specifics concerns:

LightDM appears as a service on my installation and is a 'Window Manager'

False, LightDM is a Display Manager.

how is this related to Compiz, which is also a Window Manager but not a service?

Have nothing in common. Both have different functions. Compiz is a window composer, window decorator, a window manager.

Is Metacity also a Window Manager?

Yes.

Then there comes Gnome 3, Unity, Gnome Shell and Gnome - all of which seem to be different things.

Gnome 3, Gnome Shell and Gnome are terms used colloquially as the same thing. Unity is totally different. Unity is another shell opposed to Gnome/3/Shell. Gnome 3 Shell has been commonly called as Gnome Shell in the past, right now saying GNOME, GNOME 3 Desktop Environment or Gnome Shell carry the same meaning.
Comment: I am not doubting your answer, I am asking follow-up questions to help resolve my confusion.
Comment: @jesterII each question should be searchable and answerable by all the community. You can reference this answer with your new question so the whole community know from where you are coming from. If you don't have any doubt about *this* answer and your question is just a follow up then ask a new question.
Comment: @zuba http://unix.stackexchange.com/a/149294/41104
Comment: Thanks! When I browse through the gconf database, however, I find an entry for /desktop/gnome. However, as far as I know I am using Unity on Ubuntu 12.04. Why then, does gnome exist in the database?
Comment: @jesterII Unity is a shell which use Compiz/Gnome.
Comment: Then how come [comparisons between Unity and GNOME 3 Shell](http://lifehacker.com/5853099/linux-desktop-faceoff-gnome-3-vs-ubuntu-unity) make sense, if Unity is a shell that uses Gnome?
Comment: @jesterII seem like you have many doubts. I suggest you asking a separated question for each of those doubts.
Comment: @jesterII I strongly suggest looking at the [Wikipedia page for Unity (user interface)](https://en.wikipedia.org/wiki/Unity_(user_interface)). I believe it will answer your remaining questions about Unity/Gnome.
Comment: Unity is **another shell** opposed ... Ok, and what is a shell and how it relates to Window Manager, Display Manager, and Desktop Environment ?


NSURLSession Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"

Question: I am downloading the file in background using NSURLSession background session configuration.
- (void)initBackgroundSession {

    self.backgroundSessionManager = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:IELBackgroundSesssionCourseDownload] delegate:self delegateQueue:[NSOperationQueue mainQueue]];

    [self updateCurrentDownloadingCourse];
    self.isSuspendcourseDownloadTask = false;
}

- (void)updateCurrentDownloadingCourse {

[_backgroundSessionManager getTasksWithCompletionHandler:^(NSArray<NSURLSessionDataTask *> * _Nonnull dataTasks, NSArray<NSURLSessionUploadTask *> * _Nonnull uploadTasks, NSArray<NSURLSessionDownloadTask *> * _Nonnull downloadTasks) {

    NSLog(@"Count of DownloadTask %lu",(unsigned long)downloadTasks.count);
    for (NSURLSessionDownloadTask *downloadTask in downloadTasks) {

            NSDictionary *customDescription = [downloadTask getCustomTaskDescription];
            NSString *courseId = customDescription[IELCourseJSONKeyCoureID];
            if (courseId) {

                [self setDownloadingCourse_id:courseId];
                [self setCourseDownloadTask:downloadTask];
                break;
            }

            [downloadTask resume];
    }
}];
}

Now the issue is if a download is in progress and i close the application from background by pressing home button twice. And then if i reopen the application. Then all download starts failing with given below error message. If i re-add a download task in the NSURLSession object even then it fails till i close application from background and reopen the application.
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error

Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory" UserInfo={NSErrorFailingURLKey=https://ilmsdevqa.inspiredlms.com/Content/Organizations/1544/ScormCourses/offline/2970-offline.zip, NSErrorFailingURLStringKey=https://ilmsdevqa.inspiredlms.com/Content/Organizations/1544/ScormCourses/offline/2970-offline.zip}

Comment: i did not found any solution for this issue. But this issue mostly happens when i have debugger attach.
Comment: I am also facing the similar issue :(
Comment: facing the same issue
Comment: I too facing the same, Any success?
Answer: If you force-quit the app, all background downloads will be canceled and generate this error. It's in the docs.
(Guessing that's what you mean by "I close the application from background by pressing home button twice")
Comment: the issue is that on next launch of the application does not allow to start downloading again, and each next download fails with same error.
Comment: on the next launch you get the errors for cancelling downloads by force-quit - so that is not an error. BUT it should allow you to start new ones. It looks like in the code that you are trying to re-use failed tasks, this could be the error.
Answer: I had a similar issue, not the exact same, but found this questions through a Google search - here's the error code and one solution.
Error Domain=NSCocoaErrorDomain Code=260 "The file "PlugIns" couldn't be opened because there is no such file." ...  NSUnderlyingError= ... {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

Fix: Sign the app with an Apple Developer Id -
https://developer.apple.com/developer-id/
Hack-fix:
sudo spctl --master-disable

Answer: In my case, the same error appeared when I changed connected device and  ran the app thru Xcode on another iPhone. Quitting Xcode and opening again solved the issue and the app now runs normal on the new device.


What are the steps to build a bathroom in my basement

Question: I want to build 2 bathrooms and a kitchen in my basement
I am trying to do the stuff that I can do by myself and get a prof plumber to help with the stuff that I cannot do.
I also want to prepare by buying goods that I will need in advance (Vanity, Toilet, Shower).
I also have not made my mind yet on if I am going to build the shower (tiles) or get a shower base (which is cheaper and easier to install)
I want to know the steps of doing that so I can prepare.
I am thinking like this (correct me if i am wrong)
1- Rough Plumbing for the shower, toilet and vanity
2- pipes for shower, toilet and vanity on the wall
3- bathroom tiles
4- Shower tiles (or install shower base, bath tub)
5- install shower, toilet and vanity
Comment: What about framing the walls and electric (lights, GFCI outlet)?
Comment: @SteveSh, see i missed some stuff, can you help me with identifying the processes needed in order?
Comment: You can do all of the plumbing yourself. Just not as quickly and you would need some tools. You need to figure out your local regulations. Out here in the Wild West we can do our own plumbing work without having a licensed plumber involved whatsoever in the process. There exist jurisdictions where anything beyond repairing a p-trap below the sink is a misdemeanor.
Comment: Where is the intended location relative to the existing drains? You may need to plan for an ejector pump.
Answer: A lot depends on what's already there.
When I did my basement bathroom (with shower), the drain for the shower and the toilet were already there in the floor.
So I first framed the walls (including a doorway), then ran the pipes for the sink, toilet & shower through the studs and stubbed them out.  I also installed shut off valves on the hot and cold water feed coming into the bathroom.
Then I ran the electric, insulated the walls, and installed the shower pan.  That was followed by the drywall and floor (tile over concrete in my case) and the shower surround.  I installed trim as needed, painted everything, and finally installed the vanity and toilet.
I think that's it.  I'll update the answer if more things come up.


How do I fix a leak in my sink's drain pipe?

Question: Started facing a water leak issue on pvc pipe under the bathroom sink. I am new to this and never fixed this before.
How do i fix this leak ? Any help will be greatly appreciated.

Thanks.
Comment: Find out exactly where leak is coming from.  For a drain pipe, it seems like the pipe and sink should be full of water(blocked) for that much of a leak.
Comment: Finding the source of a leak isn't rocket science. Dry the area thoroughly and run some water. Stop back when you have a more specific question.
Answer: It looks like the source of the leak is up high. You could try simply tightening that threaded joint. If it's difficult to tighten then it could be cross-threaded.
If tightening it doesn't work then make sure your sink is not clogged, unscrew that joint, re-seat it, and screw it back together.

Additionally, if your sink is clogged and has standing water then unclogging it could make the problem go away.
Comment: @longneck, that belongs in an answer or in a comment on the question. It's not relevant to this answer.
Comment: I had a similar leak months ago. The plastic drain in the bottom of the sink bowl was cracked. The crack was completely invisible until I disassembled the drain.


Automatically Generate Word Documents

Question: A real estate agent asked me to create a program to automate the process of generating rental agreement contracts. Basically the whole document is the same for most parties but only a couple of lines change (date, addresses, social security numbers, names, etc.).
Ideally they'd fill out a form with that information, press a button and then the contract is automatically generated.
I've worked with a few java libraries to create excel documents in the past but I was wondering what would be the best approach to create something like this? Probably doing a java GUI with the form to then export into word might be an overkill (considering that it needs to follow a template design with logos, specific fonts and size)? Or would programming a plugin for Word in VBA or C# be able to do the trick? Or maybe there is a simpler way that I haven't thought of yet.
Thanks again for you input!
Comment: I have done something similar with Docx4j (http://www.docx4java.org/trac/docx4j). I created .docx template and injected custom XML with data using this library. The result was perfect.
Comment: Maybe this answer can help you too http://stackoverflow.com/questions/15446805/how-to-create-a-new-word-from-template-with-docx4j
Comment: My overview of different approaches:- http://www.slideshare.net/plutext/document-generation-2012osdcsydney
Answer: Mail merge? That's what i think first and foremost.
You can also use macro from other .doc processing software and use the macro like OpenOffice.
Reference.
Comment: I'll check this out later today and see if it works for their needs! Thanks!
Answer: We developed our own library and recently published it at GitHub: https://github.com/wte4j/wte4j. We are using word documents with content controls as templates. Feel free to have a look at it.
Answer: You can use AceOffix to do this.

Make the rental agreement contract template. insert bookmarks (such as: date, address, social security number, name, etc.) in template
Call the method OpenDataRegion ("BookmarkName").Value= "XXXXXXX", to assign value to the bookmarks in the contract template

Note: AceOffix opens Word files in the client browser for online processing, so MS Office must be installed on the client computer.

Automatically Generate Word Documents


Do i need Drivers for Ubuntu 20.10

Question: i am using a dell inspiron with a single boot ubuntu 20.10 x64 (bios), and intel cpu and a switchable amd hd 8670
i was checking out some ubuntu articles(i am new to linux and had some free time) and found a good gnome-shell extension "cpu power manager" , though i didn't instal it (i dont wanna mess up with anything as i have seen glitched screens and buzzing sound on windows10 due to intel_driver issues)
amd(https://www.amd.com/en/support/graphics/amd-radeon-hd/amd-radeon-hd-8000-series-oem/amd-radeon-hd-8670) and intel both provide separate install-able drivers for my pc , though dell support site says that all needed ones come with Ubuntu itself.. shall i install them?
i remember when i had windows 10(on same pc) i had to install intel then amd then management then chipset then audio then wifi & bluetooth and touchpad drivers...(urhh what a mess it was!)
i am new to ubuntu and so, confused. BTW my current ubuntu install works perfectly fine(i only installed the updates and some apps through snapstore, till now)
Comment: The maker of the PC says you do not need to install them. I would follow that advice.
Comment: Just FYI, but drivers are strictly called (operating system theory) *kernel modules*, ie. the need to match the kernel in use. Microsoft want payment to write modules for hardware, so it's up to the makers (OEMs) themselves usually (ie. added later). Linux being open-source allows makers of components to freely add any required code to Linux meaning software works the second of release of the chipset (intel & major makes tend to like this, especially with enterprise grade hardware). For gamer hardware though they prefer secrets (closed-source) and cheaper consumer grade don't even bother..
Answer: You have no errors you have no programs not working correctly the machine starts with out error.
The maker of the PC says you do not need to install them. I would follow that advice

Do i need Drivers for Ubuntu 20.10


Unable to bulk upload log data in ArangoDB?

Question: I need to bulk upload the log data in ArangoDB. It is not in JSON and CSV format, its a log data in gz format.

18.104.22.168 - - [19/Jun/2015:16:02:45 +0000] "GET /origin-cdn.firstcry.com/brainbees/images/products/thumb/506739a.jpg HTTP/1.1" 200 21514 "-" "Mozilla/5.0 (Linux; Android 4.4.4; XT1022 Build/KXC21.5-40) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36" "-"
  22.214.171.124 - - [19/Jun/2015:16:02:45 +0000] "GET /origin-cdn.firstcry.com/brainbees/images/products/bigthumb/555258a.jpg HTTP/1.1" 200 34903 "-" "Dalvik/2.1.0 (Linux; U; Android 5.0.2; AO5510 Build/LRX22G)" "-"
  188.8.131.52 - - [19/Jun/2015:16:02:45 +0000] "GET /origin-cdn.firstcry.com/brainbees/images/products/bigthumb/555401a.jpg HTTP/1.1" 200 32334 "-" "Dalvik/2.1.0 (Linux; U; Android 5.0.2; AO5510 Build/LRX22G)" "-"

Even when we are trying for uploading single file through Arangosh then too it is not uploading and generating error that format is invalid.
I have daily data of 2 GB to upload and process, how can I do through ArangoDB?
As I have gone through documents of ArangoDB and found the bulk upload for only JSON. Any help with how to upload and process the same will be grateful?
Answer: ArangoDB only supports bulk upload of JSON, CSV, or TSV. Therefore you need to convert the log file. I good starting point is google. For example, there is a project called "log2json":
<code>https://github.com/kadnan/logs2json
</code>
with some minor tweaks you should be able to generate lines of JSON (the above project creates one large JSON, which is not what you want).


multi language web application in angular and laraval

Question: I am creating a project using angular for frontend and laraval for rest apis..In my application i have feature to change the web page to some other language. I know there is module ngx-translation which is for angular to convert web pages.but i don't know how to convert the user data which is coming from server..
I have implemented ngx-translation to covert the web pages but i have problem while converting server data like user info..
Can someone please suggest what is best idea to make multi language web application or there is any tool which can convert the web pages to some other language
Comment: What did you try so far?
Answer: For dynamic server side data, you can make an api to get key/value and save them in client side. then you must pass them to ngx-translate.
this is an accepted answer for your question:
https://stackoverflow.com/a/48260563/4751073


Javascript OR on if statement

Question: I am using the following line to validate a Credit Card form, I want to return false IF the length of the CVV is not equal to 3 OR 4.
var x = document.forms["booking"]["cvv"].value;

if ( x.length != 3 || x.length != 4) {
   alert("Please Enter a Valid CVV Number");
   return false;
}

However, when I input a 3 or 4 digit number I am returned false instead of true. I am not sure if my OR statement is valid or correct.
It is worth mentioning that if I only validate for length equals 3 the form returns true.
Comment: It's the [same issue as I answered here](http://stackoverflow.com/questions/20307689/do-while-conditions-isnt-stopping-loop-java/20307704#20307704) (the language is irrelevant in this case). Hopefully seeing how to rewrite the conditional to an equivalent form makes things more clear.
Comment: 3 is "not 4", and 4 is "not 3", so "not 3" or "not 4" is a tautology.
Comment: How about `if (x.length < 3 || x.length > 4)`
Answer: You probably mean if the length is not 3 AND not 4:
if ( x.length != 3 && x.length != 4) {
   alert("Please Enter a Valid CVV Number");
   return false;
}

The logic is somewhat reversed when doing " not equals " something, as not 3 OR not 4 is never true, as it's always not one or the other

Javascript OR on if statement


Cakephp habtm deep conditions

Question: suppose you have those model relations:
Offer HABTM Category
How would you build the find conditions to find all the categories that have at least one offer. In the same time the Offer should be Offer.enabled => 1. So find all the categories with at least one enabled offer. The conditions to check in the offer model are several, but once I can check for the enabled, I think I will be able to check for any other field.
I could bind the habtm model to Category, but in this case I can't check the Offer.enabled condition. Maybe somehow using containable?
The sql query would be :
SELECT DISTINCT Category.nome from categories as Category
LEFT JOIN categories_offers AS CategoriesOffer
ON (CategoriesOffer.category_id = Category.id)
LEFT JOIN offers as Offer ON (CategoriesOffer.offer_id = Offer.id)
WHERE Offer.enabled = 1

Thank you
Answer: Use the conditions key in your relationship definition to set the relationship up only if Offer.enabled = 1. Taken from the book. eg:
class Category extends Model {
    public $hasAndBelongsToMany = array(
        'Offer' => array(
            'conditions' => array( 'Offer.enabled' => 1 )
        )
    );
}

Comment: Thank you. This is ok only if I always need that condition. The fact is the conditions change always. However I was able to get the results using the linkable behavior.

Cakephp habtm deep conditions


How to use the merge function with excel files?

Question: So I have an excel file that contains a long list of ID numbers and batch numbers. I also have 3 other excel files that contain ID numbers that I need to find batch numbers for. Basically, my boss wants me to merge all 4 excel files together in R using the merge function in order to find the batch numbers for the 3 excel files that are missing batch numbers. I've never used the merge function before and I have no idea where to start.
Comment: See https://cran.r-project.org/web/packages/dplyr/vignettes/two-table.html Also, please do not use the rstudio tag for R questions.
Comment: I'm using RStudio Phil. Accidently left it out of the original post; my bad.
Comment: RStudio is just an IDE, and it has nothing to do with your question. Tagging it makes as much sense as tagging your computer's operating system, or the desk it's sitting on.
Comment: I'm sure you're familiar with Stack overflow and their practice of making you add tags to your question. Should I have chosen another word that made you more comfortable Phil?
Comment: Use the R tag for R questions. This is for your own benefit if you actually want your questions answered.
Comment: I've had all my questions answered so far with the RStudio tag. Thanks for the advice though!
Comment: Firstly, they weren't all answered. One can see your past questions by looking at your profile. Secondly, they were answered after the tags were edited according to the topic of your questions. Thirdly, I don't understand why you are fighting me when I'm trying to help you.
Comment: Phil your link did not help me.
Answer:
Import excel files into the data frame read_excel
Use the left_join function

See the example below
library(tidyverse)
dfExel1 = tibble(
  ID = 1:10000,
  batch = ID*2
)

dfExcel2 = tibble(
  ID = sample(1:10000, 10)
)

dfExcel2 %>% left_join(dfExel1, "ID")


! [remote rejected] HEAD -> refs/for/branch (no new changes)

Question: I have merged a branch and tried to push the changes into Gerrit,
git checkout dev
git merge feature

After merging my status shows like,
$ git status
On branch dev
Your branch is ahead of 'origin/dev' by 35 commits.
  (use "git push" to publish your local commits)

nothing to commit, working tree clean

Then I tried to push
git push origin HEAD:refs/for/dev

Getting below error,
! [remote rejected] HEAD -> refs/for/dev (no new changes)

Couple of SO answers (answer1, answer2, answer3) suggested to amend before push but I have many CLs which got merged.
Now how can I deal with this situation?
Answer: If you need to push changes for review (to refs/for/foo), always use git merge --no-ff to create a merge commit. The merge commit will be reviewed, and once it's submitted, the merged branch will be introduced to the target branch.
Without a merge commit, the merged commits have already been reviewed before on the merged branch in the perspective of Gerrit. That's why Gerrit responds with no new changes as they are not new to Gerrit.
To solve the current issue, you could try:
git reset origin/dev --hard
git merge feature --no-ff

# if your repository requires ChangeID, use "git commit --amend" to invoke the hook to generate ChangeID.
git commit --amend

git push origin HEAD:refs/for/dev


Angular resize service

Question: I'm trying to create an observable that will emit a value of true or false if the window screen is less than 520px or not.
So I have this code below:
@Injectable({
  providedIn: 'root'
})
export class ResizeService {
  private mobileView$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  mobileViewObs$ = this.mobileView$.asObservable();
  isMobile = false;
  size!: {width: number, height: number};
  constructor() {
   }

  resizeEvent(){
     fromEvent(window, 'resize').pipe(throttleTime(500), debounceTime(500)).subscribe((resizeEvent: any) => {
      this.size = {
          width: +resizeEvent.currentTarget.innerWidth,
          height: +resizeEvent.currentTarget.innerHeight
      };

      this.isMobile = this.isMobileView(this.size);

      this.mobileView$.next(this.isMobile);
    });;
  }

  isMobileView(size: {width: number, height: number}){
    if(size.width < PHONE_SIZE.width && size.height < PHONE_SIZE.height){
      return true;
    } else {
      return false;
    }
  }
}

It is working fine, but the problem is I can't set the initial size of a page. I don't know how to send the size object from the component to the service. Here is my component.ts:
@Component({
  selector: 'app-books-list',
  templateUrl: './books-list.component.html',
  styleUrls: ['./books-list.component.scss'],
})
export class BooksListComponent implements OnInit {
  @Input() book!: BookModel;

  booksArray: BookModel[] = [];
  oneBook!: BookModel;
  isMobile: boolean = false;
  size!: {width: number, height: number};

  constructor(private service: BookService, private route: ActivatedRoute,
    private resizeService: ResizeService) {}

  ngOnInit(): void {
    this.size = {width: window.innerWidth, height: window.innerHeight};

    this.resizeService.resizeEvent();
    this.resizeService.mobileViewObs$.subscribe(data => {
      this.isMobile = data;
    })

    this.service.getBooks().subscribe((books) => {
      this.booksArray = books;
    });
  }

The problem is that the first time the page reload it will always diplay false because the observable is created only on resize event. Do you know how to implement this feature?
Comment: please paste your code with the triple backticks wrappers ` ` ` code ` ` ` (with no spaces in between)
Answer: You don't need that much code actually, you can just assign the true or false directly in the service to an observable, to which you in the component subscribe. Assumingly you want to show different content in template depending on mobile/desktop view, so it's a perfect scenario to use the async pipe!
If you need the true/false in the component ts, you can of course subscribe to it, but remember to unsubscribe if that is the path you are taking!
Anyways, I suggest the following...
SERVICE:
isMobile$ = fromEvent(window, 'resize').pipe(
  startWith(window), // to have an initial value, can be any value
  mapTo(window), // map to window object instead (so we can have the initial value!)
  throttleTime(500),
  debounceTime(500),
  map((window: Window) => {
    if (window.innerWidth < PHONE_SIZE.width && window.innerHeight < PHONE_SIZE.height) {
      return true;
    }
    return false;
  })
);

And in the component you simply do....
isMobile$ = this.resizeService.isMobile$;

Then either use the async pipe or subscribe!
HERE'S A DEMO - here only the screen width is taken into consideration for easy testing :)
Comment: Thanks a lot, your code is pretty clean. But can you explain me please why I need to use mapTo(window) operator in the pipe? Is it because the observable emits an Event object and I actually need a windows object? Sorry, I'm new to RxJS and I think all this operators really got me...
Comment: As comment I added, map to window, so we can have the initial value. If you remove `startWith` and `mapTo` it won't trigger initially as resize hasn't happen when page loads. We use `window` here as when page loads, there is no resize event available (yet) as resize hasn't happened
Answer: You should use ngAfterViewInit instead of ngOnInit. You need to get the size when the component is starting to render. However, ngOnInit is used to initialized all data-bound properties.
@Component({
  selector: 'app-books-list',
  templateUrl: './books-list.component.html',
  styleUrls: ['./books-list.component.scss'],
})
export class BooksListComponent implements OnInit, AfterViewInit {
  @Input() book!: BookModel;

  booksArray: BookModel[] = [];
  oneBook!: BookModel;
  isMobile: boolean = false;
  size!: {width: number, height: number};

  constructor(private service: BookService, private route: ActivatedRoute,
    private resizeService: ResizeService) {}

  ngOnInit(): void {
    this.size = {width: window.innerWidth, height: window.innerHeight};

    this.service.getBooks().subscribe((books) => {
      this.booksArray = books;
    });

   ngAfterViewInit() {
   // removed this from ViewInit
   this.resizeService.resizeEvent();
    this.resizeService.mobileViewObs$.subscribe(data => {
      this.isMobile = data;
    })
    }
  }

Check here for more details on how to use Lifecycle hooks.

Angular resize service


How to create another AMI on the same EC2 instance

Question: I do the following actions on AWS EC2:

Start one EBS-backed EC2 instance i-1
Customize it and create one AMI, let's say it AMI-1
After i do further changes to the i-1 instance, i create a new AMI on the instance again
I hop i would get two images as AMI-1 and AMI-2 now.
But it seems only AMI-2 was created, the original AMI-1 disappear now. And the snapshot belong to AMI-1 still exists. It's strange.

Basically i want to know:

So is it the normal behavior for customized AMI on EC2?
If any way to let me create multiple AMIs on the same instance?
After the AMI-2 is created, the running instances based on AMI-1
whether be influenced?

Thanks in advance. I could not get it clear from Google or EC2 document.
Answer:
You can create multiple AMIs from a single instance.
AMIs do not disappear unless you explicitly deregister them.
If you deregister an AMI, it does not affect any running instances that were started from that AMI.
Comment: @ Eric, thanks. I confirmed that there are two AMIs on EC2 now. BTW, on AWS Console, there is only button "De-Register" for AMI, does it do the DELETE action to AMI?
Comment: deregister removes the entry in the list of usable AMIs.  It does not delete the EBS snapshot that was used for that AMI.  In fact, you could register a new AMI using the same snapshot.  I'll change my answer above so that it correctly reads "deregister" instead of the slightly misleading "delete".
Comment: @EricHammond just a minor comment - you can't register a Windows AMI against an existing Snapshot, only Linux.
Comment: @Grace as an alternative to creating lots of AMIs, why not just create snapshots of your custom configuration, start a generic instance from a vanilla AMI, and swap the storage?
Comment: @Jonners: Thanks for the clarification. I know nothing about Windows.


Python Nested dictionary data extraction

Question: I have a dictionary as follows:
{
  "result" : [{
      "conf" : 1.000000,
      "end" : 105.570000,
      "start" : 104.970000,
      "word" : "today"
    }, {
      "conf" : 1.000000,
      "end" : 106.320000,
      "start" : 106.080000,
      "word" : "yes"
    }, {
      "conf" : 1.000000,
      "end" : 106.590000,
      "start" : 106.320000,
      "word" : "sir"
    }],
  "text" : "today yes sir"
}

I want to extract the start and word variable from the inner dictionary residing within the result.
How do I do this? Any help would be grateful.
Comment: show your code what have you done so far?
Answer: Given your dictionary:
my_dict = {
  "result" : [{
      "conf" : 1.000000,
      "end" : 105.570000,
      "start" : 104.970000,
      "word" : "today"
    }, {
      "conf" : 1.000000,
      "end" : 106.320000,
      "start" : 106.080000,
      "word" : "yes"
    }, {
      "conf" : 1.000000,
      "end" : 106.590000,
      "start" : 106.320000,
      "word" : "sir"
    }],
  "text" : "today yes sir"
}

Then
start = my_dict['result'][0]['start']
word = my_dict['result'][0]['word']

Answer: So this is the dictionary you gave:
dict ={
   "result" : [{
       "conf" : 1.000000,
       "end" : 105.570000,
       "start" : 104.970000,
       "word" : "today"
     }, {
       "conf" : 1.000000,
       "end" : 106.320000,
       "start" : 106.080000,
       "word" : "yes"
    }, {
       "conf" : 1.000000,
       "end" : 106.590000,
       "start" : 106.320000,
       "word" : "sir"
     }],
   "text" : "today yes sir"
}

And this works to get the all the "word" and "start" values:
list = dict.get('result')

for i in list:
     print(i.get("start"))
     print(i.get("word"))


Ubuntu can not find python3, which is intalled

Question: I have Python installed on Ubuntu, as it appear when I execute on terminal:
$ python -V
Python 3.7.3
But some issues which depend on Python 3 are not working, I just cant execute Skype, Synaptic...
When I try to re-install Skype it returns the following error:
$ sudo apt install ./skypeforlinux-64.deb
...
E: Package python3 needs to be reinstalled, it was not possible to find such file.
I would be grateful if someone could help me.
Comment: Python should refer to the current python2. Only python3 should refer to the current python3 version installed. Did you change links in /usr/bin.  What does this show? ` ls -l /usr/bin/python*`
Comment: Please add output of `apt-cache policy python3` and `which python3`, `which python` to the question. What is your Ubuntu version?
Answer: It says Package python3 needs to be reinstalled, so maybe a reinstall will solve the problem. To reinstall python3, please run:
<code>sudo apt install --reinstall python3
</code>
After that try to install your packages.


How do I force TDS for iOS to update achievements in Game Center?

Question: I am having problems getting my achievements in TDS to register in Game Center.
I can't get the "Build 50 levels" achievement, despite me already having built 65 levels.

Strangely, after I bought Hoth Luke, the "Set of Rebel Heroes" achievement somehow activated (you can see it on the first screenshot). It is strange, because I either already had all the rebel heroes or only like a half of them - it depends on what exactly the game means.

Is there any way to force an update to the achievements in Game Center?
Comment: It's not exactly clear what you are asking.  I'm going to assume you are asking if there is a way to force an update to the achievements?  I've edited the post to make it reflect this. I also see that you are using iOS6.  Achievements seem to work better for me on iOS7 than they ever did on iOS6.
Answer: I had an issue similar to yours, in that some of my achievements did not unlock after fulfilling the criteria. If I remember correctly, I think the buggy achievements were different from yours.
I was playing TDS on my old iPhone 4S (on iOS 7), and I think I built like 50+ floors but some achievements just refused to unlock. Then I got a new iPhone 5s, and started playing TDS from the ground up but using the same Game Center login.
In my new TDS game, I've already unlocked some of those achievements, and the rest of the unlocked achievements became unlocked on my 2nd run through the game.
So if it bugs you that you can't get all those achievements even after fulfilling the criteria, you can try resetting the game and using your same Game Center account to play the new game.
Comment: Then this disproves the theory that using iOS6 causes these problems...
Comment: @Ugh It could still be a problem related to older hardware.  What phone are you playing on?
Comment: 4S. Anyway they should fix it
Answer: As you stated, Rebel Heroes ONLY refers to the 3 aliens you see at the bottom of your screen shot.  Specifically Akbar, Chewie, and Wicket.
For whatever reason, Han, Luke, Lando, and Leia are not considered heroes by the developers.  They are Men and Ladies of the Rebellion respectively.
As for why it unlocked when you purchased a different bitizen . . . My suspicion is that the achievements run a check whenever a new character is unlocked.
Game Center has always been plagued by oddities such as this, and sometimes it doesn't update if you get an achievement when you are not: signed in; on Wi-fi; or receiving cellular data.
Make certain that you are signed into Game Center, and that it confirms your log-in.  Then, try to build another level.  See if this fixes the problem.
It's the only way I can think of to possibly force an update.
Comment: "Build" like just purchase it or wait until it's built?
Comment: Just purchase I believe.
Comment: I've already purchased one Food level ~12 hours ago, and I'm sure everything was okay with my internet connection, but I'll try again soon and write there
Comment: It's a theory. It also might not appear until it completes construction.
Comment: I understand, but it won't hurt to confirm or disprove it.
I made sure I'm logged in Game Center and connected to internet and added another Food level. No reaction. The first level still needs ~5 hours to be finished
Comment: Nope, nothing happened after the first Food level was built
Comment: Oh well, that's why it was a theory.


'codeAutoRetrievalTimeout != null': is not true

Question: i started learning flutter a week ago. am trying to build Authentication system with Firebase_Auth package and am get stuck with this error. the goal is to use firebase phone auth and with codeAutoRetrievalTimeout to take the sms code automatically.
here is my code
LoginScreen.dart
import 'package:flutter/material.dart';
import 'package:michot_2/screens/HomeScreen.dart';
import 'package:firebase_auth/firebase_auth.dart';

class LoginScreen extends StatelessWidget {
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();

  Future<bool> loginUser(String phone, BuildContext context) async{
    FirebaseAuth _auth = FirebaseAuth.instance;

    _auth.verifyPhoneNumber(
        phoneNumber: phone,
        timeout: Duration(seconds: 60),
        verificationCompleted: (AuthCredential credential) async{
          Navigator.of(context).pop();

          UserCredential result = await _auth.signInWithCredential(credential);

          User user = result.user;

          if(user != null){
            Navigator.push(context, MaterialPageRoute(
                builder: (context) => HomeScreen(user: user,)
            ));
          }else{
            print("Error");
          }

          //This callback would gets called when verification is done automatically
        },
        verificationFailed: (FirebaseAuthException exception){
          print(exception);
        },
        codeSent: (String verificationId, [int forceResendingToken]){
          showDialog(
              context: context,
              barrierDismissible: false,
              builder: (context) {
                return AlertDialog(
                  title: Text("Give the code?"),
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      TextField(
                        controller: _codeController,
                      ),
                    ],
                  ),
                  actions: <Widget>[
                    FlatButton(
                      child: Text("Confirm"),
                      textColor: Colors.white,
                      color: Colors.blue,
                      onPressed: () async{
                        final code = _codeController.text.trim();
                        AuthCredential credential = PhoneAuthProvider.credential(verificationId: verificationId, smsCode: code);

                        UserCredential result = await _auth.signInWithCredential(credential);

                        User user = result.user;

                        if(user != null){
                          Navigator.push(context, MaterialPageRoute(
                              builder: (context) => HomeScreen(user: user,)
                          ));
                        }else{
                          print("Error");
                        }
                      },
                    )
                  ],
                );
              }
          );
        },
       codeAutoRetrievalTimeout: null
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
          child: Container(
            padding: EdgeInsets.all(32),
            child: Form(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Text("Login", style: TextStyle(color: Colors.lightBlue, fontSize: 36, fontWeight: FontWeight.w500),),

                  SizedBox(height: 16,),

                  TextFormField(
                    decoration: InputDecoration(
                        enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(8)),
                            borderSide: BorderSide(color: Colors.grey[200])
                        ),
                        focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(8)),
                            borderSide: BorderSide(color: Colors.grey[300])
                        ),
                        filled: true,
                        fillColor: Colors.grey[100],
                        hintText: "Mobile Number"

                    ),
                    controller: _phoneController,
                  ),

                  SizedBox(height: 16,),

                  Container(
                    width: double.infinity,
                    child: FlatButton(
                      child: Text("LOGIN"),
                      textColor: Colors.white,
                      padding: EdgeInsets.all(16),
                      onPressed: () {
                        final phone = _phoneController.text.trim();

                        loginUser(phone, context);

                      },
                      color: Colors.blue,
                    ),
                  )
                ],
              ),
            ),
          ),
        )
    );
  }
}

HomeScreen.dart
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

class HomeScreen extends StatelessWidget {

  final User user;

  HomeScreen({this.user});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text("You are Logged in succesfully", style: TextStyle(color: Colors.lightBlue, fontSize: 32),),
            SizedBox(height: 16,),
            Text("${user.phoneNumber}", style: TextStyle(color: Colors.grey, ),),
          ],
        ),
      ),
    );
  }
}

main.dart
import 'package:flutter/material.dart';
import 'package:michot_2/screens/LoginScreen.dart';
import 'package:firebase_core/firebase_core.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp();

  runApp(MyApp());
}

class MyApp extends StatefulWidget {

  // This widget is the root of your application.
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {

    return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'Michot Service',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: LoginScreen()
    );
  }
}

Comment: This is a separate issue. Please post it as a separate question.
Comment: What's the confusion here?
Comment: **Unhandled Exception: [firebase_auth/unknown] Given String is empty or null**
Answer: codeAutoRetrievalTimeout is a callback called when the code auto retrieval time is completed. It cannot be null.
If you don't want it, set it to this.
codeAutoRetrievalTimeout: (String verificationId){}

Comment: @BessTilahun This is a separate issue. Please post it as a separate question.
Comment: okay i made a bit changed
`codeAutoRetrievalTimeout: (String verificationId){
          verificationId = verificationId;
          print(verificationId);
          print("Timout");
        }`

now it is saying Unhandled Exception: [firebase_auth/unknown] Given String is empty or null
Comment: @BessTilahun yes, please post it as a separate question.
Comment: i tried but **You can only post once every 90 minutes.**
Comment: If this answer is right for this question then accept.


How to inject templates when using AngularJS?

Question: Following this tutorial:
https://scotch.io/tutorials/angular-routing-using-ui-router
I have three files:
index.html
<!DOCTYPE html>

    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

        AngularUI Router

Home

About

app.js
var routerApp = angular.module('routerApp', ['ui.router']);

routerApp.config(function($stateProvider, $urlRouterProvider) {

    $urlRouterProvider.otherwise('/home');

    $stateProvider

        // HOME STATES AND NESTED VIEWS ========================================
        .state('home', {
            url: '/home',
            templateUrl: 'partial-home.html'
        })

        // ABOUT PAGE AND MULTIPLE NAMED VIEWS =================================
        .state('about', {
            // we'll get to this in a bit
        });

});

partial-home.html

The Homey Page

This page demonstrates nested views.

This should, according to the tutorial, render the following:

But i only get the header, the partial-home template is never injected.
Where do I go wrong? Has something changed since the tutorial was published?
Comment: Did you check for any JS error on console?
Comment: Try `templateUrl: '/partial-home.html'`.  The `templateUrl` path will begin with the root of the application.  Double check that `partial-home.html` is in the correct place.
Comment: what does your folder structure look like? the templateUrl property is relative to app.js
Answer: I made one plunkr and it is working fine.

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

Just check the files and path.
Answer: Oops...
Turns out I didn't run my app from a webserver. I just opened the file in a browser and that's why it didn't work.
Everything works fine when the app ran on the server =)


Is it possible to scale up windowed SpaceChem?

Question: I like spacechem, and I like playing it windowed, but it's too small windowed, and I can't seem to find a way to scale it up (more pixels). Any tricks for this?
Answer: The maximum resolution appears to be 1024x768
For confirmation, navigate to the following directory on your computer:
%LOCALAPPDATA%\Zachtronics Industries\SpaceChem

Edit config.ini and change the windowWidth and windowHeight options.
This will adjust the size of the window, but unfortunately, the actual pixels of the game do not scale to fill the window.

(As a side note, the first splash screen that reads "A Game By Zachtronics Industries" does scale very nicely up to a very high resolution.)
Comment: This also helped answer my question "how do I get SpaceChem to correctly launch full-screen" (`windowWidth` and `windowHeight` were waaaaaaaaay higher than 1024x768, so I reset them to that and it's now filling at least one dimension of the screen again)