text:
Q: Induction motor simple power and torque The output power is 100hp and slip is 0.02 and efficiency of 90%,4 pole induction motor
Want to find the shaft torque(output torque).
So I guess to find the torque we use the equation
P(out) = T(out)/w , but i'm not sure w is same with input(?) w.
here is my tried solution
Td = p(out)/w
S= ns(1-s) , 0.02 /(1-0.02) = ns = 0.0204
And find the n
S= ns-n/ns , n= 0.01992
Pg = Tw,
T(out)= 74.6kw/[(2pi/60)n]= 35761

can i use the same w for output power torque? and why?
Also, please check the solution.

A: Torque is given by:
$$
\tau = \frac{P_{shaft}}{\omega}
$$
Where \$P_{shaft}\$ is the output power of the motor (shaft power) and \$\omega\$ is the angular frequency of rotation.
The power supply in my country is 50 Hz, so a 4-pole motor has a synchronous (zero slip) speed of 1,500 RPM. Converting to angular frequency (radians per second), we get
$$ 1,500\ RPM \times \frac{2\pi\  rad.s^{-1}}{60\ RPM} = 157.1\ rad.s^{-1} $$
Slip is 2%, so the motor is running at 98% of synchronous speed :
$$
\omega = 157.1\ rad.s^{-1} \times 0.98 = 153.9\ rad.s^{-1}
$$
The output power of your motor is 100 HP. In metric units that is
$$
P_{shaft} = 100\ HP \times \frac{746\ W}{1\ HP} = 74,600\ W
$$
Giving
$$
\tau = \frac{74,600\ W}{153.9\ rad.s^{-1}} = 484.6\ N.m
$$
Note I have written down the units of every figure I have used. This makes it much easier to spot mistakes.

A: So the key information:
Power = 100HP = 74,570W
Slip = 2%
Efficiency = 90%
Pole = 4
mains freq = 60 (determined from OP initial calc).
sync speed = 1800rpm   (main_freq/(pole/2))*60
Key equations:
P=T \$\omega\$                  P=Power, T= Torque, \$\omega\$ = rotor speed
s = (fs - fr)/fs  (s=slip, fs = slip speed, fr = sync speed)
so the slip speed = 1764rpm.
\$ Via P = T\omega =>  T = P/\omega =>  T = 74570/((1764/60)*2*pi) => T = 403Nm \$


text:
Q: How to load json data on view fields in extjs4 i am working in extjs4. i have view as-
Ext.define('Balaee.view.qb.qbquestion.editWindow',
    {extend:'Ext.form.Panel',
    alias:'widget.editWindow',
    autoScroll:true,
    store:'qb.qbquestioncategoryStore',
    bodyStyle: 'padding: 20px',
    title: '<\center>Update-Question',
    items:[
           {
               xtype:'form',
               items:[{xtype:'hidden',
                        name:'questionId'
                    },
                    {border:false,
                       layout: 'hbox',
                       margin:'10 0 0 50',
                       items:[
                    {
                       margin:'5 0 5 50',
                       xtype:'textfield',
                       fieldLabel: 'Question',
                       name: 'question',
                       width:350,
                       emptyText: 'Enter the Question'
                   },
                    { margin:'5 0 5 10',
                        xtype: 'button',
                        id:'btn5',
                        //scale:'medium',
                        width:50,
                        //name: 'add',
                        text:' Delete  ',
                        action:'delete'
                  }]
                    },

                  {
                       margin:'0 0 5 100',
                       xtype:'textfield',
                       fieldLabel: 'Keyword',
                       name: 'keyword',
                       width:350,
                       emptyText: 'Enter the related word'
                   },
                  { margin:'0 0 5 100',
                       xtype:'combo',
                       fieldLabel: 'Language',
                       width:250,
                        store:'qb.languageStore',
                        name: 'language',
                       //queryMode:'remote',
                       displayField:'language',
                       valueField:'languageId',
                       emptyText: '---Select---'
                   },
                   {
                       margin:'0 0 5 50',
                       xtype:'combo',
                       id:'combo1',
                       fieldLabel: 'Elementary',
                       name: 'Elementary',
                       width:250,
                       store:'qb.qbcomplexityStore',
                       //queryMode:'low',
                       displayField:'complexityl',
                       valueField:'complexityId',
                       emptyText: '---Select---'
                   },
                   { margin:'0 0 5 50',
                       xtype:'combo',
                       id:'combo2',
                       fieldLabel: 'Intermediate',
                       name: 'Intermediate',
                       width:250,
                       store:'qb.qbcomplexityStore',
                       //queryMode:'low',
                       displayField:'complexityl',
                       valueField:'complexityId',
                       emptyText: '---Select---'
                   },
                   { margin:'0 0 5 50',
                       xtype:'combo',
                       id:'combo3',
                       fieldLabel: 'Expert',
                       name: 'Expert',
                       width:250,
                       store:'qb.qbcomplexityStore',
                       //queryMode:'low',
                       displayField:'complexityl',
                       valueField:'complexityId',
                       emptyText: '---Select---'
                     },
                    {
                       margin:'0 0 5 100',
                       xtype:'textfield',
                       fieldLabel: 'Option',
                       name: 'option',
                       width:350,
                       emptyText: 'Enter the option',
                       id:'opts'
                   },
                   {
                       border:false,
                       layout: 'hbox',
                       margin:'7 0 5 100',
                       items:[ { //margin:'0 0 0 15',
                                   xtype: 'checkbox',
                                    fieldLabel: 'isAnswer',
                                   name: 'isAnswer',
                                    id:'anss1'
                               },
                               {
                                     margin:'0 0 0 10',
                                     xtype: 'button',
                                     id:'btn3',
                                     //scale:'medium',
                                     width:50,
                                     //name: 'add',
                                     text:' Add  ',
                                     action:'add'
                              } ] },
                    {
                       margin:'10 0 5 100',
                       xtype:'grid',
                       id:'grid1',
                       //title : 'Educational Details',
                       store:'qb.qbquestionoptionStore',
                       columns: [
                                 {
                                     text: 'Options',
                                     dataIndex: 'option',
                                     flex: 1
                                 },
                                 {
                                     text: 'Answer',
                                     dataIndex: 'isAnswer',
                                     flex: 2.5
                                 }
                       ],
                       height: 100,
                       width: 350
                   },
                   {
                        margin:'0 0 5 200',
                        xtype: 'button',
                        id:'btn4',
                        //scale:'medium',
                        width:50,
                        //name: 'add',
                        text:' Update  ',
                        action:'update'  }]}});

I have json data from server side as-
{"data":[{"questionId":"29","question":"WRHEdsgdRHW","Elementary":"Low","Intermediate":"Low","Expert":"Low","keyword":"WFHRF","language":"english","Category":[{"category":"Main","id":"1"},{"category":"GK","id":"2"}],"optionarray":[{"option":"dfbsddfb"},{"option":"sdfgsd"},{"option":"sdgsd"}]}]}

i want to load this data as by default entry in fields of above view during update functionality.So how to load this data? How to bind optionarray[] of json to grid with id "grid1"?

A: Create a Model for your Form that matches your fields. And then use loadRecord:

loadRecord: Loads an Ext.data.Model into this form (internally just calls
  Ext.form.Basic.loadRecord) See also trackResetOnLoad.

This will bind your model to a form, later on you can use updateRecord to change new data to a form fields. Here is How to use forms and model binding.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Magento model delete function I have Model class which extends Mage_Core_Model_Abstract. I have a resource which extends Mage_Core_Model_Mysql4_Abstract. Now I am deleting from controller with the following code:
public function deleteAction()
{
    $params = $this->getRequest()->getParams();
    $blogpost = $this->_createModel();
    $blogpost->setId($params['id']);
    $blogpost->delete();
    echo 'Post with id ' . $params['id'] . ' is deleted';
}

The problem is there is no error shown when I supply non existing ids. What to do ? Do I have to load that id and check whether it exists or not? or should I use the try/catch. I used try and catch but did not give any results.

A: Of course it does not throw an exception, the DELETE statement gets executed without errors eventually, it only has an affected row count of 0.
Unfortunately the row count gets lost here (Mage_Core_Model_Resource_Db_Abstract):
/**
 * Delete the object
 *
 * @param Varien_Object $object
 * @return Mage_Core_Model_Resource_Db_Abstract
 */
public function delete(Mage_Core_Model_Abstract $object)
{
    $this->_beforeDelete($object);
    $this->_getWriteAdapter()->delete(
        $this->getMainTable(),
        $this->_getWriteAdapter()->quoteInto($this->getIdFieldName() . '=?', $object->getId())
    );
    $this->_afterDelete($object);
    return $this;
}

because the return value of _getWriteAdapter()->delete() is not used anywhere
It looks like you will indeed have to load your model before deleting it, or at least check for its existence via the ressource collection.


text:
Q: How can you load the symbols of a renamed executable that crashed I've built a C++ program in C++ (e.g. app.exe). After compiling and linking I renamed the executable (e.g. app_v1.exe).
However, while running a special case my application crashed. The resulting dump file points to the renamed executable (i.e. app_v1.exe).
Visual studio does not allow me to use the debugging symbols of the original executable. Is there a change that I can do, e.g. edit the dump file so that I can use the debugging symbols of the original executable?


text:
Q: PyQt5 + QtWebEngine get html element? everyone! I want port my project from Qt WebKit to Qt WebEngine! Currently I want to get the html elemnt.
I use PyQt5 + QT 5.8.
My get elment func:
def get_elment(self,selector,func):
    js = '''
        function r()
        {
            var button = document.querySelector("%s");
            return button;
        }
        r();
    '''%selector
    self.wp.runJavaScript(js,func)

I use it :
def print_element(e):
    print "e:%s"%e
browser.get_elment('#u1 > a:nth-child(1)',print_element)

I hope e should be a html element, but it is a dict.
the result:

I search on the web, but could not find the solution. Can anyone help me ? Thanks very much!

A: Thanks for @ekhumoro.

There is no equivalent to QWebElement in Qt WebEngine. All DOM manipulations must be done in Javascript.


text:
Q: detect previous url in javascript or jQuery Is there a way to detect the previous URL that user visited before arrive on my website using javascript or jQuery?
I hope it can be possible avoid using PHP

A: document.referrer

I think is the most common one. There is also the history api

A: You seem to want to get the previous URL when the user directly enters the new URL in the browser without clicking a link. This is not possible in PHP or JavaScript. It would be a significant and quite unnecessary security risk, so browsers will refuse to send it. You can only get it through the referrer if the user clicked a link on the previous website that redirected them to yours.
Frankly, there should be no reason for the new website to know about the previous one unless the user was referred from the previous URL by clicking a link.


text:
Q: Решение квадратного уравнения, написать полностью корректный код для решения любого квадратного уравнения Задача состоит в следующем:
Дано уравнение:
ax2 + bx + c = 0.
Необходимо написать программу, которая по введённым целочисленным параметрам a,b,c решит это уравнение.
На вход даются три целых числа - a,b,c, по модулю не превышающих 1000.
В выходной файл через пробел необходимо вывести количество корней этого уравнения, после этого все корни этого уравнения в порядке неубывания, если этого сделать нельзя, то вывести -1.
Казалось бы, простая задача? Не тут-то было. Я перепробовала все способы, но чтобы ее приняли, необходимо рассмотреть все варианты решения. Вот мой код:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int a, b, c;
    cin >> a >> b >> c;
    int d;
    d = (b * b) - (4 * a * c);
    if (a == 0)
    {
        if (b != 0)
        {
            cout << 1 << " " << (-c / b);
        }
        if (b == 0)
        {
            cout << -1;
        }
    }
    if ((a != 0) and (b == 0) and (c == 0))
    {
        cout << 1 << " " << 0;
    }
    else
    {
        if (d >= 0){
            int x1, x2;
            x1 = (-b + sqrt(d)) / (2 * a);
            x2 = (-b - sqrt(d)) / (2 * a);
            if (x1 == x2)
            {
                cout << 1 << " " << x1;
            }
            if (x1 > x2)
            {
                cout << 2 << " " << x2 << " " << x1;
            }
            if (x2 > x1)
            {
                cout << 2 << " " << x1 << " " << x2;
            }
        }
    }
}

