text:
Q: Python launcher fails to connect when using Visual Studio Code on a Windows 10 pc I'm just getting started again with Python and trying to get HelloWorld.py working.
I start VSC (Visual Studio Code) from the command line with "code ." from within the HelloWorld directory.
VSC opens, as does a Windows PowerShell. I run HelloWorld.py without debugging, get another PowerShell and after a while I get a popup that says "Timed out waiting for launcher to connect".
In the Powershell, "py --version" gets me "Python 3.8.5", and "py ./HellowWorld.py" gets me "Hello World".
Here's the python code:
msg = "Hello World"
print(msg)

Here's the launch.json file:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
    {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "console": "integratedTerminal"
    }
]

}
Any help is very much appreciated.


text:
Q: vim sass.vim load time I run vim in profiler mode vim --startuptime vim.log
188.898  000.073  000.073: sourcing /home/slavik/.vim/bundle/syntastic/syntax_checkers/perl.vim
188.991  000.063  000.063: sourcing /home/slavik/.vim/bundle/syntastic/syntax_checkers/php.vim
189.069  000.047  000.047: sourcing /home/slavik/.vim/bundle/syntastic/syntax_checkers/puppet.vim
189.143  000.045  000.045: sourcing /home/slavik/.vim/bundle/syntastic/syntax_checkers/python.vim
189.226  000.054  000.054: sourcing /home/slavik/.vim/bundle/syntastic/syntax_checkers/ruby.vim
1516.865  1327.610  1327.610: sourcing /home/slavik/.vim/bundle/syntastic/syntax_checkers/sass.vim
1517.095  000.170  000.170: sourcing /home/slavik/.vim/bundle/syntastic/syntax_checkers/sh.vim
1517.225  000.082  000.082: sourcing /home/slavik/.vim/bundle/syntastic/syntax_checkers/tcl.vim
1517.318  000.061  000.061: sourcing /home/slavik/.vim/bundle/syntastic/syntax_checkers/tex.vim
1517.397  000.048  000.048: sourcing /home/slavik/.vim/bundle/syntastic/syntax_checkers/xhtml.vim
1518.369  1331.773  002.261: sourcing /home/slavik/.vim/bundle/syntastic/plugin/syntastic.vim

And find very long load sass.vim
It source:
if exists("loaded_sass_syntax_checker")
    finish
endif
let loaded_sass_syntax_checker = 1

"bail if the user doesnt have the sass binary installed
if !executable("sass")
    finish
endif

"use compass imports if available
let g:syntastic_sass_imports = ""
if executable("compass")
    let g:syntastic_sass_imports = system("compass imports")
endif

function! SyntaxCheckers_sass_GetLocList()
    let makeprg='sass '.g:syntastic_sass_imports.' --check '.shellescape(expand('%'))
    let errorformat = '%ESyntax %trror:%m,%C        on line %l of %f,%Z%m'
    let errorformat .= ',%Wwarning on line %l:,%Z%m,Syntax %trror on line %l: %m'
    let loclist = SyntasticMake({ 'makeprg': makeprg, 'errorformat': errorformat })

    let bn = bufnr("")
    for i in loclist
        let i['bufnr'] = bn
    endfor

    return loclist
endfunction

What wrong with this file?

A: I guess you should update syntastic: in the 2.0.0 changelog entry there is

Only source syntax checkers as needed - instead of loading all of them when vim starts

redpajama_set_name: RedPajamaStackExchange


text:
Q: python3 manage.py makemigrations No changes detected (fcdjango_venv) Subinui-MacBook-Pro:Impassion_community subin$ python3 manage.py makemigrations
No changes detected
I'm learning Basic Django right now, and was following the lecture, but got problem.
I followed the lecture, so first I typed the code on models.py
from django.db import models

# Create your models here.

class Impassionuser(models.Model):
    username=models.CharField(max_length=64,
                                verbose_name='사용자명')
    password = models.CharField(max_length=64,
                                verbose_name='비밀번호')
    registered_dttm = models.DataTimeField(auto_now_add=True,
                                verbose_name='등록시간')

    class Meta:
        db_table = 'Impassion_Impassionuser'

and then on Terminal, I typed
(fcdjango_venv) Subinui-MacBook-Pro:Impassion_community subin$ python3 manage.py makemigrations

but the result was
No changes detected

In the lecture, after typing python3 manage.py makemigrations
it shows
Migrations for "User" :
    user/migrations/0001_initial.py
        - Create model User

how can I get the same result?

A: Include the name of your app after the makemigrations command and make sure you have a migrations folder created within your app.


text:
Q: Oracle SQL - removing duplicates from a messy query I have a long complex (for me at least) query which returns the exact data I need. Only problem is some ids are being duplicated due to one join in the query having a many to one relationship. What I'd like to do is just take the output from the query, and select one row per unique ID. It really doesn't matter how this row is selected from the duplicate IDs, I just need it to be reduced to one row per ID in the simplest way possible.
In other words I have a long messy query that gives me the data I need with neatly named columns etc BUT duplicated IDs:
ID    column1  column2 column2...  column50
111    data    data    data   ...  data
111    data    data    data   ...  data
112    data    data    data   ...  data
113    data    data    data   ...  data
113    data    data    data   ...  data
113    data    data    data   ...  data

And I want to take this output from the query and reduce it to
ID    column1  column2 column2...  column50
111    data    data    data   ...  data
112    data    data    data   ...  data
113    data    data    data   ...  data

The challenge I'm having is that I don't know how to take the entire output from a query and do stuff with it (like remove duplicates) without first writing it to a table, and I'm not able to write to a table.

A: If the data is identical then the simplest way is to wrap your messy query in another query where you just use SELECT DISTINCT. like this:
SELECT DISTINCT *
FROM   (
  your_messy_query
)

If it is not identical then you can use:
SELECT *
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY id ORDER BY something ) AS rn
  FROM   (
    your_messy_query
  ) t
)
WHERE rn = 1;

The ORDER BY something could be:

*

*a specific set of columns if you how to retrieve the most appropriate data;

*or you could use ORDER BY ROWNUM if you just want to take the first row of each group;

*or ORDER BY NULL if you want a non-deterministic order - however, this typically seems to be implemented with the same effect as ORDER BY ROWNUM.


text:
Q: Finding if a string is an iterative substring Algorithm in C? Problem Description
I have a string S. How can I find if the string follows S = nT ?
Examples:
Function should return true if
1) S = "abab"
2) S = "abcdabcd"
3) S = "abcabcabc"
4) S = "zzxzzxzzx"

But if S="abcb" returns false.
I though maybe we can repeatedly call KMP on substrings of S and then decide.
i.e.:
for "abab": call on KMP on "a". it returns 2(two instances).
now 2*len("a")!=len(s)
call on KMP on "ab". it returns 2. now 2*len("ab")==len(s) so return true
Can you suggest any better algorithms?

A: I can think of a heuristic, only call KMP on a sub string if Len(original string)/Len of(sub string) is a positive integer.
Also the maximum length of the sub string has to be less than N/2.
EDIT
Using these Heuristics Iwrote the follwing python code because my C is rusty at the moment
oldstr='ABCDABCD'

for i in xrange(0,len(oldstr)/2):
       newslice=oldstr[0:i+1]
         if newslice*(len(oldstr)/len(newslice)) == oldstr:
             print 'pattern found', newslice
             break

A: You actually only need to care about testing substring lengths that are equal to the full string length divided by a prime number.  The reason is: If S contains n copies of T, and n is not prime, then n = ab, and so S actually also contains a copies of bT (where "bT" means "T repeated b times").  This is an extension of anijhaw's answer.
int primes[] = { 2, 3, 5, 7, 11, 13, 17 };  /* There are one or two more... ;) */
int nPrimes = sizeof primes / sizeof primes[0];

/* Passing in the string length instead of assuming ASCIIZ strings means we
 * don't have to modify the string in-place or allocate memory for new copies
 * to handle recursion. */
int is_iterative(char *s, int len) {
    int i, j;
    for (i = 0; i < nPrimes && primes[i] < len; ++i) {
        if (len % primes[i] == 0) {
            int sublen = len / primes[i];
            /* Is it possible that s consists of repeats of length sublen? */
            for (j = sublen; j < len; j += sublen) {
                if (memcmp(s, s + j, sublen)) {
                    break;
                }
            }

            if (j == len) {
                /* All length-sublen substrings are equal.  We could stop here
                 * (meaning e.g. "abababab" will report a correct, but
                 * non-minimal repeated substring of length 4), but let's
                 * recurse to see if an even shorter repeated substring
                 * can be found. */
                return is_iterative(s, sublen);
            }
        }
    }

    return len;     /* Could not be broken into shorter, repeated substrings */
}

Notice that when recursing to find even shorter repeated substrings, we don't need to check the entire string again, just the first larger repeat -- since we've already established that the remaining large repeats are, well, repeats of the first one.  :)

A: I don't see that the KMP algorithm helps in this case.  It is not a matter of determining where to begin the next match.  It seems that one way to reduce the search time is to start with the longest possibility (half the length) and work downward.  The only lengths that neeed to be tested are lengths that evenly divide into the total length.  Here is an example in Ruby.  I should add that I realize the question was tagged as C, but this was just a simple way to show the algorithm I was thinking about (and allowed me to test that it worked).
class String
def IsPattern( )
    len = self.length
    testlen = len / 2
    # the fastest is to start with two entries and work down
    while ( testlen > 0 )
        # if this is not an even divisor then it can't fit the pattern
        if ( len % testlen == 0 )
            # evenly divides, so it may match
            if ( self == self[0..testlen-1] * ( len / testlen ))
                return true
            end

        end
        testlen = testlen - 1
    end
    # must not have matched
    false
end
end

if __FILE__ == $0

   ARGV.each do |str|
       puts "%s, %s" % [str, str.IsPattern ? "true" : "false" ]
   end

end

[C:\test]ruby patterntest.rb a aa abab abcdabcd abcabcabc zzxzzxzzx abcd
a, false
aa, true
abab, true
abcdabcd, true
abcabcabc, true
zzxzzxzzx, true
abcd, false

A: I suppose you could try the following algorithm:
Lets L to be a possible substring length which generates the original word. For L from 1 to strlen(s)/2 check if the first character acquires in all L*i positions for i from 1 to strlen(s)/L. If it does then it could be a possible solution and you should check it with memcmp, if not try the next L. Of course you can skip some L values which are not dividing strlen(s).

A: Try this:
    char s[] = "abcabcabcabc";
