AttributeError: 'function' object has no attribute 'ParseFromString'

Question: I have tensorflow-gpu 1.9 and python 3.7 in my system. I receive the error in line number 51: od_graph_def.ParseFromString(serialized_graph)
I followed all the steps from here to deploy the tensorflow model.
Is there any problem in this code? How can I resolve this issue?
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
import cv2

from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from utils import label_map_util
from utils import visualization_utils as vis_util

# Define the video stream
cap = cv2.VideoCapture(0)  # Change only if you have more than one webcams

# What model to download.
# Models can bee found here: https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md
MODEL_NAME = 'ssd_inception_v2_coco_2017_11_17'
MODEL_FILE = MODEL_NAME + '.tar.gz'
DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'

# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'

# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('data', 'mscoco_label_map.pbtxt')

# Number of classes to detect
NUM_CLASSES = 90

# Download Model
opener = urllib.request.URLopener()
opener.retrieve(DOWNLOAD_BASE + MODEL_FILE, MODEL_FILE)
tar_file = tarfile.open(MODEL_FILE)
for file in tar_file.getmembers():
    file_name = os.path.basename(file.name)
    if 'frozen_inference_graph.pb' in file_name:
        tar_file.extract(file, os.getcwd())

# Load a (frozen) Tensorflow model into memory.
detection_graph = tf.Graph()
with detection_graph.as_default():
    od_graph_def = tf.compat.v1.get_default_graph
    with tf.io.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
        serialized_graph = fid.read()
        od_graph_def.ParseFromString(serialized_graph)
        tf.import_graph_def(od_graph_def, name='')