A: Вы делаете расчеты с целыми числами, а это неправильно. Да коэффициенты у вас - целые числа, но результаты операций - нет.
cout << 1 << " " << (-c / b); // неправильно

// должно быть например так
cout << 1 << " " << static_cast<double>(-c) / b;
// или в "старом" стиле с
cout << 1 << " " << double(-c) / b;

Или сразу объявить коэффициенты числами типа double
// аналогично здесь результат с плавающей точкой присваивается целому числу
int x1, x2;
x1 = (-b + sqrt(d)) / (2 * a);
x2 = (-b - sqrt(d)) / (2 * a);

И ещё вы пропустили вариант с отрицательным дискриминантом.
       if (d >= 0)
        {
            double x1 = (-b + sqrt(d)) / (2.0 * a);
            double x2 = (-b - sqrt(d)) / (2.0 * a);
            if (x1 == x2)
                cout << 1 << " " << x1;
            else
            if (x1 > x2)
                cout << 2 << " " << x2 << " " << x1;
            else
                cout << 2 << " " << x1 << " " << x2;
        }
        else // вариант с отрицательным дискриминантом
            cout << -1;


text:
Q: Check if User is Logged into App Store? Objc iOS I need to check if the users have a subscription bought it by In-App Purchase.
The problem is that my API needs to know which user already bought a subscription in order to unlock the Plus content. For an error in the purchase process we couldn't get the receipt of several users.
We know that using Restore Purchase we can get the order receipt but those users don't know that they need to restore it, so in this case we can call restore purchases automatically when the user enter in the dashboard.
The problem now is if the user don't have an apple store account associated in the device, the IAP library show a modal telling to the users that need to sign  in the itunes & apple store, and the idea is avoid show that message to the user that never has signed in the app store.
There is a way to verify if the user is logged into app store?


text:
Q: C++ proper usage, this pointer
Possible Duplicate:
When should I make explicit use of the this pointer?

I'm wondering about the proper usage of the "this" pointer.
I've seen someone create a class constructor with the argument passed variable passed in named 'data'.
However he had a private member variable named 'data' already thus he simply used:
this->data = data;
would have worked to simply use
data = data_in
(if the parameter was named data_in), and no need to invoke the "this" pointer and reference the member type.
Now I'm wondering, is this proper usage? Using this->member to reduce on naming complexity? I mean it works and I see that it accomplishes what was intended but I'm wondering if some of you more experienced C++ guys and girls can say a word or two if this is common practice?
Also, out of curiosity I've instrumented the code just to see what happens under the hood, and it seems the "this" pointer is invoked anyhow. I guess that's the way references to the class object are done anyways.

A: In most cases, specifically dereferencing the this pointer to access a non-static data-member of the class instance is unnecessary, but it can help with naming confusion, especially when the data-members of the class are defined in a separate header file from the code-module.  However, it is necessary to use the this pointer if you are accessing a non-static data-member that is a member of a base-class that is a templated class.  In other words, in a situation like:
template<typename T>
class base_class
{
    protected:
        int a;
};

template<typename T>
class derived_class : public base_class<T>
{
    void function()
    {
        a = 5; //this won't work
        this->a = 5; //this will work
    }
};

you'll note that you must use the this pointer in order to properly resolve the inherited non-static data-member from the template base-class.  This is due to the fact that base_class<T>::a is a dependent name, in this case dependent on the template parameter T, but when used without the this pointer, it is treated as a non-dependent name, and is therefore not looked up in the dependent base-class namespace.  Thus without the specific dereference of the this pointer, you'll end up with a compiler error like "a was not declared in this scope", or something similar.

A: No accessing a class member as:
this->member = something;

is same as accessing the member by itself,
member = something;

The compiler sees both as same and their is no overhead involved. Even if you use the second format the compiler does the same as first format under the hood.
In short, trying to use either of the two formats with aim of improving performance is useless. Ofcourse, You might have to use the first format in some template cases( accessing non-static data members of a templated Base class) but that is not for performance.

A: Essentially identical, except as Jason pointed out.
The nice part is that if you use this-> most editors will code complete for you, saving you typing.

A: It is "correct", but it is also poor practice.  Naming parameters the same as class members is a bad idea.  Intentionally creating naming conflicts is a bad idea.
Scoping operators are designed for when naming conflicts are unavoidable, such as when overriding a base member, or when using two libraries with identifier names chosen independently.  Don't consider them free license for doing stupid things.
Unless you're practicing for an obfuscated code contest.  Then by all means introduce naming collisions.


text:
Q: Filter with ng model not working angular js I have tried to implement a filter on angular tree with all corresponding nodes opening while filtering. Could you help me please ?
Here is the fiddle : http://jsfiddle.net/6c1mg3od/1/
What I have tried so far (without success) :
<treenode ng-repeat="n in nodes|filter:node" node=n></treenode>
<input autofocus focus-me="true" type="text" data-ng-model="node" class="form-control" placeholder="Search..." />

A: This works just as expected (updated your jsfiddle)
http://jsfiddle.net/6c1mg3od/4/
<div class=panel-left>
    <tree nodes="nodes | filter:node"></tree>
    <input type="text" ng-model="node">
</div>


text:
Q: C and D communication I read this in order to do my approach
I have a file: software_pluginInterface.di
Here I declare :
extern (C): void performComputation(char lib[], char func[], void* ptr[], int varNum );
// lib and func will be used later

Then I have the corresponding C file: software_pluginInterface.c,
where I declare :
#include "stdio.h"
#include "string.h"

void performComputation(char lib[], char func[], void * v[], int varNum)
{

  printf("there are %d variables \n", varNum);

}

Then I call this with :
performComputation(A, B, V, to!int(v.count()/3));

A, B are '\0' terminated char arrarys
V is a void pointer array with 6 elements
So I would expect a output like : there are 2 variables
But I am getting : there are 1557197040 variables
I have 64 bit OS, and I compile it all using (as in the other question)
gcc -c software_pluginInterface.c
dmd software.d software_pluginInterface.o

Then I call them using : ./software
PS: according to this page, D ints are same as C ints.

A: In D, an array consists of a pointer to some data, and a length, in C++, it's basically just a pointer. This means that your D function should be declared as:
extern (C): void performComputation(char* lib, char* func, void** ptr, int varNum );


text:
Q: making numerous pointers NULL at the same time This is a C++ class that I have made with n number of pointers.
class SomeClass
{
private:
        int* ptr1;
        int* ptr2;
        ...
        int* ptrn;

private:
        // constructors, destructors, and methods
};

During the initialization stage, I want to make all those pointers point to NULL (or make pointers point to NULL by default when they are declared) rather than doing so:
void SomeClass::MakePtrNull()
{
        ptr1 = NULL;
        ptr2 = NULL;
        ...
        ptrn = NULL;
}

Is there any easy method of accomplishing this goal? I'm just wondering if there are any ways of avoiding typing n lines of ptr = NULL; in my function. Thanks in advance.
ADDED based on the answers that I have received so far:
Unfortunately, those pointers have to be separate, as they are used for different purposes. I made the names of the pointers as such just to make a point of what I'm trying to do, but each pointer has a completely different purpose. I guess I would have to make them point to NULL as I have done already. Thanks for your answers.

A: Why don't you use an array or a vector rather than creating n individually named pointers? Then you can do the nulling in a short for loop.

A: You can do this:
void SomeClass::MakePtrNull()
{
        ptr1 = ptr2 = ptr3 = ... = ptrn = NULL;
}

A: First, the technique that does not work:
Calling memset to set the entire object to zero won't do. First, it'll cause a lot of trouble if your function has one or more virtual functions, and second, a null pointer is not guaranteed to be represented by a bit pattern of all zeros.
What I would probably do in your case is store the pointers in an array or a vector.
Then you can use the std::fill function to set them all to NULL. (Or you could use a loop if you prefer)
Of course, if you need to do this often enough, it may be worth writing a wrapper class which behaves as the pointer, but which sets it to NULL in its default constructor.
Or you could use boost::optional which works essentially like this. (although it is not specific for pointers)