int nStringLength = strlen (s);
int nMaxCheckLength = nStringLength / 2;
int nThisOffset;
int nNumberOfSubStrings;
char cMustMatch;
char cCompare;
BOOL bThisSubStringLengthRepeats;
// Check all sub string lengths up to half the total length
for (int nSubStringLength = 1;  nSubStringLength <= nMaxCheckLength;  nSubStringLength++)
{
    // How many substrings will there be?
    nNumberOfSubStrings = nStringLength / nSubStringLength;

    // Only check substrings that fit exactly
    if (nSubStringLength * nNumberOfSubStrings == nStringLength)
    {
        // Assume it's going to be ok
        bThisSubStringLengthRepeats = TRUE;

        // check each character in substring
        for (nThisOffset = 0;  nThisOffset < nSubStringLength;  nThisOffset++)
        {
            // What must it be?
            cMustMatch = s [nThisOffset];

            // check each substring's char in that position
            for (int nSubString = 1;  nSubString < nNumberOfSubStrings;  nSubString++)
            {
                cCompare = s [(nSubString * nSubStringLength) + nThisOffset];
                // Don't bother checking more if this doesn't match
                if (cCompare != cMustMatch)
                {
                    bThisSubStringLengthRepeats = FALSE;
                    break;
                }
            }

            // Stop checking this substring
            if (!bThisSubStringLengthRepeats)
            {
                break;
            }
        }

        // We have found a match!
        if (bThisSubStringLengthRepeats)
        {
            return TRUE;
        }
    }
}

// We went through the whole lot, but no matches found
return FALSE;

A: This is Java code but you should get the idea:
        String str = "ababcababc";
    int repPos = 0;
    int repLen = 0;
    for( int i = 0; i < str.length(); i++ ) {
        if( repLen == 0 ) {
            repLen = 1;
        } else {
            char c = str.charAt( i );
            if( c == str.charAt( repPos ) ) {
                repPos = ++repPos % repLen;
            } else {
                repLen = i+1;
            }
        }
    }

This will return the length of the shortest repeating chunk or the length of the string if there's no repetition.

A: You can build the suffix array of the string, sort it.
Now look for series of ever doubling suffixes and when you've reached one that's the size of the entire string (S) the first in the series will give you T.
For example:
abcd <-- T
abcdabcd <-- S
bcd
bcdabcd
cd
cdabcd
d
dabcd

x
xzzx
xzzxzzx
zx
zxzzx
zxzzxzzx
zzx <-- T
zzxzzx
zzxzzxzzx <-- S

a
apa
apapa
apapapa
pa <-- T
papa
papapa <-- Another T, not detected by this algo
papapapa <-- S

A: The brute force approach would be to pick all possible substrings and see if they can form the entire string.
We can do one better using the observation that for a substring to be a valid candidate len(str) % len(substr) == 0. This can be deduced from the problem statement.
Here is the full code:
bool isRational(const string &str){
    int len = str.length();
    const auto &factors = getFactors(len); // this would include 1 but exclude len
    // sort(factors.begin(), factors.end()); To get out of the loop faster. Why? See https://stackoverflow.com/a/4698155/1043773
    for(auto iter = factors.rbegin(); iter != factors.rend(); ++iter){
        auto factor = *iter;
        bool result = true;
        for(int i = 0; i < factor && result; ++i){
            for(int j = i + factor; j < len; j += factor, ++cntr){
                if (str[i] != str[j]) { result = false; break; }
            }
        }

        if (result) { return true;}
    }
    return false;
}

Notice that there is a faster variation in terms of time complexity which uses KMP.
The above algorithm is O(N * factorCount(N))
But the good thing about this algorithm is it can bail out much faster than the KMP algorithm. Also the number of factors do not grow much.
Here is the graph of [i, factorCount(i)] for i <= 10^6

Here is how the algorithm performs as against the KMP algorithm. Red graph is O(N * factorCount(N)) and Blue is O(N) KMP
The KMP code is picked from here

A: Here is a simple and effective solution in C as requested:

*

*it tests all factors of the length of the string in sqrt(len) iterations.

*it uses a single call to memcmp to assert the predicate for each potential pattern length.

*it returns the minimum pattern length.

#include <string.h>

// check if string s is a repeated pattern.
// return the pattern length or 0.
size_t is_iterative(const char *s) {
    size_t i, j, res = 0, len = strlen(s);
    if (len > 1 && !memcmp(s, s + 1, len - 1))
        return 1;
    for (i = 2; i <= (j = len / i); i++) {
        if (len % i == 0) {
            if (!memcmp(s, s + i, len - i))
                return i;
            if (!memcmp(s, s + j, len - j)) {
                res = len = j;
                i--;  // try the same divisor again
            }
        }
    }
    return res;
}

An much faster approach would implement these steps:

*

*initialize an array a of UCHAR_MAX+1 integers to 0.

*scan the string, counting all byte values into a.

*compute the gcd of all non-zero byte counts and the string length.

*if the gcd is 1, the string is not iterative.

*otherwise the repeat count must be a divisor of the gcd.

*only test the corresponding pattern lengths with the above method.

Here is the code:
#include <limits.h>
#include <string.h>

size_t gcd_size(size_t a, size_t b) {
    while (b != 0) {
        size_t t = b;
        b = a % b;
        a = t;
    }
    return a;
}

// check if string s is a repeated pattern.
// return the pattern length or 0.
size_t is_iterative(const char *s) {
    size_t a[UCHAR_MAX+1] = { 0 };
    size_t i, j, plen, rep, len, res = 0;
    for (i = 0; s[i]; i++) {
        a[(unsigned char)s[i]]++;
    }
    rep = len = i;
    if (rep <= 1)
        return 0;
    for (i = 0; i <= UCHAR_MAX; i++) {
        if (a[i]) {
            rep = gcd_size(a[i], rep);
            if (rep == 1)
                return 0;
        }
    }
    plen = len / rep;
    if (!memcmp(s, s + plen, len - plen))
        return plen;
    for (i = 2; i <= (j = rep / i); i++) {
        if (rep % i == 0) {
            plen = len / j;
            if (!memcmp(s, s + plen, len - plen))
                return plen;
            plen = len / i;
            if (!memcmp(s, s + plen, len - plen)) {
                res = len = plen;
                rep = j;
                i--;  // try the same divisor again
            }
        }
    }
    return res;
}

A: #include <bits/stdc++.h>
using namespace std;
int main()
{
    bool check(string, string);
    string str="abcabcabc";
    string str2="abcabcabcabcabc";
    if(str2.size()<str.size()) swap(str,str2);

    for(int i=1;i<=str.size()/2;i++)
    {
        if(check(str.substr(0,i), str))
        {
            if(check(str.substr(0,i), str2))
            {
                cout<<str.substr(0,i);
                return 1;
            }
        }
    }
    cout<<0;
}

bool check(string substring, string str)
{
    int len=substring.size();
    for(int i=0;i<str.size();)
    {
        if(str.substr(i,substring.size())==substring)
        {
            i=i+substring.size();
        }
        else
            return false;
    }
    return true;
}


text:
Q: what is the difference between data file and data block in oracle I'd like to know if there is any difference between the data block which is the  smallest logical unit of data storage in Oracle Database and the data file which is a physical file on disk that was created by Oracle Database and contains the data for a database?
Can anybody please tell me that what exactly difference between the data file and the data block?

A: The Logical Storage Structures section in the Oracle Concepts Guide has a good explanation of both data blocks and data files (pages 259 - 296).  There is quite a bit of good information including illustrations, but here are some excerpts:

data block
  Smallest logical unit of data storage in Oracle Database.
  Other names for data blocks include Oracle blocks or pages. One data
  block corresponds to a specific number of bytes of physical space on
  disk.
data file
  A physical file on disk that was created by Oracle Database
  and contains the data for a database. The data files can be located
  either in an operating system file system or Oracle ASM disk group.


text:
Q: Is there a cheat sheet for systemd, for those of us coming from sysvinit systems? I was just a user of GNU/Linux for several years, now I want to learn again at least about troubleshooting.  I could find my way with sysvinit, but systemd has me baffled.  I found quite some documentation for the last several days, but as it seems dauting for me I would like to find a cheat sheet.  I already found two, one for Fedora and a generic one, but I would like something for Debian-like systems, for exemple with Debian commands such as ifup, ifdown &c.

A: Yes there are several.
Personally I use the Fedora documentation
https://fedoraproject.org/wiki/Systemd
There are links on that page for additional resources.
Arch Linux has a nice page also
https://wiki.archlinux.org/index.php/systemd


text:
Q: Windows or Visual Studio 2022 can't find the latest installed .NET SDK due to bitness I've successfully installed the latest .NET SDK, but Windows doesn't recognize it. This is manifested by one of the following failures:

*

*dotnet --list-sdks  doesn't include the latest .NET SDK.

*Windows x64 can't find .NET 5, .NET 6, or .NET 7.

*Visual Studio can't find the latest SDK or throws one of the following errors when trying to open a project:

*

*

Project 'MyProject' load failed: The specified SDK "Microsoft.NET.Sdk" was not found.

*

Unable to locate the .NET SDK. Check that it is installed and that the version specified in global.json (if any) matches the installed version

*

The current .NET SDK does not support targeting .NET N.N. Either target .NET N.M or lower, or use a version of the .NET SDK that supports .NET N.N

How can I get Windows to recognize the latest installed version of the .NET SDK?

A: Run where dotnet from the command line. If the output is similar to:
C:\Program Files (x86)\dotnet\dotnet.exe
C:\Program Files\dotnet\dotnet.exe

Then both the 32-bit and 64-bit versions of the SDK have been installed at some time.
32 bit --- C:\Program Files (x86)\dotnet\dotnet.exe
64 bit --- C:\Program Files\dotnet\dotnet.exe

The first SDK installed on the computer puts the dotnet path in the system path. Any subsequent SDK install of a different bit size SDK also adds dotnet path to the system path, but after the first dotnet path. Therefore, only SDK's of the first bit size are available by default, using the path variable.
There are two approaches to fixing the problem:

*

*Install the latest SDK with the other bit size. This is the easiest solution.

*Change the order of C:\Program Files (x86)\dotnet\dotnet.exe and C:\Program Files\dotnet\dotnet.exe in the System  environment variables path:

Select the windows key and enter Edit, then select Edit the system variables

Select the Environment Variables button on the Advanced tab:

Select the Path > Edit under System variables (not User variables).

Find the entries for C:\Program Files\dotnet\dotnet.exe (64 bit) and C:\Program Files\dotnet\dotnet.exe (32 bit)  and using the Move up button, change to order. Here's an example:

Select the OK button until all the windows are closed. Open a new command prompt and run where dotnet.
Answer from https://github.com/dotnet/core/issues/5962
More details at https://weblog.west-wind.com/posts/2019/Apr/20/Adventures-in-NET-SDK-Installation-SDKs-not-Showing-Up


text:
Q: merge array of arrays without repeating values from same array I am looking for a javascript solution to get an array by merging multidimensional array without forming clusters of values from same arrays.
const collection = [['AA'], ['BBB'], ['CCCC']]

The result I would like to achieve is:
const result = ['ACBCABCBC']

The collection will always be sorted and it does not necessarily contain sub arrays with 1 element greater than previous element, it could be of any length larger than previous.

A: You can do it this way, using .map(), .reduce(), .join() and .split() methods.

*

*First you transform each sub array into a string.

*Then you reduce all these strings into one string.

*Next you will need to transform back this string to an array of characters using .split("").

*Finally you shuffle this array and transform it back to a string.

