text:
Q: Python3 function with pandas dataframe input runs slower then 1st time and faster the 2nd time I built 2 functions major_check_with_dataframe and major_check_with_list, and I wanted to see which one runs faster. I'm puzzled by their run time.
import numpy as np
DTYPE_FLOAT = np.float
import anapyfunc.major
import pandas as pd
from testpython.timer import timer

# wrapper function
def major_check(**kwargs):
    #return major_check_with_list(**kwargs)
    return major_check_with_dataframe(**kwargs)

# functions to be timed
def major_check_with_dataframe(df, s_major_single_hi_percent, s_major_single_lo_percent):
    ...

def major_check_with_list(source_list, s_major_single_hi_percent, s_major_single_lo_percent):
    ...

# main function starts here
t = timer.Timer(verbose = True, run = False)
t.set_name(name = 'major check timer')

a = np.random.choice(101, 2500)
b = np.random.choice(101, 2500)
c = np.random.choice(101, 2500)

s_major_single_hi_percent = 70
s_major_single_lo_percent = 10

dd = {'a' : a, 'b' : b , 'c' : c}
df = pd.DataFrame(dd)

# axis 0 = tick
# axis 1 = input arrays

t.set_name(name = 'major_check_with_dataframe')
t.start()
ret1 = anapyfunc.major.major_check_with_dataframe(
                                  df = df,
                                  s_major_single_hi_percent = s_major_single_hi_percent,
                                  s_major_single_lo_percent = s_major_single_lo_percent,
                                 )
t.stop_reset()

t.set_name(name = 'major_check_with_list')
t.start()
ret2 = anapyfunc.major.major_check_with_list(
                                source_list = [a, b, c,],
                                  s_major_single_hi_percent = s_major_single_hi_percent,
                                  s_major_single_lo_percent = s_major_single_lo_percent,
                                )
t.stop_reset()

t.set_name(name = 'major_check')
t.start()
ret3 = anapyfunc.major.major_check(
                                  #source_list = [a, b, c,],
                                  df = df,
                                  s_major_single_hi_percent = s_major_single_hi_percent,
                                  s_major_single_lo_percent = s_major_single_lo_percent,
                                 )
t.stop_reset()

Output when major_check calls major_check_with_dataframe
major_check_with_dataframe elapsed time: 94.261000 ms
major_check_with_list elapsed time: 2.316000 ms
major_check elapsed time: 3.055000 ms

Output when major_check calls major_check_with_list
major_check_with_dataframe elapsed time: 95.042000 ms
major_check_with_list elapsed time: 2.240000 ms
major_check elapsed time: 2.240000 ms

I found that if I run major_check_with_dataframe the 2nd time, its run time is reduced to nearly the same as running through major_check wrapper function.
t.set_name(name = 'major_check_with_dataframe')
t.start()
ret1 = anapyfunc.major.major_check_with_dataframe(
                                  df = df,
                                  s_major_single_hi_percent = s_major_single_hi_percent,
                                  s_major_single_lo_percent = s_major_single_lo_percent,
                                 )
t.stop_reset()

t.set_name(name = 'major_check_with_list')
t.start()
ret2 = anapyfunc.major.major_check_with_list(
                                source_list = [a, b, c,],
                                  s_major_single_hi_percent = s_major_single_hi_percent,
                                  s_major_single_lo_percent = s_major_single_lo_percent,
                                )
t.stop_reset()

t.set_name(name = 'major_check')
t.start()
ret3 = anapyfunc.major.major_check(
                                  #source_list = [a, b, c,],
                                  df = df,
                                  s_major_single_hi_percent = s_major_single_hi_percent,
                                  s_major_single_lo_percent = s_major_single_lo_percent,
                                 )
t.stop_reset()

t.set_name(name = 'major_check_with_dataframe')
t.start()
ret1 = anapyfunc.major.major_check_with_dataframe(
                                  df = df,
                                  s_major_single_hi_percent = s_major_single_hi_percent,
                                  s_major_single_lo_percent = s_major_single_lo_percent,
                                 )
t.stop_reset()

t.set_name(name = 'major_check')
t.start()
ret3 = anapyfunc.major.major_check(
                                  #source_list = [a, b, c,],
                                  df = df,
                                  s_major_single_hi_percent = s_major_single_hi_percent,
                                  s_major_single_lo_percent = s_major_single_lo_percent,
                                 )
t.stop_reset()

Output
major_check_with_dataframe elapsed time: 95.608000 ms
major_check_with_list elapsed time: 2.350000 ms
major_check elapsed time: 3.048000 ms
major_check_with_dataframe elapsed time: 2.569000 ms
major_check elapsed time: 2.520000 ms

Can it be some kind of memory cache effect?
This behavior is the same even if I put the functions in a class, use the class object to run the function once, and delete/garbage collect it after each run.
All functions correctly return expected values.
What am I missing here?
The version I'm using are:
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
pandas 0.21.0


text:
Q: AutoLayout constraint animation scales from wrong point I'm trying to achieve an animation using autolayout constraints, working together with UIStackViews. There is one animation I am getting stuck with.
I have an UIImageView (green) nested in an UIView (orange), that's in turn handled by a UIStackView. When only those elements are left visible, the views should shrink. I am trying to change the following constraints:

Normally at 64 for width and height and 10 for the leading/trailing/top/bottom constraints, I am using the following method to change them to 46 and 7 respectively:
private func setImageShrunk() {
    imageWidth.constant = 46
    imageHeight.constant = 46
    imageTopMargin.constant = 7
    imageBottomMargin.constant = 7
    imageRightMargin.constant = 7
    imageLeftMargin.constant = 7
}

This function is called by another function:
func shrinkImage(animated: Bool) {
    if(animated) {
        UIView.animate(withDuration: 1) {
            self.setImageShrunk()
            self.layoutIfNeeded()
        }
    } else {
        setImageShrunk()
    }
}

Shrinking the image without animation returns the expected result, of course abruptly. However, trying to animate it, I am getting the following result:

I want the view to shrink towards the top left corner, instead it shrinks from the center. It shouldn't "move first, scale later". Does anyone know how to achieve this using AutoLayout in iOS 11?

A: So I figured out what happened trying to make a small project to recreate the error.
In the second project, the setup was the same but the animation worked like I expected. After some thinking I realized that in this new project, I had called the animations from the UIViewController containing the UIStackView.
In the original question, I had neglected to mention that I was calling the animations from a class extending UIStackView, so the View to be animated itself. Even though it had references to the constraints from the outside, the View didn't know its environment and embedding Views. That's why it just jumped and then scaled.
I fixed the problem by transferring the animations to be done to the UIViewController containing the UIStackView.

A: If you set width and height , then no need for the right and bottom constraints , as when you change the height from 64 to 46 , then bottom distance should be 28 ( 10 + 18 ) and since you set it to 7 , then there is a conflict , same for right , so either remove them , or lower their priorities
BTW all of this is valid only if the orange view has other constraints for width & height

