text:
Q: What should happen, when we try to modify a string constant? #include<stdio.h>
#include<string.h>

int main()
{
    int i, n;
    char *x="Alice"; // ....... 1
    n = strlen(x);   // ....... 2
    *x = x[n];       // ....... 3
    for(i=0; i<=n; i++)
    {
        printf("%s ", x);
        x++;
    }
    printf("\n");
    return 0;
}

String constant cannot be modified. In the above code *x means 'A'. In line 3 we are trying to modify a string constant. Is it correct to write that statement? When I run this code on Linux, I got segmentation fault. But on www.indiabix.com, they have given answer:

If you compile and execute this program in windows platform with Turbo C, it will give lice ice ce e It may give different output in other platforms (depends upon compiler and machine). The online C compiler given in this site will give Alice lice ice ce e as output (it runs on Linux platform).

A: Your analysis is correct. The line
*x = x[n];

is trying to modify a string literal, so it's undefined behavior.

BTW, I checked the website that you linked. Just browsing it for two minutes, I've already found multiple incorrect code samples (to name a few, using gets, using char(not int) to assign return value of getchar, etc), so my suggestion is don't use it.

A: Your analysis is correct, but doesn't contradict what you quoted.
The code is broken. The answer already acknowledges that it may behave differently on different implementations, and has given two different outputs by two different implementations. You happen to have found an implementation that behaves in a third way. That's perfectly fine.

A: In this code, the memory for "Alice" will be in the read-only data section of the executable file and x is a pointer pointing to that read-only location. When we try to modify the read-only data section, it should not allow this. But char *x="Alice"; is telling the compiler that x is declared as a pointer to a character, i.e. x is pointing to a character which can be modified (i.e. is not read-only). So the compiler will think that it can be modified. Thus the line *x = x[n]; will behave differently on different compilers. So it will be undefined behavior.
The correct way of declaring a pointer to a assign string literal is as below:
const char *x ="Alice";

Only then can the behavior of the compiler be predicted.

A: Modification of a string literal is Undefined Behaviour.  So the behaviour you observe, and the two described, are consistent with the requirements of the C standard (as is emailing your boss and your spouse, or making demons fly out of your nose).  Those three are all actually quite reasonable actions (modify the 'constant', ignore the write, or signal an error).
With GCC, you can ask to be warned when you assign the address of a string literal to a pointer to (writable) char:
cc -g -Wall -Wextra -Wwrite-strings   -c -o 27211884.o 27211884.c
27211884.c: In function 'main':
27211884.c:7:13: warning: initialization discards 'const' qualifier from pointer target type [enabled by default]
     char *x="Alice"; // ....... 1
             ^

This warning is on by default when compiling C++, but not for C, because char* is often used for string literals in old codebases.  I recommend using it when writing new code.
There are two correct ways to write the code of the example, depending on whether you want your string to actually be constant or not:
const char *x = "Alice";

char x[] = "Alice";


text:
Q: Subquerying in MongoEngine Having the sample code:
import mongoengine as mongo

class User(mongo.Document):
    name = mongo.StringField()
    age = mongo.IntField()

class Post(mongo.Document):
    title = mongo.StringField()
    author = mongo.ReferenceField(User)

I want to get all the posts created by users with ages below 30, one way is to make the request in two steps:
users = User.objects(age__lt=30)
posts = Post.objects(author__in=users)

But even this is not totally bad, it is calling and connecting to the database N times unnecessarily. So I want to make the query in just one step, I tried:
posts = Post.objects(author__age__lt=30)

But does not work, it just returns me a empty list, not an error. What am I doing wrong?

A:
What am I doing wrong?

Nothing you can't query across reference fields - see Embed Vs Reference
So even if the syntax was supported it would take two queries behind the scenes.  If its something thats wanted - add a ticket to github and I'll look into adding it :)
Updates to MongoEngine are coming in thick and fast at the moment - so a new release will be coming soon!  Some exciting improvements are on the dev branch, including efficient lazy dereferencing and update deltas for atomic saving!

A:
... it is calling and connecting to the database N times unnecessarily

MongoDB supports an $in clause that allows for the selection of multiple objects with only one query, one connection. If you're seeing multiple connections, you should probably report this to the author of mongoengine.
Because MongoDB does not support joins, your method of "load users, load their posts" is generally the correct method.

What am I doing wrong?

For this level of detail, your best bet is to contact the author directly. The github page has both his e-mail and his blog. Looking at the repo, his last update was October 2010 and the last version number was 0.4. Three months with no update is a long time in this space and he doesn't even have a 1.0 version, so it's quite likely that you'll need to speak with the author directly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Efficiently label each row in a large dataframe I have a file containing dates from June 2015 + 365 days. I am using this as a lookup table because there are custom business dates (only certain holidays are observed and there are some no-work dates because of internal reasons). Using the customer business date offsets was just so slow with 3.5 million records.
initial_date | day_1      | day_2      | day_3      | ... | day_365
2015-06-01     2015-06-02   2015-06-03   2015-06-04
2015-06-02     2015-06-03   2015-06-04   2015-06-05

The idea is to 'tag' each row in the data based on the number of (custom) business dates since specific entries. Is there a better way to do this?
For example, if a new entry happens on 2016-06-28 then this is labeled as 'initial_date'. day_1 is tomorrow, day_2 is the next day, day_3 is Friday, and day_4 is next Monday.
My naive way of doing this is to create a loop which basically does this:
 df.day_1_label = np.where(df.date == df.day_1, 'Day 1', '')
 df.day_2_label = np.where(df.date == df.day_2, 'Day 2', '')

df.day_label = (df.day_1_label + df.day_2_label + ...).replace('', regex=True, inplace=True)

This would result in one label per row which I could then aggregate or plot. Eventually this would be used for forecasting. initial_date + the subset of customers from previous dates = total customers
Also, depending on what events happen, a subset of the customers would have a certain event occur in the future. I want to know on what business date from the initial_date this happens on, on average. So if we have 100 customers today, a certain percent will have an event next July 15th or whatever it might be.
Edit- pastebin with some sample data:
http://pastebin.com/ZuE1Q2KJ
So the output I am looking for is the day_label. This basically checks if the date == each date from day_0 - day_n. Is there a better way to fill that in? I am just trying to match the date of each row with a value in one of the day_ columns.

A: I think this can be made more efficiently if your data looks as I think it looks.
Say you have a calendar of dates (June 2015 + 365 days) and a data frame as for example:
cal = ['2015-06-01', '2015-06-02', '2015-06-03', '2015-06-04', '2015-06-08',
       '2015-06-09']

df = pd.DataFrame({'date': ['2015-06-04', '2015-06-09', '2015-06-09'],
                   'initial_date': ['2015-06-02', '2015-06-02', '2015-06-01']})

Keeping dates in numpy.datetime types is more efficient, so I convert:
df['date'] = df['date'].astype(np.datetime64)
df['initial_date'] = df['initial_date'].astype(np.datetime64)

Now, let's turn cal into a fast lookup table:
# converting types:
cal = np.asarray(cal, dtype=np.datetime64)

# lookup series
s_cal = pd.Series(range(len(cal)), index=cal)

# a convenience lookup function
def lookup(dates):
    return s_cal[dates].reset_index(drop=True)

EDIT:
The above lookup returns a series with a RangeIndex, which may be different from the index of df (this causes problems when assigning the result to a column). So it's probably better to rewrite this lookup so that it returns a plain numpy array:
def lookup2(dates):
    return s_cal[dates].values

It's possible to set the correct index in lookup (taken from the input dates). But such a solution would be less flexible (would require that the input be a Series) or unnecessarily complicated.

The series:
s_cal
Out[220]:
2015-06-01    0
2015-06-02    1
2015-06-03    2
2015-06-04    3
2015-06-08    4
2015-06-09    5
dtype: int64

and how it works:
lookup(df.date)
Out[221]:
0    3
1    5
2    5
dtype: int64

lookup2(df.date)
Out[36]: array([3, 5, 5])

The rest is straightforward. This adds a column of integers (day differences) to the data frame:
df['day_label'] = lookup2(df.date) - lookup2(df.initial_date)

and if you want to convert it to labels:
df['day_label'] = 'day ' + df['day_label'].astype(str)

df
Out[225]:
        date initial_date day_label
0 2015-06-04   2015-06-02     day 2
1 2015-06-09   2015-06-02     day 4
2 2015-06-09   2015-06-01     day 5

Hope this is what you wanted.


text:
Q: Any way to run shell commands on android programmatically? Is there any way to run terminal commands on my application and then access the data on my UI? Specifically top.

A: it also depends on what you are running in the terminal... if you are running "cat" on a file you can also do it like this.
final private String MEM_FILE = "/proc/meminfo";

public Long readMem() {
    String[] segs;
    FileReader fstream;
    try {
        fstream = new FileReader(MEM_FILE);
    } catch (FileNotFoundException e) {
        Log.e("readMem", "Could not read " + MEM_FILE);
        return false;
    }
    BufferedReader in = new BufferedReader(fstream, 500);
    String line;
    try {
        while ((line = in.readLine()) != null) {
            if (line.indexOf("MemTotal:") > 0) {
                Log.e("MemTotal", line);
                segs = line.trim().split("[ ]+");
                memTotal = Long.parseLong(segs[1]);
            }
            if (line.indexOf("MemFree:") > 0) {
                Log.e("MemFree", line);
                segs = line.trim().split("[ ]+");
                memFree = Long.parseLong(segs[1]);
            }
        }
        updateMem(); //call function to update textviews or whatever
        return true;
    } catch (IOException e) {
        Log.e("readMem", e.toString());
    }
    return false;
}

EDIT:
There is a perfect example for you in the android labs project called netmeter. There is a class called Top.java that actually does exactly what you want and it is used in TaskList.java to be displayed.
http://code.google.com/p/android-labs/source/browse/#svn/trunk/NetMeter/src/com/google/android/netmeter

A: Check out Log Collector as an example. Here is the relevant file.
The key is here:
ArrayList<String> commandLine = new ArrayList<String>();
commandLine.add("logcat");//$NON-NLS-1$
[...]

Process process = Runtime.getRuntime().exec(commandLine);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

A: Okay this is what exactly worked for me just in case anyone needs it in the future... :)
Surround in try and catch
try {
    Process process = Runtime.getRuntime().exec("top -n 1 -d 1");
    BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
} catch (InterruptedException e) {
    e.printStackTrace();
}

A: For Kotlin enthusiasts, you can use the following
fun executeShell() {
    val command: String = "top -n 1"
    try {
        val process: Process = Runtime.getRuntime().exec(command)
        // Read the lines using BufferedReader
        BufferedReader(InputStreamReader(process.inputStream)).forEachLine {
            // Do something on each line read
            Log.d(this::class.java.canonicalName, "$it")
        }
    } catch (e: InterruptedException) {
        Log.w(this::class.java.canonicalName, "Cannot execute command [$command].", e)
    } catch (e: Exception) {
        Log.e(this::class.java.canonicalName, "Cannot execute command [$command].", e)
    }
}

You won't even have to take care of closing the buffer, as forEachLine extension function takes care of it.