# Loading label map
# Label maps map indices to category names, so that when our convolution network predicts `5`, we know that this corresponds to `airplane`.  Here we use internal utility functions, but anything that returns a dictionary mapping integers to appropriate string labels would be fine
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(
    label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

# Helper code
def load_image_into_numpy_array(image):
    (im_width, im_height) = image.size
    return np.array(image.getdata()).reshape(
        (im_height, im_width, 3)).astype(np.uint8)

# Detection
with detection_graph.as_default():
    with tf.Session(graph=detection_graph) as sess:
        while True:

            # Read frame from camera
            ret, image_np = cap.read()
            # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
            image_np_expanded = np.expand_dims(image_np, axis=0)
            # Extract image tensor
            image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
            # Extract detection boxes
            boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
            # Extract detection scores
            scores = detection_graph.get_tensor_by_name('detection_scores:0')
            # Extract detection classes
            classes = detection_graph.get_tensor_by_name('detection_classes:0')
            # Extract number of detectionsd
            num_detections = detection_graph.get_tensor_by_name(
                'num_detections:0')
            # Actual detection.
            (boxes, scores, classes, num_detections) = sess.run(
                [boxes, scores, classes, num_detections],
                feed_dict={image_tensor: image_np_expanded})
            # Visualization of the results of a detection.
            vis_util.visualize_boxes_and_labels_on_image_array(
                image_np,
                np.squeeze(boxes),
                np.squeeze(classes).astype(np.int32),
                np.squeeze(scores),
                category_index,
                use_normalized_coordinates=True,
                line_thickness=8)

            # Display output
            cv2.imshow('object detection', cv2.resize(image_np, (800, 600)))

            if cv2.waitKey(25) & 0xFF == ord('q'):
                cv2.destroyAllWindows()
                break

Answer: You need to change this line:
od_graph_def = tf.compat.v1.get_default_graph

to
od_graph_def = tf.compat.v1.get_default_graph()

The first sets the value of od_graph_def to the function tf.compat.v1.get_default_graph, while the second sets od_graph_def to the graph returned by said function.


What is "Data Protection" option in WebBIOS 6.1-45-Rel of ServeRAID M5110e controller?

Question: What is "Data Protection"`option in WebBIOS 6.1-45-Rel during creation of new Drive Group?
Server is IBM x3650 M4 with ServeRAID M5110e controller.
User's Guide (here http://www-947.ibm.com/support/entry/portal/docdisplay?lndocid=MIGR-5086126) does not provide any details about it...
Comment: WARNING: take a look at this if you're considering enabling this option in a System x3650 M4 server. I had it enabled (no idea how, it's supposed to be off by default), and caused random controller errors (critical, fatal and catastrophic): https://www-947.ibm.com/support/entry/myportal/docdisplay?lndocid=MIGR-5093594
Answer: there is no official documentation from IBM about this feature but our local dealer referred to the documentation directly from Seagate:
http://www.seagate.com/files/staticfiles/docs/pdf/whitepaper/tp621-safeguarding-data-from-corruption-us.pdf
EDIT (To avoid link rot):
It states that the feature relies on the T10 Protection Information (T10-PI) standard which adds an extra eight bytes of information to the 512-byte sectors of hard drives, increasing sector size to 520 bytes. These extra eight bytes of metadata are used to verify the integrity of the 512 bytes of data in the sector. This should prevent data from silent corruption.
Due to the extra overhead of transferring PI metadata from the media, sequential performance of a PI drive will be reduced by approximately 1.56%.
Comment: Scutze, could you please summarize the contents of the linked file for SF readers? Otherwise your post is subject to linkrot.
Comment: This is the same protection feature that EMC/NetApp (and others) use in enterprise SAN's. Just for the record. :)
Comment: Looks like Seagate has changed the name of the file for the Whitepaper. The following link works: http://www.seagate.com/files/staticfiles/docs/pdf/whitepaper/safeguarding-data-from-corruption-technology-paper-tp621us.pdf


Como acessar o index corretamente para dados no mesmo arquivo?

Question: Tenho um arquivo
arquivo.txt:
>gb:KX262887|Organism:Zika virus|Strain Name:103451|Segment:null|Subtype:Asian|Host:Human
GTTGTTGATCTGTGTGAATCAGACTGCGACAGTTCGAGTTTGAAGCGAAAGCTAGCAACAGTATCAACAG
GTTTTATTTTGGATTTGGAAACGAGAGTTTCTGGTCATGAAAAACCCAAAAAAGAAATCCGGAGGATTCC
GGATTGTCAATATGCTAAAACGCGGAGTAGCCCGTGTGAGCCCCTTTGGGGGCTTGAAGAGGCTGCCAGC
>gb:HM045792|Organism:Chikungunya virus|Strain Name:'Vereeniging'|Segment:null|Host:Human
ACGTAGCCTACCAGTTTCTTACTGCTCTACTCTGCAAAGCAAGAGATTAAGAACCCATCATGGATCCTGT
GTACGTGGACATAGACGCTGACAGCGCCTTTTTGAAGGCCCTGCAACGTGCGTACCCCATGTTTGAGGTG
GAACCTAGGCAGGTCACACCGAATGACCATGCTAATGCTAGAGCGTTCTCGCATCTAGCTATAAAACTAA
TAGAGCAGGAAATTGATCCCGACTCAACCATCCTGGATATCGGTAGTGCGCCAGCAAGGAGGATGATGTC
>gb:KY474305|Organism:Dengue virus 1|Strain Name:00099-S|Segment:null|Subtype:1|Host:Human
CGAATCGGAAGCTTGCTTAACGTAGTTCTAGCAGTTTTTTATTAGAGAGCAGATCTCTGATGAACAACCA
ACGGAAAAAGACGGGTCGACCGTCTTTCAATATGCTGAAACGCGCGAGAAACCGCGTGTCAACTGGTTCA
CAGTTGGCGAAGAGATTCTCAAAAGGATTGCTTTCAGGCCAAGGACCCATGAAATTGGTGATGGCTTTCA
TAGCATTTCTAAGATTTCTAGCCATACCCCCAACAGCAGGAATTTTGGCTAGATGGAGCTCATTCAAGAA
GAATGGAGCGATCAAAGTGTTACG

Estou armazenando essas informações em uma lista e posteriormente em uma tabela no banco de dados porém o índice ou index difere em Host.
code:
for item in SeqIO.parse('arquivo.txt', 'fasta'):
    dado = item.description.replace('|', '\n').splitlines()
    print(dado)
    resumo = []

    for i in dado:
        d = i.replace(':', '\n').splitlines()
        resumo.append(d[1])

    id_name = resumo[0]
    organism = resumo[1]
    strain_name = resumo[2]
    segment = resumo[3]
    host = resumo[4]
    seq = item.seq

saída:
 id_name    host     organism         seq           strain_name   segment
 KX262887   Asian   Zika virus      GTTGTTGATCG     103451        null
 KY474305    1      Dengue virus 1  CGAATCTTACG     00099-S       null
 ...

saída esperada:
 id_name    host     organism         seq           strain_name   segment
 KX262887   Human   Zika virus      GTTGTTGATCG     103451        null
 KY474305   Human   Dengue virus 1  CGAATCTTACG     00099-S       null
...

Como posso acessar os índices corretamente e armazena-los na tabela?
Comment: Considera usar pandas?
Comment: Sim. Se resolver o problemaI considero usar qualquer biblioteca em Python.... @Miguel
Comment: E os nomes das colunas são fixo? Ou vão ser dinamicos?
Comment: Fixos. Tabela Mysql
Answer: Há um problema pois nem todos os dados tem o mesmo comprimento, portanto acessando esses valores a partir dos índices pode causar resultados inesperados.
Então aqui vai uma outra forma de acessar esses dados de maneira mais simples e sem utilizar nenhuma outra biblioteca adicional.
Os dados são separados com o split() e agrupados em um dicionário usando dict():
for item in SeqIO.parse('arquivo.txt', 'fasta'):
    resumo = dict(x.split(":") for x in item.description.split("|"))
    id_name = resumo["gb"]
    organism = resumo["Organism"]
    strain_name = resumo["Strain Name"]
    segment = resumo["Segment"]
    host = resumo["Host"]
    seq = item.seq


Start foreach loop on associative array at the second element

Question: I have associative array such as:
$myArray = array(
  'key1' => 'val 1',
  'key2' => 'val 2'
  ...
);

I do not know the key values up front but want to start looping from the second element.  In the example above, that would be from key2 onwards.
I tried
foreach(next(myArray) as $el) {

}

but that didnt work.
Alternatives may be array_slice but that seems messy.  Am i missing something obvious?
Answer: There really is no "one true way" of doing this. So I'll take it as a benchmark as to where you should go.
All information is based on this array.
$array = array(
    1 => 'First',
    2 => 'Second',
    3 => 'Third',
    4 => 'Fourth',
    5 => 'Fifth'
);

The array_slice() option. You said you thought this option was overkill, but it seems to me to be the shortest on code.
foreach (array_slice($array, 1) as $key => $val)
{
    echo $key . ' ' . $val . PHP_EOL;
}

Doing this 1000 times takes 0.015888 seconds.

There is the array functions that handle the pointer, such as ...

current() - Return the current element in an array.
end() - Set the internal pointer of an array to its last element.
prev() - Rewind the internal array pointer.
reset() - Set the internal pointer of an array to its first element.
each() - Return the current key and value pair from an array and advance the array cursor.

Please note that the each() function has been deprecated as of PHP 7.2, and will be removed in PHP 8.
These functions give you the fastest solution possible, over 1000 iterations.
reset($array);
while (next($array) !== FALSE)
{
    echo key($array) . ' ' . current($array) . PHP_EOL;
}

Doing this 1000 times, takes 0.014807 seconds.

Set a variable option.
$first = FALSE;
foreach ($array as $key => $val)
{
    if ($first != TRUE)
    {
        $first = TRUE;
        continue;
    }

    echo $key . ' ' . $val . PHP_EOL;
}

Doing this 1000 times takes 0.01635 seconds.

I rejected the array_shift options because it edits your array and you've never said that was acceptable.
Comment: I like the array_slice option.  Very clean
Answer: This depends on whether you want to do this just once or many times, and on whether you still need the original array later on.
"First" pattern
$first = true;
foreach ($array as $key=>value) {
    if($first) {
        $first = false;
        continue;
    }
    // ... more code ...
}

I personally use this solution quite often because it's really straight-forward, everybody gets this. Also, there is no performance hit of creating a new array and you can still operate on the original array after the loop.
However, if you have a couple of loops like this, it kind of starts looking a little unclean, because you need 5 extra lines of code per loop.
array_shift
array_shift($array);
foreach ($array as $key=>value) {
    // .... more code ....
}

array_shift is a function tailored to this special case of not wanting the first element. Essentially it's a Perl-ish way of saying $array = array_slice($array, 1) which might not be completely obvious, especially since it modifies the original array.
So, you might want to make a copy of the original array and shift it, if you need both the shifted array multiple times and also the original array later on.
array_slice
And, of course, there is array_slice itself. I don't see anything wrong with array_slice if you want the original array to remain unchanged and you need the sliced array multiple times. However, if you're positive that you always want to slice just one element off, you might as well use the shorthand array_shift (and make a copy before if needed).
Comment: I created a duplicate and used `array_shift`
Answer: You can go with the obvious way:
$flag = false;
foreach($myArray as $el) {
   if($flag) {
      // do what you want
   }
   $flag = true;
}

Comment: i am not completely sold on this.  It will work but it seems like lots of unnecessary checks during a loop.
Comment: you're right but since its a boolean check I am sure that you will never see performance loss
Answer: Just another way of flexible iteration:
reset($myArray);  // set array pointer to the first element
next($myArray);   // skip first element

while (key($myArray) !== null) {

  // do something with current($myArray)

  next($myArray);
}

As far as I know foreach is just a kind of shortcut for this construction.
From Zend PHP 5 Certication study guide:

As you can see, using this set of functions [reset, next, key,
  current, ...] requires quite a bit of work; to be fair, there are some
  situations where they offer the only reasonable way of iterating
  through an array, particularly if you need to skip back-and-forth
  between its elements. If, however, all you need to do is iterate
  through the entire array from start to finish, PHP provides a handy
  shortcut in the form of the foreach() construct.
Comment: ``
Comment: @MarkTomlin even better!
Answer: If your array was 0 based, it would be if($key>=1), but as your array starts at key 1, then this should work.
foreach ($array as $key=>$value){if($key>=2){
        do stuff
        }}

Comment: array_slice works without having to know how the key are formatted and works on non-numeric keys. It always removes the first `$offset` elements. As a general rule, it's always better to use a built in function than it is program your way around it.
Answer: You could try:
$temp = array_shift($arr);
foreach($arr as $val) {
   // do something
}
array_unshift($arr, $temp);

Comment: I think modifying the array just to iterate through it is a bad idea
Comment: @andrewtweber I don't disagree, but it depends on what the reason for skipping the first element is. There are a number of ways to achieve what the OP asked - this is an option that might be appropriate for reasons he hasn't gone into.
Answer: reset($myArray);
next($myArray);

while ($element = each($myArray))
{
    //$element['key'] and $element['value'] can be used
}

Answer: My fairly simple solution when this issue pops up. It has the nice advantage of being easily being modified to be able to skip more than just the first element if you want it to.
$doomcounter = 0;
foreach ($doomsdayDevice as $timer){ if($doomcounter == 0){$doomcounter++; continue;}

   // fun code goes here

}

Comment: array_slice does the same thing with the second argument and I'll bet it's faster, but I'll leave the benchmarking on that to someone else.


Can we use Google Translate API to index files for searching?

Question: I am using Lucene 4.2.1 to index files. I need to index multilingual content for which we use Analyzer based on the language, to tokenize and index keywords. However Lucene 4.2.1 does not have analyzers for some languages like Japanese, Korean. The one solution to this is updating the lucene version but since that involves a lot of changes for deprecated functions (in case), I'm trying to find a work around. Does anyone have any suggestions? Thank you!
Answer: Personally i would strongly suggest to invest this amount of time and upgrade to the most recent version. This "problem" is already solved in the never versions and building an own written solution may be much more time consuming than upgrading.
IMAO working with such an old version is a technical dept which should be solved. Technical dept always fires back and usually costs much more money as longer as they exist.
Comment: Thank you for your help. Yes I understand that upgrading it to the latest version should solve it better. Any suggestions on using APIs to index and search in other languages? I found some APIs created by WikiBrain but not sure how to use it in my application.
Answer: Not Sure - But Got This on Google. The Google Cloud Translation API can dynamically translate text between thousands of language pairs. The Cloud Translation API lets websites and programs integrate with the translation service programmatically. The Google Translation API is part of the larger Cloud Machine Learning API family. Please Refer Here Too https://cloud.google.com/translate/docs/ Cotton bags supplier in Dubai
Comment: Thanks for your help Yousuf! Actually I also need to index search files based on the data provided by my application. In that case the Google translate feature might not prove to be useful.


TFS 2010 Release Candidate Can't Create SharePoint Site Error

Question: I have installed a deployment of Team Foundation Server 2010 Release Candidate and I am connecting through Visual Studio 2010 Ultimate Release Candidate. When I try to create a new Team Project I get an error "TF250044 SharePoint Site can not be created in the following location: Server Name Here" It also tells me that my user account does not have permissions to create sites in SharePoint but my user account has full rights in SharePoint.
I have checked everywhere and as far as I know I have full permissions in SharePoint, if someone encountered this problem and solved it please help.
Thank You!
Comment: Is the SharePoint collection for TFS configured according to the TFS Administration Console, and can it connect successfully?
Comment: Yes from TFS point of view everything is just fine. But from the Client I can't add a Team Project. Real Frustrating...
Answer: By default when you try to create a new Team Project, Visual Studio sets a default path for the SharePoint site.
<code>[SharePoint Server]/sites/[TFS Project Collection Name]/[Team Project Name]
</code>
What you want to do is create the site collection for the [TFS Project Collection Name] or remove it and create the Team Project Site in the sites root.
Hope this helps.
Answer: Like someone else said, you might want to remove the associated SharePoint association from the TFS Admin Console and create it again.  Did you upgrade this server?  I had a problem with a recent upgrade from TFS 2008 where I had a Team Project with the same name as the new TFS Project Collection.  That created all sorts of conflicts.


Getting different Percentile results when using two different software

Question: I'm calculating 90th percentile values in two different places using two different pieces of software, and I'm getting different results.
These results need to be comparable. I understand there are different ways to calculate Percentile, but this isn't my area of expertise.
The two software is Power BI (using PERCENTILE.INC) and Math.NET C# library (Statistics.Percentile)
I've made sure that the data being fed to both methods are the same.
For example, using the following set: 49,33,28,33,21.1,9,0

Power BI comes back with 39.4
Math.NET comes back with 47.9

Can anybody tell me why these are different? Or what I should look for to get comparable results?
Comment: Sample size = 8, 90th percentile ==> 8*0.9 = 7.2 ==> the estimate should be any number between 7th and 8th. (In you case, between 33 and 49). Different software has different rules to pick up a number between between 33 and 49.
Answer: As you say, there are several different ways to define quantiles.
For your small sample: Your sorted data are as follows (from R):
x = c(49,33,28,33,21.1,9,0)
sort(x)
[1]  0.0  9.0 21.1 28.0 33.0 33.0 49.0

With this small sample of $n = 7$ observations, there is no one obvious
choice for the 90th percentile. Various statistical software programs
make different compromises.
The documentation of R's quantile procedure lists nine different rules
for such compromises accessible with the parameter type. Exact formulas and rationales for most of them are shown there. (R provides the opportunity to use different types of quantiles for compatibility with other software programs.)
Type 7, the default in R, gives one of the values for the 90th percentile that you mentioned.
quantile(x, .9)   # usually, no 'type' specified, R uses Type 7
 90%
39.4
quantile(x, .9, type=7)
 90%
39.4

Your other value results from using Type 9:
quantile(x, .9, type=9)
 90%
47.4

Because of the large gap between observations 33 and 49, a large
variety of other values are possible with different types, including
33 (from Type 3) and 49 (from Types 1 and 2).
Larger samples:  In practice, quantiles are mostly used for samples of moderate and large
size, for which the different rules don't make substantial differences.
y = sort(rnorm(1000, 50, 7))
quantile(y, .9)
     90%
59.01486
quantile(y, .9, type=1)
     90%
59.01104
quantile(y, .9, type=3)
     90%
59.01104
y[898:902]
[1] 59.00132 59.01043 59.01104 59.04926 59.09998

Consequences of rounding. Rounding a sample to integers can induce many ties, and thus fewer
differences among the rules:
z = sort(round(rnorm(1000, 50, 7)))
quantile(z, .9)
90%
 59
quantile(z, .9, type=1)
90%
 59
quantile(z, .9, type=3)
90%
 59
z[898:902]
[1] 59 59 59 59 60

When you are taking a basic statistics course, use whatever rule is given
in your text or recommended by your instructor. But be aware that if you
use software to find answers, you won't necessarily get exactly the same answer as
an answer book.
In practice, you will probably use a particular kind of statistical software,
and be happy enough with whatever rule the software uses as its default.
Addendum per comments about application: If your samples are coming from a normal population, it may be best to use the fact that the sample mean $\bar X$ and sample SD $S_X$ are based on sufficient statistics, so
tend to provide better information about the normal population than do quantiles. Then the procedure would be to find the 90th percentile of the normal distribution $\mathsf{Norm}(\bar X, S_X).$
In the simulation below, I compare the actual 90th quartiles q.9 with estimates q.e obtained under the assumption of normality. The latter estimates do a little better. If the population distribution is $\mathsf{Norm}(\mu = 25. \sigma = 5),$ then its 90th percentile is 13.41. Also, in the simulation I tried Type 9 quantiles which are said
to give unbiased approximations of population quantiles of normal distributions.
qnorm(.9, 25, 5)
[1] 31.40776

set.seed(808)
m = 10^5;  n=40;  mu=25; sg=5
q.9 = q.e = numeric(m)

for(i in 1:m) {
 x = rnorm(n, mu, sg)
 q.e[i] = qnorm(.9, mean(x), sd(x))
 q.9[i] = quantile(x, .9, type=9)   }
mean(q.e);  sd(q.e)
[1] 31.36575        # aprx 31.41
[1] 1.072285        # less variable than below
mean(q.9);  sd(q.9)
[1] 31.4376         # aprx 31.41
[1] 1.302801        # more variable than above

Both methods tend to give nearly the right 90th percentile on average,
but the method using the normal distribution is more consistently
close to the correct answer. Root mean square error (RMSE) is one way to measure 'goodness' of an estimator, low values are better. The RMSE
using quantiles is a little larger, but this method does not assume normality. (RMSE from Type 7 quantiles is about 2.87.)
sqrt(mean((q.e-31.41)^2))
[1] 1.073193               # smaller RMSE
sqrt(mean((q.9-31.41)^2))
[1] 1.303086               # larger

Something similar might be done for sampling from an exponential population, but if you have no idea what kind of distribution the
population has (or even whether it is stable), then using sample
quantiles to estimate population quantiles may be a safer course of
action.
Comment: Thank you, this has really helped. For the record, this is for a practical application. Power BI supports R so I should be able to play around with the different type parameters and get something I'm happy with. If only other libraries were that robust!
Comment: Is your goal to estimate the 90th percentile of some normal process based on a small sample `x`? If so, is 7 a typical sample size? Then you might do better to find the avg `a` and the sd `s` of the sample and then do `qnorm(.9, a, s)`. There is 'better info' about the population dist'n in `a` and `s` than in the 90th percentile.
Comment: The sample size varies but can be as low as my example and as high as 80. The goal is to generate an urgent limit line on a graph based on user fleet data.
Comment: Probably OK to use sample quantiles. See Addendum to my Answer.


Cmake complains about Could NOT find CURL (missing: CURL_LIBRARY)

Question: I am building curl and curlpp from source in my CMakeLists.txt using FetchContent to use in an executable later in my CMakeLists.txt.
cmake_minimum_required(VERSION 3.17)
project(myproject VERSION 1.0.0)

include(FetchContent)
include(CMakePrintHelpers)

cmake_print_variables(CMAKE_CXX_FLAGS)

if (WIN32)
    set(CMAKE_USE_SCHANNEL ON)
endif()

# --- CURL
FetchContent_Declare(curl
        URL                    https://github.com/curl/curl/releases/download/curl-7_75_0/curl-7.75.0.tar.xz
        URL_HASH               SHA256=fe0c49d8468249000bda75bcfdf9e30ff7e9a86d35f1a21f428d79c389d55675 # the file hash for curl-7.75.0.tar.xz
        USES_TERMINAL_DOWNLOAD TRUE)
FetchContent_MakeAvailable(curl)

add_library(curl_int INTERFACE)
target_link_libraries(curl_int INTERFACE libcurl)
target_include_directories(curl_int INTERFACE ${curl_SOURCE_DIR}/include ${curl_BINARY_DIR}/include/curl)
add_library(CURL::mylibcurl ALIAS curl_int)
set(CURL_INCLUDE_DIR
        ${curl_SOURCE_DIR}/include
        )

# --- CURL C++
FetchContent_Declare(curlpp
        GIT_REPOSITORY  https://github.com/jpbarrette/curlpp.git
        )
FetchContent_MakeAvailable(curlpp) # ----> Error occurs here
cmake_print_variables(curlpp_SOURCE_DIR curlpp_BINARY_DIR)
add_library(curlpp_int INTERFACE)
target_link_libraries(curlpp_int INTERFACE libcurlpp CURL::mylibcurl)
target_include_directories(curlpp_int INTERFACE ${curlpp_SOURCE_DIR}/include ${curlpp_BINARY_DIR}/include/curl)
add_library(CURLPP::mylibcurlpp ALIAS curlpp_int)
set(CURLPP_INCLUDE_DIR
        ${curlpp_SOURCE_DIR}/include
        )
set(CURLPP_LIB_DIR
        ${curlpp_BINARY_DIR})

cmake_print_variables(CURLPP_LIB_DIR)
cmake_print_variables(CURLPP::mylibcurlpp)

# The rest of CMakeLists.txt is omitted

However, during cmake build, when it executes FetchContent_MakeAvailable(curlpp), I get a complaint about
Could NOT find CURL (missing: CURL_LIBRARY)

I am linking curlpp with curl by target_link_libraries(curlpp_int INTERFACE libcurlpp CURL::mylibcurl) and was expecting it to be able to find it.
How could I solve this?
Comment: You have a bunch of interface libraries but nothing that compiles to a binary. Is your error message a CMake error or a compiler error? What line does it correspond to?
Answer: In the CMake of curlpp, the CURL library is required and fetched if not available:
71 message(STATUS "Looking for CURL")
72 find_package(CURL REQUIRED)
73
.  if(CURL_FOUND)
.    message(STATUS "Found CURL version: ${CURL_VERSION_STRING}")
.    message(STATUS "Using CURL include dir(s): ${CURL_INCLUDE_DIRS}")
.    message(STATUS "Using CURL lib(s): ${CURL_LIBRARIES}")
.  else()
.    message(STATUS "Fetching CURL")
.    include(FetchContent)
.    FetchContent_Declare(CURL GIT_REPOSITORY https://github.com/curl/curl.git)
.    FetchContent_MakeAvailable(CURL)
.  endif()

https://github.com/jpbarrette/curlpp/blob/master/CMakeLists.txt#L72

I could think of two problems here, but also more information might be helpful, for example, if your error is thrown in line 72 or above that.

One option would be, that you build CURL into a directory that then is not found in the curlpp find_package call.
Another option would be that your versions are not compatible, looking at the code from curlpp they by default would download the master repo of curl.


Integração do api do google drive não funciona. como faço para consertar?

Question: eu quero integrar o api do google drive no meu app. ele roda mas não conecta, como se não recebesse as informações que foram enviadas. como resolvo isso? O código é a própria google que disponibiliza só que parece estar desatualizado e não consigo reconhecer onde está o erro no codigo deles.
Comment: Você assinou sua apk? Poderia mostrar como faz a conexão? Colocou o arquivo .json gerado pelo console?
Answer: É um tanto quanto complicado apontar o que está errado!
Ainda mas sem um exemplo, ou link!
Fiz um exemplo simples de como criar um arquivo:
Não vou entrar no mérito de criar a credentials.
Caso haja dúvida, segue o link.
Ao gerar sua credentials, será disponibilizado um arquivo .json  (client_secret_xxxxxxxxxx.apps.googleusercontent.com.json), este deve ser adicionado a pasta app do seu projeto!
Esta biblioteca funciona apenas com apk 's assinadas, então quando você informa o SHA1, este deve ser gerado com seu keyStore.jks.
Para que que seu apk de debug seja assinado, adicione o seguinte código em seu grade:
android {
    signingConfigs {
        debug {
            keyAlias 'seuAlias'
            keyPassword 'senhaAlias'
            storeFile file('Caminho/keyStore.jks')
            storePassword 'senhaKeyStore'
        }
    }
}

Vamos criar uma classe abstrata que terá o GoogleApiClient, responsável por conectar no drive:
BaseActivity.java
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveFolder;

public abstract class BaseActivity extends AppCompatActivity implements  GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

    // Codigo de retorno
    public static final int RESOLVE_CONNECTION_REQUEST_CODE = 112;
    // conecta ao drive
    protected  GoogleApiClient mGoogleApiClient;

    @Override
    protected void onStart() {
        super.onStart();
        // Se estiver nulo, vamos configurar
        if(mGoogleApiClient == null){
            mGoogleApiClient = new GoogleApiClient.Builder(this).
                    addApi(Drive.API)
                    .addScope(Drive.SCOPE_FILE)
                    .addScope(Drive.SCOPE_APPFOLDER)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();
        }
        if(!mGoogleApiClient.isConnected()){
            mGoogleApiClient.connect(); // conectando ....
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode){
            // Caso seja o código que enviamos e for OK, tentamos conectar novamente
            case RESOLVE_CONNECTION_REQUEST_CODE:
                if(resultCode == RESULT_OK){
                    mGoogleApiClient.connect();
                }
                break;
        }
    }

    @Override
    protected void onPause() {
        // desconectamos
        if(null != mGoogleApiClient){
            mGoogleApiClient.disconnect();
        }
        super.onPause();
    }

    /**
     * Será invocado quando se conectar
     */
    @Override
    public void onConnected(@Nullable Bundle bundle) {

    }

    /**
     * será invocado so suspender a conexão
     */
    @Override
    public void onConnectionSuspended(int i) {
    }

    /**
     * Tratamento de falha de conexão
     */

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        if(connectionResult.hasResolution()){
            try {
                connectionResult.startResolutionForResult(this, RESOLVE_CONNECTION_REQUEST_CODE);
            } catch (IntentSender.SendIntentException e) {
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }else{
            Toast.makeText(this, "onConnectionFailed", Toast.LENGTH_SHORT).show();
        }
    }

    protected void showMessage(final String message){
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}

MainActivity.java
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFolder;
import com.google.android.gms.drive.MetadataChangeSet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class MainActivity extends BaseActivity {

    /**
     * Callback de criação de um arquivo
     */
    private final ResultCallback<DriveApi.DriveContentsResult> createFileCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
        @Override
        public void onResult(@NonNull final DriveApi.DriveContentsResult result) {

            // se não teve sucesso, exibimos o erro e saímos...
            if(!result.getStatus().isSuccess()){
                showMessage("Não foi possível criar o arquivo...");
                return;
            }
            final DriveContents driveContents = result.getDriveContents();
            new Thread(){
                @Override
                public void run() {
                    final OutputStream outputStream = driveContents.getOutputStream();
                    final Writer writer = new OutputStreamWriter(outputStream);
                    try {
                        final SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
                        writer.write("Arquivo criado através de app em "+dateFormat.format(Calendar.getInstance().getTimeInMillis()));
                        writer.close();
                    } catch (IOException e) {
                        showMessage(e.getMessage());
                    }

                    MetadataChangeSet changeSet = new MetadataChangeSet.Builder().setTitle("AppFileCreate").setMimeType("text/plain").setStarred(true).build();
                    Drive.DriveApi.getRootFolder(mGoogleApiClient).createFile(mGoogleApiClient, changeSet, driveContents).setResultCallback(fileCallback);
                }
            }.start();
        }
    };

    /*
    * Calback  de Resultado (invocado após a criação)
     */

    final private ResultCallback<DriveFolder.DriveFileResult> fileCallback = new
            ResultCallback<DriveFolder.DriveFileResult>() {
                @Override
                public void onResult(DriveFolder.DriveFileResult result) {
                    if (!result.getStatus().isSuccess()) {
                        showMessage("Error while trying to create the file");
                        return;
                    }
                    showMessage("Created a file with content: " + result.getDriveFile().getDriveId());
                }
            };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Vamos criar um arquivo
                Drive.DriveApi.newDriveContents(mGoogleApiClient)
                        .setResultCallback(createFileCallback);
            }
        });

    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        super.onConnected(bundle);

    }

}


Decomposing a group as a direct product of its kernel and image

Question:
Suppose $\phi:G\rightarrow H$ is a group homomorphism.  When is it true that $G\cong$ ker$(\phi)\oplus G/$ker$(\phi)$?

If $G$ and $H$ are abelian and there exists a homomorphism $\varphi:H\rightarrow G$ such that $\phi \varphi=1_{H}$ then this is true.
I seem to remember something about this when I studied exact sequences, but I don't have Dummit and Foote on hand.
I thought there was a case where the short exact sequence always splits like this?
Comment: The key phrase is "direct product".
Comment: It happens if and only if $\mathrm{ker}(\phi)$ has a normal complement.
Comment: what is a normal complement?
Comment: A subgroup $H$ has a complement in $G$ if there exists a subgroup $K$ such that $H\cap K=\{e\}$ and $HK=G$. If $K$ is required to be normal, it is a "normal complement". If both $H$ and $K$ are normal then you get a direct product decomposition.
Comment: How is this normal complement related to $H$, say, in the case $\phi$ is surjective?
Answer: The key phrase is "direct product"; $G\cong\ker(\phi)\oplus G/\ker(\phi)$ happens if and only if there exists some normal subgroup $N\lhd G$ such that $N\cap\ker(\phi)=1$ and $G=N\ker(\phi)$. (In particular, $N\cong G/\ker(\phi)$ here.)
If $N$ is not required to be normal then you get a "semidirect product", which characterises the $\phi\varphi=1_H$ condition you give.


Clear Chrome browser logs in Selenium/Python

Question: I have a large application and I am using Headless Chrome, Selenium and Python to test each module. I want to go through each module and get all the JS console errors produced while inside that specific module.
However, since each module is inside a different test case and each case executes in a separate session, the script first has to login on every test. The login process itself produces a number of errors that show up in the console. When testing each module I don't want the unrelated login errors to appear in the log.
Basically, clear anything that is in the logs right now -> go to the module and do something -> get logs that have been added to the console.
Is this not possible? I tried doing driver.execute_script("console.clear()") but the messages in the console were not removed and the login-related messages were still showing after doing something and printing the logs.
Answer: State in 2017 and late 2018
The logging API is not part of the official Webdriver specification yet.
In fact, it's requested to be defined for the level 2 specification. In mid 2017 only the Chromedriver has an undocumented non-standard implementation of that command.
In the sources there's no trace of a method for clearing logs:

The public API Webdriver.get_log()
which references internal Command names
which translate to acutal requests in RemoteConnection

Possible Workaround
The returned (raw) data structure is a dictionary that looks like this:
{
    u'source': u'console-api',
    u'message': u'http://localhost:7071/console.html 8:9 "error"',
    u'timestamp': 1499611688822,
    u'level': u'SEVERE'
}

It contains a timestamp that can be remembered so that subsequent calls to get_log() may filter for newer timestamps.
Facade
class WebdriverLogFacade(object):

    last_timestamp = 0

    def __init__(self, webdriver):
        self._webdriver = webdriver

    def get_log(self):
        last_timestamp = self.last_timestamp
        entries = self._webdriver.get_log("browser")
        filtered = []

        for entry in entries:
            # check the logged timestamp against the
            # stored timestamp
            if entry["timestamp"] > self.last_timestamp:
                filtered.append(entry)

                # save the last timestamp only if newer
                # in this set of logs
                if entry["timestamp"] > last_timestamp:
                    last_timestamp = entry["timestamp"]

        # store the very last timestamp
        self.last_timestamp = last_timestamp

        return filtered

Usage
log_facade = WebdriverLogFacade(driver)
logs = log_facade.get_log()

# more logs will be generated

logs = log_facade.get_log()
# newest log returned only

Answer: This thread is a few years old, but in case anyone else finds themselves here trying to solve a similar problem:
I also tried using driver.execute_script('console.clear()') to clear the console log between my login process and the page I wanted to check to no avail.
It turns out that calling driver.get_log('browser') returns the browser log and also clears it.
After navigating through pages for which you want to ignore the console logs, you can clear them with something like
_ = driver.get_log('browser')


django-orm case-insensitive order by

Question: I know, I can run a case insensitive search from DJango ORM. Like,
User.objects.filter(first_name__contains="jake")
User.objects.filter(first_name__contains="sulley")
User.objects.filter(first_name__icontains="Jake")
User.objects.filter(first_name__icontains="Sulley")

And also, I can fetch them as
user_list = User.objects.all().order_by("first_name")
# sequence: (Jake, Sulley, jake, sulley)
user_list = User.objects.all().order_by("-first_name") # for reverse
# sequence: (sulley, jake, Sulley, Jake)

Is there a direct way for a case-insensitive fetch?? As in I want a sequence as
# desired sequence: jake, Jake, sulley, Sulley

If not, then suggest a best way to do it. Thanks in advance.
Comment: This is for postgresql, but maybe it will be useful for other databases too: http://scottbarnham.com/blog/2007/11/20/case-insensitive-ordering-with-django-and-postgresql/
Answer: Since Django 1.8 it is possible with:
from django.db.models.functions import Lower
MyModel.objects.order_by(Lower('myfield'))

https://code.djangoproject.com/ticket/6498
Comment: for descending order use:

MyModel.objects.order_by(Lower('myfield').desc())
Comment: It is possible: User.objects.order_by(Lower('username'), Lower('email'))
Comment: Is it possible to use Lower with multiple columns? I can only seem to get it to work with one column.
Comment: models.py class Meta: ordering = [Lower('name')]
Answer: This answer is outdated, follow top voted solution with django >= 1.8
I found solution using .extra
class MyModelName(models.Model):
   is_mine = models.BooleanField(default=False)
   name = models.CharField(max_length=100)

MyModelName.objects.filter( is_mine=1 ).extra(\
    select={'lower_name':'lower(name)'}).order_by('lower_name')

original link:
http://naorrosenberg.blogspot.fi/2011/04/django-models-orderby-charfield-case.html
Comment: This won't work when traversing relationship, i.e "name__something" , however you can make it works with the Lower function since django 1.8 : 'from django.db.models.functions import Lower' and 'MyModelName.objects.order_by(Lower('name_something'))' here it is https://docs.djangoproject.com/en/1.9/_modules/django/db/models/functions/#Lower
Answer: Lets take an example where you have to do a case insensitive order by of the field "first_name" from the User Model
# Importing the Lower Function
from django.db.models.functions import Lower

#For ordering by Ascending order
User.objects.all().order_by(Lower('first_name'))

#For ordering by Descending order
User.objects.all().order_by(Lower('first_name').desc())

The Lower function converts all the "first_name" values into lowercase, and then it's ordered accordingly.

django-orm case-insensitive order by


How to understand logging formatter?

Question: To Python Experts:
I'm new to programming and learning logging python package.
According to logging document, I set the format of my logging message as follows:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')

Here is the output of logging message:
2016-08-09 19:57:08,363 - DEBUG -             A   B
2016-01-31  0  12
2016-02-29 -1  12

How to make A B (the column names of the datafram) to the next line?:
Also, would you please help me understand %(asctime)s - %(levelname)s - %(message)s? why put % before bracket and s after bracket?
2016-08-09 19:57:08,363 - DEBUG -
                A   B
    2016-01-31  0  12
    2016-02-29 -1  12

Answer: For your first question:
Just add an extra newline to your call of logging.debug:
For example, if your logger is called logger, and you are logging the message through logging.debug(msg), you can call logging.debug('\n' + msg) to move the message onto the newline.
As for the format: the % indicates that the upcoming text should be parsed as a format specifier. The parentheses, (), surround the name of the specifier, and the trailing s converts the input data into a string. See: difference between str.format and %.
So, %(name)s allows you to specify name which will be converted to a string. The different names, asctime, levelname, message are specified by the logging framework.
Comment: Thanks. What if my msg is a DataFrame? df = pd.DataFrame({'A': [0, -1, 3, 5, 4, 2, 1], 'B': [12, 12, 14, 15, 14, 16, 200]})   logging.debug('\n'+ df) doesn't work..@Rushy Panchal
Comment: @Lisa You can try using `str(df)`, which will convert it to a string first. However, the representation of that is defined by the DataFrame which may not be what you want.

How to understand logging formatter?


Since XHTML documents SHOULD be served as "application/xhtml+xml", and the XML DOM document object has no "cookie", what's the alternative?

Question: Since XHTML documents SHOULD be served as "application/xhtml+xml", and the XML DOM document object has no "cookie" (among other missing features), what's the cross-platform alternative to using document.cookie?
See: http://www.w3.org/TR/2002/NOTE-xhtml-media-types-20020801/

"In summary, 'application/xhtml+xml' SHOULD be used for XHTML Family
  documents, and the use of 'text/html' SHOULD be limited to
  HTML-compatible XHTML 1.0 documents. 'application/xml' and 'text/xml'
  MAY also be used, but whenever appropriate, 'application/xhtml+xml'
  SHOULD be used rather than those generic XML media types."
Answer: HTML5 has Web Storage, which offers sessionStorage and localStorage.
sessionStorage http://www.w3.org/TR/webstorage/#the-sessionstorage-attribute
localStorage http://www.w3.org/TR/webstorage/#the-localstorage-attribute


C/C++ source code parser using PYTHON

Question: Could anyone point me an already available python snippet/script which can parse C/C++ code?
Basically I wanted to create an Class-to-Function() and Object-used-file-location-mapping etc., of a C/C++ source code using python, so that I can create a new level of abstraction of code in a script readable format, which can be used for Artificial Intelligence in the Code parsing..!
Comment: have you looked at flex and bison, you wont need to redo if it satisfies what you are trying to do
Comment: You could use `gcc` or `clang` to compile C/C++ code out of python. The generated shared objects (`.so`) or dynamic link libraries (`.dll`) might be linked/loaded at run-time.
Comment: sure Will look into flex/bison now! thanks for the response
Comment: These are the links I once used to make a C like compiler: [ANSI C grammar, Lex specification](https://www.lysator.liu.se/c/ANSI-C-grammar-l.html) and [ANSI C Yacc grammar](https://www.lysator.liu.se/c/ANSI-C-grammar-y.html). However, writing a C compiler (not to mention that C++ is much more complicated) is high effort. I'm still thinking that "embedding" an existing compiler is the more reasonable option.
Comment: I think the best and easiest path would probably be the one described in Kristina's answer.

But for future references, if one chooses to go the route of writing his own parser for C and/or C++, here are some pointers:

* [ANSI C Yacc grammar](http://www.quut.com/c/ANSI-C-grammar-y.html)

* [C99 lex and yacc](https://gist.github.com/codebrainz/2933703)

* [C and C++98 yacc grammars](https://github.com/jessicah/becaml/tree/master/Traducteur/c-c%2B%2B-grammars-1.2)

* [many ANTLR grammars](https://github.com/antlr/grammars-v4) (containing ones also for C and C++14)
Answer: LLVM built with Clang will produce libclang for you which, luckily, happens to have great Python bindings right out of the box. Get the latest LLVM and Clang from the releases page, the current stable one being LLVM 6.0.0. Make sure you have the appropriate Python development dependencies and build all of it. Then you can use Clang's Tooling to do all sorts of things to transform or modify your source code, here's a good page to get you started.
I would suggest using Tooling instead of a hand rolled or generated parser especially for C++ due to its complexity. The library however handles it for you and allows you to transform or introspect the produced AST, letting you build on top of that.
No one will generally provide a fully working solution to a complex problem like you've presented, you will have to do the bulk of the work yourself, but those resources are great if you want to get started.
Comment: That's a great pointer.. Thanks for the help Kristina...!!
Comment: I also found the "cscope CLI" will act as a stand alone callback tool, that could help me achieve the relationship map from a python AI logic..!![23-04-2018 16:49]
it seems we can also use Cscope in the CLI mode rather interactive, some thing like call and get
http://tailrandom.blogspot.in/2008/10/using-cscope-from-command-line.html

C/C++ source code parser using PYTHON


Scale animation using jQuery fadeOut()

Question: I was searching a while but didn't found a post about this: I'm using jQuery fadeOut() to animate an element.
I want to fade out the element with a scale of 1.75 (175%) by using jQuery's fadeOut() function. At the moment it's a common fade out animation, but I'd like that the fade out animation scales out (element inflates).
I've made an example (the lightblue element) with a CSS animation using keyframes. I would like to solve the animation with fadeOut() (maybe you have to scroll down the snippet to see the example), is this possible? I hope this is clear enough.

$('.hide').click(function() {
  $('.animate').fadeOut(500);
});

$('.show').click(function() {
  $('.animate').fadeIn(500);
});
.animate {
  width: 150px;
  height: 150px;
  background-color: lightcoral;
  margin-top: 20px;
}

.animate--css {
  background-color: lightblue;
}

.animate--css {
  width: 150px;
  height: 150px;
  background-color: lightblue;
  margin-top: 20px;
  animation: zoomOut 1s infinite;
}

@keyframes zoomOut {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  100% {
    transform: scale(1.75);
    opacity: 0;
  }
}

<button class="hide">Fade out</button>
<button class="show">Fade in</button>

Answer: You can use start to apply a CSS before fading the element:

$('.hide').click(function() {
  $('.animate').fadeOut({'start':function() {$(this).css('transform','scale(1.75)') },'duration':500});
});

$('.show').click(function() {
  $('.animate').fadeIn({'start':function() {$(this).css('transform','scale(1)') },'duration':500});
});
.animate {
  width: 150px;
  height: 150px;
  background-color: lightcoral;
  margin-top: 20px;
  transition:0.5s all;
}

<button class="hide">Fade out</button>
<button class="show">Fade in</button>

Scale animation using jQuery fadeOut()


Vieta's Theorems Clarification

Question: For applying Vieta's Theorems on cubic equations, I've seen two conflicting answers from two different books.

 Book 1 says that for a cubic equation $px^3 + qx^2 + rx + s = 0$ has three different roots $x_1, x_2, x_3$, the following is true:
$$\begin{eqnarray*}
-q &=& x_1 + x_2 + x_3 \\
\end{eqnarray*}$$
Book 2, however, says that for a cubic equation $px^3 + qx^2 + rx + s = 0$ has three different roots $x_1, x_2, x_3$, this is true:
$$\begin{eqnarray*}
x_1 + x_2 + x_3 &=& \frac qp \\
\end{eqnarray*}$$
Can anyone tell me which one is correct?
Comment: Both are wrong, it is $x_1+x_2+x_3=-q/p$.
Comment: Good books have typos.
Comment: Thanks; as a side note, that was pretty sad, considering Book Two is pretty well known and has a 4.5-star review on Amazon.
Comment: It contained a solution using the formula, but it could just be a minor memory lapse (forgetting that is was $-\frac qp$ instead of just simply $\frac qp$
Answer: Neither is correct. It should be $x_1+x_2+x_3=-q/p$.
The cubic has shape $p(x-x_1)(x-x_2)(x-x_3)$. Expanding we get
$$px^3-p(x_1+x_2+x_3)x^2+p(x_1x_2+x_2x_3+x_3x_1)x-p(x_1x_2x_3).$$
Comparing coefficients, we get
$$x_1+x_2+x_3=-q/p,\quad x_1x_2+x_2x_3+x_3x_1=r/p, \quad x_1x_2x_3=-s/p.$$

Vieta's Theorems Clarification


Is it possible to write a numeric swap() function in JavaScript?

Question: A swap() function would result in cleaner code (DRY) than doing the work inline.  Unfortunately, the following function accomplished nothing because in JavaScript parameters are always pass-by-value:
function swap(a,b) { var temp=a; a=b; b=temp; }

Is there any way of writing a function that accomplished what this is attempting, particularly for numeric values?
I'm not impressed with the answers to this related question.
This answer has the right idea, but doesn't handle the general case.
Comment: Are you talking about variables outside the function scope?
Comment: @jsmorph: Outside the function scope of `swap()`?  Yes.
Comment: Then you're looking for something like: `function swap(_a, _b) {a = _b; b = _a}` ?
Comment: @jsmorph: Your swap function only works if you want to modify variables named 'a' and 'b' -- not what I had in mind.
Comment: Imagine my surprise when I realized that Java, also, doesn't support this: http://stackoverflow.com/questions/2393906/how-do-i-make-my-swap-function-in-java.  I've been spoiled by C++.
Answer: As you correctly identified, since the parameters are passed by value you cannot write a function that replaces the block:
var a,b;
...
var tmp = a; a = b; b = tmp;

However, you can do it if both are values of an object:
var o = {};
o.a = 3;
o.b = 4;
function swap(obj) { var tmp = obj.a; obj.a = obj.b; obj.b = tmp; }
swap(o);

You can also generalize the swap:
function swap(obj, a, b) { var tmp = obj[a]; obj[a] = obj[b]; obj[b] = tmp; }
swap(o,'a','b')

You can also make this a prototype function:
Object.prototype.swap = function(a,b) { var tmp = this[a]; this[a] = this[b]; this[b] = tmp; }
o.swap('a','b')

Comment: Alternatively, without an intermediate ``tmp`` var:

``function swap(obj) { obj.a+=obj.b; obj.b=obj.a-obj.b; obj.a-=obj.b; }``
Comment: @ThalisKalfigkopoulos there are certainly many ways to do it, but the question was focusing more on the feasibility, and by sticking to the method that the OP proposed the different ways (prototype method, straight function) are more clear
Comment: Is there some way of passing the 'local scope' as your object in order to make this work with arbitrary local variables?
Comment: You can do it if you define the function within the closure (e.g. `function foo() { function swap() { var tmp = a; a = b; b = tmp; }; var a = 3, b = 7; swap(); /* here a = 7 and b = 3 */ }` but it has to be defined in the same scope and is not really much different from inlining the swap
Comment: @Nirk: I meant something like: `swap(locals,'a','b')` to be used with your generalized `swap(obj,a,b)`, but I haven't found a way to do that.
Comment: @nobar variables declared using the `var` statement aren't visible outside of the scope in which they are declared.  The only reason the inner function works is because the variables are visible to the inner function (which is being defined in a scope which can see the local variables)
Answer: With EMCAScript 6, you can abuse the destructuring assignment feature.

var x = 1, y = 2;
console.log(`x = ${x}, y = ${y}`);

[x, y] = [y, x];
console.log(`x = ${x}, y = ${y}`);

MDN actually has this as one of its examples.
EDIT:
Somehow I missed the bold text in the question.  If you absolutely need it to be a function, this kind of fits the definition (and is definitely intended as a joke):

function swap() {
    return [arguments[1], arguments[0]];
}

var x = 1, y = 2;
console.log(`x = ${x}, y = ${y}`);

[x, y] = swap(x, y);
console.log(`x = ${x}, y = ${y}`);
Comment: @nobar fixed it! ;)
Comment: Not a *function*, but probably the nicest way to do a swap in ES6.
Answer: To make swap(a,b) work as in C, you need references to the variables. It can be done lighter than in the above answer 1. Just
function swap(n, m) {
    var temp = this[n];
    this[n] = this[m];
    this[m] = temp;
  }

The this in this function is window, and call is swap('a', 'b'). Sure, you can avoid local variable temp with either logic or arithmetic (for ints).
Comment: What Is the basis for the "this" variable?
Answer: I found this approach, which isn't too bad (at least for my purposes):
function swap( swap_name_a, swap_name_b )
   {
   eval
      (
      "var swap_temp="+swap_name_a+";"
    + swap_name_a+"="+swap_name_b+";"
    + swap_name_b+"=swap_temp;"
      );
   }

You are required to quote the arguments:
swap('a','b');

It seems to also work with more complex arguments:
swap('list[index1]','list[index2]');

Note: You will need to implement the swap() function within each scope that it will be used because it must have access to the named arguments.  This goes against the "don't-repeat-yourself" principal, but in some circumstances it may be acceptable to copy-and-paste a bit of boilerplate code like this if it results in simplification of your algorithm logic.

By the way: The example from which I derived this returned the string from swap() and relied on the caller to forward the string to eval: eval(swap('a','b')).  This solves the scope problem, but makes the swap operation more error prone -- and less attractive.
Be careful, that source also warned that this method could result in taunting.

Will time-traveling space-vampires steal your credit cards if you use eval()?  You should decide that for yourself, but here's some help:

When is JavaScript's eval() not evil?
Why is using the JavaScript eval function a bad idea?

The biggest concern I see is that this might be relatively slow (depending on how the interpreter manages caching).  If it is too slow for your purposes, then don't use it.
Comment: @icktoofay: Thanks for pointing that out.  I edited my answer to address this.
Comment: Ok, now I'm really getting silly.  You could import `swap()` into functions that require it with `eval(swapfn);`, where you have previously declared `swapfn` as a global string that contains the entire function declaration for `swap()`.
Comment: This answer is not very popular so far, and _maybe_ should be avoided in production code, but it solved my problem (for use in graphics "experiments") -- and answers the question.  Tested in Chromium and Firefox.
Comment: I have run into problems when using my "import" technique with `"use strict"`.
Comment: +1, the fact that *eval* is considered *evil*, does not make the answer invalid or bad (eval is there for some reasons, this can be one if indeed one wants it to be so). The downvotes on this site can really suck!
Comment: @NikosM. Downvotes are healthy. I didn't downvote, but I don't think whoever downvoted it was wrong because it's a really bad idea to do this unless you're the only person writing code and it's not open source. Too much room for confusion for a simple swap.


How can I iterate over all files in all folders of one master folder?

Question: So I wrote a Python scrip that would do a certain thing to a certain .txt file:
with open("1.txt") as f:
    for line in f:
        #DoStuff

Now this works for 1 .txt file.
I have One master folder, in the master folder I have different other folders, and in each folder I also have several .txt files.
How can I iterate over all this to apply my script to every .txt file in every folder in the master file?.
Comment: "One master folder" - then - "the master file" --- what ?
Comment: Your question was clear, but when it takes me less than a minute to find multiple duplicates its clear that you put no effort into solving this yourself
Comment: I'm sorry for not being clear, I'll try again:
I have one Folder, in that Folder I have several Folders.
In each one of the several Folders I have several .txt files

I wanna go over all .txt files
Comment: @Sayse instead of being rude try to actually help. This is my second day using Python, I'm still trying to learn. I tried looking up in a lot of places and all I could find was to iterate over different files in one folder.
Answer: You can use os.walk()
import os

path = 'c:\\projects\\hc2\\'

files = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
    for file in f:
        if '.txt' in file:
            files.append(os.path.join(r, file))

for f in files:
    print(f)

Output:
c:\projects\hc2\app\readme.txt
c:\projects\hc2\app\release.txt
c:\projects\hc2\web\readme.txt
c:\projects\hc2\whois\download\afrinic.txt
c:\projects\hc2\whois\download\apnic.txt
c:\projects\hc2\whois\download\arin.txt
c:\projects\hc2\whois\download\lacnic.txt
c:\projects\hc2\whois\download\ripe.txt
c:\projects\hc2\whois\out\test\resources\asn\afrinic\3068.txt
c:\projects\hc2\whois\out\test\resources\asn\afrinic\37018.txt

Comment: Was just writing the same answer... :) I would move the extension check to the last for loop and get rid of the list. Also would use os methods to extract the extension - `os.path.splitext()[1]`
Answer: You could use glob.iglob() and os.walk() for that.
Here a little function for you.
def list_of_files(path, extension, recursive=False):
    '''
    Return a list of filepaths for each file into path with the target extension.
    If recursive, it will loop over subfolders as well.
    '''
    if not recursive:
        for file_path in glob.iglob(path + '/*.' + extension):
            yield file_path
    else:
        for root, dirs, files in os.walk(path):
            for file_path in glob.iglob(root + '/*.' + extension):
                yield file_path

You need to import glob, os to use it.
In your case:
for file in list_of_files(path='master_folder_path_here', extension='txt'):
    ...

Answer: You can use glob module from python
from glob import glob

file_list = glob("(folder path)/*/*")

this will give you list of all file paths in sub-sub folder.
and then you can iterate and do your operations.
Comment: either change to `from glob import glob` or to `glob.glob("(folder path)/*/*")`
Comment: @Tomerikoo forgot about that, thank you


Storing multiple dynamic values to table

Question: I am trying to perform store multiple values into mysql db at a time. I have simple form that has dynamic input fields. When I submit the values from the form, it only inserts value for the first person. The other values are not showing at all. How can I store the values of each input field? EXAMPLE
Jquery to create fields

PHP for insert
<?php
if(isset($_POST['submit'])){

$con = new mysqli(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

$person1_faculty = $_POST['faculty_1'] ? 1 : 0;
$person1_instructor = $_POST['instructor_1'] ? 1 : 0;
$person1_name = $_POST['name_1'];
mysqli_query(
    $con,
    "INSERT INTO person (faculty_role, instructor_role, person_name) VALUES " .
    "(" . $person1_faculty . ", " . $person1_instructor . ", '" . $person1_name . "')"
);

print_r($_POST);
}

?>

HTML
<form action="test3.php" method="POST">
Select the role for each person

                    <input id="name_1" name="name_1" placeholder="Person #1 - First Name" type="text" />

                    <input id="phone_1"  name="faculty_1" type="checkbox" />Faculty

                    <input id="phone_1"  name="instructor_1" type="checkbox" />Instructor

            <input type='button' id='btnAdd' value='add another Person' />
            <input type='button' id='btnDel' value='delete Delete' />

            <input value="SAVE" name="submit" type="submit">
</form>

Answer: I detected errors in JavaScript and PHP, HTML is OK:
JavaScript: must use :first, :nth-child(2) and :nth-child(3). See Reference.

PHP: loop over name_1, name_2 and name_3, ...
<?php
if(isset($_POST['submit']))
{
  $con = new mysqli(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

  $i = 1;
  while(isset($_POST['name_' . $i]))
  {
    $person1_faculty = isset($_POST['faculty_' . $i]) ? 1 : 0;
    $person1_instructor = isset($_POST['instructor_' . $i]) ? 1 : 0;
    $person1_name = $_POST['name_' . $i];
    mysqli_query(
      $con,
      "INSERT INTO person (faculty_role, instructor_role, person_name) VALUES " .
      "(" . $person1_faculty . ", " . $person1_instructor . ", '" . $person1_name . "');"
    );
    $i++;
  }

  //print_r($_POST);

}
?>


What is the purpose of K-Theory?

Question: I have recognized that there is a theory called K-Theory in mathematics is used also for applications in mathematical physics. There is existing algebraic   K-Theory and topological K-Theory. Are these theories very similar?
For algebraic K-Theory by Milnor I have seen that the K-Groups are given by
$K_n = T^n / a \otimes (1-a)$ (Wikipedia).
Here, $T^n$ is the $n$-fold Tensor product. For n=2 one obtains abelian matrices. I don't understand this theory in depht. What is the reason that K- theory was introduced? (Is the theoretical physics application topological or algebraic?) And is there material (lecture Video or good pdf script) where the algebraic K-theory is explained?
I would greatly appreciate an answer.
Comment: What is your background and what is the motivation?
Comment: "Barely was the ink dry on Hirzebruch's note when new problems arose about the Riemann-Roch relation ... " J. Dieudonne, A History of Algebraic and Differential Topology 1900-1960, p. 598.
Comment: Concerning your last question, for "K_0" a good source is Manin's paper "Lectures on the K-functor in algebraic geometry". Also is Atiyah's book (more focused on the topological analogue). For higher $K_n$, Springer LNM 341 has a lot of information (the books by Srinivas and by Weibel are also excellent).
Comment: Algebraic K-Theory for rings is explained well by Rosenberg. For topological K theory the book of Wegge-Olsen is a good introduction.
Comment: If you want an application, it is used to classify the charges of Dp-branes in String Theory.
Answer: Here's a very quick introduction to the background ideas. On the topological side, start off with a nice space $X$. (I'm being deliberately vague about what 'nice' entails, but I at least want something paracompact and often want compact. The example to keep in mind here is a finite-dimensional smooth manifold without boundary.) Given vector bundles $\xi, \xi'\to X$, we can form $\xi \oplus \xi'$ (as well as the tensor product $\xi \otimes \xi'$). We'd like to make this operation into a group. We don't exactly have an identity element, but we can consider the trivial bundle $\theta^n \to X$ and define $\xi, \xi'$ stably equivalent if $\xi \oplus \theta^n$ and $\xi' \oplus \theta^m$ are equivalent for some $n$. In particular, $\xi$ is called stably trivial if we can take $\xi'$ trivial above. Now every bundle $\xi$ has an inverse $\xi^\perp$, and we have a nice group $\tilde K_0(X)$. With a bit of work, we can turn that into a generalized cohomology theory.
On the algebraic side, we can take a ring $A$ (say, commutative) and look at modules over it. Projective modules are, by definition, direct summands of free modules. We can therefore construct a group or ring of projective modules modulo free modules as above, taking free modules instead of trivial bundles. The connection is the general idea that projective modules over a (nice) ring are like vector bundles over a (nice) space. More precisely, Swan's theorem states that for a sufficiently nice space $X$, the map $\xi \to \Gamma(\xi)$ is an equivalence between finite-dimensional (real or complex) vector bundles and finitely-generated projective modules over $A = C^\infty(X)$ (real- or complex-valued). It's not quite that simple, though; for one thing, there isn't an obvious way of defining higher $K_*(A)$, and the ways that do exist are complicated.
Answer: In short, algebraic $K$-theory starts with the observation that the dimension of vector spaces over a field is a very useful thing! The start is the study of the $K_0$ group of a ring, which is «the best thing for $A$-modules that feels like the dimension of vector spaces».
The next player in $K$-theory is the $K_1$ of a ring $A$, which again measures how far we are from the nice situation of linear algebra: there one can take, by applying row and column operations, matrices into very simple forms. This cannot be done for general rings, and $K_1$ tells you how badly it fails.
Higher $K$-theory is considerably more difficult to motivate and to explain, but can be felt in the same way.
You should browse Jonathan Rosenberg's beautiful book on $K$-theory.
Answer:
algebraic K-Theory and topological K-Theory. Are these theories very similar?

Algebraic K-theory is far more difficult and harder to define.

For algebraic K-Theory by Milnor I have seen that the K-Groups are given by

Milnor does what is now called "Milnor K-theory of fields" in his book, with an appendix explaining the relation (due to Tate) of $K_2$ to the quadratic reciprocity law with Hilbert symbols.  This was before the general definition of algebraic K-theory by Quillen.  When people write algebraic K-theory today they mean the Quillen version (or other later developments) of higher algebraic K-theory, and specify Milnor K-theory when they mean that.

What is the reason that K- theory was introduced? (Is the theoretical physics application topological or algebraic?)

Physics uses topological K-theory of manifolds, whose motivation is to organize vector bundles over a space into an algebraic invariant, that turns out to be useful.  Some applications to the quantum Hall effect using noncommutative geometry (Bellissard) involve K-theory of operator algebras.
Algebraic K-theory started from $K_i$ defined by hand for small $i$, with relations to classical constructions in algebra and number theory, followed by Quillen's homotopy-theoretic definition for all $i$ (and later approaches due to Waldhausen and others).  The connections to algebra and number theory often persist for larger values of $i$ but in ways that are subtle and conjectural, such as special values of zeta- and L-functions.

And is there material (lecture Video or good pdf script) where the algebraic K-theory is explained?

Nothing very accessible for algebraic K-theory.  Blackadar's book for K-theory of operator algebras, and Atiyah's book for topological K-theory as it stood in the 1960's, are readable without a lot of algebraic prerequisites.
Comment: For example, the first page of the k-theory tag has elaborations of the themes of prior motivation, number theoretic applications, and the role of Milnor K theory.  http://mathoverflow.net/questions/tagged/kt.k-theory-homology
Comment: By the way, I am pretty sure there have been several variants of this question on MathOverflow.
Comment: The relation of K2 to quadratic reciprocity is an appendix by Tate in Milnor's paper, is in another appendix to another book by Milnor on symmetric bilinear forms, but is in the last chapter rather than an appendix in Milnor's book on K-theory.   The description in the answer mixes up these things somewhat.

What is the purpose of K-Theory?


Getting specific data from a website with python

Question: code:
import requests
from bs4 import BeautifulSoup

url="https://covid19.saglik.gov.tr/"
R=requests.get(url)
print(R.text)

Question:  Hello friends,I must receive below specific values from  above website. These values are changing daily.When the program runs, it should be able to print out the specified key from the website .For example: print(data["tarih"]) ,  print(data["gunluk_test"]) ,  print(data["gunluk_vaka"]  etc. in html script. How can I do that ?
CODE's OUTPUT RESULT:
var sondurumjson = [{"tarih":"13.05.2021","gunluk_test":"201.295","gunluk_vaka":"11.534","gunluk_hasta":"1.217","gunluk_vefat":"238","gunluk_iyilesen":"55.472","toplam_test":"50.259.943","toplam_hasta":"5.083.996","toplam_vefat":"44.059","toplam_iyilesen":"4.856.763","toplam_yogun_bakim":"","toplam_entube":"","hastalarda_zaturre_oran":"4,0","agir_hasta_sayisi":"2.765","yatak_doluluk_orani":"43,7","eriskin_yogun_bakim_doluluk_orani":"65,0","ventilator_doluluk_orani":"32,4","ortalama_filyasyon_suresi":"","ortalama_temasli_tespit_suresi":"8","filyasyon_orani":"99,9"}];//]]>
Answer: It looks like the dict is already recognised by python so json.loads fails did you paste the output of the api or did you print the dict that you are working on?
Anyhow if that is the result of your api you can just do this to access everything in the dictionary:
sondurumjson = [{"tarih":"13.05.2021","gunluk_test":"201.295","gunluk_vaka":"11.534","gunluk_hasta":"1.217","gunluk_vefat":"238","gunluk_iyilesen":"55.472","toplam_test":"50.259.943","toplam_hasta":"5.083.996","toplam_vefat":"44.059","toplam_iyilesen":"4.856.763","toplam_yogun_bakim":"","toplam_entube":"","hastalarda_zaturre_oran":"4,0","agir_hasta_sayisi":"2.765","yatak_doluluk_orani":"43,7","eriskin_yogun_bakim_doluluk_orani":"65,0","ventilator_doluluk_orani":"32,4","ortalama_filyasyon_suresi":"","ortalama_temasli_tespit_suresi":"8","filyasyon_orani":"99,9"}]
new_object = sondurumjson[0]

print(new_object['tarih'])

Answer: I think you should use R.json() instead of R.text
Answer: import requests
from bs4 import BeautifulSoup
import json
url="https://covid19.saglik.gov.tr/"
R=requests.get(url)
soup=BeautifulSoup(R.content,"html.parser" )
script=soup.find_all("script")[18]
s=str(script).split('\nvar sondurumjson = ')
#print(s[1])
a=str(s[1])
b=a.split("\r")
#print(b[0])
c=b[0].partition(';')
data=c[0]
#print(data)
data = json.loads(data)
print( "Tarih:", data[0]['tarih'])
print("Günlük Test:", data[0]['gunluk_test'])
print( "Günlük Vaka:", data[0]['gunluk_vaka'])


How to get taxonomy term by description, programatically

Question: In a D7 custom module, I wish to retrieve a taxonomy term by it's description (and not it's name or TID).
Right now I do have it working, but I feel the code is a bit clunky, and I feel like there is a more elegant / Drupally way of doing it.
Is there a better way of doing it then this?
<code>$vocabulary = taxonomy_vocabulary_machine_name_load('my_vocabulary');
$terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocabulary->vid));

foreach ($terms as $term) {
  if ($term->description == 'my_term_description') {
    // Do stuff when there is a match.
  }
}
</code>
Ideally, I feel like there is a better way I cannot find through Google / Drupal API etc. Something like:
<code>$term = taxonomy_by_description_load('my_vocabulary', 'my_term_description');
</code>
Thanks everyone.
Answer: Using the EntityFieldQuery (this is untested)
<code>  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'taxonomy_term')
    ->entityCondition('bundle', array('my_vocabulary'))
    ->propertyCondition('description', 'my_term_description');
  $result = $query->execute();
  $tids = array_keys($result['taxonomy_term']);

  return $tids;
</code>
More information https://www.drupal.org/docs/7/creating-custom-modules/howtos/how-to-use-entityfieldquery-for-drupal-7
Comment: Thanks! Unfortunately I don't have enough rep points to vote for an answer to my own question :(


Confusion related to multicollinearity, FA and regression of heterogeneous data

Question: I am currently working with a data set that contains about 26 IVs of almost all sorts of scale of measurement (binary, nominal, ordinal and interval scale variables). There are strong reasons to suspect that some variables are probably highly correlated, while some may not be related to any other IVs to a great extent.
I came across with great suggestions to resolve this problem in this site (which was an useful advice to use optimally scaled variables in the FA procedure and to use derived factor score as the IVs). But due to my inexperience in this field I am in need of some expert advice on the following issues:
How should I check if Multicollinearity really exists?
I am not sure how to check Multicollinearity with such a heterogeneous data. I may calculate the Heterogeneous Correlation Matrix (or Spearman's Rank Correlation) by somehow forcing me to consider the nominal variables as ordinal but even if I do it what should be the value of the correlation coefficient at which Multicollinearity can be ignored? I am also not sure if it is going to give any insight at all, as I am missing something like a VIF measure!
Should I take only those variables for a FA which are highly correlated?
Say, if I can find two sets of variables (one set containing 8 IVs and another containing 4 IVs) quite highly correlated to each other within each set, then should I use only those 12 variables for FA and derive FA scores for those two factors to use them as IVs? Clearly my intention is to use the other 14 variables separately as IVs along with the two derived scores. I am confused if I should actually use not the 12, but all 26 variables in the FA in this scenario. Remember in that case my FA scores are weighted by the other 14 unrelated variables too!
Is there any problem to categorize a proportion type DV for an ordinal logistic regression?
I've actually found people using logistic regression instead. But I want to mention here that unfortunately I don't know the number of cases (or trials) out of which each proportion was calculated. So I cannot use the number of trials as the weights in the logistic regression. In that case a logistic regression may not be accurate enough. So, as I only know the proportions, won't it be good to categorize the proportions by median split or by quartile split? So that I can use it as a DV in a logistic or in an ordinal logistic regression?
I am thankful for reading this thread patiently and hoping some expert advice.
Regards.
Comment: **Clarifications-1** From the CATPCA procedure, it seems like only two factors can be found that loads highly onto more than one variables (one factor loads on 8 variables and the other loads on 4 variables). But during the calculation of scores of these two factors, variables which do not load on more than one variable, also have a contribution. Besides the 12 variables that have high loads on the two clearer factors also have a contribution while calculating factor scores of the factors that has a single variable load.
Comment: **Clarification-2** In the 3rd query I want to know if cut points will affect the regression results. I explained why I am thinking of categorizing (I do not know the number of trials). The DV ranges from 0 to 0.75. The median is 0.10. Quartiles are: 0.05 (25th percentile), 0.10 (50th percentile), 0.17 (75th percentile).
Comment: @mbq do I need to provide anything else? It seems like none is trying to improve the answer!
Answer: I hoped that someone would come up with a brilliant answer, but in the mean time, here are my thoughts. True multicollinearity is not something you test for, in my experience. It just happens. You try to fit a model and the computer complains, because it's trying to invert a singular matrix (or nearly singular) and it has trouble converging. When the variables are nearly collinear, you start to get weird behaviour. The parameter estimates become unstable, so if you make small changes to the inputs, you get big changes in the parameter values.
But perhaps what you are interested in doing is looking to reduce the dimension of the problem. You can try several things. Look for a best subset of regressions, if you want the variables as they are. Do a principle components analysis and see if most of the variation is explained by a small combination of same. I wouldn't do FA unless I believed that the observations expressed genuine latent factors.
A cluster analysis is another way to look at groupings in the variables.
You didn't say how big your sample is, but if it's close to the number of variables, you will get collinearity for sure, or something close to it. However, that would not mean that the variables were intrinsically related. i.e. in a bigger sample, those 26 variables might not be collinear.
You have not said anything about a model, hypothesis, or anything else, so it's hard to advise beyond what I have said.
Comment: Thanks for your response. My sample size is 169. A categorical principal component analysis shows that the total variation can be explained with less than the actual dimension. The reason I used the optimally scaled variables from CATPCA in a factor analysis procedure is only to have the benefit of rotation. It seems like only two factors can be found that loads highly onto more than one variables (one factor loads on 8 variables and the other loads on 4 variables). That's why I asked the 2nd question. I hope you will suggest me about the rest of the queries too. Regards.
Comment: I'm not sure what you are doing in query 2 about only using correlated FA's, so I did not comment. Regarding logistic regression, that assumes you have a dichotomized response variable (or variable that you can dichotomize). Then you have all the same issues with collinearity and model selection that you would have with the usual multiple regression.


Windows High Contrast Mode: How are colours computed? How can colours be specified for focused elements?

Question: How does Windows High Contrast decide which colours it uses to display website elements?
And is it possible to let it display other colours when an element is focused?
For example, on https://www.post.ch/en, the "Consignment number" input field is displayed in another colour when it is focused, but for most other elements the color always stays the same, even when the focus styles define other colours.
Comment: I do not know the precise algorithm, but it uses the luminosity of the colors and the user settings to determine what color to display. The reason that the focus styles are not showing up is that they are too close to the unfocused style and therefore do not trigger the thresholds.
Answer: I think that as long as the contrast ratio is above 14:1 they keep the original color. In other case, they use the customized values.
High-contrast mode

The text colors in the high-contrast themes have been authored to be
  compliant with the Microsoft Accessibility guidelines. We maintain a
  14:1 high-contrast ratio between foreground and background. If the
  colors that are enabled by default are not suitable to a particular
  end user, they can easily be customized through the control panel
  settings for 'Window Color' in those high-contrast themes.


Intro/Outro standard practices for song to be included in DJ set

Question: I'm beginning to experiment with dance/house music, and from a practical perspective, what's the best way to make it easy for a DJ to include a song in their set?
Is there a standard practice for intros and outros that most DJs find acceptable, that makes it easier for them to work with the song?
Comment: It looks like you would do well to learn the basics of being a DJ, since then you can understand from the insider's perspective what they are looking for. One obvious thing would be giving time for beatmatching before getitng to the heart of the song. You might also choose to either have drums only **or** melody/bass/chords only at the end of a song so that a DJ can either beat match or harmony match for the next song (it's usually hard to impossible to do both). You also probably want to create a variety of options with different songs so your work can be in any part of a set.
Answer: There is no standard practice, but there is a general idea of how to carve intros and outros in order to help the song be easily mixed with others. They tend to be very simple, with little or no harmonic elements present, of at least 4 bars (around 30 secs at around 120 bpm). Tipically elements are added little by little until the whole idea is constructed.
Here's Nathan Fake's Outhouse as example:

First 4 bars (first 30 seconds) of just percussions, and the kick has little low end. Then a very filtered bass is added, which stays in one note, and that idea continues for another 4 bars while the bass gains more and more harmonics. At the one minute mark (after 8 bars) the full kick (with the low end) and a snare is added, then the hats at the 1:15 mark, and finally the whole melodic idea starts at the 1:30 mark after a small breakdown.
In this case we have a very well-defined intro of 12 bars, or around 1:30 minutes.
The outro, that I'm arbitrarily labeling based on when the bass stops having melodic movement, starts at 8:45 and continues for 2 minutes, where elements disappear little by little until only a synth melody remains.
You can see that there is a general idea of starting simple and ending simple through small increments and reductions, but there's nothing written in stone. A key idea of this example is that the song didn't start with harmony, but it did end in nothing but harmony. You can mix the intro with whatever, but you have to be careful with the outro and select a song to mix with it that doesn't clash harmonically.
Contrary to what a comment here suggests, implementing both beat match and harmony match in your mix is not "hard to impossible" to do. DJs from all the skill range (including beginners) use both all the time, so I'm not sure where that perception came from. Harmony mixing is a very simple concept, so don't shy away from it!
In the end, it comes down to preference. Some DJs find large intros and outros useful, others prefer to go direct to the "interesting part". James Holden is from the later taste (can't find the exact quote or link at the moment), and barely makes use of the outro we just heard in his Balance DJ set at the 48m 27s mark:

So, if you want to make everyone happy, include incremental intros and decremental outros, which is all there is for common practices in intros and outros. Some DJs might not make use of them, but the ones that do will appreciate it. There are many great songs out there without defined intros and outros though.
Comment: Ah with modern tools harmony and beat matching can probably be done easily at the same time. I was thinking of vinyl on turntables. If you have to change the pitch/speed control too much to match tempos, then you won't be able to match the notes as easily. I should have written "it **could** be hard to do both".
Comment: @ToddWilcox I agree, it could be hard to do both. Time stretching tools are rarely used in practice though (sound quality can be degraded too much), so the same principle applies to turntables, cd players, and software. You have to consider both the key and the pitch deviation of the track, but with some practice you can pull off extreme pitch and time deviations and remain harmonically coherent. I recommend James Holden's sets in general for an example of how well this concept can be applied.
Comment: @ToddWilcox You can change your comment by copy original comment, then delete, then paste into a new comment, then edit as desired.  It will show up as the last comment but at least it will be more accurate.  You may already know that, but thought I would offer in case  never occurred to you before.
Answer: Yes having 4 bars is ideal as is having the drums solo or just the melody or accapella even ??
Those are fun parts of a track that make it easy to work with the song in a Dj setting ... Makes it gr8 when adding in a 3rd track !
I suggest the basics of beat matching and keeping tracks together and sounding nice together for long periods  .. Maybe even start to work with tracks in similar key ??    Only because it may help train your ears for track juggling  ..
But matching the beats or Bpm and getting the basics is a gr8 place to start ...    You can go anywhere from that point and best of all you now .. have not only an understanding -   but an actual "feel" for what a proper Dj can do !
Your style can dictate how you want the Intro or anything else to flow but being able to match beats WITHOUT beat matching software -- and if you do use software it's ok but plz turn off feature until you can do on your own with ease !   It will make you a much better artist !
No matter what style you are into .. Get to the point where you can juggle 3 tables by ear !   And you have 2 tracks running at the same time about 85% of the time as you mix in the 3rd table as track one or two ends ...         Your ears will be juggling and once you have the three tables mastered you will see you have control of the sound -- no matter if it's the intro the middle or the very end  .no matter the track or where it is you can make it do exactly what you want.
Peace respect and the very best to you !
InvisibleFriend / Kind Recordings


Panels, panel node print header and footer

Question: I use Panels module and I've created Panel page, where I inserted Panel nodes.
Problem: Panel nodes have their own header and footer html tags that are printed. How to remove them? Any way to make it without custom template in code?
Answer: I should use min-panel. Panel page and panel node both have page structure.


How to pass same contextual arguments to two view blocks programmatically?

Question: I'm trying to pass same arguments to views. Here is my code:
$view = Views::getView('taxonomy_articles');
            if (!empty($age)) {
              $view->setDisplay('block_6');
              $view->setArguments([$term->tid, $age_args]);
              /*
               * override term name with age param
               */
              $termURL = Url::fromRoute('entity.taxonomy_term.canonical', array('taxonomy_term' => $term->tid, 'age' => $age));
              $termName = \Drupal::l(t($term->name), $termURL);
            }
            else {
              $view->setDisplay('block_1');
              $view->setArguments([$term->tid]);
            }

My else part gets executed and array of term ids goes to block_1, my view block machine name.
What I want is similar like:
              else {
                  $view->setDisplay(['block_1','block_7']);
                  $view->setArguments([$term->tid]);
                }

Is this possible? Can we pass array to $view->setDisplay ???
Answer: While rendering a view you can only use on display.
So it is only possible to loop through your display array and generate the view within that loop like:
          else {
              foreach (['block_1','block_7'] as $display) {
                $view->setDisplay($display);
                $view->setArguments([$term->tid]);
                // You need to render here.
                // The loop will overwrite the first display.
              }
            }

Comment: @Clive It is possible that you had trouble, but in this scenario both the view and the argument are the same, so rendering different displays should be possible. Just store them in an array or concatenate them as rendered strings (or something)  within the loop.
Comment: I've had trouble with this approach in the past and found I needed a new View object to get the second display working properly. It was a long time ago though so it may well have been fixed/improved since then (if it was even broken and not just me doing something else wrong). Thought it was worth a mention just in case


How to test a http calls from a second class func call from within first class (APEX class testing/salesforce testing)

Question: I have an apex class A. I'm calling the function of B class from within A.
class A{
    B bobj=new B();
    B.function2();

    function1(); //within class A
}

This function1 and function2 are http calls to 2 diff rest services.
I wrote a test class with httpcallmockouts for the both function1 and function2. So the order goes like this inside APex Test class-
B objB=new B();

HttpResponse res = CalloutB.getInfoFromExternalService();

A objA=new A();
HttpResponse res = CalloutA.getInfoFromExternalService();

//Till this point my test runs successfully for http calls mock

Test.startTest();

objA.function1();

//Here I get an error http callout not supported for test methods for function2 of B class.

//If I change the order above to

//A objA=new A();

//HttpResponse res = CalloutA.getInfoFromExternalService();

//B objB=new B();

//HttpResponse res = CalloutB.getInfoFromExternalService();

//Then I get error http callout not supported for test methods for function1 of A class.

Test.stopTest();

So, how do you test the http call from within another's class function calls in the first class.
Answer: This is happening because you are not initializing the httpMock class object,so your test class is trying to hit real web service call which is not allowed from test class. What you need to do it to initialize your mockClass object and use it instead to return data rather than hitting real web service endpoint

In main class which does the callout declare a variable which holds
reference to created mockClass object
Add a condition in your callout class which check if its a test class which is currently running using Test.isRunningTest() .
If its a test class then use your mock class to return data instead of real callout
If its not a test class execution context, use real callout

@isTest
global class ResultHttpMock implements HttpCalloutMock {

  global HTTPResponse respond(HTTPRequest req) {

    HttpResponse res;
    System.debug('request inside mock '+req);
    if(req != null) {

        res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody(getBody());
        res.setStatusCode(200);
        res.setStatus('OK');

    }

    return res;
}

  private static String getBody() {
    String idmJsonMockResponse = '{"ednaScoreCard":{"sc":[],"etr":[{"test":"id:0","details":"false","ts":1471432074763,"stage":"1"},{"test":"ed:37","fired":false,"details":"ed:37(false) = true","ts":1471432074763,"stage":"1"}
}

In your Class A and Class B, hold a reference to ResultHttpMock
global class HttpCalloutClass {

public static HttpCalloutMock httpMock = null;
     ......
    if(Test.istestRunning() && httpMock != null) {
        Http response = httpMock.respond(request);
    } else {
        Http response = http.send(request);
    }
 }

In your test class, initialize the httpMock object before calling functionA() and functionB()
@isTest(seeAllData=false)
public class TestHttp {

  static testMethod void testfunctionA() {

    Test.startTest();

    HttpCalloutClass.httpMock = new ResultHttpMock ();
    String result = HttpCalloutClass.functionA();

    Test.stopTest();
}

Comment: Thanks. if(Test.istestRunning() && httpMock != null) . This works great.


IE11 browser shape overflows SVG element

Question: I'm working on an SVG and trying to create half circle but the IE11 browser creates complete circle instead.
My code is like this:

<svg viewBox="0 0 80 40" class="gauge">
  <circle
    cx="40"
    cy="40"
    r="37"
    fill="transparent"
    stroke="#d2d3d4"
    stroke-width="6"></circle>
</svg>

How can I render half circle in IE11?
It is working fine on other browsers. Please find the below image for more reference.
On IE11 :

On Chrome :
Comment: overflow="hidden" on the  element?
Answer: A quick fix would be to add overflow:hidden; on the svg like so :

svg {
  overflow: hidden;
}
<svg viewBox="0 0 80 40" class="gauge">
  <circle
    cx="40"
    cy="40"
    r="37"
    fill="transparent"
    stroke="#d2d3d4"
    stroke-width="6"></circle>
</svg>

Depending on your use case, a "cleaner" solution would be to build your half circle with a path and the arc command :

<svg viewBox="0 0 80 40" class="gauge">
  <path d="M3 40 A37 37 0 0 1 77 40"
    fill="transparent"
    stroke="#d2d3d4"
    stroke-width="6" />
</svg>

This way you are sure nothing overflows the svg element.