This is how should be your code:
var result = collection.map(e => e.join(""))
  .reduce((a, b) => (a + b))
  .split("");

result = shuffle(result);
result = [result.join("")];

Demo:

function shuffle(a) {
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a;
}

const collection = [
  ['AA'],
  ['BBB'],
  ['CCCC']
]

var result = collection.map(e => e.join(""))
  .reduce((a, b) => (a + b))
  .split("");

result = shuffle(result);
result = [result.join("")];

console.log(result);

A:

collections = [['AAAAAA'], ['BBB'], ['CCCC'], ['DDDDDDD'], ['EEEEEEEEEEE']];
collection = collections.map(e => { return String(e) });
function shuffle(collection) {

  collection.sort(function (a, b) {
    // ASC  -> a.length - b.length
    // DESC -> b.length - a.length
    return b.length - a.length;
  });
  let sum = 0;
  for (let i = 1; i < collection.length; i++) {
    sum += collection[i].length;
  }
  if (sum < collection[0].length) {
    return `Letters are bound to be repeated due to huge number of characters in one array`;
  }
  else {
    array = [];

    while (collection.length > 0) {
      let max = collection[0].length;
      for (let i = 1; i < max;) {
        if (collection.length == 1) {
if(collection[0][0])
          array.push(collection[0][0]);
          break;
        }
        else if (collection[i].length > 0) {
          array.push(collection[0][0]);
          array.push(collection[i][0]);
          temp1 = collection[0].split('');
          temp1.shift();
          collection[0] = temp1.join('');
          temp = collection[i].split('');
          temp.shift();
          collection[i] = temp.join('');
        }
        else {
          collection.splice(i, 1);
          collection.sort(function (a, b) {
            // ASC  -> a.length - b.length
            // DESC -> b.length - a.length
            return b.length - a.length;
          });
        }

      }
      collection.splice(0, 1);
      collection.sort(function (a, b) {
        // ASC  -> a.length - b.length
        // DESC -> b.length - a.length
        return b.length - a.length;
      });
    }

    array=array.join('');
    console.log('ANS:', array)
    return array
  }

}

shuffle(collection);

Check it and tell me if there's an edge case.


text:
Q: Python Telethon - Send messages at timed intervals I'm trying to send a message to my group at defined time intervals, but I get a warning in the output the first time I try to send the message. Next times no warning, but nothing is posted in the group. I'm the owner of the group so in theory there shouldn't be any permissions issues.
Code
from telethon import TelegramClient
import schedule

def sendImage():
    apiId = 1111111
    apiHash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    phone = "+111111111111"
    client = TelegramClient(phone, apiId, apiHash)

    toChat = 1641242898

    client.start()

    print("Sending...")
    client.send_file(toChat, "./image.jpg", caption="Write text here")

    client.disconnect()
    return

def main():
    schedule.every(10).seconds.do(sendImage)

    while True:
        schedule.run_pending()

if __name__ == "__main__":
    main()

Output
Sending...
RuntimeWarning: coroutine 'UploadMethods.send_file' was never awaited
  client.send_file(toChat, "./image.jpg", caption="Write text here")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Sending...
Sending...
Sending...

A: Telethon uses asyncio, but schedule wasn't designed with asyncio in mind. You should consider using an asyncio-based alternative to schedule, or just use Python's builtin functions in the asyncio module to "schedule" things:
import asyncio
from telethon import TelegramClient

def send_image():
    ...
    client = TelegramClient(phone, apiId, apiHash)

    await client.start()
    await client.send_file(toChat, "./image.jpg", caption="Write text here")
    await client.disconnect()

async def main():
    while True:  # forever
        await send_image()  # send image, then
        await asyncio.sleep(10)  # sleep 10 seconds

    # this is essentially "every 10 seconds call send_image"

if __name__ == "__main__":
    asyncio.run(main())

You should also consider creating and start()ing the client inside main to avoid recreating it every time.

A: This means that you do not give time for the operation to be done, try these changes :
from telethon import TelegramClient
import schedule

async def sendImage(): # <- make it async
    apiId = 1111111
    apiHash = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
    phone = "+111111111111"
    client = TelegramClient(phone, apiId, apiHash)

    toChat = 1641242898

    client.start()

    print("Sending...")
    await client.send_file(toChat, "./image.jpg", caption="Write text here") # <- here too add await

    client.disconnect()
    return

def main():
    schedule.every(10).seconds.do(client.loop.run_until_complete(sendImage))

    while True:
        schedule.run_pending()

if __name__ == "__main__":
    main()

other thing i don't think that you should keep connecting and disconnecting, in my opinion client.start() should be out of this function and client.disconnect too

A: As the output says you need to await the response of the coroutine. The code may trigger exceptions which should be handled.
try:
    client = TelegramClient(...)
    client.start()
except Exception as e:
    print(f"Exception while starting the client - {e}")
else:
    try:
        ret_value = await client.send_file(...)
    except Exception as e:
        print(f"Exception while sending the message - {e}")
    else:
        print(f"Message sent. Return Value {ret_value}")


text:
Q: Laurent Series of $\frac{1}{(1+z^2)^2}$ Expanded to the Laurent Series at the deleted neighbourhood of $$z=i$$
and try to give the Convergence range
I'm trying to make $$\frac{1}{(1+z^2)^2}=\bigg(\frac{-1}{2z}\bigg)\bigg(\frac{1}{1+ z^2 }\bigg)\text {'}$$
$$\frac{1}{1+ z^2}={1-z^2+z^4-z^6...}=\sum_{n=0}^{\infty} {(-1)^ n(z^{2n})}$$
$$\bigg(\frac{1}{1+ z^2 }\bigg)\text {'}= \sum_{n=0}^{\infty} {(2n)(-1)^ n(z^{2n-1})}$$
so that
$$\frac{1}{(1+z^2)^2}=\bigg(\frac{-1}{2z}\bigg)\sum_{n=0}^{\infty} {(2n)(-1)^ n(z^{2n-1})}$$
$$=-\sum_{n=0}^{\infty} {(n)(-1)^n(z^{2n-2})}$$
But it seems not right...

A: Hint: Series for $\frac{1}{1+z^2}$ is $\frac{1}{1-(-z^2)}=\sum_{k=0}^{\infty}(-z^2)^k$.

A: I really can't follow what you are doing.  You start by saying, "I'm trying to make $$\frac{1}{(1+z^2)^2}=\bigg(\frac{-1}{2z}\bigg)\bigg(\frac{1}{1+ z^2 }\bigg),$$ but you surely know that this isn't a true statement.  I also don't see what it has to do with what follows.
Let me get you started: $$\frac{1}{(z^2+1)^2}=\frac{1}{(z+i)^2(z-i)^2}
$$
Now $1/(z+i)^2$ is analytic at $z=i$ and so can be developed in a Taylor series about $z=i$.  Once you do this, you can simply multiply the series by $1/(z-i)^2$ to get the desired Laurent series.


text:
Q: Why am I getting "GC overhead limit exceeded" when I use "arq" to query local rdf files I am using ARQ in order to query local RDF files. The command that I am using is the following:
./arq --data /home/datasets/a-m-00027.nt --results CSV --query myQuery.sparql

myQuery.sparql contains the query:
PREFIX basekb:<http://rdf.basekb.com/ns/>
PREFIX rdf:<http://www.w3.org/1999/02/22-rdf-syntax-ns#>

SELECT ?x
FROM  </home/data/a-m-00027.nt>
WHERE {?x rdf:type basekb:music.release}
LIMIT 10

Exception
Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded
        at java.util.concurrent.CopyOnWriteArrayList.iterator(CopyOnWriteArrayList.java:959)
        at com.hp.hpl.jena.graph.impl.SimpleEventManager.notifyAddTriple(SimpleEventManager.java:97)
        at com.hp.hpl.jena.graph.impl.GraphBase.notifyAdd(GraphBase.java:124)
        at com.hp.hpl.jena.graph.impl.GraphBase.add(GraphBase.java:203)
        at com.hp.hpl.jena.sparql.core.DatasetGraphCollection.add(DatasetGraphCollection.java:43)
        at com.hp.hpl.jena.sparql.core.DatasetGraphBase.add(DatasetGraphBase.java:82)
        at org.apache.jena.riot.system.StreamRDFLib$ParserOutputDataset.triple(StreamRDFLib.java:206)
        at org.apache.jena.riot.lang.LangNTriples.runParser(LangNTriples.java:61)
        at org.apache.jena.riot.lang.LangBase.parse(LangBase.java:42)
        at org.apache.jena.riot.RDFParserRegistry$ReaderRIOTLang.read(RDFParserRegistry.java:185)
        at org.apache.jena.riot.RDFDataMgr.process(RDFDataMgr.java:906)
        at org.apache.jena.riot.RDFDataMgr.parse(RDFDataMgr.java:687)
        at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:534)
        at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:501)
        at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:454)
        at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:432)
        at org.apache.jena.riot.RDFDataMgr.read(RDFDataMgr.java:422)
        at arq.cmdline.ModDatasetGeneral.addGraphs(ModDatasetGeneral.java:98)
        at arq.cmdline.ModDatasetGeneral.createDataset(ModDatasetGeneral.java:87)
        at arq.cmdline.ModDatasetGeneralAssembler.createDataset(ModDatasetGeneralAssembler.java:35)
        at arq.cmdline.ModDataset.getDataset(ModDataset.java:34)
        at arq.query.getDataset(query.java:176)
        at arq.query.queryExec(query.java:198)
        at arq.query.exec(query.java:159)
        at arq.cmdline.CmdMain.mainMethod(CmdMain.java:102)
        at arq.cmdline.CmdMain.mainRun(CmdMain.java:63)
        at arq.cmdline.CmdMain.mainRun(CmdMain.java:50)
        at arq.arq.main(arq.java:28)

Fact example
<http://rdf.basekb.com/ns/architecture.building_complex>        <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>       <http://rdf.basekb.com/ns/type.type>

Is the whole file being loaded into memory?

A:
Is the whole file being loaded into memory?

Exactly, here is your issue. You may be able to bump the java heap and get it to fit, as has been said.
But as an alternative, or for cases where you simply don't have enough memory, try using TDB to store and index the file then query it:
$ tdbloader --loc my_tdb_store /home/datasets/a-m-00027.nt
$ tdbquery --loc my_tdb_store --results CSV --query myQuery.sparql