A: We, can execute commands as follow, i was succesfull in doing this....! try like this, here we need to specify the complete path of command. to get the complete path of commmand, at ur terminal (android) type
*$ which ls
/system/bin*
try {

    // Executes the command.

    Process process = Runtime.getRuntime().exec("/system/bin/ls /sdcard");

    // Reads stdout.
    // NOTE: You can write to stdin of the command using
    //       process.getOutputStream().
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(process.getInputStream()));
    int read;
    char[] buffer = new char[4096];
    StringBuffer output = new StringBuffer();
    while ((read = reader.read(buffer)) > 0) {
        output.append(buffer, 0, read);
    }
    reader.close();

    // Waits for the command to finish.
    process.waitFor();

    return output.toString();
} catch (IOException e) {

    throw new RuntimeException(e);

} catch (InterruptedException e) {

    throw new RuntimeException(e);
}


text:
Q: Double Integral of piece wise function? Let $I=[0,1]\times[0,1]$ and let $$f(x)= \begin{cases}
0, & \text{if (x,y)=(0,0)}\\
\frac{x^2-y^2}{(x^2+y^2)^2}, & \text { if (x,y)$\not=$(0,0)}\\
\end{cases}
$$
Need to show that $$\int^1_0\int^1_0 f(x,y)dxdy=\int_0^1\int_0^1 f(x,y)dydx.$$
I cant seem to integrate $$\int_0^1\frac{x^2-y^2}{(x^2+y^2)^2}dx.$$
I am thinking that I could use polar coordinates maybe by $r^2=x^2+y^2$.

A: Use a trig substitution: $x=y \tan{t}$.  Then the inner integral becomes
$$-\frac1y \int_0^{\arctan{(1/y)}} dx \: \cos{2 t} = -\frac{1}{1+y^2}$$
You should be able to do the outer integral from here.

A: Note that the current $f$ is anti-symmetric about $y=x$. Fubini doesn't apply since $f$ is not locally integrable at $0$. Indeed, the iterated integrals will be off by a factor of $-1$.


text:
Q: Inline math rendering limits underneath instead of besides the sum I'm here because I'm writing a thesis in LaTeX using overleaf and I'm having some troubles with the math inline style, which is not working.
This is what I'm writing:
$p_{nj}^2=\sum\limits_{i\in j}{\left|c_{in}\right|^2}$

and this is what I'm getting:

I know that using the inline math with $...$ the sum should have the limits on its right rather than right over and below it. How could I obtain this effect?

A: With \limits, you explicitly place them underneath. If you use \sum_{...} you get them, depending on the displaystyle, either besides or underneath:
\documentclass{article}

\usepackage{mathtools}

\begin{document}

$p_{nj}^2=\sum_{i\in j}{\left|c_{in}\right|^2}$

\end{document}


text:
Q: How to get my last google map location? Google maps have this button which shows your location based on your last track. Actually if i click this button it says that it got my location from my phone and it shows the correct address. Right now my application can track the user's location, but with a major downside. If the device has no GPS it tracks the IP location which the most of the time is not the actual user's position. Is there any way that i can integrate this feature in my application? I'm searching for an API but i haven't found something yet. Thanks

A: By following I assume you are talking about WEB-application.
Your browser can detect your location if you allow that. This data (latitude and longitude) could be obtained via JavaScript.
For instance: http://www.w3schools.com/html/html5_geolocation.asp
or  https://github.com/onury/geolocator.
Hundreds of example can be googled using query "javascrip geolocation library".


text:
Q: python: бот ищет не тот message.text в telebot Написал функцию "улучшение для авто", вот код:
        elif message.text == 'Установить диски' or message.text == 'установить диски':
            def start_2(message):
                file = open(f'c://tgplay/{message.chat.id}_money.py', 'r+')
                qw1 = int(file.read())
                nums = int(qw1)-int(300000)
                file.close
                bot.send_message(message.chat.id, 'Вы установили диски ' + '{}'.format(message.text) + ' на своё авто! Чтобы посмотреть введите "Машина".')

            file = open(f'c://tgplay/{message.chat.id}_money.py', 'r+')
            moneq = int(file.read())
            file.close
            if moneq >= int(300000):
                bot.send_message(message.chat.id, 'Внимание: после установки дисков на своё авто, вы больше не сможете его удалить!')
                if message.text == 'yokatta' or message.text == 'Yokatta':
                    file = open(f'c://tgplay/{message.chat.id}_avtoylych.py', 'x+', encoding="utf-8")
                    file.write(str('Yokatta'))
                    file.close
                elif message.text == 'racing superturismo' or message.text == 'Racing superturismo':
                    file = open(f'c://tgplay/{message.chat.id}_avtoylych.py', 'x+', encoding="utf-8")
                    file.write(str('Racing superturismo'))
                    file.close
                elif message.text == 'borbet' or message.text == 'Borbet':
                    file = open(f'c://tgplay/{message.chat.id}_avtoylych.py', 'x+', encoding="utf-8")
                    file.write(str('Borbet'))
                    file.close
                elif os.path.isfile(f'c://tgplay/{message.chat.id}_avtoylych.py'):
                    bot.send_message(message.chat.id, 'У вас уже есть диски на авто!')
                    return
                msg = bot.send_message(message.chat.id, 'Введите название дисков:')
                bot.register_next_step_handler(msg, start_2)
            else:
                bot.send_message(message.chat.id, 'Недостаточно средств!')

И когда я тестирую команду, бот визуально пишет что диск добавлен, но на background'e ничего не записывается, в чем ошибка? по моему написано всё правильно. Не судите строго, я новичок и прошу у вас помощи, заранее спасибо огромное!

A: Вы не закрываете файл, так как закрытие файла пишется со скобками:
file.close => file.close()
И ещё пару советов:
'Текст '+'{}'.format(переменная)+'текст' можно заменить на: f'Текст {переменная} текст'
А проверку, что написано в сообщении можно сделать с помощью нижнего регистра:
message.text = 'хОЧу пОМЕНять ДисКИ'
if message.text.lower() == 'хочу поменять диски':
    print(message.text)
Вывод: хОЧу пОМЕНять ДисКИ


text:
Q: I need help for a formula var a = document.forms[0].elements[0].value;
var b = document.forms[0].elements[1].value;
var c = document.forms[0].elements[2].value;
var d = document.forms[0].elements[3].value;
var Xp = document.forms[0].elements[4].value;
var Yp = document.forms[0].elements[5].value;

document.forms[0].elements[7].value = a/c;

document.forms[0].elements[8].value = (b*c-a*d)/(c*c);

document.forms[0].elements[9].value = c;

document.forms[0].elements[10].value = d;