A: Have you set the anchor point of the UIView? It is now shrinking on the center point, instead of the top left corner. Also you should create a custom animation defining the two animation and link them together. You can find lot of solutions for this on the net, but here is an example. It is for sprite kit, but the idea is the same.
        #if os(iOS)
    let transform:SKAction = SKAction.move(to: CGPoint(x: -40, y: -45), duration: 0.3)
    let rotateAction:SKAction = SKAction.rotate(toAngle: degree(-20), duration: 0.3)
        #else
        let transform:SKAction = SKAction.move(to: CGPoint(x: -40, y: 60), duration: 0.3)
        let rotateAction:SKAction = SKAction.rotate(toAngle: degree(-20), duration: 0.3)
        #endif
    let endAction:SKAction = SKAction.perform(#selector(GameScene.animateToTableEnded), onTarget: self)
    let combineAction:SKAction = SKAction.sequence([SKAction.group([transform, rotateAction]), endAction])

Actually here the grouping makes the magic.
Here is a solution for core animations from the Apple documentation.
let fadeOut = CABasicAnimation(keyPath: "opacity")
fadeOut.fromValue = 1
fadeOut.toValue = 0
fadeOut.duration = 1

let expandScale = CABasicAnimation()
expandScale.keyPath = "transform"
expandScale.valueFunction = CAValueFunction(name: kCAValueFunctionScale)
expandScale.fromValue = [1, 1, 1]
expandScale.toValue = [3, 3, 3]

let fadeAndScale = CAAnimationGroup()
fadeAndScale.animations = [fadeOut, expandScale]
fadeAndScale.duration = 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android App Unintentionally Restarting Tablet I'm working with a SM-t230NU andorid tablet. We have an android application running on it that is quite simple. All it does is find/verify Bluetooth a connection, collects data, displays it and does a fairly simple GUI(in min3d) off of the data. The problem is that on very rare occasion, after a long time of running the entire tablet just restarts. No warnings, no prompts.
We have had multiple versions of this demo all of the other were stable on the variety of phones that we have. I'm currently running tests on multiple phones and the tablet. I'm running old versions of the app on the tablet, while I try the new app on phones.
I'm honestly suspecting that something is wrong with our tablet. That said I hate blaming hardware. Is it even possible for an android app to crash the whole OS?
Any help would be appreciated,
Thank you.
EDIT*
I caught a stack trace. The restart occured at 14:07
02-26 14:06:18.050: D/dalvikvm(17266): VFY: replacing opcode 0x6e at 0x0002
02-26 14:06:18.290: W/initializeBluetooth(17266): Initialize Called
02-26 14:06:18.300: E/BluetoothHeadset(17266): BTStateChangeCB is registed
02-26 14:06:18.300: E/BluetoothHeadset(17266): BluetoothHeadset service is inded
02-26 14:06:18.360: W/Bluetooth Connect(17266): No Connected Device Found
02-26 14:07:10.260: W/System.err(17266): android.os.DeadObjectException
02-26 14:07:10.270: W/System.err(17266): at adroid.os.BinderProxy.transact(Native Method)
02-26 14:07:10.270: W/System.err(17266): at com.samsung.android.multiwindow.IMultiWindowFacade$Stub$Proxy.getMultiWindowStyle(IMultiWindowFacade.java:475)
02-26 14:07:10.270: W/System.err(17266): at com.samsung.android.multiwindow.MultiWindowFacade.getMultiWindowStyle(MultiWindowFacade.java:57)
02-26 14:07:10.270: W/System.err(17266): at android.app.Activity.getMultiWindowStyle(Activity.java:4565)
02-26 14:07:10.270: W/System.err(17266): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1676)
02-26 14:07:10.270: W/System.err(17266): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
02-26 14:07:10.270: W/System.err(17266): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6529)
02-26 14:07:10.270: W/System.err(17266): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:812)
02-26 14:07:10.270: W/System.err(17266): at android.view.Choreographer.doCallbacks(Choreographer.java:612)
02-26 14:07:10.270: W/System.err(17266): at android.view.Choreographer.doFrame(Choreographer.java:582)
02-26 14:07:10.270: W/System.err(17266): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:798)
02-26 14:07:10.281: W/System.err(17266): at android.os.Handler.handleCallback(Handler.java:733)
02-26 14:07:10.281: W/System.err(17266): at android.os.Handler.dispatchMessage(Handler.java:95)
02-26 14:07:10.281: W/System.err(17266): at android.os.Looper.loop(Looper.java:146)
02-26 14:07:10.281: W/System.err(17266): at android.app.ActivityThread.main(ActivityThread.java:5602)
02-26 14:07:10.281: W/System.err(17266): at java.lang.reflect.Method.invokeNative(Native Method)
02-26 14:07:10.291: W/System.err(17266): at java.lang.reflect.Method.invoke(Method.java:515)
02-26 14:07:10.291: W/System.err(17266): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
02-26 14:07:10.291: W/System.err(17266): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
02-26 14:07:10.291: W/System.err(17266): at dalvik.system.NativeStart.main(Native Method)
02-26 14:07:10.311: D/GC(17266): <tid=17266> veglGetDisplayBackBuffer, can't dequeuebuffer from nativeWindow = 0x77964380!
02-26 14:07:10.311: D/v_gal(17266): [tid=17266] _SwapBuffersRegion(1238): Get back buffer failed
02-26 14:07:10.311: W/HardwareRenderer(17266): EGL error: EGL_BAD_NATIVE_WINDOW

A: My phone, Samsung Galaxy S4 has almost full memory, I can't update my applications due to lack of storage.
2 of the Applications I'm currently working on has GoogleMaps integration. Both applications literally freeze my phone when I try to lunch the MapActivities. I have to pull the battery out so that I can restart the phone.
I suggest monitoring the memory consumption, CPU status periodically. Maybe start a service which writes this kind of data to a file periodically and read from it.

A: Should have figured this out sooner. The stack trace has zero calls to any of our Java files. Our code was exacerbating an issue internal to the device itself. After a factory reset everything functioned as expected.


text:
Q: Access a php global in twig template I need to access a global defined with php function define(MY_GLOBAL, 'foo'); in a twig template.
I can't use the detour $app['twiq']->addGlobal(); because I'm in my config file
Any ideas ?

A: That's not a global, that's a constant. For accessing constants, there's the aptly named constant():
{{ constant('MY_GLOBAL') }}


text:
Q: How to copy one file based on a variable I am building a python script to basically edit lots of files by means of searching and replacing words in the file.
There is an original file named: C:\python 3.5/remedy line 1.ahk
There is a file containing the words I want to replace (search words) in the original document and a text file that has the list of the new words that I would like to be placed into the final document.
The script then runs and works perfect. The final document is then created and named based on a line in the final text file (code begins on line 72). A way so I can tell what the final product is by looking at it. This file is originally named output = open("C:\python 3.5\output.ahk", 'w') and later in the script it is renamed based on line 37 in the script.  All that works fine.
So the seemingly simple part left that I can't seem to figure out is how to take this one file and move it to a directory where it belongs. That directory is created based on the same line in that the file gets its name from (code starts on line 82). How do I simply move my file into a directory that has been created by the script, i.e. based on a variable (code starts on line 84 for this) so the name of the file is based on a variable.
    import shutil
    #below is where your modified file sits, before we move it into it's own     directory named dst, based on a variable #mainnewdir
    srcdir = r'C:\python 3.5/'+(justfilename)
    dst = (mainnewdir)+(justfilename)
    shutil.copyfile(src, dst)

*

*Why does it format it with extra \ in the code?

*Why does it seem to not give me a error if I use a / vs. a \ slash?

Here is the entire code, like I said only the last part of moving the file does not work:
    import os
    import linecache
    import sys
    import string
    import re

    ## information/replacingvalues.txt this is the text of the values you         want in your final document
    #information = open("C:\python 3.5\replacingvalues.txt", 'r')
    information = open("C:\python 3.5/replacingvalues.txt", 'r')
    # information = open("C:\Program Files (x86)\Python35-        32\Scripts\Text_Find_and_Replace\information/replacingvalues.txt",

    # Text_Find_and_Replace\Result/output.txt This is the dir and the sum or         final document

    # output = open("C:\python 3.5\output.ahk", 'w')
    createblank = open ("C:\python 3.5/output.ahk", 'w')
    createblank.close()
    output = open("C:\python 3.5\output.ahk", 'w')
    # field = open("C:\Program Files (x86)\Python35-        32\Scripts\Text_Find_and_Replace\Field/values.txt"
    # Field is the file or words you will be replacing
    field = open("C:\python 3.5/values.txt", 'r')

    # modified code for autohot key
    # Text_Find_and_Replace\Test/remedy line 1.ahk is the original doc you want modified
    with open("C:\python 3.5/remedy line 1.ahk", 'r') as myfile:
    inline = myfile.read()
    ## remedy line 1.ahk

    informations = []
    fields = []
    dictionary = {}
    i = 0

    for line in information:
        informations.append(line.splitlines())

    for lines in field:
        fields.append(lines.split())
        i = i + 1;

    if (len(fields) != len(informations)):
        print("replacing values and values have different numbers")
        exit();
    else:
        for i in range(0, i):
            rightvalue = str(informations[i])
            rightvalue = rightvalue.strip('[]')
            rightvalue = rightvalue[1:-1]

            leftvalue = str(fields[i])
            leftvalue = leftvalue.strip('[]')
            leftvalue = leftvalue.strip("'")

            dictionary[leftvalue] = rightvalue

            robj = re.compile('|'.join(dictionary.keys()))
            result = robj.sub(lambda m: dictionary[m.group(0)], inline)

       output.write(result)
        information.close;
        output.close;
        field.close;
        output.close()

    import os
    import linecache
    linecache.clearcache()
    newfilename= linecache.getline("C:\python 3.5/remedy line 1.txt",37)
    filename = ("C:\python 3.5/output.ahk")
    os.rename(filename, newfilename.strip())
    #os.rename(filename, newfilename.strip()+".ahk")
    linecache.clearcache()

    ############## below will create a new directory based on the the word         or words in line 37 of the txt file.

    newdirname= linecache.getline("C:\python 3.5/remedy line 1.txt",37)
    #newpath = r'C:\pythontest\automadedir'
    #below removes the /n ie new line raw assci
    justfilename = (newdirname).strip()
    #below removes the .txt from the rest of the justfilename..
    autocreateddir = (justfilename).strip(".txt")
    # below is an example of combining a string and a variable
    # below makes the variable up that will be the name of the new directory         based on reading line 37 of a text file above

    mainnewdir= r'C:\pythontest\automadedir/'+(autocreateddir)
    if not os.path.exists(mainnewdir):
        os.makedirs(mainnewdir)

        linecache.clearcache()
    # ####################################################
    #below is where your modified file sits, before we move it into it's own         directory named dst, based on a variable #mainnewdir
    srcdir = r'C:\python 3.5/'+(justfilename)
    dst = (mainnewdir)+(justfilename)
    shutil.copyfile(src, dst)

A: backslashes do not have a mind of their own.
When you paste windows paths as-is and they contain \n, r, \b, \x, \v, \U (python 3), (refer to table here for all of them), you're just using escape sequences without noticing it.
When the escape sequence doesn't exist (ex \p) it works. But when it's known the filenames are often invalid. Which explains the apparent randomness of the issue.
To be able to safely paste windows paths without changing/escaping them, just use the raw prefix:
my_file = r"C:\temp\foo.txt"

so the backslashes won't be interpreted. One exception though: if string ends with backslash you still have to double it.


text:
Q: Passing data from text field to Firebase I am getting error in ToDoViewController.Swift here is the overall code:
I am makeing a simple app for taking orders from customers. and orders will store in Firebase.
View Controller.Swift
import UIKit
import Firebase

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var todoList = [Todo]()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        loadData()
    }

    func loadData() {
        self.todoList.removeAll()
        let ref = FIRDatabase.database().reference()
        ref.child("todoList").observeSingleEvent(of: .value, with: { (snapshot) in
            if let todoDict = snapshot.value as? [String:AnyObject] {
                for (_,todoElement) in todoDict {
                    print(todoElement);
                    let todo = Todo()
                    todo.name = todoElement["name"] as? String
                    todo.message = todoElement["message"] as? String
                    todo.reminderDate = todoElement["date"] as? String
                    self.todoList.append(todo)
                }
            }
            self.tableView.reloadData()

        }) { (error) in
            print(error.localizedDescription)
        }

    }

    //MARK: TableView datasource

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.todoList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoCell")
        cell!.textLabel?.text = todoList[indexPath.row].name
        return cell!
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

    }
}