(You can delete the store once you've finished, it is just a directory named my_tdb_store)
As a third alternative, you can skip sparql completely. You query just finds the first ten things with type basekb:music.release, which you can find like this:
$ riot /home/datasets/a-m-00027.nt | \
  grep '<http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://rdf.basekb.com/ns/music.release> .' | \
  cut -d ' ' -f 1 | \
  head -10

which uses minimal memory.

A: cause you're out of memory as the exception tells you:
java.lang.OutOfMemoryError: GC overhead limit exceeded

It is well possible that you're actually not out of memory, but that it's just your JVM settings that won't exceed a certain amount of memory by default. As described in https://stackoverflow.com/a/21197787/1423333 try running
JVM_ARGS="-Xmx4096M" ./arq --data /home/datasets/a-m-00027.nt --results CSV --query myQuery.sparql


text:
Q: How to show that $G$ has no element of order $pq$. Let $G=\langle a,b |a^q=1,b^{p^2}=1,  bab^{−1}=a^i,   ord_q(i)=p^2\rangle$, here $p^2 \mid q-1$ and $p< q$ are primes and I am assuming that $|G|>12$. Thus $G$ has a normal sylow $q$-subgroup.
How can I show $G$ has no element of order $pq$?

A: Consider the general element $a^mb^n$, with $0\le m<q$ and $0<n<p^2$.  We can assume $n\neq0$, since if $n=0$, this "general element" has order $q$.
Note that
$$ (a^mb^n)^2 = a^m(b^na^mb^{-n})b^{2n}$$
and that thing in the middle is $a^{mk}$, with $k=i^n$. So our product is $a^{m(k+1)}b^{2n}$.
Doing this $p$ times gives
$$ (a^mb^n)^p = a^{rm}b^{pn}$$
where $r=1+i^n+i^{2n}+\ldots i^{(p-1)n}$.
For $a^mb^n$ to have order $pq$, the element above must be in the unique Sylow $q$-subgroup of $G$; that is, we need $b^{pn}=1$, so that $p|n$.
But $r=\dfrac{i^{pn}-1}{i^n-1}$, and if $p|n$, the we have $r\equiv0\pmod{q}$.  In other words, $(a^mb^n)^p=1$.


text:
Q: Ubuntu 21.04 beta on Mac Mini won't boot after updates I've been trying to set up an old Apple Mac Mini as an Ubuntu desktop machine for testing, etc. I was able to install the last LTS - Ubuntu 20.04 - and distros based upon that such as Mint, however with Ubuntu 21.04 beta it's a different story.
Ubuntu 21.04 installs fine, and installs updates during the install.  Come time for reboot or a power on, however, I just get a white screen.  No GRUB menu, no messages, nothing.
If I install Ubuntu 21.04 without applying updates, it works fine, so what is breaking the install? I've tested with and without drive encryption, and it makes no difference. Am I missing a step after updating?


text:
Q: Magento 2 currency rates not imported I am trying to enable more currencies and then try to import rates from web service in Magento 2.
When I do
Stores > Currency > Currency Rates > Import

It shows following error:

We can't retrieve a rate from http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=INR&ToCurrency=GBP.
We can't retrieve a rate from http://www.webservicex.net/CurrencyConvertor.asmx/ConversionRate?FromCurrency=INR&ToCurrency=USD.

I also do search for same issue but cant find solution.

A: If you visit that URL, you'll notice it says:
{"code":"PAGE_NOT_FOUND","message":"Page not found"}

Not good. If you then go to webservicex.net and scroll through its list of API, you'll notice that none refer to currency conversion. Also, not good.
If you web search for currency import in Magento 2, you'll come to this shopgo module, which says:

Magento 2.0's default and only currency import service WebserviceX tends to go down from time to time. And sometimes, it returns empty results for some currencies.

Three times the charm: webservicex.net is probably not going to work. Try installing the module from shopgo, which uses other providers.


text:
Q: Apollo client for store in React app - best practises? I feel the hardest part going the Apollo/GraphQl pathway is deciding patterns rather than learning the syntax.
Having moved all app store from Redux to Apollo cache I am a few days later still struggling with a best way to have components communicate and commonly access the Apollo store.
I could write pages about different implementations but the questions remains as I haven't found any articles or code examples and the forums are dead silent about this - how are others doing this?
To add some to the discussion I have only one React state in top-level (parent) component:
 {dispatch: (...dispatch function...), actionType, actionPayload}
and distribute these through by props and React Context to child components deep down the tree. Parent then monitors dispatched functions and handles most of them (like data manipulations) and passes unhandled actions down the tree. It feels much like Redux but the store is 100% in Apollo.
This has been a thready path and I feel my current pattern will likely change a lot so I'd love to hear from others. Components communicating and app store are the core of every app, surely there must be others out there?!


text:
Q: Big Problem when using Class Interface with Custom Event in C# I need to do this (with a custom slider or a standard control ):
        ISlider ISlider;
        ISlider = slider as ISlider;
        if (ISlider != null)
        {
            ISlider.CustomEvent += new CustomEventDelegate(MyCustomEventHandler);
        }
        else
        {
            // standard control
            this.slider.ValueChanged += new RoutedPropertyChangedEventHandler<double>(this.slider_ValueChange);
        }

But C# refused because it says interface cannot contain fields (CustomEvent) and if I don't declare CustomEvent in interface my code above cannot compile either so what can I do ?
In the interface ISlider I just tried to declare:
CustomEventDelegate CustomEvent ;

A: CustomEvent should indeed not be declared as a field in ISlider.  It should be declared as an event:
public delegate void CustomEventDelegate(/*whatever*/);

public interface ISlider {
    event CustomEventDelegate CustomEvent;
}

And fix your code so typenames and reference variable names are distinct:
    ISlider itf;
    itf = slider as ISlider;
    if (itf != null)
    {
        itf.CustomEvent += new CustomEventDelegate(MyCustomEventHandler);
    }


text:
Q: Images as pagination links in cakephp 2.x I have a gallery custom coded using cakePHP. Currently, I'm trying to get the pagination links for next and previous page to appear as images. The links work perfectly as text. In order to output them as simple text, I use the following code:
<?php
echo $this->Paginator->prev();
echo $this->Paginator->next();
?>

However, this outputs the links as text saying << Previous and Next >> respectively. I want to replace said output for images I have. I have looked around and found something that replaces the text for the image:
echo $this->paginator->prev($this->html->image('/images/icon_prev.png'), array('escape' => false));

However, it seems to break the link: While the link for the standard previous/next buttons go as:
http://galleryurlhere/albums/view/7/page:2

The new image link outputs them as:
http://galleryurlhere/albums/view/page:2

Thus failing to send the album ID as a variable and therefore breaking the pagination. Can anyone help me with this? I've tried overloading the function with the variable (Which I can access from the code), but that doesn't seem to be working. Any clue what I'm doing wrong?

A: This does not make much sense but the problem is in how you call the Helper.
This does NOT work properly
echo $this->paginator->prev( $this->html->image('/images/icon_prev.png'), array('escape' => false) );

while this DOES:  (note the capital "P")
echo $this->Paginator->prev( $this->html->image('/images/icon_prev.png'), array('escape' => false) );

More details
It seems like $this->Paginator is not the same object as $this->paginator (spl_object_hash()). Similarly I would use $this->Html and not $this->html as my Html Helper.


text:
Q: Displaying from multiple table based on the time and showing the source table So, for example, I have 3 tables
Table 1: name
id | name | time
 1 | Bob  | 20.42

Table 2: item
id | item   | time
 1 | Bottle | 18.42
 2 | Box    | 21.42

Table 3: food
id | Food | time
1 | Steak | 19.42

So I want to display them like this
From table item: 1 | Bottle
From table food: 1 | Steak
From table name: 1 | Bob
From table item: 2 | Box

A: Use UNION ALL:
select id, name
from (
    select * from name
    union all
    select * from item
    union all
    select * from food ) t
order by t.`time`

A: DROP TABLE IF EXISTS name;

CREATE TABLE name
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,name VARCHAR(12) NOT NULL
,time TIME NOT NULL
);

INSERT INTO name VALUES
(1,'Bob','20:42:00');

DROP TABLE IF EXISTS item;

CREATE TABLE item
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,item VARCHAR(12) NOT NULL
,time TIME NOT NULL
);

INSERT INTO item VALUES
(1,'Bottle','18:42:00'),
(2,'Box','21:42:00');

DROP TABLE IF EXISTS food;

CREATE TABLE food
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,food VARCHAR(12) NOT NULL
,time TIME NOT NULL
);

INSERT INTO food VALUES
(1,'Steak','19:42');

SELECT *, 'name' source FROM name
UNION ALL
SELECT *, 'item' FROM item
UNION ALL
SELECT *, 'food' FROM food
ORDER BY time;
+----+--------+----------+--------+
| id | name   | time     | source |
+----+--------+----------+--------+
|  1 | Bottle | 18:42:00 | item   |
|  1 | Steak  | 19:42:00 | food   |
|  1 | Bob    | 20:42:00 | name   |
|  2 | Box    | 21:42:00 | item   |
+----+--------+----------+--------+


text:
Q: How to unlock the last level? In Face Raiders, the level after the Bonus Level has a Keyhole on it, signifying that it is locked. When I press it, It says:
                                   ???
                            Try merging faces in
                            Nintendo 3DS camera!
                              Keep Collecting!

Does this mean that I have to go to the camera and actually merge faces? Or do I continue collecting faces like the game asks me to?

A: Yep, you need to go to the 3DS camera and merge the faces. That's the requirement for unlocking the Bonus Level.
The steps for doing so are as follows:

*

*Go to the 3DS Camera.

*Flip the switch on the bottom right corner of the screen.

*On the menu that appears, tap the camera icon (located on the rightmost side).

*On the next menu, select the head with a question mark icon.

*Find someone (or something) and take a picture of it.

Do it a few times and it should unlock the bonus stage.
If it doesn't, try the following: Look to see if the UFO brings some merged faces over to the main stages. If so, play that stage, and locate and destroy the UFO with the merged face. This will "rescue" that face. After successfully completing the stage with the rescuing, you should unlock the Bonus Level (provided you completed all previous stages).
Hope this answer helps!


text:
Q: Extracting values from a database to populate a dropdown I have a db, am trying to extract values into a list
Here is the code I am trying to run (I had to adapt it from elsewhere), which should return an array, from which I want to select the AllianceName attribute
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");

$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass");
if (!$con) {
  exit('Connect Error (' . mysqli_connect_errno() . ') '
           . mysqli_connect_error());
}
//set the default client character set
mysqli_set_charset($con, 'utf-8');
mysqli_select_db($dbname, $con);

$options = array();
$options[] = "<option value=''>--?--</option>";
$query = "
SELECT *
FROM `City`
GROUP BY `AllianceName`
";

$db = mysqli_query($query);
foreach ( $db as $d ) {
  $options[] = "<option value='{".$d['AllianceName']."}'></option>";
}
?>
<select class="" id="articles" size="1" name="articles">
<?php echo implode("\n", $options); ?>
</select>*/

Right now this only returns the --?-- that I have defined in the options array. It does not parse any of the values from the query. I know the query by itself is correct since I have run it exactly in this syntax in the SQL server and it works.
I am pretty sure that this is a syntax error ... var_dump($db) gives me a bool(false) output.
Here's the latest code I am using:
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");

$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}
?>
<select class="Select" id="articles" size="1" name="articles">
<?php
$sql = <<<SQL
    SELECT DISTINCT `AllianceName`
    FROM `City`
SQL;
if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
     echo "<option value="'.{$row['AllianceName']}.'"></option>";
}
?>
</select>

The query by itself runs fine when I just echo the results. Trying to put it into a dropdown fails every time. No values get populated.