A: I recommend you to do the following, if you have to keep the pointers separately (probably the most pressing need would be if the pointers can have different types)
class SomeClass {
    struct Pointers {
        int* ptr1;
        int* ptr2;
        float* ptrn;
    } ptrs;

public:
    void MakePtrNull();
};

void SomeClass::MakePtrNull()
{
    // clears all pointers at once
    ptrs = Pointers();
}

This does work, because value-initialization for classes that doesn't have a user declared constructor will value initialize all its members. Value initialization of a pointer will create a null pointer.

A: Why not use a default constructor:
SomeClass::SomeClass() : ptr1(NULL), ptr2(NULL), ...
{

}

You could also do:
ptr1 = ptr2 = ptr3 = NULL;

A: Instead of int *, create a smart-pointer-like class which works exactly like a int *, but default-constructs with NULL:
template <typename T>
class MyPointer {
    T *p;

public:
    MyPointer() : p(NULL) { }
    MyPointer(T *o) : p(o) { }
    operator T*() const { return p; }
    // ...and the rest of the traditional smart-pointer operators
};

Then, use it in your class:
class SomeClass
{
private:
        MyPointer<int> ptr1;
        MyPointer<int> ptr2;
        ...
        MyPointer<int> ptrn;

private:
        // constructors, destructors, and methods
};

Every variable of the MyPointer<int> type will be automatically initialized correctly in SomeClass's constructors, without the need for any extra typing. If you did not forget or incorrectly implement any of MyPointer's methods, it will act exactly like a normal pointer, and have the exact same size and performance.

A: You could put the pointers into a struct and then memset() the struct when needed.  The pointers are still separated, but you have the means of targeting them as a single unit without affecting the rest of your class.  For example:
struct MyPointers
{
    int* ptr1;
    int* ptr2;
    ...
    int* ptrn;
};

class SomeClass
{
private:
    MyPointers ptrs;
    ...
};

void SomeClass::MakePtrNull()
{
    memset(&ptrs, 0, sizeof(ptrs));
}

A: Use a vector for this (because by the sounds of it you won't need to ever edit the list in the future - and you need random access). You can do it like this:
class PointerList
{
private:
    typedef std::vector<int*> IntPtrVector;
    IntPtrVector m_ptrVec;

public:
    PointerList()
    {
        m_ptrVec.reserve(5);
        for (int i = 0; i < 5; i++)
            m_ptrVec.push_back(NULL);
    }

    int* getPointer(int index)
    {
        return m_ptrVec[index];
    }

    void setPointer(int index, int* ptr)
    {
        assert(index <= 4);
        m_ptrVec[index] = ptr;
    }
};

EDIT
Though to be honest this reeks of ghettoness. Are you sure your problem requires this solution? If you elaborate more on your specific problem, in another question perhaps, I'm sure you can get some better answer on how to accomplish what you want more elegantly - rather then by creating a second problem.


text:
Q: Prove that $I-T$ is an isomorphism if $T:V \to V$ and $T^3=0$ and find $(I-T)^{-1}$
Given a linear map of finite dimension $T:V \to V$ and $T^3=0$ and $\exists v \in V| T^2(v) \neq 0$ prove that $I-T$ is an isomorphism and find $(I-T)^{-1}$.

We can think of the identity $(I-T^3)=(I-T)(I+T+T^2)$ and because $T^3=0$ then $(I-T)(I+T+T^2)=I$ therefore $I-T$ is invertible and $(I-T)^{-1}=(I+T+T^2)$.
This means that $\text{ker}T=\{0\}$ because for any $v \in V$ there's only the trivial solution to $Ax=v$.
My question is because the linear map is not actually defined (we don't know if it's $\mathbb F^n\to \mathbb F^m$) how do we know that the matrix $A$ exists such that $Ax=v$? Is it because we're guaranteed a unique representation matrix for any linear map?

A: You need no matrix. Your computation is right:
$$
(I-T)(I+T+T^2)=I-T+T-T^2+T^2-T^3=I
$$
so $(I-T)^{-1}=I+T+T^2$. Since also $(I+T+T^2)(I-T)=I$, you don't even have to invoke finite dimension in order to conclude $I-T$ is an isomorphism, because you found its inverse.
The assumption that $T^2\ne0$ is redundant. It can be used to show that, if $\dim V=3$, then $\{v,T(v),T^2(v)\}$ is a basis of $V$ as soon as $T^2(v)\ne0$.
Note also that $\ker T\ne\{0\}$, otherwise $T$ would be injective (and surjective in case $V$ is finite dimensional) and $T^3\ne0$.


text:
Q: How to turn on and off aeroplane mode via termux-api? I had  checked this
https://github.com/termux/termux-api/issues/138
but no use

A: Changing the state of the Airplane Mode Settings toggle is facilitated by a Special Android API which accesses and Modifies System Settings, which is NOT a part of Termux. Until the devs themselves introduce a command to do so, you will need superuser i.e. root privileges to do so. I hope the svc commands will help.


text:
Q: What's the better database design: more tables or more columns? A former coworker insisted that a database with more tables with fewer columns each is better than one with fewer tables with more columns each.  For example rather than a customer table with name, address, city, state, zip, etc. columns, you would have a name table, an address table, a city table, etc.
He argued this design was more efficient and flexible.  Perhaps it is more flexible, but I am not qualified to comment on its efficiency.  Even if it is more efficient, I think those gains may be outweighed by the added complexity.
So, are there any significant benefits to more tables with fewer columns over fewer tables with more columns?

A: I have a few fairly simple rules of thumb I follow when designing databases, which I think can be used to help make decisions like this....

*

*Favor normalization. Denormalization is a form of optimization, with all the requisite tradeoffs, and as such it should be approached with a YAGNI attitude.

*Make sure that client code referencing the database is decoupled enough from the schema that reworking it doesn't necessitate a major redesign of the client(s).

*Don't be afraid to denormalize when it provides a clear benefit to performance or query complexity.

*Use views or downstream tables to implement denormalization rather than denormalizing the core of the schema, when data volume and usage scenarios allow for it.

The usual result of these rules is that the initial design will favor tables over columns, with a focus on eliminating redundancy.  As the project progresses and denormalization points are identified, the overall structure will evolve toward a balance that compromises with limited redundancy and column proliferation in exchange for other valuable benefits.

A: It depends on your database flavor.  MS SQL Server, for example, tends to prefer narrower tables.  That's also the more 'normalized' approach.  Other engines might prefer it the other way around.  Mainframes tend to fall in that category.

A: A fully normalized design (i.e, "More Tables") is more flexible, easier to maintain, and avoids duplication of data, which means your data integrity is going to be a lot easier to enforce.
Those are powerful reasons to normalize.  I would choose to normalize first, and then only denormalize specific tables after you saw that performance was becoming an issue.
My experience is that in the real world, you won't reach the point where denormalization is necessary, even with very large data sets.

A: Each table should only include columns that pertain to the entity that's uniquely identified by the primary key. If all the columns in the database are all attributes of the same entity, then you'd only need one table with all the columns.
If any of the columns may be null, though, you would need to put each nullable column into its own table with a foreign key to the main table in order to normalize it. This is a common scenario, so for a cleaner design, you're likley to be adding more tables than columns to existing tables. Also, by adding these optional attributes to their own table, they would no longer need to allow nulls and you avoid a slew of NULL-related issues.

A: The multi-table database is a lot more flexible if any of these one to one relationships may become one to many or many to many in the future.  For example, if you need to store multiple addresses for some customers, it's a lot easier if you have a customer table and an address table.  I can't really see a situation where you might need to duplicate some parts of an address but not others, so separate address, city, state, and zip tables may be a bit over the top.

A: Like everything else: it depends.
There is no hard and fast rule regarding column count vs table count.
If your customers need to have multiple addresses, then a separate table for that makes sense. If you have a really good reason to normalize the City column into its own table, then that can go, too, but I haven't seen that before because it's a free form field (usually).
A table heavy, normalized design is efficient in terms of space and looks "textbook-good" but can get extremely complex. It looks nice until you have to do 12 joins to get a customer's name and address. These designs are not automatically fantastic in terms of performance that matters most: queries.
Avoid complexity if possible. For example, if a customer can have only two addresses (not arbitrarily many), then it might make sense to just keep them all in a single table (CustomerID, Name, ShipToAddress, BillingAddress, ShipToCity, BillingCity, etc.).
Here's Jeff's post on the topic.

A: There are advantages to having tables with fewer columns, but you also need to look at your scenario above and answer these questions:
Will the customer be allowed to have more than 1 address? If not, then a separate table for address is not necessary. If so, then a separate table becomes helpful because you can easily add more addresses as needed down the road, where it becomes more difficult to add more columns to the table.

A: It doesn't sound so much like a question about tables/columns, but about normalization. In some situations have a high degree of normalization ("more tables" in this case) is good, and clean, but it typically takes a high number of JOINs to get relevant results. And with a large enough dataset, this can bog down performance.
Jeff wrote a little about it regarding the design of StackOverflow. See also the post Jeff links to by Dare Obasanjo.

A: I would argue in favor of more tables, but only up to a certain point.  Using your example, if you separated your user's information into two tables, say USERS and ADDRESS, this gives you the flexibility to have multiple addresses per user.  One obvious application of this is a user who has separate billing and shipping addresses.
The argument in favor of having a separate CITY table would be that you only have to store each city's name once, then refer to it when you need it.  That does reduce duplication, but in this example I think it's overkill.  It may be more space efficient, but you'll pay the price in joins when you select data from your database.

A: i would consider normalizing as the first step, so cities, counties, states, countries would be better as separate columns... the power of SQL language, together with today DBMS-es allows you to group your data later if you need to view it in some other, non-normalized view.
When the system is being developed, you might consider 'unnormalizing' some part if you see that as an improvement.

A: I think balance is in order in this case.  If it makes sense to put a column in a table, then put it in the table, if it doesn't, then don't.  Your coworkers approach would definately help to normalize the database, but that might not be very useful if you have to join 50 tables together to get the information you need.
I guess what my answer would be is, use your best judgement.

A: There are many sides to this, but from an application efficiency perspective mote tables can be more efficient at times.  If you have a few tables with a bunch of columns every time the db as to do an operation it has a chance of making a lock, more data is made unavailable for the duration of the lock.  If locks get escalated to page and tables (well hopefully not tables :) ) you can see how this can slow down the system.