ToDoViewController
import UIKit
import Firebase

class ToDoViewController: UIViewController {

    var todo:Todo?

    @IBOutlet weak var nameField: UITextField!
    @IBOutlet weak var messageField: UITextField!
    @IBOutlet weak var dateFormatter: UIDatePicker!

    @IBAction func Done(_ sender: Any) {
        if todo == nil {
            todo = Todo()
        }

        // first section
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd/MM/yyyy hh:mm"

        todo?.name = self.nameField.text
        todo?.message = self.messageField.text
        todo?.reminderDate = dateFormatter.string(from: self.dateFormatter.date)

        //second section
        let ref = FIRDatabase.database().reference()
        let key = ref.child("todoList").childByAutoId().key

        let dictionaryTodo = [ "name"    : todo!.name! ,
                               "message" : todo!.message!,
                               "date"    : todo!.reminderDate!]

        let childUpdates = ["/todoList/\(key)": dictionaryTodo]
        ref.updateChildValues(childUpdates, withCompletionBlock: { (error, ref) -> Void in
            self.navigationController?.popViewController(animated: true)
        })
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let todoVC = self.storyboard!.instantiateViewController(withIdentifier: "ToDoVC") as! ToDoViewController
        todoVC.todo = todoList[indexPath.row]
        self.navigationController?.pushViewController(todoVC, animated: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        if self.todo != nil {
            nameField.text = self.todo?.name
            messageField.text = self.todo?.message
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "dd/MM/yyyy hh:mm"
            let date = dateFormatter.date(from: self.todo!.reminderDate!)
            datePicker.date = date!
        }
    }
}

 Todo.Swift
import UIKit
class Todo: NSObject {
    var name :String?
    var message: String?
    var reminderDate: String?
    // id which is set from firebase to uniquely identify it
    var uniqueId:String?
}

A: Something is wrong with your code:

*

*Use of un-resolved identifier 'todoList':

todoList is declared in View Controller.Swift and you cannot use it in ToDoViewController.

*Cannot assign to property: 'date' is a method:

In the code datePicker is undefined and @IBOutlet weak var dateFormatter: UIDatePicker! should be:
@IBOutlet weak var datePicker: UIDatePicker!

AND In the image dateFormatter.date = date! should be:
datePicker.date = date!


text:
Q: Drupal Localhost images not working I am working on a local drupal site and the images are not appearing. I can upload them into content but they appear as broken links in the admin section and are not shown at all in the front end.
Does anyone have any suggestions or encountered this before?
If it helps I am using core Drupal 7 with MAMP and Bootstrap theme.
Thanks

A: What is showing as the file location of a broken image?
I assume you already checked the directory and file permissions of the files folder(?).


text:
Q: Replacing static site with Django/Serving static files with mod_wsgi I have an existing static website that is served via apache. I wanted to add dynamic features to that site so I created a Django app that lives in a subfolder (ie. /django-site/). I have this configured like this:
    WSGIDaemonProcess django_site processes=5 threads=5 user=user group=group python-home=path/to/virtualenv
    WSGIScriptAlias /django-site /var/www/django_site/wsgi.py
    <Location /django-site>
    WSGIProcessGroup group
    </Location>

But now I would like to replace certain pages that were originally static pages in the root directory. But I don't want to replace all of the static pages.
I know that Django recommends putting your static files in a subdirectory like /media or /static and Django configured to be the root directory but since I have a long legacy of these static pages being in the root directory and external links to these pages I don't want to change that.
Is there a recommended way to replace these static pages with a dynamic ones?
Here are a few ideas that I have thought of:

*

*Use ProxyPass to replace pages one at a time

*Redirect static pages to dynamic versions, change internal links to new dynamic version

*Move dynamic site to root, and use something like whitenoise to serve those files

A: You could use Apache mod_rewrite to keep the existing links functional. The documentation suggests this:

Description:
How can we transform a static page foo.html into a dynamic variant foo.cgi in a seamless way, i.e. without notice by the browser/user.

Solution:
We just rewrite the URL to the CGI-script and force the handler to be cgi-script so that it is executed as a CGI program. This way a request to /~quux/foo.html internally leads to the invocation of /~quux/foo.cgi.

RewriteEngine  on
RewriteBase    "/~quux/"
RewriteRule    "^foo\.html$"  "foo.cgi"  [H=cgi-script]


text:
Q: Split up JSON Object into multiple  I'm currently trying to create a Character Ranking system similar to this one.
With the official API I am able to append all the data via $.getJSON and the URL into a table.
So far I'm showing 20 characters and got all the character data inside multiple table rows (one for each character), but haven't figured out how I can split up the character object into multiple , so that I have better control of addressing them via CSS.
Here's the code:
<!DOCTYPE html>

    <meta charset="utf-8">

    <button>Anzeige der Top 20 Spieler in der Incursion Liga</button>

                Anzahl der Spieler:
                Suchbeginn:

                Spieler: (max. 20 angezeigt)

The whole JSON object where I append my data from can be found here.

A: You can access the character properties within your $.each function using the non-stringified value variable. For example, to access the character name, use value.character.name
$("#tdRanking").append("
" + JSON.stringify(index, null, '\t') + '' + value.character.name + "
");

I've added an example on codepen
Please note that i am not using ajax to retrieve the data as your data source is not being served over https://


text:
Q: T-testing on sparse data Problem: I have two stochastic processes, $S_1$ and $S_2$, that frequently are zero, but occasionally have positive values with unknown probabilities $q_1$ and $q_2$. e.g.
$$
S_1 = \{0,0,0,0,0,21,0,0,0,0,\dots,0,0,112,0,0,0,\dots 0,0,47,0,0,0 \} \\
S_2 = \{0,0,0,31,0,0,0,0,0,0,\dots,0,23,0,0,0,0,0,\dots 0,0,0,0,212 \}
$$
I know a probability density function $p(q|S)$ that tells me the probability of $q$ being a certain value.
I have no information that suggests the values of $q_1$ and $q_2$ influence the values of non-zero elements in $S_1$ and $S_2$.
I have no information about the shape of the distribution of the value of non-zero elements in $S_1$ or $S_2$.
I assume the distributions of $S_1$ and $S_2$ are independent and all samples of $S_1$ and $S_2$ are independent.
Goal: I wish to test if $S_1$ and $S_2$ have a similar mean.
Suggested Approach: I define a function $T(S_1,S_2,\alpha \in \mathbb{R})$ which is equal to the p-value of a two-sided t-test applied to the non-zero elements of $S_1$, and $\tilde{S}_2 = \{\alpha \cdot s \text{ for all }s \in S\}$. This amounts to the p-value of a t-test for the hypothesis that the non-zero elements of $S_1$ have a mean equal to $\alpha$ times the mean of the non-zero elements of $S_2$.
Using this function, I can test for the expectation of the p-value associated with $S_1$ and $S_2$ having the same overall mean by calculating:
$$
\int_0^1\int_0^1 T\left(S_1,S_2,\frac{q_1}{q_2}\right) \cdot p(q_1|S_1) \cdot p(q_2|S_2)dq_1dq_2
$$
Can I then use this expected p-value in place of a normal one? or can I do something like:
$$
\int_0^1\int_0^1 \left(T\left(S_1,S_2,\frac{q_1}{q_2}\right)<0.05\right) \cdot p(q_1|S_1) \cdot p(q_2|S_2)dq_1dq_2
$$
Question: Is this approach valid? or am I reaching new and hitherto unexplored levels of stupidity? I feel like a traditional welches t-test will suffer due to the high variances induced by the zero elements and will not take advantage of my possession of a posterior for q.


text:
Q: Adding and handling custom settings tab to fusion element I'm developing an add on that wraps standard fusion shortcode around content coming from webservices calls.
By now I created 3 or 4 custom components whose option panel embed the corresponding short code parameters input section and pass those arguments "under the hood" the original fusion shortcode.
I'm conscious that this approach is not the cleanest and shows its limits when i try to use it on Fusion_container elements.
So my question is: is it possible to inject a custom settings group inside existing elements?
I'd like to add the "My Custom Settings" (in the screenshot is just a mock done in Chrome):

Second question, if this is possible, how can I then handle custom parameters inected? to be more specific: i'd like to render fusion Container only if some conditions are met.
Thanks!


text:
Q: Destroy instance of all prefab clone not working I am writing a restart function where i want to delete the instance of all prefabs belonging to a panel. This code adds a new input field to the parent
private void ShowInputField(){

    GameObject inputFieldGameObject = inputFieldObjectPool.GetObject();

    //reset pool since it may have been disabled by the DeActivatePreviousInputFields function
    InputField inputField = inputFieldGameObject.GetComponent<InputField>();
    inputField.Select ();
    inputField.ActivateInputField ();
    inputField.interactable = true;
    inputField.readOnly = false;

    //make this the previous inputs
    previousInputs = inputFieldGameObject;

    //assign the prefab to its parent panel
    inputFieldGameObject.transform.SetParent (inputFieldParent);
    inputFieldGameObject.transform.localScale = Vector3.one;
    Canvas.ForceUpdateCanvases ();

    //make scroll bar always show the last added input field
    GameObject.Find ("ScrollView").GetComponent<ScrollRect> ().horizontalNormalizedPosition = 1;

}

The image below shows how it looks like before the restart

the code for the restart which destroys all instances of the prefab and adds one again is shown below.
void RestartGame(){
    //gets all elements of the parent
    InputField [] childElements = letterPanel.GetComponentsInChildren<InputField> ();
    Debug.Log (childElements.Count());
    foreach (var item in childElements) {
        Destroy (item);
    }
    ShowInputField()
}

this is supposed to destroy all instances of the prefab but it does not it only makes them editable with the image below showing it

How do I solve this problem? Thank you in advance...

A: You were trying to destroy the current item from the list you were enumerating through, but this is an input field which you can cannot destroy. Instead by referring to the gameobject it belongs to and destroying that, you remove the Input fields.

A: I did this and it worked
void RestartGame(){
    //gets all elements of the parent
    InputField [] childElements = letterPanel.GetComponentsInChildren<InputField> ();
    Debug.Log (childElements.Count());
    foreach (vInputField item in childElements) {
        if(item.name.Contains("InputField")){
            Destroy (item.gameObject);
        }
    }
    ShowInputField()
}


text:
Q: iterate users in friends list over same modal and access database content I am making a chat box for my website. As per current implementation,i i am iterating over the current friends list and and anchor tag triggers a modal for that particular user. The modal is common for all users as it only changes the data inside.
Now, i have used jquery to fetch the message history ( from model object ) and display is modal body.
I can click on different users and view the messages in their respective models correctly. However, when i try to submit the form to send another message it gets added to the message box of first user. This is happening for all users in the friend list.
How can i trigger the form to post in the model of the correct user.
Template
{% for friend in friends_list %}

{{friend.to_user.usercreation.fname}}  {{friend.to_user.usercreation.lname}}

                <form  action="{% url 'usercreation:addmessage' friend.to_user.usercreation.pk %}" method="post">
                    {% csrf_token %}

BlogChat

                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                          ×
                        </button>

                            <input style="width:330px;height:40px" type="text" name="addmessage" value="" placeholder="Type..">
                            <button style="float:right;" type="submit" class="btn btn-primary">Send message</button>

                  </form>
            {% endfor %}

JQUERY:

VIEWS:
def fetcher(request):
if request.is_ajax():
    name = User.objects.get(username=request.GET.get('search', None))
    b = ChatMessage.objects.get(user1 = request.user,user2 = name)
    print(b.message)
    data = {
        'list': b.message,
    }
    print(data)
    return JsonResponse(data)

def addmessage(request,pk):
if request.method=='POST':
    print(request.user)
    print(User.objects.get(username=UserCreation.objects.get(pk=pk)))
    obj = ChatMessage.objects.get(user1 = request.user , user2 = User.objects.get(username=UserCreation.objects.get(pk=pk)) )
    obj2 = ChatMessage.objects.get(user2 = request.user , user1 = User.objects.get(username=UserCreation.objects.get(pk=pk)) )
    name = request.POST.get('addmessage')

    obj.message += ('\n'+str(request.user)+': '+name)
    obj2.message += ('\n'+str(request.user)+': '+name)
    obj.save()
    obj2.save()
return HttpResponseRedirect(reverse('usercreation:profile',args=[request.user.usercreation.pk]))

Models:
class ChatMessage(models.Model):
user1 = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="participant1")
user2 = models.ForeignKey(User, on_delete=models.CASCADE , related_name="participant2")
message = models.TextField(default="")
date = models.DateTimeField(auto_now=True, db_index=True)


text:
Q: Lubuntu 16.04 - no internet on the new ISP "Gateway/Cable modem/coax" connection It is Lubuntu mini.iso with no desktop environment, only fvwm, so please, I can use only the terminal. I don't have any network manager installed.
There are two different routers:
On the sim router the wired internet connection works for the Lubuntu device.
Immediately as I change the Ethernet cable from the above SIM router, to the other provider(router) which has only tv cable/coax connection through only a cable model(Gateway), there is no more internet connection.
With the same network cable/router port(from the second tv cable/coax/Gateway ISP)  the internet works on Windows 7 and 10.
From what I could see for the two different routers/connections the IPs are dynamically.
Tell me please what logs do you need from the working and no-working connections, in order to see the differences...
Thank you.
Working internet connection:
~$ ifconfig -a
eth0      Link encap:Ethernet  HWaddr 68:f7:28:21:c8:85
          inet addr:192.168.8.100  Bcast:192.168.8.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:6773 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6029 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:5842607 (5.8 MB)  TX bytes:1038943 (1.0 MB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:7609 errors:0 dropped:0 overruns:0 frame:0
          TX packets:7609 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:766404 (766.4 KB)  TX bytes:766404 (766.4 KB)

wlan0     Link encap:Ethernet  HWaddr ac:b5:7d:f2:ef:2f
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

Non interet working connection(immediatelly after I only change the ethernet cable from a router to another)
~$ ifconfig -a
eth0      Link encap:Ethernet  HWaddr 68:f7:28:21:c8:85
          inet addr:192.168.8.100  Bcast:192.168.8.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:15580 errors:0 dropped:0 overruns:0 frame:0
          TX packets:14234 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:11441631 (11.4 MB)  TX bytes:2455373 (2.4 MB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:8093 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8093 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:839056 (839.0 KB)  TX bytes:839056 (839.0 KB)

wlan0     Link encap:Ethernet  HWaddr ac:b5:7d:f2:ef:2f
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

I am not interested in the WiFi connection.
There are two different routers:
One is connected to the internet through a sim card - one ISP (Linux has internet)
The second ISP is connected to the internet through a coaxial/tv cable/Gateway/Modem cable. (no internet on Linux for this one)
No configurations have been changed to any of the two routers or any machines Linux/Windows 7/Windows 10.
Only change the same cable for all the 3 difference devices from a router to another. Windows 10 and Windows 7 have internet connection on both routers.
Linux has internet only on the first SIM router.
For the non working internet connection to the link led from the router where is the Linux Ethernet cabled plugged, only the orange
 led one blinks, but for the other internet working devices connected via Ethernet cable to the same router, blinks also the green led on the router.
Working internet connection:
~$ ping google.com
PING google.com (195.249.145.114) 56(84) bytes of data.
64 bytes from cache.google.com (195.249.145.114): icmp_seq=1 ttl=58 time=26.0 ms
64 bytes from cache.google.com (195.249.145.114): icmp_seq=2 ttl=58 time=35.6 ms
64 bytes from cache.google.com (195.249.145.114): icmp_seq=3 ttl=58 time=44.4 ms
64 bytes from cache.google.com (195.249.145.114): icmp_seq=4 ttl=58 time=43.2 ms
64 bytes from cache.google.com (195.249.145.114): icmp_seq=5 ttl=58 time=43.2 ms
64 bytes from cache.google.com (195.249.145.114): icmp_seq=6 ttl=58 time=39.4 ms
^C
--- google.com ping statistics ---
6 packets transmitted, 6 received, 0% packet loss, time 5008ms
rtt min/avg/max/mdev = 26.059/38.670/44.463/6.378 ms

~$ ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=57 time=48.4 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=57 time=57.6 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=57 time=56.1 ms
^C
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2004ms
rtt min/avg/max/mdev = 48.494/54.102/57.670/4.023 ms

Non working internet connection for ping google.com after pending/waiting a few minutes, it appears:
~$ ping google.com
ping: unknown host google.com

~$ ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
From 192.168.8.100 icmp_seq=1 Destination Host Unreachable
From 192.168.8.100 icmp_seq=2 Destination Host Unreachable
From 192.168.8.100 icmp_seq=3 Destination Host Unreachable
From 192.168.8.100 icmp_seq=4 Destination Host Unreachable
From 192.168.8.100 icmp_seq=5 Destination Host Unreachable
From 192.168.8.100 icmp_seq=6 Destination Host Unreachable
From 192.168.8.100 icmp_seq=7 Destination Host Unreachable
From 192.168.8.100 icmp_seq=8 Destination Host Unreachable
^C
--- 8.8.8.8 ping statistics ---
10 packets transmitted, 0 received, +8 errors, 100% packet loss, time 9026ms
pipe 3

I run dhcpcd eth0 with the working internet cabled in, and after dhcpcd loaded everything, I plugged the cable in the non-working internet router, and the internet worked, maybe because dhcpcd was running.
I restarted the device to see if it will still work but when Linux loaded after restart it appeared in the  console:
Failed to start LSB: IPV4 DHCP client with IPV4ALL support.
See 'systemctl status dhcpcd.service' for details
16.780656 usb 1-1.4.3: device descriptor read/64, error -110
A start job is running to Raise network interfaces ( ** min **s / 5min 7s)

The last part "A start job is running..." where I have to wait 5 min and 7s it seams that appears every time that the internet doesn't work. It has never appeared when the internet worked, but it always appears when internet doesn't work...
After starting Linux with the non-working internet in, I also tried dhcpcd eth0 but...
eth0: waiting for carrier
timed out
dhcpcd exited

And again...
I have just(nothing less or more) only moved the cable from the non-internet connection router to the internet working connection router
dhcpcd eth0
Loaded all the things successfully(with the internet connection plugged) It is right that would not be a good idea to paste in here the output of "dhcpcd eht0" ?
Unplug the working internet connection and plug in to the non-internet connection, but surprise, now I am posting from the non-working internet connection which it seams that now is working because of the dhcpcd eth0
But, if I will restart like last time, I think it will happen again like before
As soon as "waiting for carrier" without touching anything else, I unplugged only the head on the network cable from the Linux machine, insert it in the Windows 7 machine, disable the wireless at all from the Windows machine, enable LAN, and internet is working... This could mean that the router/cable/port of the router work properly?
I will try also to reset the router...
Could it be any other configurations of Linux, considering that the internet works after I use dhcpcd eth0 with the internet-working router plugged in, and after that, plugging in the non-internet router and still has internet connection... (until restart)

The only way the internet was working IN THE NON-INTERNET WORKING ROUTER (the same network cable/the same router port, everything the same like when it doesn't work) was dhcpcd eht0 WHEN THE NETWORK CABLE WAS PLUGGED IN THE WORKING INTERNET ROUTER and after that only moving the cable from the working-internet-router to the non-working-internet router.
But if I will restart the machine, no internet until I will not repeat the before steps.
I've also reset for a few times the router, restarted it (unplug from the electricity for at least 30 second) tried to reconnect the Linux machine to the non-internet-router with another cable router and also to another port router, but still not working, until I will not do the step from the beginning.
The same Ethernet cable and router port from the non-internet router provide internet instantly when is plugged into another Windows 7 and Windows 10 machines, without to change anything in Windows or in the fresh/new/from scratch reset router.
uname -a
Linux WindowsXP 4.4.0-78-generic #99-Ubuntu SMP Thu Apr 27 15:29:09 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.2 LTS
Release:    16.04
Codename:   xenial

Here it is /var/log/dmesg
https://paste.debian.net/hidden/8226e135/
All the following commands are outputed with the internet working(connected to the usually non-internet router, until I will not do the steps from the beginning of this replay)
lshw -C network  *-network DISABLED
       description: Wireless interface
       product: QCA9565 / AR9565 Wireless Network Adapter
       vendor: Qualcomm Atheros
       physical id: 0
       bus info: pci@0000:02:00.0
       logical name: wlan0
       version: 01
       serial: ac:b5:7d:f2:ef:2f
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list rom ethernet physical wireless
       configuration: broadcast=yes driver=ath9k driverversion=4.4.0-78-generic firmware=N/A latency=0 link=no multicast=yes wireless=IEEE 802.11bgn
       resources: irq:18 memory:90500000-9057ffff memory:90580000-9058ffff
  *-network
       description: Ethernet interface
       product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:03:00.0
       logical name: eth0
       version: 10
       serial: 68:f7:28:21:c8:85
       size: 100Mbit/s
       capacity: 1Gbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix vpd bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=full firmware=rtl8168g-3_0.0.1 04/23/13 ip=192.168.110.11 latency=0 link=yes multicast=yes port=MII speed=100Mbit/s
       resources: irq:88 ioport:1000(size=256) memory:90404000-90404fff memory:90400000-90403fff

more /etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 208.67.222.222
nameserver 208.67.220.220
nameserver 192.168.8.1

route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         192.168.110.1   0.0.0.0         UG    202    0        0 eth0
192.168.110.0   *               255.255.255.0   U     202    0        0 eth0

The var/log/kern.log it was to big to paste anywhere, and I don't know why I could not upload the file to any file hosting site, or on Google drive, or elsewhere. The file has only 2.1M. I've also tried to copy it/rename it, but it is not possible to upload it anywhere. even here on the forum as an File Attachment. Maybe because of the file content.

Considering the before post, when I was connected on the internet through the regularly/usually non-working-internet router, but this time, before restart the internet was working on it(the reason for the working internet connection you can see at the beginning of the before post)
I only restarted the machine, without to touch anything else, router, cable or anything else.
Immediately after restart:
~$ ping google.com
ping: unknown host google.com

~$ ping 8.8.8.8
connect: Network is unreachable

~$ sudo dhcpcd eth0
[sudo] password for globalisation:
eth0: waiting for carrier
timed out
dhcpcd exited

From the above post/replay it seams that 192.168.110.0 is the Gateway, It seams that it is right, because when I write in the browser it asks for the username and password of the modem/password
ping 192.168.110.1
connect: Network is unreachable
globalisation@WindowsXP:~$ ping 192.168.110.0
connect: Network is unreachable
globalisation@WindowsXP:~$ ping 192.168.8.1
connect: Network is unreachable
globalisation@WindowsXP:~$ ping 8.8.8.8
connect: Network is unreachable
globalisation@WindowsXP:~$ ping google.com
ping: unknown host google.com

:~$ dmesg |grep eth[0-9]
[    2.981426] r8169 0000:03:00.0 eth0: RTL8168g/8111g at 0xffffc90000768000, 68:f7:28:21:c8:85, XID 10900800 IRQ 88
[    2.981432] r8169 0000:03:00.0 eth0: jumbo features [frames: 9200 bytes, tx checksumming: ko]
[   15.883064] r8169 0000:03:00.0 eth0: link down
[   15.883066] r8169 0000:03:00.0 eth0: link down

:~$ sudo lshw -C network
  *-network DISABLED
       description: Wireless interface
       product: QCA9565 / AR9565 Wireless Network Adapter
       vendor: Qualcomm Atheros
       physical id: 0
       bus info: pci@0000:02:00.0
       logical name: wlan0
       version: 01
       serial: ac:b5:7d:f2:ef:2f
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress bus_master cap_list rom ethernet physical wireless
       configuration: broadcast=yes driver=ath9k driverversion=4.4.0-78-generic firmware=N/A latency=0 link=no multicast=yes wireless=IEEE 802.11bgn
       resources: irq:18 memory:90500000-9057ffff memory:90580000-9058ffff
  *-network
       description: Ethernet interface
       product: RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller
       vendor: Realtek Semiconductor Co., Ltd.
       physical id: 0
       bus info: pci@0000:03:00.0
       logical name: eth0
       version: 10
       serial: 68:f7:28:21:c8:85
       size: 10Mbit/s
       capacity: 1Gbit/s
       width: 64 bits
       clock: 33MHz
       capabilities: pm msi pciexpress msix vpd bus_master cap_list ethernet physical tp mii 10bt 10bt-fd 100bt 100bt-fd 1000bt 1000bt-fd autonegotiation
       configuration: autonegotiation=on broadcast=yes driver=r8169 driverversion=2.3LK-NAPI duplex=half firmware=rtl8168g-3_0.0.1 04/23/13 latency=0 link=no multicast=yes port=MII speed=10Mbit/s
       resources: irq:88 ioport:1000(size=256) memory:90404000-90404fff memory:90400000-90403fff

:~$ ifconfig -a
eth0      Link encap:Ethernet  HWaddr 68:f7:28:21:c8:85
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:1761 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1761 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:130352 (130.3 KB)  TX bytes:130352 (130.3 KB)

wlan0     Link encap:Ethernet  HWaddr ac:b5:7d:f2:ef:2f
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

:~$ more /etc/resolv.conf
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver 208.67.222.222
nameserver 208.67.220.220

:~$ route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface

Internet working connection on the regularly non-internet working router:
:~$ ethtool eth0
Settings for eth0:
    Supported ports: [ TP MII ]
    Supported link modes:   10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Half 1000baseT/Full
    Supported pause frame use: No
    Supports auto-negotiation: Yes
    Advertised link modes:  10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
    Advertised pause frame use: Symmetric Receive-only
    Advertised auto-negotiation: Yes
    Link partner advertised link modes:  10baseT/Half 10baseT/Full
                                         100baseT/Half 100baseT/Full
                                         1000baseT/Full
    Link partner advertised pause frame use: No
    Link partner advertised auto-negotiation: Yes
    Speed: 100Mb/s
    Duplex: Full
    Port: MII
    PHYAD: 0
    Transceiver: internal
    Auto-negotiation: on
Cannot get wake-on-lan settings: Operation not permitted
    Current message level: 0x00000033 (51)
                   drv probe ifdown ifup
    Link detected: yes

No internet(because of restart) for the same above non-internet working router. There is no link detected, but  this same cable/machine/port had internet before restart...
:~$ ethtool eth0
Settings for eth0:
    Supported ports: [ TP MII ]
    Supported link modes:   10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Half 1000baseT/Full
    Supported pause frame use: No
    Supports auto-negotiation: Yes
    Advertised link modes:  10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
    Advertised pause frame use: Symmetric Receive-only
    Advertised auto-negotiation: Yes
    Link partner advertised link modes:  10baseT/Half 10baseT/Full
                                         100baseT/Half 100baseT/Full
                                         1000baseT/Full
    Link partner advertised pause frame use: No
    Link partner advertised auto-negotiation: Yes
    Speed: 100Mb/s
    Duplex: Full
    Port: MII
    PHYAD: 0
    Transceiver: internal
    Auto-negotiation: on
Cannot get wake-on-lan settings: Operation not permitted
    Current message level: 0x00000033 (51)
                   drv probe ifdown ifup
    Link detected: yes

The always internet working router( completely another provider, another connections, another router)
:~$ ethtool eth0
Settings for eth0:
    Supported ports: [ TP MII ]
    Supported link modes:   10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Half 1000baseT/Full
    Supported pause frame use: No
    Supports auto-negotiation: Yes
    Advertised link modes:  10baseT/Half 10baseT/Full
                            100baseT/Half 100baseT/Full
                            1000baseT/Full
    Advertised pause frame use: Symmetric Receive-only
    Advertised auto-negotiation: Yes
    Link partner advertised link modes:  10baseT/Half 10baseT/Full
                                         100baseT/Half 100baseT/Full
    Link partner advertised pause frame use: Symmetric
    Link partner advertised auto-negotiation: Yes
    Speed: 100Mb/s
    Duplex: Full
    Port: MII
    PHYAD: 0
    Transceiver: internal
    Auto-negotiation: on
Cannot get wake-on-lan settings: Operation not permitted
    Current message level: 0x00000033 (51)
                   drv probe ifdown ifup
    Link detected: yes

Regards.

A: It seams that these two commands resolve the problem:
sudo ethtool -s eth0 autoneg off speed 100 duplex full
sudo dhcpcd eth0
Only that now, still have to find out how they could run on the system start, because after every restart the two commands should be used.
It seams that in adding them in /etc/rc.local doesn't have any effect.
Still at he boot there are these 3 issues:
[FAILED] Failed to start LSB: IPV4 DHCP client with IPV4LL support
[17.289877] usb 1-1.4.3: device descriptor read/64, error -110
A start job is running for Raise network interfaces (**min **s / 5min 8s)

And there is waiting time until the 5min 8s passes.
This last error it appears always only when the internet connection is not recognized, but never when the internet connection works from the beginning immediately after restart, without to use any commands in order to start the internet.

A: It seams that the final result, in order to have internet access automatically after reboot/shutdown/sleep with no more manual commands:
/etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

source /etc/network/interfaces.d/*

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
iface eth0 inet dhcp
    pre-up ethtool -s eth0 autoneg off speed 100 duplex full

allow-hotplug eth0

/etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

echo 70 > /sys/class/backlight/intel_backlight/brightness
rfkill block bluetooth
rfkill block wifi
ethtool -s eth0 autoneg off speed 100 duplex full
ip link set eth0 up

exit 0


text:
Q: Is it possible to make an iframe truly responsive using HTML & CSS I have some simple code for an iframe. I want to display a webpage within a webpage seamlessly i.e no scroll bar
I have tried hidden overflow but I just cant seem to get it right
HTML

CSS
.frame-area {
  display: block;
  width: 100%;  /* RESPONSIVE WIDTH */
  max-width: 100%;
  height: 100%;
  overflow: hidden;  /* EDIT TO hidden FOR NO SCROLLBAR */
  border: #999999 1px solid;
  margin: 0px;
  padding: 0px;
  }

The results I have is a full width page with only a small amount of height
I wish it to display full width and height and be fully responsive

A: To make your iframe full height and width of your page use this css and iframe tag.
[EDIT] Due to your comment that there is a footer I have edited so it will work with a footer.  The footer disappeared because the iframe was 100% height and pushed it off at the bottom, which caused a scroll bar to appear. See below for the fix.
In the example code below, notice the CSS for the footer shows 30px height. So the iframe should be 30px less than the screen height to allow for the footer space. This is possible to do using height:calc(100% - 30px); of course substitute the actual height of your footer for 30px.
body {
    margin:0;
    padding:0;
}

.frame-area {
    position:absolute;
    height:calc(100% - 30px); /* example below if your footer is 30px in height */
    width:100%;
    border:none;
}

footer {
    position:absolute;
    bottom:0;
    height:30px; /* match this height in your iframe width calc value */
}

And with the CSS above, you can simplify the iframe tag's formatting:
<iframe name="Framename" src="https://website" class="frame-area"
This is the footer


text:
Q: Why are attributes in different objects connected to each other when a default argument is given? I am implementing a basic node object in python. Basically, I implemented a node class with the attribute f_pointers and set it to the default value []. When ever I try to change f_pointers of (lets say) node_a, I will end up changing f_pointers of node_b, which are programmed to be completely unrelated.
I have already solved the problem by instead changing the default value to None and setting up the forward_pointers in __init__. However, I would still like to know how to avoid this problem in the future and possibly learn something new about Python.
For the sake of simplicity, I removed some unnecessary parts of the code.
class Node:
     def __init__(self, f_pointers = []):
          self.f_pointers = f_pointers
     def get_pointers(self):
          return self.f_pointers
     def add_pointers(self, new_pointer):
          self.f_pointers.append(new_pointer)

a = Node()
b = Node()
print(a.get_pointers, b.get_pointers)

>>> [] []

a.add_pointers("a")
print(a.get_pointers, b.get_pointers)

>> ["a"] ["a"]

a.add_pointers("b")
print(a.get_pointers, b.get_pointers)

>> ["a","b"] ["a","b"]

As can be seen, a and b are completely unrelated objects (other than the fact that they are of the same type Node) but will affect each other. Why does this happen?

A: It's because you are referencing to the same list (the one instantiated in the __init__ default params list definition like __init__(self, f_pointers=[]). What happens is that when you say in the __init__ method code block that self.f_points = f_pointers you are basically referencing the same list every time you instantiate a new Node object.
The reasons are explained further here
What you do want to do instead is instantiate a new list for every init like:
def __init__(self, f_pointers=None):
    self.f_pointers = []

A: You should do it like this.
class Node:
    def __init__(self, f_pointers=None):
        if f_pointers:
            self.f_pointers = f_pointers
        else:
            self.f_pointers = []
    def get_pointers(self):
        return self.f_pointers
    def add_pointers(self, new_pointer):
        self.f_pointers.append(new_pointer)

a = Node()
b = Node()

print(a.get_pointers(), b.get_pointers())

a.add_pointers("a")
print(a.get_pointers(), b.get_pointers())

You get this kind of behavior because in your case a.f_pointers and b.f_pointers is the same list, which was generated, when you described your class Node.
So a.f_pointers is b.f_pointers == True in your case


text:
Q: Wait for Node constructor to connect to api before issuing commands Sorry if the question title is a tad ambiguous, but I'm not entirely sure how to word it.
I'm writing an NPM module that talks to a json-rpc api - this is the current setup.
// The module
function MyModule(config) {
    // do some connection stuff here
    connected = true
}

MyModule.prototype.sendCommand = function() {
    if(connected) {
        // do command
    } else {
        // output an error
    }
}

module.exports = MyModule;

// The script interacting with the module
var MyModule = require('./MyModule');
var config = {
    // config stuff
};
var mod = new MyModule(config);
var mod.sendCommand;

The command won't send, as at this point it hasn't connected, I assume this is due to NodeJS' asynchronous, non-blocking architecture and that I perhaps need to use promises to wait for a response from the API, where would I implement this? Do I do it in my module or do I do it in the script interacting with the module?

A: You will need to use either a callback or promises or something like that to indicate when the connection is complete so you can then use the connection in further code that is started via that callback.
Though it is generally not considered the best practice to do asynchronous stuff in a constructor, it can be done:
function MyModule(config, completionCallback) {
    // do some connection stuff here
    connected = true
    completionCallback(this);
}

var mod = new MyModule(config, function(mod) {
    // object has finished connecting
    // further code can run here that uses the connection
    mod.sendCommand(...);
});

A more common design pattern is to not put the connecting in the constructor, but to add a method just for that:
function MyModule(config) {
}

MyModule.prototype.connect = function(fn) {
    // code here that does the connection and calls
    // fn callback when connected
}

var mod = new MyModule(config);
mod.connect(function() {
    // object has finished connecting
    // further code can run here that uses the connection
    mod.sendCommand(...);
});

A: don't use promises, use node's programming model where you don't "call functions" but you "call functions with a result handler for dealing with the data once it's actually available":
MyModule.prototype.sendCommand = function(handler) {
  if(connected) {
    // run stuff, obtain results, send that on:
    handler(false, result);
  } else {
    // output an error, although really we should
    // just try to connect if we're not, and say
    // there's an error only when it actually fails.
    handler(new Error("ohonoes"));
  }
}

and then you call the function as
var MyModule = require('./MyModule');
var mod = ...
mod.sendCommand(function(err, result) {
  // we'll eventually get here, at which point:
  if (err) { return console.error(err); }
  run();
  more();
  code();
  withResult(result);
});


text:
Q: Comparison of two rows based on another data frame Let's start with the main data set:
> dput(tbl_test1)
structure(list(X1 = structure(c(17L, 14L, 20L, 16L, 1L, 2L, 3L,
4L, 15L, 8L, 9L, 10L, 11L, 12L, 13L, 21L, 22L, 23L, 18L, 19L,
5L, 6L, 7L), .Label = c("Astra_1", "Astra_2", "Astra_3", "Astra_4",
"Audi_1", "Audi_2", "Audi_3", "BMW_1", "BMW_2", "BMW_3", "BMW_4",
"BMW_5", "Fiat_1", "Mazda_2", "Mercedes_1", "Nexia_1", "Porsche_1",
"Scania_1", "Scania_2", "Tico_1", "VW_1", "VW_2", "VW_3"), class = "factor"),
    X2 = structure(c(2L, 3L, 10L, 7L, 8L, 12L, 9L, 14L, 11L,
    4L, 5L, 6L, 15L, 13L, 4L, 5L, 9L, 14L, 11L, 1L, 3L, 10L,
    16L), .Label = c("Astra_1", "Astra_3", "Astra_4", "Audi_1",
    "Audi_2", "Audi_3", "BMW_1", "BMW_2", "Mazda_2", "Mercedes_1",
    "Nexia_1", "Porsche_1", "Scania_2", "Tico_1", "VW_2", "VW_3"
    ), class = "factor"), AUC_1 = c(5860133.702, 1296009.939,
    333123.4932, 250348.9407, 1376193.334, 4080502.863, 3777603.233,
    3503973.487, 99101538.62, 231873.8462, 87258.75465, 147430.9913,
    1028986.892, 1451482.832, 8136.72382, 25311.41683, 131352.7137,
    565410.8186, 30196.23792, 70184.82268, 2526321.019, 381643.2138,
    819687.9824), AUC_2 = c(4849720.322, 928980.4715, 320547.6185,
    223287.2029, 1340641.323, 4720329.699, 4369150.434, 3371021.243,
    108591253.3, 266489.7601, 85384.84604, 165726.7626, 1052130.559,
    1470876.65, 9499.927679, 49309.74984, 138482.765, 444600.7911,
    25132.73714, 55453.67019, 2038911.81, 422559.3293, 1445477.433
    ), ratio = c(1.20834467, 1.395088463, 1.03923247, 1.121196994,
    1.02651866, 0.864452935, 0.864608186, 1.039439753, 0.91261069,
    0.87010415, 1.021946618, 0.889602795, 0.978003046, 0.98681479,
    0.856503765, 0.513314647, 0.948513078, 1.271726974, 1.201470327,
    1.265647926, 1.2390536, 0.90317072, 0.567070757), Country = structure(c(1L,
    1L, 2L, 4L, 6L, 6L, 6L, 6L, 5L, 8L, 8L, 8L, 8L, 8L, 7L, 7L,
    7L, 7L, 9L, 9L, 3L, 3L, 3L), .Label = c("France", "Germany",
    "Ireland", "Italy", "Norway", "Poland", "Spain", "Sweden",
    "Ukraine"), class = "factor")), .Names = c("X1", "X2", "AUC_1",
"AUC_2", "ratio", "Country"), class = "data.frame", row.names = c(NA,
-23L))

I would like to compare the cars from first two columns by looking on another table. To explain in more in detail let me put the next table:
> dput(tbl_test2)
structure(list(X = structure(c(17L, 14L, 20L, 16L, 1L, 2L, 3L,
8L, 9L, 10L, 11L, 12L, 4L, 15L, 13L, 21L, 22L, 23L, 18L, 19L,
5L, 6L, 7L), .Label = c("Astra_1", "Astra_2", "Astra_3", "Astra_4",
"Audi_1", "Audi_2", "Audi_3", "BMW_1", "BMW_2", "BMW_3", "BMW_4",
"BMW_5", "Fiat_1", "Mazda_2", "Mercedes_1", "Nexia_1", "Porsche_1",
"Scania_1", "Scania_2", "Tico_1", "VW_1", "VW_2", "VW_3"), class = "factor"),
    X10 = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), X34 = c(0L, 0L,
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 1L, 0L, 1L), X59 = c(0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
    1L, 1L), X84 = c(0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L,
    1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L), X110 = c(0L,
    0L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L,
    0L, 0L, 0L, 0L, 0L, 1L, 0L), X134 = c(0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L), X165 = c(1L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L),
    X199 = c(1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), X234 = c(1L,
    0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L,
    0L, 1L, 0L, 0L, 0L, 0L, 0L), X257 = c(1L, 0L, 0L, 0L, 1L,
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 1L, 0L, 0L,
    0L, 0L, 0L), X362 = c(0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L),
    X433 = c(0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L, 0L), X506 = c(0L,
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L,
    1L, 1L, 1L, 0L, 0L, 0L, 0L), X581 = c(0L, 0L, 0L, 0L, 0L,
    0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L,
    0L, 0L, 0L), X652 = c(0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L,
    0L, 0L, 1L, 0L, 0L, 0L, 0L, 1L, 0L, 1L, 0L, 0L, 0L, 0L),
    X733 = c(0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 1L,
    0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), X818 = c(0L,
    0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L, 0L,
    0L, 0L, 0L, 1L, 0L, 0L, 0L), X896 = c(0L, 0L, 0L, 0L, 0L,
    1L, 1L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L,
    0L, 0L, 0L), X972 = c(0L, 0L, 0L, 0L, 0L, 1L, 1L, 0L, 0L,
    0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L),
    X1039 = c(0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L, 0L, 0L,
    1L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 0L, 0L, 0L)), .Names = c("X",
"X10", "X34", "X59", "X84", "X110", "X134", "X165", "X199", "X234",
"X257", "X362", "X433", "X506", "X581", "X652", "X733", "X818",
"X896", "X972", "X1039"), class = "data.frame", row.names = c(NA,
-23L))

The table above stores the cars from the previous data set in the first column and in the next columns we have two numbers: 0 or 1.
I would like to add new column to the first data which indicates if car from the first column for example Porsche_1 (full name is important. I mean with _) and the car from second column Astra_3 have the number 1 in the same column in data set number 2. That's not correct so we put 0 or NA in this additional column. If both would have the number one in the same column like Porsche_1 and Astra_1 - the number 1 should be put in the additional column.
Desired out: The numbers for the last column were generated randomly!
           X1         X2        AUC_1        AUC_2     ratio Country Comp
1   Porsche_1    Astra_3  5860133.702 4.849720e+06 1.2083447  France  0
2     Mazda_2    Astra_4  1296009.939 9.289805e+05 1.3950885  France  1
3      Tico_1 Mercedes_1   333123.493 3.205476e+05 1.0392325 Germany  1
4     Nexia_1      BMW_1   250348.941 2.232872e+05 1.1211970   Italy  0
5     Astra_1      BMW_2  1376193.334 1.340641e+06 1.0265187  Poland  0
6     Astra_2  Porsche_1  4080502.863 4.720330e+06 0.8644529  Poland  1
7     Astra_3    Mazda_2  3777603.233 4.369150e+06 0.8646082  Poland  0
8     Astra_4     Tico_1  3503973.487 3.371021e+06 1.0394398  Poland  1
9  Mercedes_1    Nexia_1 99101538.620 1.085913e+08 0.9126107  Norway  1
10      BMW_1     Audi_1   231873.846 2.664898e+05 0.8701041  Sweden  0

A: One way to achieve that could be to use mapply and check if any 1 of tbl_test2 (except the first column) in the row that has the first car name in X is also 1 for the row that contains the second car name in X (that is, check if for any column, we have TRUE & TRUE), you get TRUE or FALSE for each pair, which you can then convert into 0/1 with as.integer :
tbl_test1$Comp <- mapply(function(x, y) as.integer(any(unlist(tbl_test2[tbl_test2$X==x, -1]) & unlist(tbl_test2[tbl_test2$X==y, -1]))),
                         x=as.character(tbl_test1$X1),
                         y=as.character(tbl_test1$X2))

head(tbl_test1)
#           X1         X2        AUC_1        AUC_2     ratio Country Comp
#1   Porsche_1    Astra_3  5860133.702 4.849720e+06 1.2083447  France    0
#2     Mazda_2    Astra_4  1296009.939 9.289805e+05 1.3950885  France    0
#3      Tico_1 Mercedes_1   333123.493 3.205476e+05 1.0392325 Germany    1
#4     Nexia_1      BMW_1   250348.941 2.232872e+05 1.1211970   Italy    0
#5     Astra_1      BMW_2  1376193.334 1.340641e+06 1.0265187  Poland    0
#6     Astra_2  Porsche_1  4080502.863 4.720330e+06 0.8644529  Poland    0

Edit
If you want to know the column numbers that match, you can use:
mapply(function(x, y) paste(which(unlist(tbl_test2[tbl_test2$X==x, -1]) & unlist(tbl_test2[tbl_test2$X==y, -1]))+1, collapse=","), x=as.character(tbl_test1$X1), y=as.character(tbl_test1$X2))

A: Using dplyr, you can, on a per-row basis, count the number of matching 1 in your second data.frame for the rows corresponding to the names in X1 and X2, and then find whether or not there is at least one match:
library(dplyr)
tbl_test1 %>% rowwise() %>%
  mutate(nmatch = sum(which(tbl_test2[grep(X1, tbl_test2$X),]==1)
                      %in% which(tbl_test2[grep(X2, tbl_test2$X),]==1)),
         Comp = as.integer(nmatch!=0))

#            X1         X2      AUC_1       AUC_2     ratio Country nmatch  Comp
#        (fctr)     (fctr)      (dbl)       (dbl)     (dbl)  (fctr)  (int) (int)
# 1   Porsche_1    Astra_3  5860133.7   4849720.3 1.2083447  France      0     0
# 2     Mazda_2    Astra_4  1296009.9    928980.5 1.3950885  France      0     0
# 3      Tico_1 Mercedes_1   333123.5    320547.6 1.0392325 Germany      2     1
# 4     Nexia_1      BMW_1   250348.9    223287.2 1.1211970   Italy      0     0
# 5     Astra_1      BMW_2  1376193.3   1340641.3 1.0265187  Poland      0     0
# 6     Astra_2  Porsche_1  4080502.9   4720329.7 0.8644529  Poland      0     0
# 7     Astra_3    Mazda_2  3777603.2   4369150.4 0.8646082  Poland      0     0
# 8     Astra_4     Tico_1  3503973.5   3371021.2 1.0394398  Poland      0     0
# 9  Mercedes_1    Nexia_1 99101538.6 108591253.3 0.9126107  Norway      1     1
# 10      BMW_1     Audi_1   231873.8    266489.8 0.8701041  Sweden      0     0
# ..        ...        ...        ...         ...       ...     ...    ...   ...

Note: the nmatch columns is just a bonus, you could do all in on step and just have Comp of course.


text:
Q: Create index with multi field mapping syntax with NEST 2.x I just can't seem to get the syntax correct for multi field mapping in NEST 2.0--if that's the correct terminology. Every example I've found for mapping seems to be <= the 1.x version of NEST. I'm new to Elasticsearch and NEST, and I've been reading their documentation, but the NEST documentation hasn't been completely updated for 2.x.
Basically, I don't need to index or store the entire type. Some fields I need for indexing only, some fields I'll need to index and retrieve, and some I don't need for indexing, just for retrieval.
MyType
{
    // Index this & allow for retrieval.
    int Id { get; set; }

    // Index this & allow for retrieval.
    // **Also**, in my searching & sorting, I need to sort on this **entire** field, not just individual tokens.
    string CompanyName { get; set; }

    // Don't index this for searching, but do store for display.
    DateTime CreatedDate { get; set; }

    // Index this for searching BUT NOT for retrieval/displaying.
    string CompanyDescription { get; set; }

    // Nest this.
    List<MyChildType> Locations { get; set; }
}

MyChildType
{
    // Index this & allow for retrieval.
    string LocationName { get; set; }

    // etc. other properties.
}

I've have been able to index the entire object and child as-is using the following as an example:
client.Index(item, i => i.Index(indexName));

However, the actual object is a lot larger than this, and I really don't need most of it. I've found this, which looks like what I think I want to do, but in an older version: multi field mapping elasticsearch
I think "mapping" is what I'm going for, but like I said, I'm new to Elasticsearch and NEST and I'm trying to learn the terminology.
Be gentle! :) It's my first time to ask a question on SO. Thanks!

A: In addition to Colin's and Selçuk's answers, you can also fully control the mapping through the fluent (and object initializer syntax) mapping API. Here's an example based on your requirements
void Main()
{
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    var connectionSettings = new ConnectionSettings(pool);

    var client = new ElasticClient(connectionSettings);

    client.Map<MyType>(m => m
        .Index("index-name")
        .AutoMap()
        .Properties(p => p
            .String(s => s
                .Name(n => n.CompanyName)
                .Fields(f => f
                    .String(ss => ss
                        .Name("raw")
                        .NotAnalyzed()
                    )
                )
            )
            .Date(d => d
                .Name(n => n.CreatedDate)
                .Index(NonStringIndexOption.No)
            )
            .String(s => s
                .Name(n => n.CompanyDescription)
                .Store(false)
            )
            .Nested<MyChildType>(n => n
                .Name(nn => nn.Locations.First())
                .AutoMap()
                .Properties(pp => pp
                    /* properties of MyChildType */
                )
            )
        )
    );
}

public class MyType
{
    // Index this & allow for retrieval.
    public int Id { get; set; }