A: There are a couple problems here.
First you don't need the GROUP BY 'AllianceName' in your query, you are not performing any functions on your data, that might have been causing you to not return any results.
Secondly, normally you loop through query results with a while loop. You don't have to, but its common practice, so your code should look like this..
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");

$con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname");
if (!$con) {
  exit('Connect Error (' . mysqli_connect_errno() . ') '
       . mysqli_connect_error());
}
//there is no need to make an array first, just have it spit out the options if you aren't making a class or function
?>
<select class="" id="articles" size="1" name="articles">
<?php
$query = "SELECT * FROM `City` ";
$db = mysqli_query($query);
while ( $d=mysqli_fetch_assoc($db)) {
  echo "<option value='{".$d['AllianceName']."}'></option>";
}
?>
</select>

Try that out and see if it works for you.

A: From the mysqli_query() docs:

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
  EXPLAIN queries mysqli_query() will return a mysqli_result object. For
  other successful queries mysqli_query() will return TRUE.

So what you have after the query succeeded is a mysqli_result object. Now you have to fetch the result into an (associative) array or object, row by row.
if($query === false) die('Query failed to execute');

while($row = $result->fetch_assoc()) {
    echo $row['AllianceName'] . PHP_EOL;
}

All this is described in hundreds of tutorials in the web, so please read one of these. I recommend these written in the current decade, e.g. http://codular.com/php-mysqli

A: Here is the code that finally worked. Both @Syndrose and @Zombiehunter provided clues to this.
@Syndrose - you might want to take into account the syntax used here as this is what was failing from your codebase...especially the syntax for the echo  tag line.
<?php
//database connection file setting.inc will need to be modified for production
include ("settings.inc");

$db = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

if($db->connect_errno > 0){
    die('Unable to connect to database [' . $db->connect_error . ']');
}
$sql = <<<SQL
    SELECT DISTINCT `AllianceName`
    FROM `City`
SQL;
if(!$result = $db->query($sql)){
    die('There was an error running the query [' . $db->error . ']');
    }
?>
<select  style="width:300px" class="" id="AllianceName" size="1" name="Alliance Name">
<?php
while($row = $result->fetch_assoc()){
     echo '<option value='.$row['AllianceName'].'>'.$row['AllianceName'].'</option>';
}
?>
</select>


text:
Q: Contour integral of inverse square root. I want to calculate the below complex integral on the upper-semi-circle which its radius goes to infinity:
$$ \oint \frac{dz}{\sqrt{1+z^2}}$$
I tried with the substitution $z = R e^{i \theta}$ where $0<\theta<\pi$, and then took the limit where $R$ goes to infinity, but I counldn't find sensible result.  Is it due to the fact that my substitution crosses the branch cut? (Either the cut taken from $i$ to infinity or to connect $-i$ and $i$.) If this is the case, how can one evaluate this integral, by the way if it converges.

A: Idea:
Note that for large $R$ we have that $\sqrt{1+z^2} \approx z$. This result is analytic without any branch cut. So it is useful for integration.
Formal:
We have to branch points of $\sqrt{1+z^2}$ at $z=\pm i$. We may choose the branch cut between between these branch points. With this choice, we have that (for $|z| > 1$)
$$ \sqrt{ 1+z^2} = z \sqrt{1+1/z^2}$$
where on the right hand side the branch cut does not play a role [as $\operatorname{Re}(1+1/z^2)>0$].
With that we have for the upper semi-circle ($z= R e^{i\theta}$)
$$\int  \frac{dz}{\sqrt{1+z^2}} = \int  \frac{dz}{z \sqrt{1+1/z^2}}  = i \int_{0}^{\pi} d\theta + O(1/R) \to \pi i \quad (R\to \infty).$$
To this, we add the contribution of the integral along the real line. For this we obtain
$$\int_{-\infty}^{\infty}\frac{dx}{\pm\sqrt{1+x^2}}$$
where the sign $+$ has to be chosen for $x>0$ and $-$ for $x<0$ (given that the branch cut is between $+i$ and $-i$). Due to the fact that we integrate an odd function, this part of the contour vanishes and we have that
$$\oint \frac{dz}{\sqrt{1+z^2}} = i \pi\;.$$


text:
Q: OpenCV: Differentiate between two very similar contours I use openCV to find contours in images.
The problem is, that some of the contours are just some artifacts I do not want to identify.
In the following image you see an example:

I am interested in the countours 20 and 21. 19 should be ignored.
UPDATE:
I am not interested in the size of the contours, the pixels within the contiour is what differntiates them.
here is another example:

Countour 18 is kindy blurry, has no "sharp contours" within it. Countour 16 has clearer edges and the colorintensity is focused in the center.
I would like to know if there is a way to identify contours like that?
I tried it with  blurry detection (see here) but the output between the multiple images was very very differnet...
Thanks for any help!