A: Hmm.
I think its a wash and depends on your particular design model. Definitely factor out entities that have more than a few fields out into their own table, or entities whose makeup will likely change as your application's requirements changes (for instance - I'd factor out address anyways, since it has so many fields, but I'd especially do it if you thought there was any chance you'd need to handle foreign country addresses, which can be of a different form. The same with phone numbers).
That said, when you're got it working, keep an eye out on performance. If you've spun an entity out that requires you to do large, expensive joins, maybe it becomes a better design decision to spin that table back into the original.

A: When you design your database, you should be as close as possible from the meaning of data and NOT your application need !
A good database design should stand over 20 years without a change.
A customer could have multiple adresses, that's the reality. If you decided that's your application is limited to one adresse for the first release, it's concern the design of your application not the data !
It's better to have multiple table instead of multiple column and use view if you want to simplify your query.
Most of time you will have performance issue with a database it's about network performance (chain query with one row result, fetch column you don't need, etc) not about the complexity of your query.

A: There are huge benefits to queries using as few columns as possible. But the table itself can have a large number. Jeff says something on this as well.
Basically, make sure that you don't ask for more than you need when doing a query - performance of queries is directly related to the number of columns you ask for.

A: I think you have to look at the kind of data you're storing before you make that decision. Having an address table is great but only if the likelihood of multiple people sharing the same address is high. If every person had different addresses, keeping that data in a different table just introduces unnecessary joins.
I don't see the benefit of having a city table unless cities in of themselves are entities you care about in your application. Or if you want to limit the number of cities available to your users.
Bottom line is decisions like this have to take the application itself into considering before you start shooting for efficiency. IMO.

A: First, normalize your tables. This ensures you avoid redundant data, giving you less rows of data to scan, which improves your queries. Then, if you run into a point where the normalized tables you are joining are causing the query to take to long to process (expensive join clause), denormalize where more appropriate.

A: Good to see so many inspiring and well based answers.
My answer would be (unfortunately): it depends.
Two cases:
* If you create a datamodel that is to be used for many years and thus possibly has to adept many future changes: go for more tables and less rows and pretty strict normalization.
* In other cases you can choose between more tables-less rows or less tables-more rows. Especially for people relatively new to the subject this last approach can be more intuitive and easy to comprehend.
The same is valid for the choosing between the object oriented approach and other options.


text:
Q: How to use python to delete a column and rows in excel, that contains certain values Just trying to get python to open a file,  read a file,  do value set in which if the data that has a 1.00 and has another value thats over 0.93 in that row/column then it  gets deleted, if not then go over row/column to the next row/column, both files are closed, then rename new file into original file

A: There is a package named xlrd that you can use to read data from excel file and modify/delete to suit your need.


text:
Q: Ubuntu 21.10: Unable to Boot - Unable to mount root FS on unknown-block(0,0) I recently updated to Ubuntu 21.10 from 21.04 and after rebooting, I get the following error:

I am able to boot using am older kernel version and from searching, I have running sudo dpkg --configure -a and sudo update-initramfs -u including for the problematic Kernel version but I am still unable to boot using the latest kernel.
Any idea on how I can resolve this?

A: I ended up resolving the issue by installing the package linux-generic-hwe-20.04 through the command line with the command sudo apt install linux-generic-hwe-20.04 in a terminal window.
It seems like there were some problems which occurred during the update and some packages were missing.


text:
Q: Autofac - resolving component with parameters dynamically I have a class that takes an interface as a constructor argument. There are two implementations of this interface and I want to decide what implementation to use at runtime based on a variable.
The problem is that the class above is deep in an object heirarchy that is resolved by Autofac and so I can't pass in the argument.
Somehing like below is what I am trying to achieve.
public interface IInterface1 {}
public interface IInterface2 {}

public class Class1 : IInterface2
{
    public Class1(IInterface1 interface1)
    {
    }
}

public class Class2
{
    public Class2(IInterface2 interface2)
    {
    }
}

public class Class3
{
    public void GetClass2Instance(string interface1ImplementationToChoose)
    {
        // want to change which implementation of IInterface1 is resolved based on the interface1ImplementationToChoose variable
        var class2 = container.Resolve<Class2>();
    }
}

Any ideas?
UPDATE:
To clarify, this is an existing object hierarchy that is used by existing applications that work fine. Also, the object model is much larger than the one shown in this example. As a result I don't really want to have to pass down a factory to each constructor in the object graph to be used by a class deep in that graph.
Is there a way of getting a different implementation of IInterface1 passed into Class1 without Class2 knowing anything about it?
Thanks

A: Yes, inject a factory that hides how the types are chosen:
public class Class3
{
   private Func<string, Class2> _class2Factory;
   public Class3(Func<string, Class2> class2Factory)
   {
        _class2Factory = class2Factory;
   }

   public void GetClass2Instance(string interface1ImplementationToChoose)
   {
       var class2 = _class2Factory(interface1ImplementationToChoose);
   }
}

And then the container setup, something along these lines:
builder.RegisterType<Implementation1>().Named("imp1").As<IInterface1>();
builder.RegisterType<Implementation2>().Named("imp2").As<IInterface1>();
builder.Register<Func<string, Class2>>(c =>
    {
        var context = c.Resolve<IComponentContext>();
        return imp => new Class2(context.Resolve<IInterface1>(imp));
    });
builder.RegisterType<Class3>();

You can now use Class3 like this:
public class Class4
{
     public Class4(Class3 class3)
     {
         var class2with1 = class3.GetClass2Instance("imp1");
         var class2with2 = class3.GetClass2Instance("imp2");
     }
}

NOTE: I have assumed that you meant that Class2 should be injected with varying implementations of the same interface IInterface1. Your sample is a bit confusing since you are showing two classes that implements different interfaces.


text:
Q: RegExp to match anyname/anynamewithid/date/string I want to write a regular expression to match the given pattern
anyname/anyname2/anydate/string
anyname: It must accept valid names including underscore (_)
anyname2: It must accept valid names including underscore(_) or hiffen (-)
anydate: The date must be in the format like 'yyyy-mm-dd'. Ex: 2016-12-10
string: This string contains predefined strings. it needs to match only the required characters like, [computer],[desktop],[laptop]. Other than these 3, it should not match any other.
Note: The expression must also match '/' as in the above mentioned pattern

A: Your requirements aren't terribly clear, but if I understand them correctly, then something like the following should work:
\w+/[\w\-]+/\d{4}-[01]\d-[0-3]\d/(computer|desktop|laptop)


text:
Q: Sequence contains more than one element? Using ASP.NET MVC5 I'm getting this error:
System.InvalidOperationException: Sequence contains more than one element
   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
   at System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
   at System.Data.Entity.Internal.Linq.DbQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
   at System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](DbSet`1 set, IEnumerable`1 identifyingProperties, InternalSet`1 internalSet, TEntity[] entities)
   at System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate[TEntity](IDbSet`1 set, Expression`1 identifierExpression, TEntity[] entities)
   at ArtistDatabase.Migrations.Configuration.Seed(ArtistDBContext context) in C:\Users\Will\Desktop\ArtistDatabase\ArtistDatabase\Migrations\Configuration.cs:line 196
   at System.Data.Entity.Migrations.DbMigrationsConfiguration`1.OnSeed(DbContext context)
   at System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
   at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
   at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
   at System.Data.Entity.Migrations.DbMigrator.<>c__DisplayClassc.<Update>b__b()
   at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
   at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
   at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
   at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run()
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
   at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force)
   at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0()
   at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Sequence contains more than one element