    // Index this & allow for retrieval.
    // **Also**, in my searching & sorting, I need to sort on this **entire** field, not just individual tokens.
    public string CompanyName { get; set; }

    // Don't index this for searching, but do store for display.
    public DateTime CreatedDate { get; set; }

    // Index this for searching BUT NOT for retrieval/displaying.
    public string CompanyDescription { get; set; }

    // Nest this.
    public List<MyChildType> Locations { get; set; }
}

public class MyChildType
{
    // Index this & allow for retrieval.
    public string LocationName { get; set; }

    // etc. other properties.
}

This produces the mapping
{
  "properties": {
    "id": {
      "type": "integer"
    },
    "companyName": {
      "type": "string",
      "fields": {
        "raw": {
          "type": "string",
          "index": "not_analyzed"
        }
      }
    },
    "createdDate": {
      "type": "date",
      "index": "no"
    },
    "companyDescription": {
      "type": "string",
      "store": false
    },
    "locations": {
      "type": "nested",
      "properties": {
        "locationName": {
          "type": "string"
        }
      }
    }
  }
}

Calling .AutoMap() causes NEST to infer the mapping based on the property types and any attributes applied to them. Then .Properties() overrides any of the inferred mappings. For example

*

*CompanyName is mapped as a multi_field with the field companyName analyzed using the standard analyzer and companyName.raw not analyzed. You can reference the latter in your queries using .Field(f => f.CompanyName.Suffix("raw"))

*Locations is mapped as a nested type (automapping by default would infer this as an object type mapping). You can then define any specific mappings for MyChildType using .Properties() inside of the Nested<MyChildType>() call.

A: As far as I can see, you don't have any complex types that you are trying map. So you can easily use NEST attributes to map your objects.
Check this out:
[Nest.ElasticsearchType]
public class MyType
{
    // Index this & allow for retrieval.
    [Nest.Number(Store=true)]
    int Id { get; set; }