document.forms[0].elements[11].value = Yp-(a/c*Xp)-((b*c-a*d)/(c*c)*(Math.log(Math.abs(c*Xp+d))));`

element 11 should be -1 but instead i get 6.20. I understood that the error is from Math.log to ;
is Math.log the natural logarithm? cause i have to do that

A: See the documentation of Math.log : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log
For further help you should ask your math teacher or someone who knows about algorithms ;-P
maybe you should see the part:
((b*c-a*d)/(c*c)*(Math.log(Math.abs(c*Xp+d))))
Maye you want to have the braces done like (x/(z*y)) or ((x*y)/z).

A: Edit : Using forms to input data Working code
<!DOCTYPE html>

<form id="frm1" action="" method = "Get">
  a: <input type="number" name="a" value="1">

  b: <input type="number" name="b" value="-3">

  c: <input type="number" name="c" value="1">

  d: <input type="number" name="d" value="4">

  Xp: <input type="number" name="Xp" value="1">

  Yp: <input type="number" name="Yp" value="-11.2661">

  <input type="button" id = "Submit" value="Read" onClick="foo(this.form)"/>
</form>

The problem lied with the (c*Xp + d). You see instead of evaluating (1+4) = 5 the code saw c d and Xp as strings and came out with (1+4) = 14 as adding one string to another.
using z = ((c*1))*(Xp) + (d*1)) must somehow cast the values to double so they evaluate to the right digit of 5.


text:
Q: Creating an euclidean distance matrix of tensors I have 10000 of matrixes with the shape (32, 32, 3). I want to create an euclidean distance matrix between all the matrixes. At the end, it is going to be like,
[0, d2, d3, d4, ...]
[d1, 0, d3, d4, ...]
[d1, d2, 0, d4, ...]
[d1, d2, d3, 0, ...]

How I can make it in the fastest way? I have tried the following, but it takes ages to finish.
import numpy as np
dists = []
for a in range(len(X_test)):
    dists.append([])
    for b in range(len(X_test)):
        dists[a].append(np.linalg.norm(X_test[a] - X_test[b]))
print dists

A: You can cut the time in half by exploiting the fact that the distance matrix is symmetrical and only compute the upper triangular portion by using using
for b in range(a+1, len(X_test)):

on line 5.
I don't see any other obvious optimizations while keeping the problem exactly the same, but it also seems that you're working with 32x32 images in a three channel format. That's 3072 dimensions! Why not first down-sample to 4x4, convert to HSL color space, and keep only Hue and Lightness to get a (4,4,2) "signature" for each image. If your problem is mostly about shape, you can throw away Hue too and basically work with black-and-white images.
(4,4,2) has only 32 dimensions, for a savings of 100 compared to (32,32,3). And if you did want to do the full comparison in the (32,32,3) space, you could do that only on images that are already very similar in the (4,4,2) space.

A: I have read Divakar comment.
Rather than asking "Show me Divakar" I asked myself "What is this pdist/cdist stuff?" — I read about pdist and norm and I came out with the following code
Import stuff:
In [1]: import numpy as np
In [2]: from scipy.spatial.distance import pdist

Generate a random sample, not necessarily as large as the OP's one, and reshape it as suggested by Divakar
In [3]: a = np.random.random((100,32,32,3))
In [4]: b = a.reshape((100,32*32*3))

Using the magic of IPython, let's benchmark the two approaches
In [5]: %%timeit
   ...: dists = []
   ...: for i in range(len(a)):
   ...:     dists.append([])
   ...:     for j in range(len(a)):
   ...:         dists[i].append(np.linalg.norm(a[i] - a[j]))
128 ms ± 337 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [6]: %timeit pdist(b)
12.3 ms ± 252 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Divakar's was 1 order of magnitude faster — but what about the accuracy?
Let's repeat the computations...
In [7]: dists1 = []
   ...: for i in range(len(a)):
   ...:     dists1.append([])
   ...:     for j in range(len(a)):
   ...:         dists1[i].append(np.linalg.norm(a[i] - a[j]))
In [8]: dists2 = pdist(b)

To compare the results, we must be aware that pdist computes only the upper triangle of the square matrix of distances (because the matrix is symmetric and the principal diagonal is identically equal to zero) so we must be careful in checking our results: hence I check the off diagonal part of the first row of dists1 with the first 99 elements of dists2 using allclose
In [9]: np.allclose(dists1[0][1:], dists2[:99])
Out[9]: True

The result is the same, nice.
What about an estimate of the time required for 10,000 elements? The feeling is that's quadratic, but let's experiment doubling the number of elements
In [10]: b = np.random.random((200,32*32*3))
In [11]: %timeit pdist(b)
48 ms ± 97.7 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [12]:

the new timing is 4 times the initial one, so my estimate for your computation, on my feeble pc and using Divakar's proposal, is 12ms x 100 x 100 = 120,000ms = 120s.  You should read carefully the excellent answer by olooney and decide what you really want to do.


text:
Q: Uniqueness of Laplace equation by energy method. Is there any energy method to show the uniqueness of the Laplace equation(2D)?
I can show easily the uniqueness of the Laplace equation with the Dirichlet conditions by using Green's identity. But I want to know that, Do we have any energy method? (Like we have an energy method to prove the uniqueness of heat and wave equations.) If it is then please specify!


text:
Q: Why trajectories are tangent to eigenline with smaller eigen value? I solved a matrix and got two eigen values which are 1 and 2. The eigen vectors corresponding to the values are (1,1) and (2,3).
This is an Unstable node.
While constructing the phase portrait I don't understand why the trajectories initially are tangent to eigenline with smaller eigen value.


text:
Q: find the longest palindrome I want to return the longest palindrome, for example "civic" return "civic", "fawziizw" return "wziizw"
This is what I tried:
int ispalindrome (char str[],int start,int end) {
    int i=0;
    int j=0;
    int counter=0;
    for(i=start; i<strlen(str); i++) {
        if (str[i]==str[end-i]){
            counter++;
        }
    }
    if(counter==i){
        return counter;
    } else
        return 0;
}

void longestPalindrome(char str[]) {
    int len = strlen(str);
    int i=0;
    int j=0;
    int start=0;
    Int end =0;
    int counter=0;
    int check=0;
    if (strlen(str)-1==1||strlen(str)-1==2) {
        printf("%s",str);
    } else {
        for (i=0; i<len; i++) {
            counter=0;
            for(j=len-1; j>=0; j--) {
                if(str[i]==str[j]) {
                    counter= ispalindrome(str,i,j);
                    if (counter>check&&counter>0) {
                        check=counter;
                        start=i;
                        end=j;
                    }
                }
            }
        }
        for(i=start; i<=end; i++) {
            printf("%c",str[i]);
        }
    }
}

So it works with a palindrome like "civic" or "madam", but when I try with "fawziizw" it returns "f" instead  of "wziizw".

A: That was close!
In the function ispalindrome(), you miss the final characters, since start might not be 0, and i being from start (>0) will have end-i miss the end of the string
int ispalindrome (char str[],int start,int end) {
    int i=0;
    int j=0;
    int counter=0;
    for(i=start; i<strlen(str); i++) {
            if (str[i]==str[end-i]){ // <===== end-i not ok if start>0
                counter++;
        }}
        if(counter==i){
        return counter;}
        else
            return 0; // better to leave whenever it's not a palindrome
    }

I suggest a simpler version. We use i as a counter from 0, since start might be >0, in order not to miss the final characters in that case
int ispalindrome (char str[],int start,int end) {
    for(int i=0 ; i < end-start ; i++) {
          if (str[start+i] != str[end-i]){
                return 0; // <== return 0 if not a palindrome
        }}
     return end - start + 1;
}

Then it should work better. In the next function, you could change
for(j=len-1; j>=0; j--)

to
for(j=len-1; j>i; j--)

Just in case you're interested, a lighter version of the longestPalindrome function

void longestPalindrome(char str[]) {
    int len = strlen(str);
    int i,j;
    int tempstart=0;
    int tempend=0;
    int counter;
    int tempcounter=0;
     for (i=0; i<len; i++) {
          for(j=len-1; j>i; j--) { // >i
                counter= ispalindrome(str,i,j);
                if (counter>=tempcounter&&counter>0) {
                     tempcounter=counter;
                     tempstart=i;
                     tempend=j;
                }
          }
     }
     for(i=tempstart; i<=tempend; i++) {
          printf("%c",str[i]);
     }
     printf("\n");
}

which does basically the same.

A: I've made this one that defines a length, and checks if there any sub-strings (of the original string) of this length that is palindrome.
The length initially is equal to the length of the entire string (so, the first sub-string is actually the entire original string), and decreases by 1 at every iteration. So, the first palindrome sub-string found is the longest palindrome.
#include <stdio.h>
#include <string.h>

int ispalindrome(char *start, int length){
    int i;
    for(i=0; i < length-1-i; ++i){
        if (start[i] != start[length-1-i]){
            return 0;
        }
    }
    return 1;
}

void longestPalindrome(char str[]) {
    int lenstr, length, i, j;
    lenstr = strlen(str);
    for (length=lenstr; length > 0; --length){
        for(i=0; length+i <= lenstr; ++i){
            if(ispalindrome(str+i, length)){
                for(j=0; j<length; ++j){
                    printf("%c", str[i+j]);
                }
                return;
            }
        }
    }
}


text:
Q: Problem About unitary operators Suppose $H(t)$ is a operator defined as follows:
$$T(t+\epsilon,t)=1-\frac{i\epsilon}{\hbar}H(t)$$
Show that if $H(t)$ is hermitian, $T$ must be unitary. Suppose $\epsilon^2$ can be neglected.
I tried first finding $H(t)$:
$$H(t)=\frac{\hbar}{i\epsilon}(1-T(t+\epsilon,t))$$
Then applying the properties of Hermitian operators:
$$H^{\dagger}=H$$
But I did not get a satisfactory answer. Please give me some advices. Thanks.

A: Hint: $T$ is unitary if $T^\dagger T = I$ (identity), so find $T^\dagger$ and use that $H$ is Hermitian and that $\epsilon^2$ is negligible to prove that $T$ satisfies the identity above.


text:
Q: Linq query is super slow? I copied the sql query built by linq from sql profiler here is what's annoying about it:

*

*It prefixes select ..columnNames.. from (select ..columnNames.. from ( select cNames from view)
Comments: the 2 select statements here are unnecessary.

*this query takes 14 seconds to execute

*when I remove the last line, containing all the params like the @p_linq_0 .. and fill the param values in where condition and execute the very same dynamic query it takes 1 sec or less. Even otherwise this query is taking 0 sec when performed from sql studio. This is so lame of linq.
I might move this to stored proc but I'm scared of using linq now
After further research i found out:
Query 1 :
exec sp_executesql N'SELECT * from TableView WHERE Id = @Id', N'@Id int', @Id = 1

Query 2:
exec sp_executesql N'SELECT * from TableView WHERE Id = 1'

Query 1 takes 12 seconds, Query 2 takes 0 second. This explains why linq query is slow. So now, does that mean I should always use stored procedures or am I missing something?
Why can't Microsoft fix Linq query building, how difficult is it to parse that string and replace the param values instead of passing those params as arguments to sp_executesql

A: I'm with you.  I mean, you could probably uncover the reason for this catastrophic performance hit you've discovered and find a remedy.  But in practice this sort of thing happens with Linq to SQL and spending this extra time to optimize your Linq statement so that the SQL query is more performant on the back-end kind of defeats the purpose.  Linq is supposed to make things easier.
Personally I use Linq-to-SQL or Entity Framework for performing CRUD operations on single records.  And then with any large SELECT statements I'll simply write a stored proc as I've always done.  This seems to be a good compromise between productivity and performance that has worked well for me.
EDIT:
In fact the Entity Framework guys anticipated this.  And Entity Framework works pretty well with stored procedures.  You can add a stored proc to your Entity Framework model and get all that strongly typed goodness.  Then you can call that stored proc from code.

A: You should build the Where predicate dynamically taking out the Application specific daysRange
like so
var query = from v in tableView
            where v.Id == Id
            orderby v.RDate descending
            select v;

if(!daysRange.Equals("All"))
{
  query = query.Where(v => v.RdDate >= fromDate && v.RDate <= toDate);
}

query.ToList();

A: This will work.
ParameterExpression parameterExpression = Expression.Parameter(typeof(TableView), "v");
Expression equalsExpression = Expression.Equal(Expression.Property(parameterExpression, "Id"), Expression.Constant(Id));
Expression<Func<TableView, bool>> predicate = Expression.Lamda<Func<TableView, bool>>(equalsExpression, parameter);

var query = from v in tableView
            orderby v.RDate descending
            select v;

if(!daysRange.Equals("All"))
{
  query = query.Where(v => v.RdDate >= fromDate && v.RDate <= toDate);
}

query.Where(predicate).ToList();


text:
Q: Minimum polynomial of (2n,2n) matrix The question is minimul polynomial of $(2n,2n)$ matrix
\begin{pmatrix}
0 & \cdots & 0 & 1 & \cdots & 1\\
\vdots & \ddots & \vdots & \vdots & \ddots &\vdots\\
0 & \cdots & 0 & 1 & \cdots & 1\\
1 & \cdots & 1 & 0 & \cdots & 0\\
\vdots & \ddots & \vdots & \vdots & \ddots &\vdots\\
1 & \cdots & 1 & 0 & \cdots & 0\\
\end{pmatrix}
is $t^3 - n^2t$ ($t$ is variable nad 2 $\leq$ $n$).

A: Let $J$ be the $n\times n$ all-1's  matrix.
A simple calculation shows that the minimal polynomial of $J$ is $t(t-n)$.
Hence the minimal polynomial of $-J$ is $t(t+n)$.
The matrix in the question is clearly similar to $\begin{pmatrix}J & O\\O&-J\end{pmatrix}$. It is therefore killed by the least common multiple of the minimal polynomials of $J$ and $-J$, that is $t(t^2-n^2)$; and is clearly not killed by any proper divisor.
Hence the minimal polynomial is as required.


text:
Q: Is there a way to collect WMI or WBEM/CIM data with Collectd? I've got an Ubuntu server running statsd, collectd and Graphite. I'm looking to collect data from Windows servers via WMI. I don't see an official plugin for WMI or WBEM/CIM on Collectd's web site. Is there a third party plugin available, or some kind of translation layer I might be able to put in place?

A: WMI Client for Linux
You'll have to build it from source if you're not using a Debian derivative, but I use this with Nagios and a couple of other homebrew applications. It's a WMI client and is capable of running pretty much any WMI query and results can be dumped and rearranged using any of the standard *nix manipulation tools.


text:
Q: Plotting Function in a function not working I consistently have problems using the plot tool when I want to find how some function (like maximization) varies as I change a parameter.
In this example, I want to find how a function's imaginary part obtains its maximum as a function of another parameter. So I want to plot this maximum calcuation vs the parameter that I am varying.
Here is my attempt at the code:
    NewIm[expression_] := (num = Numerator[expression];
   den = Denominator[expression];
   {reNum, imNum} = ComplexExpand[ReIm[num]]; {reDen, imDen} =
    ComplexExpand[ReIm[den]];
   imout = (imNum reDen - reNum imDen)/(reDen^2 + imDen^2));

NewRe[expression_] := (num = Numerator[expression];
   den = Denominator[expression]; {reNum, imNum} =
    ComplexExpand[ReIm[num]]; {reDen, imDen} =
    ComplexExpand[ReIm[den]];
   reout = (reNum reDen + imNum imDen)/(reDen^2 + imDen^2));

MaxFINDER[\[Chi]_] :=
  NMaximize[
   Simplify[
    NewIm[\[Chi]]], \[CapitalOmega]c > .001 && \[CapitalOmega]d >
     0, {\[CapitalOmega]c, \[CapitalOmega]d, \[CapitalDelta]p, \
\[CapitalDelta]c, \[CapitalDelta]s, \[CapitalDelta]d, \[Phi]},
   MaxIterations -> 10000];

pCs\[Chi]2fun[\[Beta]_]  := (I E^(I \[Phi]) \[CapitalOmega]c)/(
   8 (-(\[Gamma]a/2) + I \[CapitalDelta]a) ((\[Beta] \[Gamma]a)/2 + (
      I \[Gamma]a \[CapitalDelta]c)/2 - I \[Beta] \[CapitalDelta]p - (
      I \[Gamma]a \[CapitalDelta]p)/
      2 + \[CapitalDelta]c \[CapitalDelta]p - \[CapitalDelta]p^2 + \
\[CapitalOmega]c^2/4)) /. {\[Gamma]a ->
     1, \[CapitalDelta]a -> \[CapitalDelta]c + \[CapitalDelta]p - \
\[CapitalDelta]s};

(*level5\[Chi]2 = -(\[ExponentialE]^(\[ImaginaryI] \[Phi])(50 \
\[CapitalOmega]c \[CapitalOmega]d)/((\[Gamma]a^2+2 \[ImaginaryI] \
\[Gamma]a (50 \[CapitalDelta]c-51 \[CapitalDelta]p)+50 (4 \
\[CapitalDelta]c \[CapitalDelta]p-4 \
\[CapitalDelta]p^2+\[CapitalOmega]c^2)) ((\[Gamma]a+2 \[ImaginaryI] (\
\[CapitalDelta]c-\[CapitalDelta]p-\[CapitalDelta]s)) (\[Gamma]a+2 \
\[ImaginaryI] (\[CapitalDelta]c+\[CapitalDelta]d-\[CapitalDelta]p-\
\[CapitalDelta]s))+\[CapitalOmega]d^2)))/.{\[Gamma]a\[Rule]1, \
dephasing\[Rule]10^-4,\[CapitalDelta]a->-1(-\[CapitalDelta]p +\
\[CapitalDelta]c-\[CapitalDelta]s+\[CapitalDelta]d)};*)
(*
MaxFINDER[psC\[Chi]2]
MaxFINDER[level5\[Chi]2]*)
MaxFINDER[pCs\[Chi]2fun[.1]]
Plot[Evaluate[MaxFINDER[pCs\[Chi]2fun[bacon]]], {bacon, .1, 2},
 PlotPoints -> 15]

As you can see, if I run the fuction I created, I can find the maximum values for individual values of beta, but I'm still can't figure out how to get the plot tool to actually plot these.
The plot comes out blank, and I've tried a number of different suggestions that I've seen on previous stack-exchange questions.
Any ideas?

A: Your code is a bit of a mess, but here is a slightly cleaner version. First of all, user-defined functions should begin with lower case letter; second, you should localise your variables; third, if your functions depend on the denominator and numerator of your arguments, you should Rationalize those, for otherwise Numerator[0.1] == 0.1 and Denominator[0.1] == 1 instead of 1 and 10; and fourth, you should use patterns to make sure the functions are only evaluated for numeric arguments. Finally, the minimisation step is rather slow, so it is better to generate points and ListPlot them instead of just Plotting the actual function.
Clear[newIm, newRe, maxFINDER, pCsχ2fun]
newIm[expression_?NumericQ] := Module[{num = Numerator[Rationalize[expression, 0]], den = Denominator[Rationalize[expression, 0]], reNum, imNum, reDen, imDen},
   {reNum, imNum} = ReIm[num]; {reDen, imDen} = ReIm[den];
   (imNum reDen - reNum imDen)/(reDen^2 + imDen^2)
];
newRe[expression_?NumericQ] := Module[{num = Numerator[Rationalize[expression, 0]], den = Denominator[Rationalize[expression, 0]], reNum, imNum, reDen, imDen},
   {reNum, imNum} = ReIm[num]; {reDen, imDen} = ReIm[den];
   (reNum reDen + imNum imDen)/(reDen^2 + imDen^2)
];

pCsχ2fun[β_?NumericQ, Δc_, Δp_, Δs_, ϕ_, Ωc_] := With[{γa = 1, Δa = Δc + Δp - Δs}, (I E^(I ϕ) Ωc)/(8 (-(γa/2) + I Δa) ((β γa)/2 + (I γa Δc)/2 - I β Δp - (I γa Δp)/2 + Δc Δp - Δp^2 + Ωc^2/4))]

maxFINDER[bacon_?NumericQ] := NMaximize[{newIm[pCsχ2fun[bacon, Δc, Δp, Δs, ϕ, Ωc]], Ωc > .001 && Ωd > 0}, {Ωc, Ωd, Δp,  Δc, Δs, Δd, ϕ}, MaxIterations -> 10000][[1]];

ListPlot[Table[{b, maxFINDER[b]}, {b, .1, 2, .1}], Joined -> True]

On a second thought, I'm not sure why you even define newRe and newIm at all: these are identical to the built-in Re and Im! Your code can be simplified a lot:
maxFINDER[β_?NumericQ] := NMaximize[{(-Ωc (β (2-8 Δp (Δc+Δp-Δs))+4 (Δc-Δp) (Δc+2 Δp-Δs)+Ωc2) Cos[ϕ]+2 Ωc (-Δc+2 β Δc+Δp+4 β Δp+4 Δc2 Δp-4 Δp3-2 β Δs-4 Δc Δp Δs+4 Δp2 Δs+(Δc+Δp-Δs) Ωc2) Sin[ϕ])/((1+4 (Δc+Δp- Δs)2) (4 (β2+(Δc-Δp)2) (1+4 Δp2)+4 (β+2 (Δc-Δp) Δp) Ωc2+Ωc4)), Ωc > .001 && Ωd > 0}, {Ωc, Ωd, Δp, Δc, Δs, Δd, ϕ}, MaxIterations->10000][[1]]

which yields the same plot as before, with no need to define any auxiliary functions.


text:
Q: youtube.videos().insert AttributeError: 'NoneType' object has no attribute 'videos' I am coding this very simple example to try to decrypt one of the examples given by the youtube API v3 examples. For what I read here, the method videos.insert should be available in order to upload a given video, but python returns :
    youtube.videos().insert
AttributeError: 'NoneType' object has no attribute 'videos'

In order to discover what is going on, I have re-installed my virtualenv and I have installed google-api-client lib via easyinstall --upgrade. It has installed me the following libs :
google-api-python-client==1.4.2
httplib2==0.9.2
oauth2client==1.5.2
pyasn1==0.1.9
pyasn1-modules==0.0.8
rsa==3.3
simplejson==3.8.1
six==1.10.0
uritemplate==0.6
wheel==0.26.0

This method is not available, but the imports are fine ( no error on imports )
The pseudo-code :
import httplib2
import os
from oauth2client import tools
from oauth2client.client import AccessTokenCredentials
from oauth2client.client import AccessTokenRefreshError
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
import urllib

def authenticate():
    #scope = "https://www.googleapis.com/auth/youtube.upload"
    service = build('youtube', 'v3', http=http)
    acc_token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    flow = AccessTokenCredentials(
        acc_token, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36')
    http = httplib2.Http()
    http = flow.authorize(http)

def initialize_upload(youtube):
    tags = None
    youtube.videos().insert
    media_body = MediaFileUpload('1977.mp4', mimetype='video/mp4',
                                 chunksize=1024 * 1024, resumable=True)

def execute():
    youtube = authenticate()
    initialize_upload(youtube)

execute()

A: Your authenticate function contains no return statements, hence its return value is None. The error is an obvious consequence of this.
You probably wanted to return service. Though I believe your code contains other errors, since you are trying to pass an http argument to build which is defined afterwards.

A: Here is link that got me started with uploading. I'm now working on refreshing my auth token.
https://developers.google.com/youtube/v3/guides/uploading_a_video


text:
Q: CSS/HTML Tooltip Positioning Not Working in Mozilla Firefox So, I've gone ahead and added a tooltip on a small lead generation form I've been working on. Everything is going well; however, it seems the positioning on one element is not functioning properly, in Mozilla Firefox. When testing in Chrome, Internet Explorer, and Safari everything goes fine. In Firefox, the tooltip is not placed just above the image that calls it, but rather off to the right and up.
Here is what it should look like:
http://img84.imageshack.us/img84/3930/correctx.jpg
Here is what is shouldn't look like:
http://img198.imageshack.us/img198/5223/incorrectw.jpg
Below is the related code, HTML:

How can we contact you?

            <input id="phone_number" name="phone_number" type="text" />
            <input id="alternate_phone_number" name="alternate_phone_number" type="text" />
            <input id="email_address" name="email_address" type="text" />

When should we call?

            <fieldset id="contact_time">

<input id="contact_time_radio_morning" name="contact_time" type="radio" value="morning" />Morning

<input checked="checked" id="contact_time_radio_afternoon" name="contact_time" type="radio" value="afternoon" />Afternoon

<input id="contact_time_radio_evening" name="contact_time" type="radio" value="evening" />Evening
            </fieldset>

And the CSS:
    body{background:#0d2635 url('../images/background.jpg') no-repeat center top;font-family:Arial,Helvetica,sans-serif;margin:0;text-align:center;}
    h1{color:#fff;cursor:pointer;font-size:18px;font-weight:bold;margin:0;}
    h2{color:#ff0;cursor:pointer;font-size:14px;font-weight:bold;margin:0;text-indent:3px;}
    input[type="text"]{-khtml-border-radius:8px;-moz-border-radius:8px;-webkit-border-radius:8px;background-image:url('../images/background_text_inputs.jpg');border-color:#195d82 #11415c #6198b7 #1e74a6;border-radius:8px;border-width:1px;color:#aaa;float:left;font-size:12px;font-weight:bold;height:25px;line-height:100%;margin-top:8px;outline:none;padding:0;text-indent:5px;}
    input[type="text"]:focus{color:#fff;border:1px solid #ff0;}
    input[type="radio"]{cursor:pointer;}
    img{border:none;}
    img.information_icons{left:-2px;position:relative;top:4px;}
    img.information_icons_small{left:-2px;position:relative;top:3px;}

        div#contact_container{float:left;width:300px;}
            input#phone_number{float:left;margin-right:10px;width:140px;}
            input#alternate_phone_number{float:left;width:140px;}
            input#email_address{float:left;margin-right:10px;width:280px;}
            div.vertical_filler_small{float:left;height:10px;width:300px;}
            fieldset#contact_time{border:none;display:block;float:left;}
                div.contact_time_containers{cursor:pointer;float:left;margin-right:5px;}
                    span.contact_time_options{color:#ccc;font-size:14px;font-weight:bold;margin:0;}

    a[data-tooltip]:link,a[data-tooltip]:visited{position:relative;text-decoration:none;}
    a[data-tooltip]:before{content:"";visibility:hidden;}
    a[data-tooltip]:after{-moz-border-radius:10px;-moz-box-shadow:0 8px 6px -6px black;-webkit-border-radius:10px;-webkit-box-shadow:0 8px 6px -6px black;background-color:#294466;border:1px solid #0f2e4d;border-radius:10px;box-shadow:0 8px 6px -6px black;color:#ff0;content:attr(data-tooltip);left:-16px;font-size:12px;padding:5px 15px;position:absolute;top:-20px;visibility:hidden;white-space:nowrap;}
    a[data-tooltip]:hover:before,a[data-tooltip]:hover:after{-moz-transition:visibility 0s linear .1s;visibility:visible;}

A: Try Something Like This in CSS:

 #contact_container { Position:relative; }

 a[data-tooltip] { Position:absolute; top:0px; /* Set Top Position According to your style*/ Left:0px; /* Set LeftPosition According to your style*/ }

Hope it work for you...


text:
Q: Loop through a list of dictionaries and return another list in ansible Let's say I have this list:
myList
- name: Bob
  age: 25
- name: Alice
  age: 18
- name: Bryan
  age: 20

All I want is to loop through myList and get a list of names and set it to a variable nameList:
nameList
- name: Bob
- name: Alice
- name: Bryan

Is there a short syntax for this in ansible?

A: If you need a list of dictionaries with single name key (as in your example, then:
{{ myList | map('json_query','{name:name}') | list }}

This results in:
[
  { "name": "Bob" },
  { "name": "Alice" },
  { "name": "Bryan" }
]

If you need plain list of names:
{{ myList | map(attribute='name') | list }}

This results in:
[ "Bob", "Alice", "Bryan" ]


text:
Q: Large VIRT memory in Fortran I have a large Fortran/MPI code that when running uses a very large amount of VIRT memory (~20G) although the actual memory used (500 mb) is quite modest.
How can I profile the code to understand which part produces this huge VIRT memory?
At this stage, I'm even happy to use a brute force approach.
What I have tried is to put sleep statements in the code and recorded the memory usage through "top" to try to pin-point by bisection where the big allocation are.
However, this does not work as the sleep call puts the memory usage to 0. Is there a way to freeze the code while keeping current memory usage?
PS: I have tried VALGRIND but the code being so large, VALGRIND never finished. Is there an alternative to VALGRIND that is "easy" to used?
Thank you,
Sam

A: A solution for this is this modified (to get VIRT memory) subroutine from Track memory usage in Fortran 90
subroutine system_mem_usage(valueRSS)
use ifport !if on intel compiler
implicit none
integer, intent(out) :: valueRSS

character(len=200):: filename=' '
character(len=80) :: line
character(len=8)  :: pid_char=' '
integer :: pid
logical :: ifxst

valueRSS=-1    ! return negative number if not found

!--- get process ID

pid=getpid()
write(pid_char,'(I8)') pid
filename='/proc/'//trim(adjustl(pid_char))//'/status'

!--- read system file

inquire (file=filename,exist=ifxst)
if (.not.ifxst) then
  write (*,*) 'system file does not exist'
  return
endif

open(unit=100, file=filename, action='read')
do
  read (100,'(a)',end=120) line
  if (line(1:7).eq.'VmSize:') then
     read (line(8:),*) valueRSS
     exit
  endif
enddo
120 continue
close(100)

return
end subroutine system_mem_usage


text:
Q: WrappedAttributeError 'IsAdminUser' object has no attribute 'authenticate' I'm using Django Rest Framework with permission_classes to create an API. My understanding is that once I go to that API with an unauthenticated user I should be redirected to the login form, right? Instead, I get the following error:
WrappedAttributeError at /sessions/api/listPatients/
'IsAdminUser' object has no attribute 'authenticate'
There's no redirect to the login form... and I don't understand why.
Why is this happening? What am I doing wrong? How to fix that?
Here's the urls.py:
path('api/getSessions/',
     views.GetSessions.as_view(),
     name="GetSessionsAPI"),

And here's the view that I'm trying to go to:
class GetSessions(generics.ListCreateAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = SessionSerializer

    def get_queryset(self):
        if self.request.user.is_authenticated:
            return Session.objects.filter(
                patient__created_by_user=self.request.user)
        else:
            raise PermissionDenied

and here's the other one raising the error:
class ListPatients(generics.ListAPIView):

    permission_classes = (permissions.IsAuthenticated,)
    serializer_class = PatientsSerializer

    def get_queryset(self):
        if self.request.user.is_authenticated:
            try:
                return Patient.objects.filter(
                    created_by_user=self.request.user).\
                   filter(curently_active=True)
            except Patient.DoesNotExist:
                raise PermissionDenied
    else:
        raise PermissionDenied

Here's the full traceback:
WrappedAttributeError at /sessions/api/listPatients/
'IsAdminUser' object has no attribute 'authenticate'
Request Method: GET
Request URL:    http://localhost:8000/sessions/api/listPatients/
Django Version: 2.0.5
Exception Type: WrappedAttributeError
Exception Value:
'IsAdminUser' object has no attribute 'authenticate'
Exception Location: /Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/request.py in _authenticate, line 375
Python Executable:  /Users/karol/Development/ZS_2_0/ZS_2_0_venv/bin/python
Python Version: 3.6.4
Python Path:
['/Users/karol/Development/ZS_2_0/zapiszsesje_2_0',
 '/Users/karol/Development/ZS_2_0',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/patient',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/services',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/notes',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/practice',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/activity_logger',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/session',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/my_calendar',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/session/tests',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/zapiszsesje_2_0/users',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/zapiszsesje_2_0',
 '/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python36.zip',
 '/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6',
 '/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
 '/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages',
 '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/zapiszsesje_2_0',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0',
 '/Users/karol/Development/ZS_2_0/zapiszsesje_2_0/zapiszsesje_2_0']
Server time:    Sat, 17 Nov 2018 15:29:56 +0100
Traceback Switch to copy-and-paste view

/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/request.py in wrap_attributeerrors
        yield ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/request.py in user
                self._authenticate() ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/request.py in _authenticate
                user_auth_tuple = authenticator.authenticate(self) ...
▶ Local vars
During handling of the above exception ('IsAdminUser' object has no attribute 'authenticate'), another exception occurred:
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/django/core/handlers/exception.py in inner
            response = get_response(request) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response
                response = self.process_exception_by_middleware(e, request) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/django/core/handlers/base.py in _get_response
                response = wrapped_callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py in inner
                return func(*args, **kwds) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/django/views/decorators/csrf.py in wrapped_view
        return view_func(*args, **kwargs) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/django/views/generic/base.py in view
            return self.dispatch(request, *args, **kwargs) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/views.py in dispatch
            response = self.handle_exception(exc) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/views.py in handle_exception
            self.raise_uncaught_exception(exc) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/views.py in dispatch
            self.initial(request, *args, **kwargs) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/views.py in initial
        self.perform_authentication(request) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/views.py in perform_authentication
        request.user ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/request.py in user
                self._authenticate() ...
▶ Local vars
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/contextlib.py in __exit__
                self.gen.throw(type, value, traceback) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/request.py in wrap_attributeerrors
        six.reraise(type(exc), exc, info[2]) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/django/utils/six.py in reraise
            raise value.with_traceback(tb) ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/request.py in wrap_attributeerrors
        yield ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/request.py in user
                self._authenticate() ...
▶ Local vars
/Users/karol/Development/ZS_2_0/ZS_2_0_venv/lib/python3.6/site-packages/rest_framework/request.py in _authenticate
                user_auth_tuple = authenticator.authenticate(self) ...
▶ Local vars

UPDATE:
This error goes away when I change the following line in my base.py settings file:
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.permissions.IsAdminUser', # <- commenting out solves the problem!
    ),

However, the line has been added following the book Two Scoops of Django ...

A: Turned out it was my mistake which got uncovered thanks to the comments under my question:
By mistake I have added 'rest_framework.permissions.IsAdminUser', to DEFAULT_AUTHENTICATION_CLASSES instead of DEFAULT_PERMISSION_CLASSES inside my settings file.
That solved the problem - thanks! :)

A: For me the same problem occurred when by accident I typed in authentication_classes instead of permission_classes
class MyView(ApiView)
  authentication_classes = (AllowAny, ) # Should be permission_classes!

  def get(request):
    pass

A: when you create a authentication model, you need TokenAuthentication in your viewsets classes.
for example:
class LessonViewSet(viewsets.ModelViewSet):
    queryset = Lesson.objects.all()
    serializer_class = LessonSerializer
    authentication_classes = (TokenAuthentication)
    premission_classes = (IsAuthenticated, )


text:
Q: Pass flags to Python Script from Node/Express app python-shell I am trying to figure out how to pass flags to a python script from a Node/Express application. When in the command line I execute the script by running:
python ndbc.py --buoy 46232

I am using the python-shell module, which I think should allow me to do this, but I am not entirely sure how it works.
python-shell documentation:
https://github.com/extrabacon/python-shell#running-a-python-script-with-arguments-and-options

A: Adapted from the README, something like this should work:
var PythonShell = require('python-shell');

var options = {
  args: ['--buoy', '46232']
};

PythonShell.run('ndbc.py', options, function (err, results) {
  if (err) throw err;
  console.log('results: %j', results);
});

A: I found another solution that used the child_process Module:
var exec = require('child_process').exec;
var pyArgs = {
  // make arguments that take no parameters (ie, --json) true or false
  "buoy": '46232',
  "datasource": 'http',
  "json": true,
  "datatype": "spectra",
  "units": 'ft'
};
//example
pyArgs.datatype = '9band';

function flagGen(args) {
  var flags = '';
  for (var a in args) {
    if (args.hasOwnProperty(a)) {
      if (typeof(pyArgs[a]) == 'string'){
        flags += " --" + a + ' ' + pyArgs[a];
      }
      else {
        if (pyArgs[a] == true)
          flags += ' --' + a;
      }
    }
  }
  return flags;
}

var pyPath = './';
var buoyData = ''
var execstr = 'python ' + path.join(pyPath, 'ndbc.py') + flagGen(pyArgs);
var child = exec(execstr, function(error, stdout, stderr) {
  if (error) {
    console.log(stderr)
  }
  else {
    buoyData= JSON.parse(stdout);
    console.log(buoyData);
  }
});

A: Tested:

const PyShell = require("python-shell");

let options = {
    mode: 'text',
    pythonPath: 'your_python_path',
    pythonOptions: ['-u'], // get print results in real-time
    args: ['-p {"a":1, "b":"123"}']
};

let pyshell = new PyShell.PythonShell('your_script_path', options);

pyshell.on('message', function(message) {
    // received a message sent from the Python script (a simple "print" statement)
    console.log("Received", message);
});

// end the input stream and allow the process to exit
pyshell.end(function(err, code, signal) {
    if (err) throw err;
    console.log('The exit code was: ' + code);
    console.log('The exit signal was: ' + signal);
    console.log('finished');
});


text:
Q: Is there an App that removes unused classes from frameworks? So to give you an idea of what it is I am trying to do, OOCSS Framework uses a ton of classes, I'm about to package up a mobile site that is about ~2.5 megs and would like to remove all unused classes from the files. Sure, I could do it by hand but it would be much easier if something like this existed for the future.

A: There is a Firefox extension called Dust Me Selectors

It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored in your user preferences, so that as you continue to navigate around a site, selectors will be crossed off the list as they're encountered.
  You'll end up with a profile of which selectors are not used anywhere on the site.

or give Unused Css a try

http://unused-css.com/

from Unused Css site:
Latish Sehgal has written a windows application to find and remove unused CSS classes. I haven't tested it but from the description, you have to provide the path of your html files and one CSS file. The program will then list the unused CSS selectors. From the screenshot, it looks like there is no way to export this list or download a new clean CSS file. It also looks like the service is limited to one CSS file. If you have multiple files you want to clean, you have to clean them one by one.
Dust-Me Selectors is a Firefox extension (for v1.5 or later) that finds unused CSS selectors. It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered. This tool is supposed to be able to spider a whole website but I unfortunately could make it work. Also, I don't believe you can configure and download the CSS file with the styles removed.
Topstyle is a windows application including a bunch of tools to edit CSS. I haven't tested it much but it looks like it has the ability to removed unused CSS selectors. This software costs 80 USD.
Liquidcity CSS cleaner is a php script that uses regular expressions to check the styles of one page. It will tell you the classes that aren't available in the HTML code. I haven't tested this solution.
Deadweight is a CSS coverage tool. Given a set of stylesheets and a set of URLs, it determines which selectors are actually used and lists which can be "safely" deleted. This tool is a ruby module and will only work with rails website. The unused selectors have to be manually removed from the CSS file.
Helium CSS is a javascript tool for discovering unused CSS across many pages on a web site. You first have to install the javascript file to the page you want to test. Then, you have to call a helium function to start the cleaning.
UnusedCSS.com is web application with an easy to use interface. Type the url of a site and you will get a list of CSS selectors. For each selector, a number indicates how many times a selector is used. This service has a few limitations. The @import statement is not supported. You can't configure and download the new clean CSS file.
CSSESS is a bookmarklet that helps you find unused CSS selectors on any site. This tool is pretty easy to use but it won't let you configure and download clean CSS files. It will only list unused CSS files.


text:
Q: Chrome mobile debugging over usb, no console.log In Google Chrome when inspecting a web page from a mobile device connected via USB, the javascript console does not print console.log statements.  It also doesn't respond to alerts.  It doesn't seem to support any interaction at the command line, such as setting variables.  Is there something I need to do to get the console to behave normally, as if I was debugging Chrome for desktop?

A: Figured it out immediately.  I had turned off Javascript on the mobile browser and forgot to turn it back on.


text:
Q: Iterative Quicksort steps? I have to implement an iterative quicksort in java for homework.
i've search a lot about it but i couldn't find a website with a clear explanation about how to implement an iterative quicksort.
i have found this code in java, and it sorts very well, but i can't tell how does it work, i know how the recursive quicksort works though.
i've commented the code with my questions
public static void iterativeQsort(int[] arr) {
    Stack<Integer> stack = new Stack<Integer>();
    stack.push(0);
    stack.push(arr.length);
    while (!stack.isEmpty()) {
        int end = stack.pop();
        int start = stack.pop();
        if (end - start < 2) continue;
        int p = start + ((end-start)/2);
        p = partition(arr,p,start,end);

        stack.push(p+1);
        stack.push(end);

        stack.push(start);
        stack.push(p);

    }
}

private static int partition(int[] arr, int p, int start, int end) {
    int l = start;
    int h = end - 2; //what is h and l variables for and why h has to be end -2?
    int piv = arr[p];
    swap(arr,p,end-1);

    while (l < h) {
        if (arr[l] < piv) {
            l++;
        } else if (arr[h] >= piv) {
            h--;
        } else {
            swap(arr,l,h);
        }
    }
    int idx = h;  // what is idx exactly?
    if (arr[h] < piv) idx++;
    swap(arr,end-1,idx);
    return idx;  //why return idx.
}
private static void swap(int[] arr, int i, int j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

i'm mostly confused by the partition method, i don't know what it does.
if someone could explain me the main steps to make an iterative quicksort i'll be very happy.
Thanks for your help.


text:
Q: Average color of multiple images merged together I have all these layers in Photoshop:

I also have these images in Python. In Photoshop, I can get the average color of the entire document from the RGB channel of the document. In Python, I was thinking I would blend the images together using cv2.addWeighted, and then use the histograms of the three channels to get the average color. However, my average color does not match with the one obtained from Photoshop.
Here is my code so far:
    im1 = cv2.imread('a1.png')
    im2 = cv2.imread('a2.png')
    im3 = cv2.imread('a3.png')
    alpha = 0.5
    beta = (1.0 - alpha)
    blended = cv2.addWeighted(im1, alpha, im2, beta, 0.0)
    blended = cv2.addWeighted(blended, alpha, im3, beta, 0.0)
    # cv2.imwrite('blended.png', blended)
    averageColor = []

    chans = cv2.split(blended)
    colors = ("b", "g", "r")
    for (chan, color) in zip(chans, colors):
        # create a histogram for the current channel and plot it
        hist = cv2.calcHist([chan], [0], None, [256], [0, 256])
        for i in range(len(hist)):
            if (hist[i]) != 0:
                averageColor.append(i)
                break

    print("Average color: ", averageColor)
    base_color = np.fill((aw, ah, 3), averageColor)
    base_color_layer = Image.fromarray(base_color)
    base_color_layer.save("Base Color.png")

im3 is the "dup" layer containing only one color (129, 127, 121). im2 is all the Mask layers summed together using np.add. im1 is the Background image.
Any thoughts?

A: # given
im1 = cv2.imread('a1.png')
im2 = cv2.imread('a2.png')
im3 = cv2.imread('a3.png')

# calculations
averageIm = np.mean([im1, im2, im3], axis=0)
averageColor = averageIm.mean(axis=(0,1))

Assuming the images are color without alpha, and assuming you want each picture to have equal weight.
This is not equivalent to a stack of layers and giving each layer the same transparency, because that is equivalent to exponential/geometric average, i.e. alpha * im1 + (1-alpha) * (alpha * im2 + (1-alpha) * (im3)) which gives an image successively less weight the lower it is on the stack. it goes like [0.5, 0.25, 0.25], or [0.5, 0.25, 0.125, 0.0625, ...]

A: Disclaimer: I would highly recommend you do this with the CUDA API (either in C or with the Python bindings) but since the qn is about pure python, see below
I'm not going to add all the cv2 reading code bc idk the API but let's assume you've got images 1...n in a list called images and each image is a 3d array of width x height x rgba and let's assume all images are the same size

Image_t = list[list[list[int]]]

def get_average_colour(images: list[Image_t]) -> Image_t:
    new_image: Image_t = []
    image_width = len(images[0][0])  # len of first row in first image
    image_height = len(images[0])  # number of rows
    colour_channel_size = len(images[0][0][0])

    for h in range(image_height):
        row = []
        for w in range(image_width):
            curr_pixel = [0] * colour_channel_size
            for img in images:
                for chan, val in enumerate(img[h][w]):
                    curr_pixel[chan] += val
                row.append(list(map(lambda v: int(v / len(images), curr_pixel))  # This will average out your pixel values
        new_image.append(row)

    return new_image


text:
Q: Why is the wrong form opening when I click the doc link I created from a SSJS function? Ok, this is weird.  I created an xpage input form.  After the form is filled out, a document is created.  I then create an email to notify people that the document has been created.  I drop a doclink to the newly created document in the body of the email.  During testing, I noticed that when I click the link in the email, the wrong Notes Form is opened.  Instead of the 'TrainingRequest' form displaying the fields, the form 'Feedback' opens up instead.  Here's what I checked:
- On the xpage data section, the 'form' is set to 'TrainingRequest'.
- When I open the document via the doc link, the field 'form' has the value 'TrainingRequest', which is correct.  Yet it's displaying the 'Feedback' form.
- When I check the other field properties of the document, all the correct fields from the 'TrainingRequest' form are there and populated correctly.
- When I open the document via the view, the correct Notes form 'TrainingRequest' opens.
- There is no default form in the database design.

Has anyone seen this before?
thanks
clem

A: Doc links are always created using the default view of your application. If there is a form formula in this view then this overrides the form in the document. Remove the form formula of the default view and it works.
I almost NEVER use form formulas in my application because of the side effects.

A: Source code would be useful. But initial best guess based on what you're saying is you have two datasources on the XPage, neither have ignoreRequestParams set, so you're editing the same document with both data sources. ignoreRequestParams missing will ignore any properties you define.


text:
Q: Jqgrid can Edit but not Add I have my grid running and I can EDIT data but I cannot ADD new rows of data. When I submit the add form nothing happens and I get nothing back on my PHPMyAdmin page to show that the grid is hit the database with the INSERT statement.
Here is my Edit code.
    <?php

$dbhost = "localhost";
$dbuser = "root";
$dbpass = "*****";
$dbname = "******";

// connect to the database
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Connection Error: " . mysql_error());
mysqli_select_db($conn,$dbname) or die("Error conecting to db.");

//$id = "'".$_POST['id']."'";
$unit = "'".$_POST['unit_id']."'";
$div = "'".$_POST['div_id']."'";
$titleorg = "'".$_POST['title_org']."'";
$shortdesc = "'".$_POST['short_desc']."'";
$longdesc = "'".$_POST['long_desc']."'";
$unitdesc = "'".$_POST['unit_desc']."'";
$enabled = "'".$_POST['avail_ind']."'";
$active = "'Y'";

switch($_POST['oper'])
{
    case "add":
        $query = "INSERT INTO depunits (unit_id, div_id, title_org, short_desc, long_desc, unit_desc, avail_ind,active_ind) values ($div,$unit,$titleorg,$shortdesc,$longdesc,$unitdesc,$enabled,$active)";
        mysqli_query($conn,$query);
    break;

    case "edit":
        $query = "UPDATE depunits SET unit_id=$unit,div_id=$div,title_org=$titleorg,short_desc=$shortdesc,long_desc=$longdesc,unit_desc=$unitdesc,avail_ind=$enabled where unit_id=$unit";
        mysqli_query($conn,$query);
    break;
}

?>


text:
Q: Xamarin.Android Adyen Integration & Bindings Library .aar Hello colleagues developers,
I'm currently developing a Xamarin Form app that requires the integration of a Payment Service Provider. My company requires that I use Adyen as the PSP.
Adyen itself doesn't provide any information on Xamarin integration. Information exist for Android and IOS but can't find anything for Xamarin forms / Xamarin.Android.
I've created a Bindings Library (android).
I've added the.aar file provided by Adyen into it.
Then I built it with the LibraryProjectZip property but after adding the reference to my Xamarin.android project, I can't use any methods that should be in it...
I've tried this process with another .aar and everything went fine...
Does any of you have already integrated Adyen in a Xamarin form / Xamarin.android app ?
Thanks in advance,
Noste


text:
Q: Apply javascript for mobile or desktop only I have 2 scripts one that I would like to use for any screen width less than 990px and another for anything greater.  These scripts come from a 3rd party and only work on the actual domain (so testing will be hard for anyone else).
Here are the scripts they gave me:
For mobile:
<script>
    (function(){
        var t = document.getElementsByTagName("script")[0];
        var s = document.createElement("script"); s.async = true;
        s.src = "//integration.nfusionsolutions.biz/client/jh/widget/module/accordionchart/nfaccordion";
        t.parentNode.insertBefore(s, t);
    })();
    </script>

For Desktop:
<script>
    (function(){
                var t = document.getElementsByTagName("script")[0];
                var s = document.createElement("script"); s.async = true;
                s.src = "//integration.nfusionsolutions.biz/client/jh/widget/module/spottableextended/nfspotextended";
                t.parentNode.insertBefore(s, t);
    })();
    </script>

I have tried this for the desktop view but I know something is off.
For Desktop:
 <script>

        (function(){
        var viewportWidth = $(window).width();
        if (viewportWidth > 900) {
                    var t = document.getElementsByTagName("script")[0];
                    var s = document.createElement("script"); s.async = true;
                    s.src = "//integration.nfusionsolutions.biz/client/jh/widget/module/spottableextended/nfspotextended";
                    t.parentNode.insertBefore(s, t);
       } })();
        </script>

Any suggestions?

UPDATE*** Code based on response below

    <script>
if ( $(window).width() > 990) {
  (function(){
                var t = document.getElementsByTagName("script")[0];
                var s = document.createElement("script"); s.async = true;
                s.src = "//integration.nfusionsolutions.biz/client/jackhunt/widget/module/spottableextended/nfspotextended";
                t.parentNode.insertBefore(s, t);
    })();
}
else {
  (function(){
        var t = document.getElementsByTagName("script")[0];
        var s = document.createElement("script"); s.async = true;
        s.src = "//integration.nfusionsolutions.biz/client/jackhunt/widget/module/accordionchart/nfaccordion";
        t.parentNode.insertBefore(s, t);
    })();
}
</script>

A: If you're not using jQuery, you can't use a jQuery method. Use the following condition instead:
if (window.innerWidth > 900) { // code for large screens

A: You can use sompething like this, if you have size screen informations :
if ( $(window).width() > 990) {
  //Add your javascript for large screens here
}
else {
  //Add your javascript for small screens here
}

EDIT : if really jQuery can't be used, you can try to use :
window.innerWidth

to get the width. But it'll depend too of the resized window...!


text:
Q: How can I convert PDF Files to TIFF files with compression (Group 4 compression) I am trying to complete a task to convert PDF's to TIFF files with CCITT t.4 compression. I am using the PymuPDF library/Pillow. From the code below, I am can generate the TIFF files fine, but I can't seem to add the compression to them no matter what I try. Anyone have any idea how I can accomplish this?
import fitz
import os

mat = fitz.Matrix(300 / 72, 300 / 72)  # sets zoom factor for 300 dpi
doc = fitz.open(r"C:\testtiff4\test.pdf")

page_count = doc.pageCount

for page in range(0, page_count):
    page_load = doc.loadPage(page)
    pix = page_load.get_pixmap(matrix=mat)
    img_filename = os.path.join(r"C\testtiff4", "page-%04i.tiff" % page_load.number)
    pix.pil_save(img_filename, format="TIFF", dpi=(300,300), compression="group4")

When running the above code, I get the error:

OSError: encoder error -2 when writing image file

A: You need to have libtiff installed in order to write Group4 compressed files. Check like this:
python -m PIL

Sample Output
--------------------------------------------------------------------
Pillow 8.0.1
Python 3.9.1 (v3.9.1:1e5d33e9b9, Dec  7 2020, 12:10:52)
   [Clang 6.0 (clang-600.0.57)]
--------------------------------------------------------------------
Python modules loaded from /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/PIL
Binary modules loaded from /Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/PIL
--------------------------------------------------------------------
--- PIL CORE support ok, compiled for 8.0.1
--- TKINTER support ok
--- FREETYPE2 support ok, loaded 2.10.4
--- LITTLECMS2 support ok, loaded 2.10
--- WEBP support ok, loaded 1.1.0
--- WEBP Transparency support ok
--- WEBPMUX support ok
--- WEBP Animation support ok
--- JPEG support ok, compiled for 9.0
--- OPENJPEG (JPEG2000) support ok, loaded 2.3.1
--- ZLIB (PNG/ZIP) support ok, loaded 1.2.11
--- LIBTIFF support ok, loaded 4.1.0
*** RAQM (Bidirectional Text) support not installed
*** LIBIMAGEQUANT (Quantization method) support not installed
--- XCB (X protocol) support ok


text:
Q: Difference of Environment.DEFAULT_SCHEMA and database in Hibernate What is the difference in Hibernate of
cfg.setProperty(Environment.DEFAULT_SCHEMA, "exampleDB");
with
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/exampleDB</property>
Is default schema and DB in the connection URL completely different things?
I noticed that if I omit the setting of Environment.DEFAULT_SCHEMA and do the following:
Configuration cfg = new Configuration();
System.out.println("Default schema:"+cfg.getProperty(Environment.DEFAULT_SCHEMA));
sessionFactory = cfg.configure().buildSessionFactory();

The console prints: Default schema:null.
So what is the use of Environment.DEFAULT_SCHEMA and the difference with the connecting DB?

A: The default schema property is used when your DBA creates multiple schemas within a single database. I've seen this with postgres where everyone uses one database URL but under that there are separate schemas for each application.
By using the default schema property it allows you to keep the schema names off your entities. This is particularly useful if you're running tests against HSqlDB which does not support schemas and you deploy against a DB that is using schemas. Having a null value just means it defaults back to the DB default schema.

A: refer to:
http://www.youtube.com/watch?v=ReAZmA83Myg&feature=related
and
http://www.java-forums.org/database/1467-variables-hibernate-cfg-xml-file.html
what I understand:
in hibernate.cfg.xml you can setup;
<property name="hibernate.default_schema">exampleDB</property>

or you can construct the hibernate.cfg file at execution time;
cfg.setProperty(Environment.DEFAULT_SCHEMA, "exampleDB");

how you can create default schema for later use;
new SchemaExport(config).create(true,true); //First parameter (true) creates new schema

edit:
and another reference:
http://docs.jboss.org/hibernate/core/3.3/api/org/hibernate/cfg/Environment.html
Provides access to configuration info passed in Properties objects.
Hibernate has two property scopes:
Factory-level properties may be passed to the SessionFactory when it instantiated. Each instance might have different property values. If no properties are specified, the factory calls Environment.getProperties().
System-level properties are shared by all factory instances and are always determined by the Environment properties.

The only system-level properties are
hibernate.jdbc.use_streams_for_binary
hibernate.cglib.use_reflection_optimizer

Environment properties are populated by calling System.getProperties() and then from a resource named /hibernate.properties if it exists. System properties override properties specified in hibernate.properties.
The SessionFactory is controlled by the following properties. Properties may be either be System properties, properties defined in a resource named /hibernate.properties or an instance of java.util.Properties passed to Configuration.buildSessionFactory()

A: Setting the hibernate property causes hibernate to qualify all table names in the sql it emits, i.e. instead of
select count(*)
from mytable

it would send
select count(*)
from myschema.mytable

to the database.
The effect of appending to the connection string is database specific. Some databases (e.g. Oracle) do not support specifying the default schema in the connection string. (source)


text:
Q: How Do Create WebService that Receives XML? I need to build a web service that accepts XML data. (It must accept XML, do not suggest alternative formats as that is not an option.)
I have googled "tutorial xml webservice c#" (and various permutations thereof) and followed several tutorials. I understand how to create a webservice in general and have created several basic web services to add numbers, convert temperatures, etc.
Unfortunately all my searches that include the keywords "xml" and "webservice" only turn up tutorials on how to parse XML files once you have them or read them from a file. I need to know how to get them in the first place. I cannot find anything that explains how to build a webservice that accepts XML as input.
What is the parameter type I should use for a webservice method that should receive XML? Is it a string? Is it an XmlDocument? Something else?
Can someone provide links to tutorial on how to create the C# classes and whatnot from the XSD?
Everything I have found indicates that's it is usually done by creating the classes in C# and then using a tool to create the XSD. However, I need to go the opposite direction. Where can I go to learn to do this? I don't care if I have to do it by hand; I'm not looking for a tool to do it for me.
Clearly I am very inexperience with web services, so I appreciate any help you can offer. But please don't direct me to basic "web service tutorials" because I have already done several (I stopped when they started repeating material I'd already done).
Also, please do not tell me "You need to learn about XML, Web Services, Serialization, etc" and other such overly broad hand-waving answers. I am aware that I need to earn about those things, and I am working on it. If you could be more specific, such as "first learn about X classes in c#, then learn about Y" or "learn about X concepts in WSDL, then learn about Y concepts of serialization in C#, etc", that would help.
If anyone could direct me to any free online courses / tutorial series that go through the process, that would be awesome as well.
Edit: Ok, apparently this question is not as specific as I think it is, so here is an example.
This is what another agency will send to my web service:
<Person>
    <LegalName>
      <FirstName>Ralph</FirstName>
      <LastName>Anderson</LastName>
      <PhoneticFirstName>rah-lf</PhoneticFirstName>
    </LegalName>
    <SSN>122-34-1232</SSN>
    <Demographics>
      <Sex>male</Sex>
      <Height>502</Height>
    </Demographics>
    <DriversLicense>
      <DriversLicenseNumber>1234</DriversLicenseNumber>
      <IssuingState>CA</IssuingState>
    </DriversLicense>
<Person>

My understanding is I need to write something like this:
public Service () {

    [WebMethod]
    public void CreateRecord(XmlDocument newRecord)
    {
        // do stuff
    }
}

A: If I understand the question correctly, you probably want to take a string as the parameter and parse it once you've received it. There are other ways to accomplish the same thing, but without more information, I can't suggest them.
In order to parse the string once you've received it you can reverse engineer your XSD into C# classes using the xsd.exe tool: http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=vs.110).aspx. The command would look something like xsd.exe /c your.xsd.
Then, you would use the XmlSerializer's DeSerialize method to turn the XML string into objects.
Hope this helps.


text:
Q: App store approval process for Hybrid Apps I want to know what is the process that apple follows to approve a hybrid app (developed using PhoneGap) submitted to the App Store?
I read that PhoneGap is approved by Apple as a framework for building native apps but couldn't find any guidelines for the same.
So i would like to know some key points that should be taken into consideration while developing hybrid apps that will prevent it from being rejected on the app store.
Thanks!!!

A: http://developer.apple.com/appstore/resources/submission/tips.html
http://developer.apple.com/appstore/resources/approval/guidelines.html
check out the point 12.3 in particular


text:
Q: Pass hidden value with checkbox together I have a form where I have id of product and id of campaign related with one item. I want to display only one checkbox but pass both productID and campaignID.
{!! Form::open(['url' => 'filter', 'method' => 'POST']) !!}
    @foreach ( $row as $id )
        <input type="checkbox" name="products[]" value="{{ $id->$productID }}">
        <input type="hidden" name="campaignID[]" value="{{ $id->$campaignID }}">
        <input type="submit">
    @endforeach
{!! Form::close() !!}

Now when I select one checkbox it passes the correct productID but also it passes all campaingIDs as well.
Is it possible to do it like this?
Edit
For example:

*

*Item A - ProductID: 1, CampaignID: 100

*Item B - ProductID: 2, CampaignID: 200

*Item C - ProductID: 3, CampaignID: 300

When I select item A, I get productID 1, but for campaignID I get 100, 200, 300.

A: In this case, it seems to be better to just pass the product id and retrive the campaing from the related product model.
i.e. like this
Blade Template
{!! Form::open(['url' => 'filter', 'method' => 'POST']) !!}
    @foreach ( $row as $id )
        <input type="checkbox" name="products[]" value="{{ $id->$productID }}">
        <input type="submit">
    @endforeach
{!! Form::close() !!}

Controller
$product_id = ...
$product = Product::find($product_id);
$campaign_id = $product->campaignId;


text:
Q: While loop wont loop with inFile I'm currently writing a program that reads in a .txt file. The program is supposed to read a character, output an error, and continue reading the rest of the lines, and follow suit. I'm not sure where I'm going wrong.
#include <iostream>
#include <cmath>
#include <string>
#include <stream>

using namespace std;

int main(){

    double runningTotal;
    int c = 0;

    string fileName;
    ifstream infile;
    cout << "Enter a file name\n";
    cin >> fileName;

    infile.open(fileName.c_str());

    if (!infile.is_open()) {
        cout<<"Error! invalid entry please retry!\n";
    }
    else {
        string line;

        int a, b;
        while (!inflile.fail()) {
            infile >> a >> b;
            c = a + b;
            runningTotal = c;
            cout <<a<<" + "<<b<<" = " << runningTotal<<endl;
        }
        getline(infile, line, '\n');
        if (infile.fail()){
            getline(infile, line, '\n');
            cout<<"stop being stupid\n";
        }
    }
}


text:
Q: How to select all data with query LIKE in Codeigniter Why can not I use '%' or '' in LIKE query builder to select all data?
I try in SQL shell can, but in query builder can not
My Model
public function ajax_getTargetMhs($where,$where2) {
        $this->db3->SELECT("nim,nama,kodeunit")
                    ->FROM("akademik_ms_mahasiswa")
                    ->LIKE('kodeunit',$where)
                    ->LIKE('periodemasuk',$where2);
        $query = $this->db3->get();
        if( $query->num_rows() > 0 ) {
            return $query->result();
        } else {
            return array();
        }
    }

My Controller
public function getTargetMhs($where,$where2) {
        $json =$this->Survey_Model->ajax_getTargetMhs($where,$where2);
        $arr = array();
            foreach ($json as $results) {
            $arr['data'][] = array(
                   $results->nim,
                   $results->nama,
                   $results->kodeunit
                    );
            }
         //save data mysql data in json encode format
          echo json_encode($arr);
    }

I can't access like this
'ajax': "<?php echo base_url(); ?>survey/getTargetMhs/"+'SINF/'+'%',

A: The method like() accepts a third parameter that describes which "side" of the "matching" string to put wildcard characters on. Acceptable values are 'none', 'left', 'right', 'both'.
If you don't pass a "side" value then 'both' is used. Not sure which is the correct choice for you. If you want to construct the whole matching argument yourself then 'none' should work.
Documentation on like() HERE


text:
Q: DataTable createdRow isn't adding attribute to the rows? I'm trying to add data-foo attribute to each row of my DataTable. I need this attribute for sorting data however I tried the below but it's not adding the defined attribute
cx.common.data.cxAdminDataTables.EbFaqCategory = $CxRecordsTable.cxAdminDataTable({
    ajaxUrl: '<?php echo $this->CxHelper->Route('eb-admin-get-general-faq-categories')?>',
    // Per-row function to iterate cells
    "createdRow": function (row, data, rowIndex) {
        // Per-cell function to do whatever needed with cells
        $.each($('tr', row), function (colIndex) {
            // For example, adding data-* attributes to the cell
            $(this).attr('data-foo', "bar");
        });
    },
    columns: [
        cx.common.admin.tableEditColumn('id', { delete: true }),
        { data: 'category_name' },
        { data: 'faq_order' },
        cx.common.admin.tableDateColumn('date_created')
    ]
});

My View Code:

                <input type="text" class="form-control filter" placeholder="Name">

                <input type="text" class="form-control filter" placeholder="Order">

                <input type="text" class="form-control filter" placeholder="Date Created">

            Name
            Order
            Date Created

Js:
var $sortable = $( ".faq-categories-table > tbody" );
$sortable.sortable({
    stop: function ( event, ui ) {
        var parameters = $sortable.sortable( "toArray");
        console.log(parameters);
        $.ajax({
            url: '<?php echo $this->CxHelper->Route('eb-admin-change-general-faq-category-order')?>',
            type: 'POST',
            data: { value: parameters },
            success: function (data) {
                cx.common.data.cxAdminDataTables.EbFaqCategory.cxAdminDataTable("reloadAjax");
            }
        });

    }
});

A: $.each($('tr', row) will not work, because row is already a tr tag, and using $ with a second parameter will restrict the selection inside the context as a second argument. There is no tr inside the tr, so your selection is empty.
try simply with:
"createdRow": function (row, data, rowIndex) {
    // Per-cell function to do whatever needed with cells
    $(row).attr('data-foo', "bar");
},


text:
Q: jqxhr to local server can't find php file I have updated this question as per Cimbali's suggestion. This is now the js code that specifies the request:
......
function editFiltName($thisFiltCell)    {
  var cellText=$thisFiltCell.text();
  var idx=$thisFiltCell.index(); //alert("idx: idx");
  var newFN=prompt("Enter new filter name below - up to 12 characters.", cellText);
    switch (newFN)  {
        case    null        : return;   // cancel key hit
        case    cellText    : return;  // no change
        case    ""          : ; //$thisFCell.text('Filter' + (idx+1));
        default             : $thisFiltCell.text(newFN);
    }
    var action='updateFiltName';
    var request = MrAjax(action,newFN,idx);
} // end main function
//*******************************************
function MrAjax(action,P1,P2)  {
    console.log("Ajax-> action: "+action+" P1: "+P1+" P2: "+P2);
    var jqxhr=$.ajax({
        type: "POST",
        url: "../phpMain/editTblField.php",
        data: {action:action, P1:P1, P2:P2}
    });
    jqxhr.always(function() { console.log("jqxhr.status: " + jqxhr.status ); });
} // end MrAjax

This is now the console output when I enter some data:

Any suggestions? Note that console error is followed immediately by a 'success' response for the same file. But the php file still does not run. I get no php error response from the server - nor do I see my embedded echo I placed on the 1st line of the php file echo("Got here!);. That's true even when I comment out everything but that line.
I don't think it's in the php code but just in case, here it is:
<?php
echo "Got here!";
?>

Thanks again for taking a look.

A: Your error comes from a typo in your console log, you mixed up concatenations from different languages.
Instead of console.log("jqxhr.status: " . jqxhr.status ); you want console.log("jqxhr.status: " + jqxhr.status );
A second error seems to be that the status field doesn't exist (from your comment). However, from the jquery doc, http://api.jquery.com/jQuery.ajax/#jqXHR :

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.
[...]
For backward compatibility with XMLHttpRequest, a jqXHR object will expose the following properties and methods:
readyState
status
statusText
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
getAllResponseHeaders()
getResponseHeader()
statusCode()
abort()

I also ready it is a Deferred object, so maybe this strange behaviour comes from trying to access the status field before it exists. Try waiting for the completion of the request.
So instead of console.log("jqxhr.status: " + jqxhr.status );, use the following :
jqxhr.always(function() { console.log("jqxhr.status: " + jqxhr.status ); });

or
jqxhr.always(function(data, textStatus, errorThrown) { console.log("jqxhr.status=" + jqxhr.status + " : " + textStatus ); });


text:
Q: What is the proper way to send a broadcast from an activity to a service? I have an activity with a button than sends a broadcast to an accessibility service (they're in the same app but different processes). I'm sorry if this was already answered many times but I can't find the proper method to do it. To be clear what I wrote works but I don't know if it's the proper way. I wrote this in the activity:
Intent intent = new Intent("roastie_toastie");
sendBroadcast(intent);

And in the accessibility service wrote this:
IntentFilter intentFilter = new IntentFilter("roastie_toastie");
receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
};
registerReceiver(receiver, intentFilter);

Does anything else need to be added to the intent and intentFilter to be sure that this broadcast does not consume any battery and is only sent and received inside the app?

A:
is there any way to also specify the sender's packageName for the receiver's IntentFilter so that it only listens to broadcasts from inside the app?

No, sorry. However, if this is all one app, then you do not need to use registerReceiver().
Presumably, right now, in your manifest, you have a <service> element that has android:process to have the service run in a separate process from the rest of the app. You can have a <receiver> element that has the same android:process attribute, to have it run in the same process as the service. If you have the <receiver> also be android:exported="false", then only your app can send broadcasts to it. Your sending code would use an explicit Intent, identifying the specific BroadcastReceiver class.
Once you have your broadcast over to the service's process via that BroadcastReceiver, it and the service can communicate via some common process-wide singleton.


text:
Q: iOS enable action extension programmatically I would like to know if there is a way to enable action extension programmatically in containing app so that the user don't need to enable it manually.

A: It's been a long time since the question was asked, but FWIW here is the answer. Yes, I programmatically invoke an action extension by using undocumented NSExtension interface. I learned about this strategy from this post https://ianmcdowell.net/blog/nsextension/. This design is in fact very much usable and technically speaking it works perfectly for me, except for limitations imposed by extensions themselves, particularly memory limitations. For instance, my action extension is limited to 16 Mb, which in my case was very impactful.
Regarding the fact that NSExtension interface is not documented, I opened a source code level support case with Apple to help me implement my design and I asked them about the legitimacy of this interface. The answer was that it would be totally fine if I used it and it should not negatively affect Apple review.
The post I linked to above provided a very useful blueprint, but I had to put in quite a lot of additional code to come up with a working solution. If there is interest in how I did it, I can put together some shareable snippets and post them here.


text:
Q: How to perform a numerical integration (with limits) of discrete data in Python using Scipy? I have an experimental time signal, and I need to compute some integral out of it. In detail, I need to compute the PSD, and then compute the power in some bands of frequencies. So, it seems that scipy is the best way to compute integrals. But the algorithms simpson and trapezoid compute for the whole array. There are no integration limits
I can write a function to perform the search of the arrays and get the index of the integration limits, applying then simpson to an slice of the original array. But I was wondering if there is any other way.
Thanks
MWE
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import welch
from scipy.integrate import simpson

t_0 = 0
t_N = 5
N = 10000
freq = N/(t_N-t_0)
w_1 = 1
w_2 = 5
x = np.linspace(t_0,t_N,N)
y = np.cos(2*np.pi*w_1*x) + np.sin(2*np.pi*w_2*x) + \
    0.05*np.random.randn(x.shape[0])

This is the time signal
plt.plot(x,y)
plt.xlabel('t')
plt.ylabel('signal')

The PSD
f,p = welch(y,fs=freq,nperseg=2**13)
plt.plot(f,p, '-*')
plt.xlim([0,10])
plt.xlabel('f [Hz]')
plt.ylabel('PSD')

My integration function
def psd_integrate(f, p, f0, fN):
    k0, = np.where(f >= f0) # tuple unpack
    k0 = k0[0] # get 1st index
    kN, = np.where(f <= fN) # tuple unpack
    kN = kN[-1] # get last index
    return simpson(p[k0:kN], f[k0:kN])

EDIT: Forgot to add. I'm using seaborn, that's why the plots looks different from default matplotlib