These are my two modals, I'm new to this, but I'm not sure if it's because of them both having "Name" and "Picture", or because of the "ArtistID" in the Artwork modal, though it's supposed to be a foreign key.
Artists
public class Artist
{
    public int ArtistID { get; set; }
    //----------------------------------------------------------------------------------------------
    [Required,StringLength(60, MinimumLength = 3), Display(Name = "Artist")]
    public string Name { get; set; }
    //----------------------------------------------------------------------------------------------
    [DataType(DataType.ImageUrl)]
    public string Picture { get; set; }
    //----------------------------------------------------------------------------------------------
    [System.ComponentModel.DataAnnotations.Schema.Column(TypeName = "datetime2")]
    [Display(Name = "Date of Birth"),DataType(DataType.Date),DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
    public DateTime BirthDate { get; set; }
    //----------------------------------------------------------------------------------------------
    [Required,StringLength(30)]
    public string Nationality { get; set; }
    //----------------------------------------------------------------------------------------------
    [Display(Name = "Style/Movement")]
    public string ArtStyle { get; set; }
    //----------------------------------------------------------------------------------------------
    [DataType(DataType.MultilineText)]
    public string Info { get; set; }
    //----------------------------------------------------------------------------------------------
    [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
    [StringLength(5)]
    public string Rating { get; set; }
    //----------------------------------------------------------------------------------------------
    [Display(Name = "Famous work: "),DataType(DataType.ImageUrl)]
    public string Artwork1 { get; set; }
    //----------------------------------------------------------------------------------------------
    [Display(Name = " "), DataType(DataType.ImageUrl)]
    public string Artwork2 { get; set; }
    //----------------------------------------------------------------------------------------------
    [Display(Name = " "), DataType(DataType.ImageUrl)]
    public string Artwork3 { get; set; }
    //----------------------------------------------------------------------------------------------
    public virtual ICollection<Artwork> Artworks { get; set; }
}

public class ArtistDBContext : DbContext
{
    public DbSet<Artist> Artists { get; set; }
    public DbSet<Artwork> Artworks { get; set; }
}

Artwork
public class Artwork
    {
        public int ArtworkID { get; set; }
        //------------------------------------------------------------------------
        //foreign key for Artists
        public int ArtistID { get; set; }
        //------------------------------------------------------------------------
        [StringLength(60), Display(Name = "Artist")]
        public string Name { get; set; }
        //------------------------------------------------------------------------
        [Required, DataType(DataType.ImageUrl)]
        public string Picture { get; set; }
        //------------------------------------------------------------------------
        [DataType(DataType.MultilineText)]
        public string Info { get; set; }
        //------------------------------------------------------------------------
        public virtual Artist Artist { get; set;}
    }

Migration Artwork(1)
public override void Up()
    {
        DropPrimaryKey("dbo.Artists");
        DropColumn("dbo.Artists", "ID");
        CreateTable(
            "dbo.Artworks",
            c => new
                {
                    ArtworkID = c.Int(nullable: false, identity: true),
                    ArtistID = c.Int(nullable: false),
                    Name = c.String(),
                    Info = c.String(),
                })
            .PrimaryKey(t => t.ArtworkID)
            .ForeignKey("dbo.Artists", t => t.ArtistID, cascadeDelete: true)
            .Index(t => t.ArtistID);
        AddColumn("dbo.Artists", "ArtistID", c => c.Int(nullable: false, identity: true));
        AddPrimaryKey("dbo.Artists", "ArtistID");
    }

    public override void Down()
    {
        DropForeignKey("dbo.Artworks", "ArtistID", "dbo.Artists");
        DropIndex("dbo.Artworks", new[] { "ArtistID" });
        DropPrimaryKey("dbo.Artists");
        DropColumn("dbo.Artists", "ArtistID");
        DropTable("dbo.Artworks");
        AddColumn("dbo.Artists", "ID", c => c.Int(nullable: false, identity: true));
        AddPrimaryKey("dbo.Artists", "ID");
    }

Migration ArtworkAnnotations(2)
public override void Up()
    {
        AlterColumn("dbo.Artworks", "Name", c => c.String(nullable: false, maxLength: 60));
    }

    public override void Down()
    {
        AlterColumn("dbo.Artworks", "Name", c => c.String());
    }

Migration Picture(3)
public override void Up()
    {
        AddColumn("dbo.Artworks", "Picture", c => c.String());
    }

    public override void Down()
    {
        DropColumn("dbo.Artworks", "Picture");
    }

Config.cs
nternal sealed class Configuration : DbMigrationsConfiguration<ArtistDatabase.Models.ArtistDBContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
    }