A: after finding contours you can find the area of that individual contour and set a if else condition to select that contours
(contours, hierarchy) = cv2.findContours(control, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
 for pic, contour in enumerate(contours):
      area = cv2.contourArea(contour)
            if (area > 200):

in a program i used that contours whose are more than 200 you can also use this


text:
Q: What should be the values of GOPATH and GOROOT? I'm trying to install doozer like this:
$ goinstall github.com/ha/doozer

I get these errors.

goinstall: os: go/build: package could not be found locally
goinstall: fmt: go/build: package could not be found locally
goinstall: io: go/build: package could not be found locally
goinstall: reflect: go/build: package could not be found locally
goinstall: math: go/build: package could not be found locally
goinstall: rand: go/build: package could not be found locally
goinstall: url: go/build: package could not be found locally
goinstall: net: go/build: package could not be found locally
goinstall: sync: go/build: package could not be found locally
goinstall: runtime: go/build: package could not be found locally
goinstall: strings: go/build: package could not be found locally
goinstall: sort: go/build: package could not be found locally
goinstall: strconv: go/build: package could not be found locally
goinstall: bytes: go/build: package could not be found locally
goinstall: log: go/build: package could not be found locally
goinstall: encoding/binary: go/build: package could not be found locally

A: First run go env.
If you see that the go isn't installed, you can install it via homebrew or via package and/or other ways.
If you are seeing output then your Go is installed.
It shows you all the envs that are set and are not.
If you see empty for GOROOT:

*

*Run which go (On my computer : /usr/local/go/bin/go)

*then export like this  export GOROOT=/usr/local/go
If you see empty for GOPATH:

*

*Create any directory anywhere on your computer for go projects in my case: ~/GO_PROJECTS

*Then export GOPATH=~/GO_PROJECTS

A: Regarding GOROOT specifically, Go 1.9 will set it automatically to its installation path.
Even if you have multiple Go installed, calling the 1.9.x one will set GOROOT to /path/to/go/1.9 (before, if not set, it assumed a default path like /usr/local/go or c:\Go).
See CL Go Review 53370:

The go tool will now use the path from which it was invoked to attempt to locate the root of the Go install tree.
  This means that if the entire Go installation is moved to a new location, the go tool should continue to work as usual.
This may be overriden by setting GOROOT in the environment, which should only be done in unusual circumstances.
  Note that this does not affect the result of the runtime.GOROOT() function, which will continue to report the original installation location; this may be fixed in later releases.

A: In modern Go, you don't need to set GOPATH or GOROOT. In fact, unless you're doing something very specialized, it's best to have them unset on your system.
Use Go modules. Having installed Go, pick a directory where you want to work. Then:
$ mkdir example
$ cd example
$ go mod init example.com

Note that the module name example.com is arbitrary; if you keep your work on GitHub, this could be something like github.com/your-username/project-name.
The last command will have created a go.mod file; now you can grab dependencies with go get:
$ go get rsc.io/quote

Now your code using this dependency:
$ touch main.go

Place this in main.go:
package main

import (
    "fmt"

    "rsc.io/quote"
)

func main() {
    fmt.Println(quote.Go())
}

And run with:
$ go run .

W.r.t. original question, you can now get your doozer dependency with:
$ go get github.com/ha/doozer

Now you can use the doozer module in your code. And so on. You can also examine the go.mod file in your directory to see the dependencies listed, along with their versions. Each module is self-contained, with its own versions of dependencies. You can have two modules alongside each other, each with its own go.mod file pointing to different versions of some dependency - this will all work OK because of the isolation between modules.
For additional information, start with the official tutorial here. In several chapters, it walks you through the steps shown above, as well as writing your own reusable modules and packages, and importing them from other modules. Additional interactive tutorials are available at https://play-with-go.dev/

A: GOPATH and GOROOT configurations are deprecated.
You can use the GO module instead.
For example:
mkdir go_app
cd go_app
go mod init go_app

A: As mentioned above:

The GOPATH environment variable specifies the location of your
  workspace.

For Windows, this worked for me (in Ms-dos window):
set GOPATH=D:\my_folder_for_go_code\

This creates a GOPATH variable that Ms-dos recognizes when used as follows:
cd %GOPATH%

A: Lots of answers but no substance, like robots doing cut and paste on what's on their system. There is no need to set GOROOT as an environment variable. However, there is a beneficial need to set the GOPATH environment variable, and if not set it defaults to ${HOME}/go/ folder.
It is the PATH environment variable that you must pay attention because this variable is the variable that can change your go version. Not GOROOT! Forget GOROOT.
Now, if you switch or change to a new go version, your downloaded packages will use the default $HOME/go folder and it will mixed-up with whatever your previous go version was. This is not good.
Therefore, this is where GOPATH you need to define in order to isolate downloaded packages of the new go version.
In summary, forget GOROOT. Think more on GOPATH.

A: GOPATH is discussed here:

The GOPATH Environment Variable
GOPATH may be set to a colon-separated list of paths inside which Go
  code, package objects, and executables may be found.
Set a GOPATH to use goinstall to build and install your own code and
  external libraries outside of the Go tree (and to avoid writing
  Makefiles).

And GOROOT is discussed here:

$GOROOT The root of the Go tree, often $HOME/go. This defaults to the
  parent of the directory where all.bash is run. If you choose not to
  set $GOROOT, you must run gomake instead of make or gmake when
  developing Go programs using the conventional makefiles.

A: GOPATH is discussed in the cmd/go documentation:

The GOPATH environment variable lists places to look for Go code. On
  Unix, the value is a colon-separated string. On Windows, the value is
  a semicolon-separated string. On Plan 9, the value is a list.
GOPATH must be set to get, build and install packages outside the
  standard Go tree.

GOROOT is discussed in the installation instructions:

The Go binary distributions assume they will be installed in
  /usr/local/go (or c:\Go under Windows), but it is possible to install
  the Go tools to a different location. In this case you must set the
  GOROOT environment variable to point to the directory in which it was
  installed.
For example, if you installed Go to your home directory you should add
  the following commands to $HOME/.profile:
export GOROOT=$HOME/go
export PATH=$PATH:$GOROOT/bin

Note: GOROOT must be set only when installing to a custom location.

(updated version of Chris Bunch's answer.)

A: I read the go help gopath docs and was still incredibly confused, but found this little nugget from another go doc page:

The GOPATH environment variable specifies the location of your workspace. It is likely the only environment variable you'll need to set when developing Go code.

http://golang.org/doc/code.html#GOPATH

A: Run go help environment it has documentation for every environment variable that can be listed by go env command

A: Starting with go 1.8 (Q2 2017), GOPATH will be set for you by default to $HOME/go
See issue 17262 and Rob Pike's comment:

$HOME/go it will be.
There is no single best answer but this is short and sweet, and it can only be a problem to choose that name if $HOME/go already exists, which will only happen for experts who already have go installed and will understand GOPATH.

A: Here is a my simple setup:
directory for go related things: ~/programming/go
directory for go compiler/tools: ~/programming/go/go-1.4
directory for go software      : ~/programming/go/packages

GOROOT, GOPATH, PATH are set as following:
export GOROOT=/home/user/programming/go/go-1.4
export GOPATH=/home/user/programming/go/packages
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin

So, in short:
GOROOT is for compiler/tools that comes from go installation.
GOPATH is for your own go projects / 3rd party libraries (downloaded with "go get").

A: The GOPATH should not point to the Go installation, but rather to your workspace (see https://golang.org/doc/code.html#GOPATH). Whenever you install some package with go get or go install, it will land within the GOPATH. That is why it warns you, that you most definitely do not want random packages from the internet to be dumped into your official installation.

A: You generally should not set GOROOT explicitly. The go command identifies the appropriate GOROOT automatically based on its own directory location.

GOPATH defaults to $HOME/go. You only need to set it explicitly if you want to put it somewhere else.
GOPATH contains:

*

*Binaries installed using go install, located at $GOPATH/bin.¹

*

*This location can be overridden using the GOBIN environment variable.

*A cache of downloaded module source code and checksums, located at $GOPATH/pkg/mod.

*

*This location can be overridden using the GOMODCACHE environment variable.

If you set both GOBIN and GOMODCACHE, and do not set GO111MODULE=off, then GOPATH itself should have essentially no effect.

In addition, in the legacy GOPATH mode (when GO111MODULE=off is also set), GOPATH contains:

*

*Source code used to build packages, stored in a directory tree rooted at $GOPATH/src.

*Non-binaries installed using go install, located at $GOPATH/pkg.

*

*Installing non-binary packages is no longer particularly useful: the go command has a cache of built artifacts, which has been required since Go 1.12 even in GOPATH mode.

*The build cache is not located within GOPATH. Its location can be set with the GOCACHE environment variable.

¹ Binaries can also be installed using go get on Go 1.17 and earlier, but go install is preferred as of Go 1.16; see https://golang.org/doc/go1.16.

A: Here is one solution (single user):
GOROOT=$HOME/.local # your go executable is in $GOROOT/bin
GOPATH=$HOME/.gopath
PATH=$GOROOT/bin:$GOPATH/bin:$PATH

go complains if you change .gopath to .go.
I wish they went with how the rust/cargo guys did and just put everything at one place.

A: There's a command you can use: go env GOPATH

A: You don't need to explicitly set GOROOT (Modern versions of Go can figure it out on their own based on the location of the go binary that you run).
Also, got the follow error when trying to work with vgo:
go: modules disabled inside GOPATH/src by GO111MODULE=auto; see 'go help modules'

Removing GOROOT, updating my GOPATH and export GO111MODULE="on" resolved the issue.
GOPATH see in here

GOPATH may be set to a colon-separated list of paths inside which Go code, package objects, and executables may be found.
Set a GOPATH to use goinstall to build and install your own code and external libraries outside of the Go tree (and to avoid writing Makefiles).

A: As of 2020 and Go version 1.13+, in Windows the best way for updating GOPATH is just typing in command prompt:
setx GOPATH C:\mynewgopath

A: If you are using the distro go, you should point to where the include files are, for example:
$ rpm -ql golang | grep include
/usr/lib/golang/include

(This is for Fedora 20)

A: the values should be (MACOS):
GOROOT="/usr/local/go" --> all binaries file core go
GOPATH="/Applications/proyectos/go" --> the route to workspace (custom workspace)

A: in osx, i installed with brew, here is the setting that works for me
GOPATH="$HOME/my_go_work_space" //make sure you have this folder created

GOROOT="/usr/local/Cellar/go/1.10/libexec"

A: I had to append
export GOROOT=/usr/local/Cellar/go/1.10.1/libexec

to my ~/.bash_profile on Mac OS X

A: There is also a case where when we use go it compiles all the go files.
So lets say we had one file main.go and later we changed the current file to main_old.go and then added our new main.go file. Then when we build our app all the go files will get compiled. So the error that's happening might be due to compilation error in some other go files.

A: Once Go lang is installed, GOROOT is the root directory of the installation.
When I exploded Go Lang binary in Windows C:\ directory, my GOROOT should be C:\go.
If Installed with Windows installer, it may be C:\Program Files\go (or C:\Program Files (x86)\go, for 64-bit packages)
 GOROOT = C:\go

while my GOPATH is location of Go lang source code or workspace.
If my Go lang source code is located at C:\Users\\GO_Workspace, your GOPATH would be as below:
 GOPATH = C:\Users\<xyz>\GO_Workspace

A: For all newcomers they could do a simply export GOPATH=$HOME/go if you are using Ubuntu or do go help gopath for more information.


text:
Q: Showing that Normalized Redundancy is nonreliant on the properties of Bijection and Monotonicity In information theory, the concept of mutual information states that for two features of arbitrary discretized probability, the following formula holds true:
\begin{aligned}
I(X;Y) = \sum_{y \in Y} \sum_{x \in X}
                 \ p(x,y)\ \log_b{ \left( \frac{p(x,y)}{p_1(x)\ p_2(y)}
                              \right) }
\end{aligned}
And that for continuous distributions:
\begin{aligned}
I(X;Y) = \int_Y \int_X
                 \ p(x,y)\ \log_b{ \left( \frac{p(x,y)}{p_1(x)\ p_2(y)}
                              \right) } \; dx\ dy
\end{aligned}
(Source.)
It is further posited, as an application of mutual information, computing the nat, bit, or ban length of the combined source signal, with respect to the log base used, provides a useful normalized metric that can be used to show bags of information explain, or do not explain, one other.
That is, the absolute redundancy of information, $R$, may be expressed in terms of mutual information and the Shannon entropy of $X$ and $Y$ as:
\begin{aligned}
R= \frac{I(X;Y)}{H(X)+H(Y)}
\end{aligned}
Where $H(X)$ is defined in the discrete case as:
\begin{aligned}
H(X) =-\sum_{x \in X}\ {p(x)\ \log_b\ p(x)},
\end{aligned}
$H(Y)$ using the same formula.
(Source 1, Source 2, further information.)
One may then normalize this value by computing $R_{\max }$ as:
\begin{aligned}
R_{\max }=\frac{\min (H(X),H(Y))}{H(X)+H(Y)}
\end{aligned}
Then, using the properties of mutual information and Shannon entropy, normalize between $[0, R_{\max }]$, since the result is guaranteed to be positive and upwardly bounded by $R_{\max }$.

Assuming all of this is correct, I am attempting to use this as a drop-in replacement for Pearson's and Spearman's correlations for determining feature dependence in pairspace, for relationships that are neither bijective nor monotonic (that is, for bags of categorical data with overlap and no defined natural order).
My question, then, is a means to or illustration of these properties (a lack of reliance on bijection and monotonicity) in closed form, such that I may present these data to my peers in a mathematically rigorous way. I am not a mathematician, and as point of fact, discovering these properties took me a great deal of research to piece together.
My long term goal is to use these formulae to provide a strong model for explainability without relying on crude determinants for correlation. So, a bonus question better directed towards Stats.SE, which may see a subset of this question: how might one derive a convincing PDF or discretized p-value from normalized redundancy within the result space? My intuition states that it's a simple matter of discretization, using normalized redundancy as a score.


text:
Q: Plain  element vs Bootstrap's dropdown element rendered on mobile device Today I've learnt something new, that <select> element rendered completely different on a desktop and mobile browser. The problem that I haven't use it before and almost all stuff I've done,  is by using Bootstrap's elements.
So my question is actually 2 questions are following:

*

*Why <select> tag rendered differently on mobile chrome and desktop chrome when I debugging in mobile mode? Is it intended behaviour or I can consider it as bug? For example open following page http://www.w3schools.com/tags/tag_select.asp from desktop browser in dev mobile mode and on a hardware device, you will see the difference.

*What is the best approach to achieve consistency across various devices? Can I be sure that in all new mobile devices <select> will be rendered "in a mobile way", or just implement my own select element based on Bootstrap modal combined with List group as I've done here: http://codepen.io/anatoly314/pen/EPBmrM?editors=1010 ?

A: DevTools Device Mode does not emulate mobile-specific UA handling of form elements. This is actually very tricky to do since those things are compiled for that platform build.
The best thing to do is know there will be a difference. In the case of select elements it really doesn't matter much. Since the mobile UX is a full screen scroll selector of the choices.
The absolute best thing, as always, is use Device Mode as a guideline. It is not absolute nor can it be. You will always need to do on-device testing to verify everything works as expected. DM simply gets you 85-90% of the way there without issue.


text:
Q: what will be the o/p of this c code? why?
Possible Duplicate:
in c printf() returns what

what will be the o/p of this c code? why?
i=printf("hellow");
printf("%d",i);

Thanks..

A: Homework? Anyway, printf returns the number of characters printed. That should help.

A: Output is
hellow6
as printf returns number of characters it has printed...

A: Output will be:
hellow6

Reason:
The first printf will print 6 characters ("hellow"), which will be the return value, assigned to i.
The second printf will print i, which will be 6.
Since there is no NewLine or other separator specified, the two will be run together as hellow6.

A: Assuming that you ran the code and see the output:
hellow6
The explanation is, printf returns the number of characters it was able to write successfully.


text:
Q: Find missing rows for a column in the same table I need to find the missing rows that exist in a table of our SQL Server.  I have a list of 3 items, for example, that must always exist for each header_id as individual rows with the appropriate product_id.
So ideally the data should be appear as this:
header_id    product_id       product_group_id
    10       Main Product     7
    10       Bundle Item 1    50
    10       Bundle Item 2    50
    10       Bundle Item 3    50

However, due to the process in which the information is added to the database it requires each line to be added individually by the data entry person.  As a result we are seeing values such as this where "Bundle Item 2" is missing:
header_id    product_id       product_group_id
    10       Main Product     7
    10       Bundle Item 1    50
    10       Bundle Item 3    50

The following script displays the header_id's that are missing a missing product_id however it only provides the product_id of "Main Product".
SELECT header_id, product_id, product_group_id
FROM Table1
WHERE
   (product_id = 'Main Product')
   AND (header_id NOT IN (SELECT product_id
                          FROM table1 AS table1_1
                          WHERE (product_id = 'Bundle Item 2')))

I know I can use unions to group multiple queries and force a description value such as this below but would prefer an alternative way if possible.
SELECT header_id, product_id, product_group_id, 'Bundle Item 2' as Description
FROM Table1
WHERE
   (product_id = 'Main Product')
   AND (header_id NOT IN (SELECT product_id
                          FROM table1 AS table1_1
                          WHERE (product_id = 'Bundle Item 2')))
UNION
SELECT header_id, product_id, product_group_id, 'Bundle Item 3' as Description
FROM Table1
WHERE
   (product_id = 'Main Product')
   AND (header_id NOT IN (SELECT product_id
                          FROM table1 AS table1_1
                          WHERE (product_id = 'Bundle Item 3')))

A: yup,you hv to redesign your DB.There can be so many data namely anything.how do i know under which main product id comes what all sub product id.and if anything is missing .I cannot hard code 'Bundle Item 2'.
If each main product will have at least 3 sub product then using row_number you can find...what ?
Declare @t table (header_id int,product_id varchar(50),product_group_id int)
insert into @t
 select   10,       'Main Product',     7 union all
select  10,       'Bundle Item 1'  ,  50  union all
select    10,       'Bundle Item 2' ,   50 union all
select    10,       'Bundle Item 3'  ,  50

select *,row_number()over(order by product_id)rn from @t where product_group_id<>7

A: If you know you need exactly those four products, then you can handle this by creating all possible combinations of header_id and product.  Then use left outer join to find the ones that are missing:
with prods as (
      select 'Main Product' as product union all
      select 'Bundle Item 1' union all
      select 'Bundle Item 2' union all
      select 'Bundle Item 3'
     ),
     allheaderprods as (
      select distinct header_id, product
      from prods cross join
           table1
     )
select ahp.*
from allheaderprocs ahp left outer join
     header h
     on ahp.header_id = h.header_id and
        ahp.product = h.product
where ahp.header_id is null;


text:
Q: search and append a string inside a configuration file i have a folder that contain more than 200 folder every folder has a file named default.conf. the issue is i want search and append inside all default.conf files this : $site/
for example i have :
/var/rSave/$site/default.conf
and all default.conf their is a line contain : root_path    /var/rSave/
so i want to change all lines in default.conf files to the next :
root_path    /var/rsave/sitename.com/
that's why i try to execute the  next shell :
for site in $(ls /var/rSave/); do
sed -i "s/ snapshot_root   \/var\/rSave\/ / snapshot_root   \/var\/rSave\/$site\/ /g" /var/rSave/$site/default.conf ;
done

but it's not working.

A: You typed snapshot_root instead of root_path
for site in $(ls /var/rSave/); do
   sed -i "s/root_path \/var\/rSave\//root_path \/var\/rSave\/$site\/ /g" /var/rSave/$site/default.conf ;
done


text:
Q: How Properly run a background service? This is my problem : I want to add some background notification to my application.
So I thought to use alarmanager and a broadcast Receiver in the order to repeat the task.
But how can I start the broadcast in one activity for later on destroy it in a different activity without creating more than 1 broadcast?

A: Each activity should register a broadcast receiver in each of the activities' onResume method. Don't forget to unregister in onPause.

A: Here is my code for notification,
  public class NotificationService extends Service {
// constant
public static final long NOTIFY_INTERVAL = 30 * 1000; // 30 seconds
long current_times;
String c_time;
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
static HttpClient client = new DefaultHttpClient();
private Timer mTimer = null;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@TargetApi(Build.VERSION_CODES.GINGERBREAD) @SuppressLint("NewApi") @Override
public void onCreate() {
    // cancel if already existed

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    SharedPreferences.Editor editor = getSharedPreferences("notification_oldtime", MODE_PRIVATE).edit();

     editor.putInt("old_trail_time", 0);
     editor.putInt("old_sample_time", 0);
     editor.putInt("old_neworder_time", 0);

     editor.commit();

    if(mTimer != null) {
        mTimer.cancel();
    } else {
        // recreate new
        mTimer = new Timer();
    }
    // schedule task
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}

public long current_time_get(){

    return current_times;

}

class TimeDisplayTimerTask extends TimerTask {

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override
    public void run() {
        // run on another thread

        mHandler.post(new Runnable() {

            @Override
            public void run() {
                // display toast

                DBAdapter.init(getApplicationContext());
                SharedPreferences prefs = getSharedPreferences("notification_oldtime", MODE_PRIVATE);
                SharedPreferences.Editor editor = getSharedPreferences("notification_oldtime", MODE_PRIVATE).edit();

                int sample_order_new_count=0,trail_order_new_count=0,new_order_new_count=0,old_sample_order_count=0,old_trail_order_count=0,old_new_order_count=0;
                String      search_read_URL=DBAdapter.getUrlName()+"/web/dataset/search_read";
                JSONArray sample_jsonarray,trail_jsonarray,new_jsonarray;

                JSONObject jsonObj_sample,jsonObj_trail,jsonObj_newOrder;
                StringEntity sample_entity,new_order_entity,trail_entity;
                String responseBody_sample,responseBody_Trail,responseBody_NewOrder;

            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            try{

                DBAdapter.init(getApplicationContext());
                //  notification for sample order
                HttpPost sample_get = new HttpPost(search_read_URL);
                HttpPost new_order_get = new HttpPost(search_read_URL);
                HttpPost trail_get = new HttpPost(search_read_URL);
                Log.d("service","start");
                sample_entity = new StringEntity(" {\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{\"model\":\"sale.sample.order\",\"fields\":[\"partner_id\",\"distributor_id\",\"marketing_person_id\",\"__last_update\"],\"domain\":[],\"context\":{\"lang\":\"en_US\",\"tz\":false,\"uid\":"+Integer.valueOf(DBAdapter.getMarketPersonUid())+",\"params\":{\"page\":0,\"limit\":500,\"view_type\":\"list\",\"model\":\"sale.sample.order\",\"menu_id\":378,\"action\":446,\"_push_me\":false},\"bin_size\":true},\"offset\":0,\"limit\":500,\"sort\":\"\"},\"id\":780343122}");
                new_order_entity=new StringEntity("{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{\"model\":\"new.order.log\",\"fields\":[\"name\",\"partner_id\",\"distributor_id\",\"marketing_person_id\",\"__last_update\"],\"domain\":[],\"context\":{\"lang\":\"en_US\",\"tz\":false,\"uid\":"+Integer.valueOf(DBAdapter.getMarketPersonUid())+",\"params\":{\"page\":0,\"limit\":500,\"view_type\":\"list\",\"model\":\"new.order.log\",\"menu_id\":355,\"action\":418,\"_push_me\":false},\"bin_size\":true},\"offset\":0,\"limit\":500,\"sort\":\"\"},\"id\":674827326}");
               trail_entity=new StringEntity("{\"jsonrpc\":\"2.0\",\"method\":\"call\",\"params\":{\"model\":\"leather.trial.order\",\"fields\":[\"partner_id\",\"distributor_id\",\"marketing_person_id\",\"__last_update\"],\"domain\":[],\"context\":{\"lang\":\"en_US\",\"tz\":false,\"uid\":"+Integer.valueOf(DBAdapter.getMarketPersonUid())+",\"params\":{\"page\":0,\"limit\":500,\"view_type\":\"list\",\"model\":\"leather.trial.order\",\"menu_id\":375,\"action\":442,\"_push_me\":false},\"bin_size\":true},\"offset\":0,\"limit\":500,\"sort\":\"\"},\"id\":455581058}");

                sample_get.setHeader("Content-Type", "application/json");
                sample_get.setHeader("Cookie:","session_id="+DBAdapter.getSessionId());
                sample_get.setEntity(sample_entity);

                new_order_get.setHeader("Content-Type", "application/json");
                new_order_get.setHeader("Cookie:","session_id="+DBAdapter.getSessionId());
                new_order_get.setEntity(new_order_entity);

                trail_get.setHeader("Content-Type", "application/json");
                trail_get.setHeader("Cookie:","session_id="+DBAdapter.getSessionId());
                trail_get.setEntity(trail_entity);

                responseBody_sample = client.execute(sample_get, responseHandler);
                jsonObj_sample = new JSONObject(responseBody_sample);
                JSONObject json=jsonObj_sample.getJSONObject("result");
                sample_jsonarray = json.getJSONArray("records");

                responseBody_Trail=client.execute(trail_get, responseHandler);
                jsonObj_trail=new JSONObject(responseBody_Trail);
                JSONObject json1=jsonObj_trail.getJSONObject("result");
                trail_jsonarray = json1.getJSONArray("records");

                responseBody_NewOrder=client.execute(new_order_get,responseHandler);
                jsonObj_newOrder=new JSONObject(responseBody_NewOrder);
                JSONObject json2=jsonObj_newOrder.getJSONObject("result");
                new_jsonarray=json2.getJSONArray("records");

                long server_Time = 0;

                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

                String new_order_name="",trail_order_name="",sample_order_name="";

                 for (int m = 0; m <trail_jsonarray.length(); m++) {
                  JSONObject c =  trail_jsonarray.getJSONObject(m);
                  JSONArray cus_json_array=c.getJSONArray( "partner_id");
                  JSONArray market_person_json_array=c.getJSONArray( "marketing_person_id");
                   Date date = format.parse(String.valueOf(c.getString("__last_update")));
                   server_Time = date.getTime();

                 DBAdapter.init(getApplicationContext());
                 long current_time=Long.parseLong(DBAdapter.getCurrentTime());
                 Log.d("trail ct"+current_time,"st"+server_Time);
                 if(server_Time>current_time){
                     trail_order_new_count++;
                     Log.d("trail_order cus name",cus_json_array.getString(1));
                     trail_order_name=trail_order_name+" "+"Customer="+cus_json_array.getString(1)+"\n"+"Marketing Person="+market_person_json_array.getString(1);
                }
                 else{
                     m=trail_jsonarray.length();
                 }

               }

                 for (int m = 0; m <sample_jsonarray.length(); m++) {
                     JSONObject c = sample_jsonarray.getJSONObject(m);
                     JSONArray cus_json_array=c.getJSONArray( "partner_id");
                     JSONArray market_person_json_array=c.getJSONArray( "marketing_person_id");
                   Date date = format.parse(String.valueOf(c.getString("__last_update")));
                   server_Time = date.getTime();

                 DBAdapter.init(getApplicationContext());
                 long current_time=Long.parseLong(DBAdapter.getCurrentTime());
                 Log.d("sample ct"+current_time,"st"+server_Time);
                    if(server_Time>current_time){
                     sample_order_new_count++;
                     Log.d("sample_order cus name",cus_json_array.getString(1));
                     sample_order_name=sample_order_name+" "+"Customer="+cus_json_array.getString(1)+"\nMarketing Person="+market_person_json_array.getString(1);
                    }

                 else{
                     m=trail_jsonarray.length();
                 }

                  }

                 for (int m = 0; m <new_jsonarray.length(); m++) {
                     JSONObject c =  new_jsonarray.getJSONObject(m);
                     JSONArray cus_json_array=c.getJSONArray( "partner_id");
                     JSONArray market_person_json_array=c.getJSONArray( "marketing_person_id");
                   Date date = format.parse(String.valueOf(c.getString("__last_update")));
                   server_Time = date.getTime();

                 DBAdapter.init(getApplicationContext());
                 long current_time=Long.parseLong(DBAdapter.getCurrentTime());
                 Log.d("newOrder ct"+current_time,"st"+server_Time);
                 if(server_Time>current_time){
                     new_order_new_count++;
                     Log.d("new_order cus name",cus_json_array.getString(1));
                     new_order_name=new_order_name+" "+"Customer="+cus_json_array.getString(1)+"\nMarketing Person="+market_person_json_array.getString(1);
                    }

                 else{
                     m=trail_jsonarray.length();
                 }

                  }

               int newOrder_ID=100,sampleOrder_ID=200,trailOrder_ID=300;
               final NotificationManager mgr=
                          (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
                    PendingIntent i2=PendingIntent.getActivity(getApplicationContext(), 1,
                         new Intent(getApplicationContext(),MainActivity.class),
                         0);

                Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

                if (new_order_new_count>prefs.getInt("old_neworder_time", 0)) {
                          NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(getApplicationContext());
                          mBuilder .setStyle(new NotificationCompat.BigTextStyle().bigText(new_order_name));
                          mBuilder.setContentText(new_order_name);
                          mBuilder.setContentTitle(new_order_new_count+" New Orders");
                          mBuilder.setSmallIcon(R.drawable.bkg_new_logo);
                          //mBuilder.setNumber(++numMsg);
                          mBuilder.setContentIntent(i2);
                          Log.d(String.valueOf(old_new_order_count),String.valueOf(new_order_new_count));
                          if(old_new_order_count!=new_order_new_count){
                          mBuilder.setSound(alarmSound);
                          }
                          mgr.notify(newOrder_ID, mBuilder.build());
                          old_new_order_count=new_order_new_count;
                       editor.putInt("old_neworder_time", new_order_new_count);
                      editor.commit();
                    }
              if (sample_order_new_count>prefs.getInt("old_sample_time", 0)) {
                      NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(getApplicationContext());
                      mBuilder .setStyle(new NotificationCompat.BigTextStyle().bigText(sample_order_name));
                      mBuilder.setContentText(sample_order_name);
                      mBuilder.setContentTitle(sample_order_new_count+" Sample Orders");
                      mBuilder.setSmallIcon(R.drawable.bkg_new_logo);
                      //mBuilder.setNumber(++numMsg);
                      mBuilder.setContentIntent(i2);
                      if(old_sample_order_count!=sample_order_new_count){
                      mBuilder.setSound(alarmSound);
                      }
                      mgr.notify(sampleOrder_ID, mBuilder.build());
                      old_sample_order_count=sample_order_new_count;
                      editor.putInt("old_sample_time", sample_order_new_count);
                      editor.commit();
              }
             if (trail_order_new_count>prefs.getInt("old_trail_time", 0)) {
                  NotificationCompat.Builder  mBuilder = new NotificationCompat.Builder(getApplicationContext());
                  mBuilder .setStyle(new NotificationCompat.BigTextStyle().bigText(trail_order_name));
                  mBuilder.setContentText(trail_order_name);
                  mBuilder.setContentTitle(trail_order_new_count+" Trail Orders");
                  mBuilder.setSmallIcon(R.drawable.bkg_new_logo);
                  //mBuilder.setNumber(++numMsg);
                  mBuilder.setContentIntent(i2);
                  if(old_trail_order_count!=trail_order_new_count){
                  mBuilder.setSound(alarmSound);
                  }
                  mgr.notify(trailOrder_ID, mBuilder.build());
                  old_trail_order_count=trail_order_new_count;

                  editor.putInt("old_trail_time", trail_order_new_count);
                  editor.commit();
             }

            }
               catch(Exception e){
                   e.printStackTrace();
               }
               }

        });
    }

}
}

You can set the periodic time using NOTIFY_INTERVAL.
 In my code I use 30 seconds.
every 30 seconds my service run in background.
I hope this code help you..


text:
Q: Create charge using Stripe in Laravel working in test mode but not in live Hope somebody can help me with this one.
I am clueless right now.
I just started stripe for the first time.
Looks like an amazing service.
Have created a test application and started testing.
Everything works as it should.
Now after signing up, I want to go live.
Here is where the problem occurs.
Somehow, it keeps saying no such token, when I can see the token standing in the stripe account. The id of the account and our database is completely the same.
Stripe::setApiKey('[our live token]');

/*
* create new customer
*/
$results = \Stripe\Charge::create([
   "amount"            =>          '10',
   "currency"          =>          "jpy",
   "source"            =>          $getCommission->unique_id,
   "description"       =>          "test charge"
]);

Anybody has ever experienced this?
It keeps saying the following
No such token: cus_EuguGZgeDoCxBj

Help is highly appriciated.
Wesley

A: You are providing customer id instead of source token.
Source Token :
Source token is token which is used for referenced of your cards. Generated from Stripe.js
\Stripe\Stripe::setApiKey("sk_test_4eC39HqLyjWDarjtT1zdp7dc");

\Stripe\Charge::create([
      "amount" => 2000,
      "currency" => "usd",
      "source" => "tok_amex", // obtained with Stripe.js
      "description" => "Charge for jenny.rosen@example.com"
 ]);

How to get Default Source :

*

*Get Stripe Customer

*Get default source on the Behalf of that customer
  \Stripe\Stripe::setApiKey("sk_test_4eC39HqLyjWDarjtT1zdp7dc");

  $customer = \Stripe\Customer::retrieve('cus_EkSwM3JX7f0ueA');
  $customer->default_source; // use this as source token

Use default source as source token


text:
Q: multiple markers at this line I get the below error in the line this.viewcam.setOnClickListerner(new view.OnClickListerner()).
I get this error in eclipse.
Multiple markers at this line

*

*The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (new OnClickListener(){})

*view cannot be resolved to a type

    public class Main extends Activity
    implements View.OnClickListener
    {
    Button viewcam;
    EditText editTextIp;
    EditText login;
    EditText passwd;
    public void onCreate(Bundle paramBundle)
    {
      super.onCreate(paramBundle);
      setContentView(R.layout.main);
      this.viewcam = ((Button)findViewById(R.id.viewcam));
      this.viewcam.setOnClickListener(new view.OnClickListener() {
  public void onClick(View v) {
  // TODO Auto-generated method stub
    if (v == this.viewcam)
      {
        Log.i("login", this.login.getText().toString());
        Log.i("Passwd", this.passwd.getText().toString());
        Intent localIntent1 = new Intent(v.getContext(), MjpegSample.class);
        Log.i("My ip", this.editTextIp.getText().toString());
        localIntent1.putExtra("ip", "http://" +                 this.editTextIp.getText().toString() + "/");
        localIntent1.putExtra("user", this.login.getText().toString());
        localIntent1.putExtra("passwd", this.passwd.getText().toString());
        startActivityForResult(localIntent1, 1000);
      }     }
               });
 this.editTextIp = ((EditText)findViewById(R.id.ip));
 this.login = ((EditText)findViewById(R.id.username));
 this.passwd = ((EditText)findViewById(R.id.password));

}
  }

A: Change
 this.viewcam.setOnClickListener(new view.OnClickListener() {

To
 this.viewcam.setOnClickListener(new OnClickListener() {

A: You need to capitalize View in
this.viewcam.setOnClickListener(new view.OnClickListener() {

so it should be
this.viewcam.setOnClickListener(new View.OnClickListener() {


text:
Q: in-App purchase restore button alternative placement My app was rejected because of not having 'restore' button... i'm in a situation where i don't have space to put 'restore' button, i have tableView and on the right navigation, i have segment and left is obviously 'back' button.. the only option left for me is to drag down the tableview, which will messup my beautiful interface...
current purchase process: user taps on the tableview, it brings up an Alert to confirm user wants to buy product, upon confirmation, in-App purchase methods fires... i was wondering if there is an alternate way to put 'restore' button or should i put 'restore' button in alert or actionsheet maybe? and not getting rejected by Apple again? please help!

A: Do you have a settings page in your app anywhere?  Most apps with IAP put the "Restore purchases" there.  If your app is a list of items the user can purchase, consider adding a final row in your table view and have that row be "restore purchases"


text:
Q: Silence biber warning "Invalid field 'XXX' for entrytype 'YYY'" I have created a few aliases of bibliography types, e.g. standard is a report or software is online. Now, when using such types in my bib file and enabled --validate-datamodel, I get warnings like:

Datamodel: Entry 'Spread' (thesis.bib): Invalid field 'url' for entrytype 'software'

How can I make biber happy about this again? Any way to enhance the data model for the aliases?
MWE
\documentclass{article}

\usepackage{filecontents}

\begin{filecontents}{test.bib}
@standard{RFC4627,
 date = {2006},
 editor = {IETF},
 number = {4627},
 title = {The application/json Media Type for {JavaScript} Object Notation ({JSON})},
 type = {RFC},
 url = {http://www.ietf.org/rfc/rfc4627.txt},
 urldate = {2016-09-08}
}

@software{Spread,
 label = {Spread},
 title = {The Spread Toolkit},
 url = {http://www.spread.org/},
 urldate = {2016-09-08}
}
\end{filecontents}

\usepackage[backend=biber,style=alphabetic]{biblatex}

\DeclareBibliographyAlias{software}{online}
\DeclareBibliographyAlias{standard}{report}
\bibliography{test}

\begin{document}
    \nocite{*}
    \printbibliography{}
    % should still work
    \printbibliography[heading=bibintoc,type=software,title={List of Software Packages}]{}
\end{document}

Compiled using latexmk with the following latexmkrc:
$pdf_mode = 1;
$pdflatex = 'pdflatex -shell-escape -interaction=nonstopmode';

$biber = 'biber --validate-datamodel %O %S';

A: As explained in What exactly is the relationship BibLaTeX refers to as an alias of an entry type? And how should the formatting of aliased entry types be configured? the alias defined by \DeclareBibliographyAlias is only for bibliography driver purposes. The alias is only accessible for biblatex. In particular Biber does not know about it.
You could do
\DeclareDriverSourcemap[datatype=bibtex]{
  \map{
    \pertype{software}
    \step[typesource=software, typetarget=online, final]
    \step[fieldset=keywords, fieldvalue={,type:software}, append]
  }
  \map{
    \pertype{standard}
    \step[typesource=standard, typetarget=report, final]
    \step[fieldset=keywords, fieldvalue={,type:standard}, append]
  }
}

This will remap @software to @online and @standard to @report for all intents and purposes (so you can't select by type any more). To remedy this, we add keywords that give the former type with the keyword type:<type>.
Now your filtering is not type=<type>, but keyword = {type:<type>}, i.e.
\printbibliography[heading=bibintoc, keyword=type:software],

instead of \printbibliography[heading=bibintoc, type=software].


text:
Q: trouble while using anaconda2 and pycharm after i installed anaconda2, and my interpreter is the python.exe in anaconda2. But there is no package like numpy, scipy, matplotlib .etc in the environment.

A: You should install additional packages like numpy and scipy via pip command, for example:
pip install numpy