    // Index this & allow for retrieval.
    // **Also**, in my searching & sorting, I need to sort on this **entire** field, not just individual tokens.
    [Nest.String(Store = true, Index=Nest.FieldIndexOption.Analyzed, TermVector=Nest.TermVectorOption.WithPositionsOffsets)]
    string CompanyName { get; set; }

    // Don't index this for searching, but do store for display.
    [Nest.Date(Store=true, Index=Nest.NonStringIndexOption.No)]
    DateTime CreatedDate { get; set; }

    // Index this for searching BUT NOT for retrieval/displaying.
    [Nest.String(Store=false, Index=Nest.FieldIndexOption.Analyzed)]
    string CompanyDescription { get; set; }

    [Nest.Nested(Store=true, IncludeInAll=true)]
    // Nest this.
    List<MyChildType> Locations { get; set; }
}

[Nest.ElasticsearchType]
public class MyChildType
{
    // Index this & allow for retrieval.
    [Nest.String(Store=true, Index = Nest.FieldIndexOption.Analyzed)]
    string LocationName { get; set; }

    // etc. other properties.
}

After this declaration, to create this mapping in elasticsearch you need to make a call similar to:
var mappingResponse = elasticClient.Map<MyType>(m => m.AutoMap());

With AutoMap() call NEST will read your attributes from your POCO and create a mapping request accordingly.
Also see "Attribute Based Mapping" section from here.
Cheers!

A: At the time of writing, Nest does not offer a way to map a property in your class to multiple fields in your document mapping using built in attributes. However, it does provide the facilities needed to do anything with your mappings that you could do if you wrote the JSON yourself.
Here's a solution I've put together for my own needs. It shouldn't be hard to use it as the starting point for whatever you need to do.
First, here's an example of the mapping I want to generate
{
   "product":{
      "properties":{
         "name":{
            "type":"string",
            "index":"not_analyzed",
            "fields":{
               "standard":{
                  "type":"string",
                  "analyzer":"standard"
               }
            }
         }
      }
   }
}

The product document would then have the name field, which is indexed but not analyzed, and the name.standard field, which uses the standard analyzer.
The C# class that I generate the mapping from looks like this
[ElasticsearchType]
public class Product
{
    [WantsStandardAnalysisField]
    public string Name { get; set; }
}

Note the WantsStandardAnalysisField attribute. That's a custom attribute with no special properties added. Literally just:
public class WantsStandardAnalysisField : Attribute {}

If I were to use AutoMap as-is, my custom attribute would be ignored and I would get a mapping that has the name field, but not name.standard. Luckily, AutoMap accepts an instance of IPropertyVisitor. A base class called NoopPropertyVisitor implements the interface and does nothing at all, so you can subclass it and override only the methods you care about. When you use a property visitor with AutoMap, it will generate a document mapping for you but give you a chance to modify it before it gets sent to Elastic Search. All we need to do is look for properties marked with our custom attribute and add a field to them.
Here's an example that does that:
public class ProductPropertyVisitor : NoopPropertyVisitor
{
    public override void Visit(IStringProperty type, PropertyInfo propertyInfo, ElasticsearchPropertyAttributeBase attribute)
    {
        base.Visit(type, propertyInfo, attribute);

        var wsaf = propertyInfo.GetCustomAttribute<WantsStandardAnalysisField>();
        if (wsaf != null)
        {
            type.Index = FieldIndexOption.NotAnalyzed;
            type.Fields = new Properties
            {
                {
                    "standard",
                    new StringProperty
                    {
                        Index = FieldIndexOption.Analyzed,
                        Analyzer = "standard"
                    }
                }
            };
        }
    }
}

As you can see, we can do pretty much anything we want with the generated property, including turning off analysis for the main property and adding a new field with its own settings. For fun, you could add a couple properties to the custom attribute allowing you to specify the name of the field you want and the analyzer to use. You could even modify the code to see if the attribute has been added multiple times, letting you add as many fields as you want.
If you were to run this through any method that generates a mapping using AutoMap, such as:
new TypeMappingDescriptor<Product>().AutoMap(new ProductPropertyVisitor())

You'll get the desired multi-field mapping. Now you can customize mappings to your heart's content. Enjoy!

A: I think you have at least 2 possibilities to solve your problem:

*

*On indexing: Create something like a metadata model, which is stored just for retrieving. See the _source field to limit the return to this field.

*On searching: Specify the fields you want to query: if you don`t want to query the CreatedDate, just don't include it in your search.

In my case I am using both of these approaches to get very fast results :-)


text:
Q: Why isn't my media query with a max width of 470px working? If you look at the code, there are two media queries, the one with a max width of 1024 pixels seems to work fine and apply all the styles but the one with a max width of 470 pixels won't work or apply any of the styles. Why is this happening? Any help appreciated.
https://codepen.io/FreemanW/pen/QWwRBMP?editors=1100
@media (max-width: 470px) {
  .banner {
    align-items: flex-end;
  }

  .title-box {
    width: 100%;
  }

  .container {
    width: 100%;
  }
}
 ``

A: Everything within 470px is also within 1024px, so perhaps there's some sort of conflict going on there.
You could try using max-width: 470px and min-width: 471px, thus dividing your options into non-overlapping values :)

A: Be sure that the media-query with the smaller screen-width is at the end.
That works:

@media (max-width: 1024px) {
  h1 {
    color: blue;
  }
}

@media (max-width: 470px) {
  h1 {
    color: red;
  }
}

TEST

That doesn't works:

@media (max-width: 470px) {
  h1 {
    color: red;
  }
}

@media (max-width: 1024px) {
  h1 {
    color: blue;
  }
}

TEST