    protected override void Seed(ArtistDatabase.Models.ArtistDBContext context)
    {
        context.Artists.AddOrUpdate(i => i.Name,
            new Artist
            {
                ArtistID = 1,
                Name = "Pablo Ruiz y Picasso",
                Picture = "http://a5.files.biography.com/image/upload/c_fit,cs_srgb,dpr_1.0,h_1200,q_80,w_1200/MTE1ODA0OTcxNzU0MDk2MTQx.jpg",
                BirthDate = DateTime.Parse("25-10-1881"),
                Nationality = "Spanish",
                ArtStyle = "Cubism, Surrealism",
                Info = "Picasso was a Spanish painter, sculptor and ceramicist, among other things. He spent most of his adult life in France, " +
                " and is regarding as one of the greatest and most influential artists of the 20th century. He is known as co-founding of the" +
                " 'Cubist' movement; the invention of constructed sculpture, also being the co-inventor of collage, and for the wide variety" +
                " of styles that he helped develop and explore. Picasso, Henri Matisse and Marcel Duchamp are regarded as the three artists" +
                " who most defined the revolutionary developments in the plastic arts in the opening decades of the 20th century, responsible" +
                " for significant developments in painting, sculpture, printmaking and ceramics. Picasso demonstrated extraordinary artistic" +
                " talent in his early years, painting in a naturalistic manner through his childhood and adolescence.During the first decade" +
                " of the 20th century, his style changed as he experimented with different theories, techniques, and ideas.His work is often" +
                " categorized into periods.While the names of many of his later periods are debated, the most commonly accepted periods in his" +
                " work are the Blue Period(1901–1904), the Rose Period(1904–1906), the African - influenced Period(1907–1909)," +
                " Analytic Cubism(1909–1912),and Synthetic Cubism(1912–1919),also referred to as the Crystal period. Exceptionally prolific" +
                " throughout the course of his long life, Picasso achieved universal renown and immense fortune for his revolutionary artistic" +
                " accomplishments, and became one of the best - known figures in 20th - century art.",
                Artwork1 = "https://s-media-cache-ak0.pinimg.com/originals/34/c4/8c/34c48c9178f215e2670feec774036803.jpg",
                Artwork2 = "http://paintingandframe.com/uploadpic/pablo_picasso/big/les_demoiselles_d_avignon_c_1907.jpg",
                Artwork3 = "http://www.pablopicasso.org/images/paintings/blue-nude.jpg"
            },

            new Artist
            {
                ArtistID = 2,
                Name = "Leonardo da Vinci",
                Picture = "http://www.leonardodavinci.net/images/leonardo-da-vinci.jpg",
                BirthDate = DateTime.Parse("15-04-1452"),
                Nationality = "Italian",
                ArtStyle = "High Renaissance",
                Info = "Leonardo di ser Piero da Vinci was an Italian polymath whose areas of interest included invention, painting," +
                " sculpting, architecture, science, music, mathematics, engineering, literature, anatomy, geology, astronomy, botany, writing, history," +
                " and cartography. He has been variously called the father of palaeontology, ichnology, and architecture, and is widely considered one" +
                " of the greatest painters of all time. Sometimes credited with the inventions of the parachute, helicopter and tank, he epitomised" +
                " the Renaissance humanist ideal.Many historians and scholars regard Leonardo as the prime exemplar of the 'Universal Genius' or " +
                "'Renaissance Man', an individual of 'unquenchable curiosity' and 'feverishly inventive imagination'. According to art historian Helen" +
                " Gardner, the scope and depth of his interests were without precedent in recorded history, and 'his mind and personality seem to us" +
                " superhuman, while the man himself mysterious and remote'. Marco Rosci notes that while there is much speculation regarding his life" +
                " and personality, his view of the world was logical rather than mysterious, and that the empirical methods he employed were unorthodox" +
                " for his time. Leonardo was, and is, renowned primarily as a painter. Among his works, the Mona Lisa is the most famous and most" +
                " parodied portrait and The Last Supper the most reproduced religious painting of all time, their fame approached only by Michelangelo's" +
                " The Creation of Adam. Leonardo's drawing of the Vitruvian Man is also regarded as a cultural icon, being reproduced on items as" +
                " varied as the euro coin, textbooks, and T-shirts. Perhaps fifteen of his paintings have survived. Nevertheless, these few works," +
                " together with his notebooks, which contain drawings, scientific diagrams, and his thoughts on the nature of painting, compose a" +
                " contribution to later generations of artists rivalled only by that of his contemporary, Michelangelo.",
                Artwork1 = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg/402px-Mona_Lisa,_by_Leonardo_da_Vinci,_from_C2RMF_retouched.jpg",
                Artwork2 = "https://upload.wikimedia.org/wikipedia/commons/2/23/Leonardo_da_Vinci_-_Last_Supper_(copy)_-_WGA12732.jpg",
                Artwork3 = "http://blog.world-mysteries.com/wp-content/uploads/2011/01/vitruvian_man_mixed.jpg"
            },

            new Artist
            {
                ArtistID = 3,
                Name = "Georgia O'Keeffe",
                Picture = "http://1874.img.pp.sohu.com.cn/images/blog/2008/11/16/20/26/11e4d90ce26g213.jpg",
                BirthDate = DateTime.Parse("15-11-1887"),
                Nationality = "American",
                ArtStyle = "American Modernism",
                Info = "Georgia Totto O'Keeffe was an American artist. She is best known for her paintings of enlarged flowers, New York skyscrapers," +
                " and New Mexico landscapes. O'Keeffe has been recognized as the 'Mother of American modernism'. O'Keeffe studied at the School of the" +
                " Art Institute of Chicago from 1905 to 1906. In 1907, she attended the Art Students League in New York City, where she studied under" +
                " William Merritt Chase. In 1908, she won the League's William Merritt Chase still-life prize for her oil painting Dead Rabbit with" +
                " Copper Pot. Her prize was a scholarship to attend the League's outdoor summer school in Lake George, New York. While in the city" +
                " in 1908, O'Keeffe attended an exhibition of Rodin's watercolors at the gallery 291, owned by her future husband, photographer Alfred" +
                " Stieglitz. O'Keeffe abandoned the idea of pursuing a career as an artist in late 1908, claiming that she could never distinguish" +
                " herself as an artist within the mimetic tradition which had formed the basis of her art training. She took a job in Chicago as" +
                " a commercial artist. She did not paint for four years, and said that the smell of turpentine made her sick. She was inspired to" +
                " paint again in 1912, when she attended a class at the University of Virginia Summer School, where she was introduced to the innovative" +
                " ideas of Arthur Wesley Dow by Alon Bement. Dow encouraged artists to express themselves using line, color, and shading" +
                " harmoniously. From 1912-14, she taught art in the public schools in Amarillo in the Texas Panhandle. She attended Teachers College" +
                " of Columbia University from 1914–15, where she took classes from Dow, who greatly influenced O'Keeffe's thinking about the process of" +
                " making art. She served as a teaching assistant to Bement during the summers from 1913–16 and taught at Columbia College, Columbia," +
                " South Carolina in late 1915, where she completed a series of highly innovative charcoal abstractions. After further course work at" +
                " Columbia in early 1916 and summer teaching for Bement, she took a job as head of the art department at West Texas State Normal College" +
                " from late 1916 to February 1918, the fledgling West Texas A&M University in Canyon just south of Amarillo. While there, she often" +
                " visited the Palo Duro Canyon, making its forms a subject in her work.",
                Artwork1 = "http://www.georgiaokeeffe.net/images/paintings/rams-head.jpg",
                Artwork2 = "https://learnodo-newtonic.com/wp-content/uploads/2015/09/Red-Canna-1924-Georgia-OKeeffe.jpg",
                Artwork3 = "http://www.themasterpiececards.com/hs-fs/hub/40667/file-25876050-jpg/images/okeeffe_jack_2_from_nga-resized-600.jpg?t=1465250810631"
            },

            new Artist
            {
                ArtistID = 4,
                Name = "Vincent van Gogh",
                Picture = "http://site.artsheaven.com/blog/wp-content/uploads/2015/10/vincent.jpg",
                BirthDate = DateTime.Parse("30-03-1853"),
                Nationality = "Dutch",
                ArtStyle = "Post-Impressionism",
                Info = "Vincent Willem van Gogh was a Dutch painter who is among the most famous and influential figures in the history of Western art." +
                " In just over a decade he created about 2100 artworks, including around 860 oil paintings, most of them in the last two years of his" +
                " life. They include landscapes, still lifes, portraits and self-portraits, and are characterised by bold, symbolic colours, and" +
                " dramatic, impulsive and highly expressive brushwork that contributed to the foundations of modern art. He sold only one painting" +
                " during his lifetime and became famous after his suicide at age 37, which followed years of poverty and mental illness. Van Gogh's" +
                " early works, mostly still lifes and depictions of peasant labourers, contain few signs of the vivid colour that distinguished his" +
                " later work. In 1886 he moved to Paris and discovered the French Impressionists. As his work developed he created a new approach to" +
                " still lifes and local landscapes. His paintings grew brighter in colour as he developed a style that became fully realised during his" +
                " stay in Arles in the south of France in 1888. He lived there in the Yellow House and, with the French artist Paul Gauguin, developed a" +
                " concept of colour that symbolised inner emotion. During this period he broadened his subject matter to include olive trees, cypresses," +
                " wheat fields and sunflowers. In Nuenen, Van Gogh focused on painting and drawing. Working outside and very quickly, he completed" +
                " sketches and paintings of weavers and their cottages. In August 1884, Margot Begemann, a neighbour's daughter and ten years" +
                " his senior, began joining him on his painting forays; she fell in love, and he reciprocated, though less enthusiastically. They" +
                " decided to marry, but the idea was opposed by both families, following which Margot took an overdose of strychnine. She was saved" +
                " when Van Gogh rushed her to a nearby hospital. On 26 March 1885, his father died of a heart attack. Van Gogh painted several" +
                " groups of still lifes in 1885. During his two - year stay in Nuenen, he completed numerous drawings and watercolours, and nearly" +
                " 200 oil paintings.His palette consisted mainly of sombre earth tones, particularly dark brown, and showed no sign of the vivid colours" +
                " that distinguish his later work.Considered a madman and a failure in his lifetime,Van Gogh exists in the public imagination as the" +
                " quintessential misunderstood genius, the artist 'where discourses on madness and creativity converge'.His reputation began to grow" +
                " in the early 20th century as elements of his painting style came to be incorporated by the Fauves and German Expressionists.He attained" +
                " widespread critical, commercial and popular success over the ensuing decades, and is remembered as an important but tragic painter," +
                " whose troubled personality typifies the romantic ideal of the tortured artist.",
                Artwork1 = "https://upload.wikimedia.org/wikipedia/commons/9/94/Starry_Night_Over_the_Rhone.jpg",
                Artwork2 = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Vincent_van_Gogh_-_De_slaapkamer_-_Google_Art_Project.jpg/1280px-Vincent_van_Gogh_-_De_slaapkamer_-_Google_Art_Project.jpg",
                Artwork3 = "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b4/Vincent_Willem_van_Gogh_128.jpg/175px-Vincent_Willem_van_Gogh_128.jpg"
            },

            new Artist {
                ArtistID = 5,
                Name = "Salvador Dali",
                Picture = "https://s-media-cache-ak0.pinimg.com/originals/4b/78/e7/4b78e72934aa5cdcb6a8bff7b23b4b51.jpg",
                BirthDate = DateTime.Parse("11-05-1904"),
                Nationality = "Spanish",
                ArtStyle = "Cubism, Dada, Surrealism",
                Info = "",
                Artwork1 = "https://upload.wikimedia.org/wikipedia/en/4/43/Dali_Elephants.jpg",
                Artwork2 = "http://www.dalipaintings.net/images/paintings/dream-caused-by-the-flight-of-a-bee.jpg",
                Artwork3 = "http://www.dalipaintings.net/images/paintings/swans-reflecting-elephants.jpg",
            },

            new Artist
            {
                ArtistID = 6,
                Name = "Andy Warhol",
                Picture = "https://upload.wikimedia.org/wikipedia/commons/2/2b/Andy_Warhol_by_Jack_Mitchell.jpg",
                BirthDate = DateTime.Parse("06-08-1928"),
                Nationality = "American",
                ArtStyle = "Pop art",
                Info = "",
                Artwork1 = "https://upload.wikimedia.org/wikipedia/en/thumb/1/1f/Campbells_Soup_Cans_MOMA.jpg/300px-Campbells_Soup_Cans_MOMA.jpg",
                Artwork2 = "https://vmfa.museum/collections/wp-content/uploads/sites/9/2013/12/Warhol_85_453_v1_KW_200909_XL-878x1024.jpg",
                Artwork3 = "https://cdn.kastatic.org/ka-perseus-images/329f84364bd08b80515b71fa830da2d2b6802c0c.jpg",
            },

            new Artist
            {
                ArtistID = 7,
                Name = "Michelangelo",
                Picture = "https://upload.wikimedia.org/wikipedia/commons/5/5e/Miguel_%C3%81ngel,_por_Daniele_da_Volterra_(detalle).jpg",
                BirthDate = DateTime.Parse("06-03-1475"),
                Nationality = "Italian",
                ArtStyle = "High Renaissance",
                Info = "",
                Artwork1 = "https://upload.wikimedia.org/wikipedia/commons/b/b4/Michelangelo_-_Creation_of_Adam.jpg",
                Artwork2 = "https://upload.wikimedia.org/wikipedia/commons/2/24/'David'_by_Michelangelo_JBU0001.JPG",
                Artwork3 = "http://www.italianrenaissance.org/wp-content/uploads/2012/07/Michelangelo-pieta.jpg",
            },

            new Artist
            {
                ArtistID = 8,
                Name = "Claude Monet",
                Picture = "http://www.notesontheroad.com/images/stories/yings_links/Birthdays/Monet/claude-monet.jpg",
                BirthDate = DateTime.Parse("14-11-1840"),
                Nationality = "French",
                ArtStyle = "Impressionism",
                Info = "",
                Artwork1 = "",
                Artwork2 = "",
                Artwork3 = "",
            }

        );

        context.Artworks.AddOrUpdate(i => i.ArtistID,
            new Artwork
            {
                ArtworkID = 1,
                ArtistID = 1,
                Name = "Guernica",
                Picture = "https://upload.wikimedia.org/wikipedia/en/7/74/PicassoGuernica.jpg",
                Info = "",
            },

            new Artwork
            {
                ArtworkID = 2,
                ArtistID = 1,
                Name = "The Weeping Woman",
                Picture = "http://totallyhistory.com/wp-content/uploads/2012/12/pablo-picasso-weeping-woman.jpg",
                Info = "",
            },

            new Artwork
            {
                ArtworkID = 3,
                ArtistID = 1,
                Name = "Three Musicians",
                Picture = "http://www.pablopicasso.org/images/paintings/three-musicians.jpg",
                Info = "",
            },

            new Artwork
            {
                ArtworkID = 4,
                ArtistID = 1,
                Name = "Le Rêve",
                Picture = "https://upload.wikimedia.org/wikipedia/en/9/9d/Le-reve-1932.jpg",
                Info = "",
            }

        );

A: When you seed your Artworks, you are not using AddOrUpdate correctly.
It expects a unique identifier, so instead of:
context.Artworks.AddOrUpdate(i => i.ArtistID,

You should use:
context.Artworks.AddOrUpdate(i => i.ArtworkID,

A: You are using Linq method SingleOrDefault, which will throw exception if more than one element will be found in the query.If you anticipate that predicate can match more than one element you could use method FirstOrDefault which will get firs matching element or return null if not found or change the predicate to be more detailed.


text:
Q: Error trying to run R in Sublime using REPL R on Mac "FileNotFoundError" I am trying to run R from Sublime Text 3 on a Mac. I have followed various online instructions (http://tomschenkjr.net/blog/using-sublime-text-2-for-r/) but can't get it to work on my Mac.  I have configured the SublimeREPL settings for user as:
{
    "default_extend_env": {"PATH": "{PATH};~/Applications/R.app"},
    "show_transferred_text": true
}

and configured the Main.sublime-menu file to include the path to R.app as follows:
"cmd": {"linux": ["R", "--interactive", "--no-readline"],
        "osx": ["~/Applications/R.app", "--interactive", "--no-readline"],
        "windows": ["Rterm.exe", "--ess", "--encoding=$win_cmd_encoding"]},

I have tried other paths to no avail.  Any help?  Many thanks!

A: Make sure you have the latest R installed.
Then, try changing
~/Applications/R.app to "/Library/Frameworks/R.framework/Resources/bin/R".
So, it should look something like:
"osx": ["/Library/Frameworks/R.framework/Resources/bin/R", "--interactive", "--no-readline"],


text:
Q: Shorten long code lines containing anchor tags in HTML I want a max character length of 80 characters on my text. It is being stopped by long, long links to which I can not find a way to shorten down in the actual code. Not on the website, but the actual code. Just to make it look cleaner and shorter and without the use of websites like shorturl.
An example of a long link that i have is this.

But i want to be able to like cut it in half in the code so it displays for example like this:

All I am getting is errors with it taking on the first part of the link that contains the line break. I can not find any way to fix the problem.
I wonder if there is any possible way I can get done something similar.

A: Option 1
You can use something like a url shortener, and then past the shortened link in your code.
URL shorteners

*

*https://bit.ly

*https://shorturl.a

*https://cutt.ly
Option 2
You can create another webpage with a list of the links and and use a GET request to access them.
If you are using PHP:

display web page (Example):


text:
Q: PHP script not responding after some time I am executing one php script, if data is less (approx 30K), it will take 3 minutes and display the output.
But if data is huge, then execution time is approx 7-8 minutes, but browser is not showing the output. I checked the script with the logs, script is executing till the last line of the code, but browser is not responding that output.
I tried with the lots of options like increase memmory limit, max execution time, but didn't get the solution.
Kindly look into that.....

A: You need to output some data to the browser. It the browser has to wait for minutes the browser will think that there is a connection timeout.
If possible you could begin to send the html header and flush it to the client.

A: You can just use
header('Connection: keep-alive');
flush();

If you have a loop, you can put this in it at last so it will continue your connection.


text:
Q: Single Select() statement or multiple for transformation with multiple steps? In C#, I have a collection of objects that I want to transform to a different type. This conversion, which I would like to do with LINQ Select(), requires multiple operations in sequence. To perform these operations, is it better to chain together multiple Select() queries like
resultSet.Select(stepOneDelegate).Select(stepTwoDelegate).Select(stepThreeDelegate);

or instead to perform these three steps in a single call?
resultSet.Select(item => stepThree(stepTwo(stepOne(item))));

Note: The three steps themselves are not necessarily functions. They are meant to be a concise demonstration of the problem. If that has an effect on the answer please include that information.

A: Any performance difference would be negligible, but the definitive answer to that is simply "test it". The question would be more around readability, which one is easier to understand and grasp what is going on.
Cases where I have needed to Project on a Projection would include when working with EF Linq expressions where I ultimately need to do something that isn't supported by EF Linq so I need to materialize a projection (usually to an anonymous type) then finish the expression before selecting the final output.  In these cases you would need to use the first example.
Personally I'd probably just stick to the first scenario as to me it is easy to understand what is going on, and it easily supports additions for other operations such as filtering with Where or using OrderBy etc.  The second scenario only really comes up when I'm building a composite model.
.Select(x => new OuterModel
{
   Id = x.Id,
   InnerModel = x.Inner.Select(i => new InnerModel
   {
      // ...
   })
}) // ...

In most cases though this can be handled through Automapper.
I'd be wary of any code that I felt needed chaining a lot of Select expressions as it would smell like trying to do too much in one expression chain.  Making something easy to understand, even if it involves a few extra steps and might add a few milliseconds to the execution is far better than having the risk of needing to track down bugs that someone introduced because they misunderstood potentially complex looking code.


text:
Q: Non-writable dir with files inside of tar archive I have a tar.gz archive that I can't extract because one of the directories doesn't have writing permissions at all despite having multiple directories and files inside. So I end up with the half-extracted archive, files inside of this dir can't be extracted because of no writing permissions.
How can I fix it without root permissions?

A: The "delay-directory-restore" will set the directory permissions and time after restoring all the directory content:
tar --delay-directory-restore


text:
Q: UIAlertView + TextField = Error? I am making a application so data can be saved to a Table View and I wanted to use the UIAlertView Controller in a way so people can use it to create a new Cell (task) but I know how to make a textField in a UIAlertView but how do use the textField data and use it in a UIAlertView Action button!
@IBAction func addNewTask() {

        var alertController = UIAlertController(title: "Add A New Task", message: "Add The Correct Information To Add A New Task!", preferredStyle: .Alert)

        // Create the actions
        var Exit = UIAlertAction(title: "Add Task", style: UIAlertActionStyle.Default) {
            UIAlertAction in
            NSLog("OK Pressed")

        }
        var cancelAction = UIAlertAction(title: "Exit App", style: UIAlertActionStyle.Cancel) {
            UIAlertAction in
            NSLog("User Exited The App!")
            exit(2)

        }

        alertController.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in
            // Here you can configure the text field (eg: make it secure, add a placeholder, etc)

        }

        // Add the actions
        alertController.addAction(Exit)

        alertController.addAction(cancelAction)

        // Present the controller
        self.presentViewController(alertController, animated: true, completion: nil)

    }

This is the code but how can I use the data from the alertController.addTextFieldWithConfigureationHandler and put it in the Exit Action! So the main thing I want this to do just know is when the user types in the textbox and clicks Exit a label will change to that text from the textField but without using a viewController! I am using Swift, Xcode 6.3.1
Thanks,
George Barlow
p.s. Sorry for the longwinded question!

A: In your UIAlertAction called Exit (btw, you should consider changing the name to something like exit or exitAction), you can access the UITextField and its contents in the following way:
// Create the actions
var Exit = UIAlertAction(title: "Add Task", style: UIAlertActionStyle.Default) {
    UIAlertAction in
    let loginTextField = alertController.textFields![0] as! UITextField
    let inputText = loginTextField.text
    println("The input text is: \(inputText)")
    NSLog("OK Pressed")
}

A: " . .. you can also add text fields to the alert interface. The alert controller lets you provide a block for configuring your text fields prior to display. The alert controller maintains a reference to each text field so that you can access its value later." https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertController_class/index.html#//apple_ref/occ/cl/UIAlertController
There is a textfield property on the UIAlertViewController that you can access.
alertController.textFields

The text fields are added to this array in the same order that you added them to the alert controller.
Inside your completion for the exit action:
UITextField *taskTextField = alertController.textFields.firstObject

*Edit: in swift:
if let taskTextField = alertController.textFields![0] as! UITextField {
    let taskText = taskTextField.text
    ...
}

A: You can do something like this:
class ViewController: UIViewController {

        @IBOutlet weak var myLabel: UILabel!
        var mytextField: UITextField!

        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.

        }

        override func viewDidAppear(animated: Bool) {
            addNewTask()
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }

        func addNewTask() {
            var alertController = UIAlertController(title: "Add A New Task", message: "Add The Correct Information To Add A New Task!", preferredStyle: .Alert)

            // Create the actions
            var Exit = UIAlertAction(title: "Add Task", style: UIAlertActionStyle.Default) {
                UIAlertAction in
                NSLog("OK Pressed")

                self.myLabel.text = self.mytextField.text

            }
            var cancelAction = UIAlertAction(title: "Exit App", style: UIAlertActionStyle.Cancel) {
                UIAlertAction in
                NSLog("User Exited The App!")
                exit(2)

            }

            alertController.addTextFieldWithConfigurationHandler { (textField: UITextField!) -> Void in
                // Here you can configure the text field (eg: make it secure, add a placeholder, etc)

                self.mytextField = textField
            }

            // Add the actions
            alertController.addAction(Exit)

            alertController.addAction(cancelAction)

            // Present the controller
            self.presentViewController(alertController, animated: true, completion: nil)
        }

    }


text:
Q: Rails 3: Render differently if email is opened on an iPhone? I have an email which renders perfectly on a standard machine. However, when a user opens the email on their iphone there is a gray box that suddenly enlarges and takes up more space than it normally should. Is there a hack that I can use in order to have my html.erb page recognize whether or not it is being rendered in an iphone and adjust itself accordingly?

A: Its basically the CSS you would have to modify in general.
Follow this link showing which styles etc. are supported on iphone devices and which are not..

A: In order to get user's browser information, there is a cool gem called Browser. I strongly recommend you to check out its repo on Github.
Once you install this gem,
browser.mobile?

will give you true or false and you'll be able to do whatever you want depending on the answer.


text:
Q: Firefox can't establish a connection to the server at www.google.com My home page in Firefox [v4.0] and Internet Explorer [v9.0.8112.16421, Update Versions RTM (KB982861)] is currently set to Google but when I depress the quick start icon to start up either browser, I am getting the following immediate results:
Unable to connect (In Firefox)

Firefox can't establish a connection to the server at www.google.com.

*

*The site could be temporarily unavailable or too busy. Try again in a few moments.

*If you are unable to load any pages, check your computer's network connection.

*If your computer or network is protected by a firewall or proxy, make sure that Firefox is permitted to access the Web.

Internet Explorer cannot display the webpage

What you can try:
Diagnose Connection Problems
More information
This problem can be caused by a variety of issues, including:

*

*Internet connectivity has been lost.

*The website is temporarily unavailable.

*The Domain Name Server (DNS) is not reachable.

*The Domain Name Server (DNS) does not have a listing for the website's domain.

*There might be a typing error in the address.

*If this is an HTTPS (secure) address, click Tools, click Internet Options, click Advanced, and check to be sure the SSL and TLS protocols are enabled under the security section.

  For offline users
You can still view subscribed feeds and some recently viewed webpages.
To view subscribed feeds:

*

*Click the Favorites button , click Feeds, and then click the feed you want to view.

  To view recently visited webpages (might not work on all pages):

*

*Press Alt, click File, and then click Work Offline.

*Click the Favorites button, click History, and then click the page you want to view.

Thankfully, I am able to use one browser that I have installed on my computer (Mathon v3.0.20.5000) to search online for technical assistance in this matter.  I have seen several WinSock error issues mentioned; but, they are pointing to Windows XP and I am using Windows 7 Pro and remain uncertain whether anything identified as a fix for one OS will work in another.
Things I've tried:

*

*HiJackThis

*Complete scan with Avira AntiVirus Premium.

What am I overlooking?  What should I do to address this problem?

A: Go to START -> and in search field type CMD and press enter. After black window shows up type in ping google.com and see if it responds. If it doesn't then DNS probably is not working or is not set correctly. This is basic test and it would be nice if you can provide this.


text: Q: Chromecast Audio/PulseAudio-DLNA Lag I successfully connected a Chromecast audio unit using Pulseaudio-DLNA to my Dell Inspiron 13 7348 running Kubuntu 16.04. However, there is always a 2-5 second lag from when I press to play a sound to the sound coming out of the speakers. Is there any way to fix this problem?


text:
Q: Can a WCF service hosted as windows service accessed from both windows and web clients? I currently have a WCF service hosted as a window service. I'm consuming this service from a windows console application through a TCP binding. Everything is fine with that. Now, I'm writing an Angular app which should also consume the same service. I was wondering if I can define a HTTP binding on the same service. I do not want to host the same service on IIS for the web client. Is there a way to continue to use the service hosted already?

A: As far as I know, angular app consumes web service which is Restful-style service, but WCF Service communicate with the client by using SOAP message, and the browser does not support SOAP message. In that case, we use the WebHttpBinding to create HTTP-mode web service, and then we could access it by the browser. we also could access it by javascript(ajax).
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-create-a-basic-wcf-web-http-service


text:
Q: Use JavaScript variable as iframe src? I'm trying to use a JavaScript variable as the src in a <iframe>, the user will then be able to load other content by choosing scr in a menu, which changes the variable. the default src URL is apps/start.php.
Here some code from my index.php:
    <script>
        var appurl = "start.php";
        document.getElementById("app").src = "apps/" + appurl();
    </script>

    <iframe id="app" src="">

    </iframe>

The problem is that i can't get this first small part working... The <script> tag is in the <head>. And when the src is changing will the new document automatically load?

A: The problem is that the Javascript is run before the iframe is there. Put your javascript below your iFrame or inside the document ready and it will work.
Example document onload:
<script>
    window.onload = function ()
    {
        var appurl = "start.php";
        document.getElementById("app").src = "apps/" + appurl();
    }
</script>

<iframe id="app" src="">

</iframe>

A: Wait for the page to load (note that this is only going to work when the iframe is on your domain)
window.onload = function(){
 var appurl = "start.php";
 document.getElementById("app").src = "apps/" + appurl;
};

A: <script>
    window.onload = function ()
    {
        var appurl = "start.php";
        document.getElementById("app").src = "apps/" + appurl;
    }
</script>

<iframe id="app" src="">

</iframe>

A: Try
<script>
window.onload = function(){
 var appurl = 'start.php';
 document.getElementById("app").src = "apps/" + appurl;
};
</script>


text:
Q: mysql limit - a general question Assuming the query
SELECT * FROM table WHERE a='1' and b='2' and c>'3' and d>'4' and e!='5' and f='6'

returns 10000 results.
My question is, let's say I limit the search to the first 10 results like this:
SELECT * FROM table WHERE a='1' and b='2' and c>'3' and d>'4' and e!='5' and f='6' LIMIT 10

Will mysql search through all the 10000 results or it will stop at the 10th result?

A: LIMIT will only display the rows specified, based on their position within the resultset.  Without an ORDER BY, you're relying on the order the records were inserted.
You'll probably be interested to read about MySQL's ORDER BY/LIMIT performance...

A: Since there is no ORDER BY, it will stop at the 10th result (after going through as many non-matching rows as necessary).  As OMG Ponies says, which 10 rows you get is unspecified.


text:
Q: Gitlab CI can't install gem I'm building a rails app using gitlab ci and a few issues came up.

*

*The first was it couldn't find rake to run the tests

*

*I installed rake on my digital ocean manually to solve this

*Then it was complaining the gitlab_ci_runner is not in the sudoers list

*

*I added gitlab ci to the sudoers list which solved that problem

Now when running bundle install it is complaining that Bundler::GemspecError: Could not read gem for every single gem unless I install them myself.
Am I missing something with the way I setup gitlab ci?

A: Try using the 'gitlab_ci_runner' w/o switching user.
sudo -u gitlab_ci_runner -H bundle install --deployment

If you're root user that has a password (meaning your NOT using a SSH-Key) use this to switch back to root user.
su


text:
Q: How to select rows in a list of data frames by column values I have a list (lfs01)with four data frames, each data frame has a different number of columns and rows.
I would like to filter the rows in all data frames by values in one column (if == 1). The variable is called "a" in the first two data frames and "A" in the last two.
I looked at previous similar questions but unfortunately I did not find the solution.
Here are things I have tried:
data<-lapply(lfs01, function(x) filter(x ,'a'==1))

data<-lapply(lfs01, function(x) filter(x ,'a'==1|'A' ==1))

```

# Result:  a - list of 4 data frames with 0 rows.

 ```
data<-as.list(1:4)
for(i in 1:length(lfs01)){
  data[[i]]<-lfs01[[i]]%>%
    filter('a'== 1)
}
```
# and

```
data<-map(lfs01, ~filter(.x, 'a'%in%1 ))

```

# Results as above - list of 4 data frames with 0 rows.

Many thanks in advance!

A: One possible approach could be to rename the columns so that all the dataframes have the same name and it is easy to subset them. Another approach could be to subset the dataframes based on position if you know the position of that column beforehand.
If none of the above is possible then we can check if a particular name exists and use the subset command accordingly.
lapply(lfs01,function(x) if('a' == names(x)) subset(x,a == 1) else subset(x,A == 1))

A: We can change the column names to either lower or upper case and use the same filter
library(purrr)
library(dplyr)
map(lfs01, ~ .x %>%
                rename_all(tolower) %>%
                filter(a == 1)
   )

In the OP's post, the column names are quoted inside filter which wouldn't work.  So, it can be
map(lfs01, ~ .x %>%
                  filter(a == 1))


text:
Q: I want to hide the output when I type in the make command in the terminal So I'm on Linux and I've been tinkering around with cs50. I've figured out a way to emulate the make command that is used in the course. When I type this make command, a line will print that I would like to not see.
Terminal example:
[ja@pc cs50]$ make hello

clang -fsanitize=integer -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wshadow    hello.c  -lcrypt -lcs50 -lm -o hello

[ja@pc cs50]$

I would like to remove this line that prints after I use the make command.

Here is what my .bashrc looks like for the command:
#configure clang

export CC=clang

export CFLAGS="-fsanitize=integer -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wshadow"

export LDLIBS="-lcrypt -lcs50 -lm"


text:
Q: Relation between station and Ad Object let's say I have a station which is connected to my network but is not a part of the domain. If I add the station to the domain, meaning create an AD Object, is there a property in the object that connects me with the station?
I mean except the hostname. It doesn't count really because it's easy to change.
Thanks


text:
Q: How to authenticate a site with Python using Requests? How can I get this to work? I've been trying for days and keep hitting the same dead ends. I've tried all the examples I could find to no avail.
import requests

s = requests.Session()
payload = {'login_username': 'login', 'login_password': 'password'}
url = 'http://rustorka.com/forum/login.php'
requests.post(url, data=payload)
r2 = requests.get('http://rustorka.com/forum/index.php')
print(r2.text)
s.cookies


text:
Q: VBA: How to locate range being edited through "fill down" or "copy/paste" (or any multiple cells) in worksheet module I have two worksheets with five columns that I want to keep track of any changes made. I present the original state of these columns in worksheet A and mark the change in worksheet B.
Screenshot of worksheet B
Following is the look of worksheet B, let's say that worksheet A has the "ORIG" part but with filters and everthing:

Note: I already wrote another worksheet subroutine, that will filter to "All the same?" = False (meaning that this row is changed) whenever this worksheet is activated.
I already wrote the code that would work for the change of one cell (e.g. when you edit the cell with F2 and then hit ENTER when you are done) --  a worksheet subroutine that is triggered when the worksheet is changed. The subroutine will check for the changed range, and if the range is a specified area, correponding area is updated in another worksheet.
Worksheet Subroutine
Private Sub Worksheet_Change(ByVal target As Range)
    Dim start_row As Long: start_row = 4
    Dim last_row As Long: last_row = findLastRow()

' when values are changed in "REPORT", check if values are ouputable and update these values
    If IsInArray(Number2Letter(target.Column), inputColumns) And target.row >= start_row And target.row <= last_row Then
        ' Update corresponding cell in worksheetB
    End If
End Sub

Other UDF/UDS
Public Function Number2Letter(ColumnNumber As Long) As String
'convert a given number into it's corresponding Letter Reference
    Dim columnLetter As String
    columnLetter = Split(Cells(1, ColumnNumber).Address, "$")(1)
    Number2Letter = columnLetter
End Function

Public Function IsInArray(valToBeFound As Variant, arr As Variant) As Boolean
'INPUT: Pass the function a value to search for and an array of values of any data type.
'OUTPUT: True if is in array, false otherwise

    Dim element As Variant
    On Error GoTo IsInArrayError: 'array is empty
        For Each element In arr
            If element = valToBeFound Then
                IsInArray = True
                Exit Function
            End If
        Next element
    Exit Function
IsInArrayError:
    On Error GoTo 0
    IsInArray = False
End Function

Public Function findLastRow() As Long
'Finds the last non-blank cell on a sheet
    Dim lRow As Long
        lRow = Cells.Find(what:="*", _
                        After:=Range("A1"), _
                        lookat:=xlPart, _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).row
    findLastRow = lRow
End Function

For simplicity, I hid the "do something" part, but that part already works. Same thing with UDF/UDS as I only showed them if someone is interested. In addition, the array inputColumns already exists, so don't worry about that part either.
What I am asking for:

1. Is there such a property like targetRange that would work for fill down or paste, like I mentioned?
2. Or is there a different worksheet event that I can use?
3. If neither exists, I am thinking of mark original state in an array and compare it with what is visible on first worksheet every time we get to worksheet B. The problem with this approach is that it consumes both space and speed. Could you think of a better way?
Thank you!

A: I think that the Intersect function will help you out a lot here.  You can define a range that you want to 'audit' and compare it against all the values that are changed by a single operation in your worksheet.  If there's any overlap, write out the value of those cells to some target destination.
Private Sub Worksheet_Change(ByVal target As Range)

    Dim AuditRange As Range
    Set AuditRange = Range("B4:F16") 'your "Audit Area"

    Set range_auditedAndChanged = Intersect(target, AuditRange)
    If Not range_auditedAndChanged Is Nothing Then

        For Each c In range_auditedAndChanged
                'put in whereever your audit workbook is for Sheets("Sheet2")
                Sheets("Sheet2").Range(c.Address).Value = c.Value
        Next c

    End If
End Sub

Right now, you only get the values audited - no formats of any kind.  You could change the Value assignment to some kind of copy, but that would hijack the user experience for a moment even with screen updating turned off.
At any rate, I think this is cleaner and quite performant and has a lot fewer UDFs to manage.  Hope it helps.