text:
Q: Returning a view with previous inputs using Laravel I have a form, when submitted, invokes an AJAX request. This ajax request performs back-end validation on the inputs. If an error is detected, it displays the error messages. So if the user fills out 30 fields, and one is not valid, I would like to return all those inputs with an error message.
My Laravel Code:
Route::post('/roa', function() {
$m = Request::except('_token');
$name = "form1_sections/" . $m['nextTab'] . "_form";//next view name
$name2 = "form1_sections/" . $m['currentTab'] . "_form";//current view name

$var= parse_str($m['inputs'], $output);//data from ajax is a string

if ($m['currentTab']=='section2'){//i'm only doing validation on one section right now
//to simplify the code.
    $rules = [
        'TB1_course.*' => 'required'
    ];
    $validator=Validator::make($output, $rules);
    if ($validator->passes()){//if no error, return the next view
        return ["view" => view("$name")-> render(), "value"=>1, "inputs"=>$output];
    }
    return ["view" => view("$name2")->withInput($output)->withErrors($validator) -> render(), "value"=>1, "inputs"=>$output];
}
return ["view" => view("$name") -> render()];
});

My Ajax request:
$('#form').on('submit', function (e) {
    var formData = $('#form').serialize();
    e.preventDefault();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: '/roa',
        dataType: 'json',
        data: {inputs: formData, nextTab: relatedTabID, currentTab: tabID},
        success: function(data){
            $('#tabShow').html((data.view));
        },
        error: function () {
            alert('error');
        }
    });
});

I am successfully able to receive all the error messages, but the withInput($output) for some reason is not working. Thank you for all your help.

A: 'view' => view('template')->withInput()?


text:
Q: Partial display of figure captions in the list of figures Consider the below figure and the caption.

Now I want to display only part of the caption in the list of figures instead of the entire caption. For example, here I would like to display "Figure 1.3: Burke-Schumann flame structure in mixture fraction space", only in the list of figures. Is there a way to do this?

A: Figure captions: Use the optional argument of \caption:
\caption[short title for list of figures]{long title for text}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i use external thermometers with vb.net i am a programmer, i primarily use asp.net to write web apps. I have a need to use some external temperate sensors and a controller to run a solar water heater. I will need to be able to monitor more than one temperature sensor and start/stop a water pump based on certain logic. I can code this but my question is where do i find such equipment i.e. what can i search for etc. and how can i get it to interface so i can use it in programming.
Many thanks

A: Look at netduino and the micro framework. This article seems to cover what you want http://blogs.msdn.com/b/vbteam/archive/2011/08/02/temperature-monitoring-using-vb-net-and-the-micro-framework-and-a-netduino.aspx


text:
Q: Django import-export fields I have a short question about django-import-export. In my model I have choice list:
STATE_CHOICES = ((NEW_STATE, u'New'),
                 (DELIVERED_STATE, u'Delivered'),
                 (LOST_STATE, u'Lost'),

And method that handles mapping choices for names
@staticmethod
def get_status_name_by_status(status):
    return next((s[1] for s in MyModel.STATE_CHOICES if s[0] == status), 'Uknown')

I want to import/export some data
class MyModelResource(resources.ModelResource):
    status = fields.Field(column_name='status', attribute='order',
                          widget=ForeignKeyWidget(Order, 'status'))

I want to use my get_status_name_by_status method so the choices will be converted to names. But there is no possibility to use method here, only fields are allowed. Any tip how this can be done ?

A: You can use 'get_FOO_display' to achieve this in the Django Admin:
class MyModelResource(resources.ModelResource):
    status = fields.Field(
        attribute='get_status_display',
        column_name=_(u'Status')
    )

A: if you want import and export having different field inside Django import-export.
class CommonResourcesClass(resources.ModelResource):
    class Meta:
        model = Model
        fields = None

class ExportResourcesClass(resources.ModelResource):
    class Meta:
        model = Model
        fields = None

class ModelAdmin(ImportExportModelAdmin, ImportExportActionModelAdmin):
    list_display = ()
    resource_class = CommonResourcesClass
    def get_export_resource_class(self):
        return ExportResourcesClass

A: Not all data can be easily extracted from an object/model attribute. In order to turn complicated data model into a (generally simpler) processed data structure, dehydrate_fieldname method should be defined:
class MyModelResource(resources.ModelResource):
    status_name = fields.Field()

    def dehydrate_status_name(self, myModel):
        MyModel.get_status_name_by_status(myModel.status)

A: A hack method to realize this quickly, just configure _choice_fields to your choices fields, that's it.
import import_export
from import_export import resources

class MyModelResource(resources.ModelResource):
    _choice_fields = [
        'field_a', 'field_b',
    ]
    for _field_name in _choice_fields:
        locals()[_field_name] = import_export.fields.Field(
            attribute='get_%s_display' % _field_name,
            column_name=MyModel._meta.get_field(_field_name).verbose_name
        )


text:
Q: Calling a Gradle Task conditionally Assume I have 2 tasks:
tasks.register('taskA') {
  // do something
}

tasks.register('taskB') {
  // do something else
}

for my gradle build, I only want to call task "build" and depending on a
condition, it should decide which other task to call:
tasks.register('build') {
    doLast {
        if (condition == true) {
            // tasks.named('taskA').execute {}
        } else {
            // tasks.named('taskB').execute {}
        }
    }
}

there is no such function as "execute", but whats the best practice in Gradle
to archive that behaviour ? I also read that one should avoid "dependsOn" if possible.

A: You sample shows that the build task is being created. Generally, this task is already created for you when you apply one of the provided Gradle plugins such as the Java Plugin. The Base Plugin is generally applied when applying a plugin Gradle provides. Some use cases you may apply the plugin manually. This answer assumes the Java plugin is applied, uses the Kotlin DSL, and Gradle 8.

You can use a task predicate to conditionally execute tasks. The recommendation to avoid using dependsOn is because usually there is an idiomatic way to express your intent in Gradle. In this case, a task predicate is exactly what you need here. For example:
tasks {
    val taskA by registering {
        onlyIf("condition A is satisfied") {
            1 + 1 == 2
        }
        doLast {
            // task execution logic
        }
    }
    val taskB by registering {
        onlyIf("condition A is satisfied") {
            1 + 1 == 2
        }
        doLast {
            // ...
        }
    }
    build {
        dependsOn(taskA, taskB)
    }
}

Breaking this down:

*

*Register the task as you did, but make use of the onlyIf predicate. Task will only execute if the predicate is satisfied.

*Use doLast { } for your task execution logic. For more complex uses, consider creating a custom task type.

*The built-in build task does not carry any meaningful semantics in Gradle, it is a "catch all" build everything task. So, it is fine to use dependsOn in this case.


text:
Q: How to display values from lists in a UI QML (QT) inside a Repeater I've been facing this issue for days without coming to a conclusion, I hope someone could give me some useful hints to solve it.
I'll try to simplify the issue with an example:

*

*In my C++ code I defined the class MyObjectModel that will act
later as a model in the Repeater block in my main ui.qml file.
MyObjectModel is visible to the QQmlApplicationEngine.

*MyObjectModel
has 2 attributes (lists) : xCoordinatesList and yCoordinatesList.
They represent the x and y pixel coordinates of a list of points.
I.e. xCoordinatesList = [100, 200], yCoordinatesList = [10, 20] mean logically that I have 2 points with the following pixel coordinates that I want to display on the screen: (100,10), (10,20).

*The xCoordinatesList and yCoordinatesList are Roles of my model
for the QML engine.  This means for instance that in a common
.qml file i can clearly print the content of xCoordinatesList by
typing:
Component.onCompleted
{
    console.log("x coordinates: ",xCoordinatesList);
}

The question is: how can I display at the same time the list of points on the screen?
If I want to display only one dot (so one couple of coordinates) my code works. I really don't know how to extend it to make it print all of them.
In my MainForm.ui.qml I defined a Repeater inside a Rectangle :
Rectangle
 {
 ....
            Repeater
        {
            model: dotModel

             delegate:
                 DotItem
                 {
                 id: dotItem;
                 objectName: "dotItem";
                 DotPositionOnMap
                 {
                     id: dotPositionId;
                     objectWidth: dotItem.width;
                     objectHeight: dotItem.height;
                 }
                 x: dotPositionId.xPositionOnMap;
                 y: dotPositionId.yPositionOnMap;
                 }
         }
....
}

I need a Repeater because MyObjectModel which holds the two lists of x and y coordinates can dynamically change over time.
dotModel is just a fake model I use for an other purpose.
DotItem  is my qml Item that identifies the red dot circle image I want to depict on the screen for each couple of elements in xCoordinatesList, yCoordinatesList.
DotItem.ui.qml
import QtQuick 2.4
import QtQuick.Layouts 1.1

Item
{
    width:  10
    height: 10
    opacity: 1
    Image
    {
      id: dotItemImage
      anchors.fill: parent
      source: "red_dot.png"
    }
}

red_dot.png image should be displayed for each point depicted on the screen.
DotPositionOnMap.qml is responsible for computing the right x and y pixel position on the screen.
import QtQuick 2.5
import "calcCurrentPos_script.js" as CurrentPos

Item
{
// Values filled from MainForm.ui.qml
property int objectWidth
property int objectHeight

// Getting current coordinates
// Fetching element 0 from both lists
property real currentx: CurrentPos.getCurrentxPoint(0);
property real currenty: CurrentPos.getCurrentyPoint(0);

// Generating the x and y pixel position on map.
// Toy example
property int xPositionOnMap : currentx-(objectWidth/2);
property int yPositionOnMap : currenty-(objectHeight/2);
}

Where calcCurrentPos_script.js
function getCurrentxPoint(val)
{
    return xCoordinatesList[val];
}

function getCurrentyPoint(val)
{
    return yCoordinatesList[val];
}

In this way I can only display one dot on the screen since I specify in DotPositionOnMap.qml which point to fetch:
// Fetching element 0 in this case
property real currentx: CurrentPos.getCurrentxPoint(0);
property real currenty: CurrentPos.getCurrentyPoint(0);

I used javascript for this attempt because I thought I could use a for loop to scan all the elements to be displayed, but it didn't work.
Extract of my model
QVariant MyModelObject::data(const QModelIndex& index, int role) const
{
    const MyModelObject& object = objects.values().value(index.row());
    ....
    if(role == XRole)
    {
    QList<TrackPoint> tkrList = object.getList();
    QList<QVariant> tkrVariantList;
    for(auto track: trackpointList)
        {
        tkrVariantList.append(track.getPosition().getX());
        }

    return QVariant(tkrVariantList);
    }
    else if(role == YRole)
    {
    QList<TrackPoint> tkrList = object.getList();
    QList<QVariant> tkrVariantList;
    for(auto track: trackpointList)
        {
        tkrVariantList.append(track.getPosition().getY());
        }
    return QVariant(tkrVariantList);
    }
}

....
....
QHash<int, QByteArray> MyModelObject::roleNames() const
{
  QHash<int, QByteArray> roles;
  roles[XRole]        = "xCoordinatesList";
  roles[YRole]      = "yCoordinatesList";
  return roles;
}

I truly appreciate any ideas concerning the generalisation of this implementation.
Thank you

A: The Qt documentation is very clear. The first you have to read is that article. I think that in your case the simpliest way is list-based model. Or, of cource, you can subclass QAbstractListModel.
Your question is not so clear and you didn't provide the code of your model but maybe this small example will help you:
Declaration
    class MyModel : public QAbstractListModel
    {
        Q_OBJECT
    public:
        enum PointRoles {
                  XRole = Qt::UserRole + 1,
                  YRole
              };
        MyModel(QObject *parent = Q_NULLPTR);
        int rowCount(const QModelIndex &parent = QModelIndex()) const;
        QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
        QHash<int, QByteArray> roleNames() const;

    private:
        QList<QPoint> m_list;
    };

Implementation
MyModel::MyModel(QObject *parent) :
    QAbstractListModel(parent)
{
}

QHash<int, QByteArray> MyModel::roleNames() const {
     QHash<int, QByteArray> roles;
     roles[XRole] = "xcoord";
     roles[YRole] = "ycoord";
     return roles;
 }

int MyModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return m_list.count();
}

QVariant MyModel::data(const QModelIndex &index, int role) const
{
    if(role == XRole)
        return m_list[index.row()].x();
    else if(role == YRole)
        return m_list[index.row()].y();

    return QVariant();
}

Registation
qmlRegisterType<MyModel>("qt.test", 1, 0, "PointModel");

Usage
Window {
    visible: true
    width: 800
    height: 800
    PointModel {id: mymodel}
    Repeater {
        model: mymodel
        delegate: Rectangle {
            x: 100 + xcoord
            y: 100 + ycoord
            width: 20
            height: 20
            color: "red"
            radius: 10
        }
    }
}

A: * SOLVED *
In your main.qml you can have something like this, which handles the global drawing routine.
    Repeater
    {
        model: dotModel
        delegate:
        DotPositionOnMap{}
    }

DotPositionOnMap.qml will read the list of x and y coordinates and for each element of both will create a dot Item object which will be displayed on the screen.
import QtQuick 2.5

Item
{

id: dotPositionOnMap
objectName: "dotoPositionOnMap"

Component.onCompleted:
{
 // yCoordinatesList would have given the same result
 var dotListLength = xCoordinatesList.length;

// Dot properties can by handled dynamically
var dotWidth = 5;
var dotHeight = 5;
var dotRadius = 10;
var dotColor = "red"

// For each entry of xCoordinatesList and yCoordinatesList
// I generate a DotShape qml object that will display a dot on the screen
for(var i = 0; i < dotListLength; i++)
{

    var currentXValue = xCoordinatesList[i];
    var currentYValue = yCoordinatesList[i];
    // x and y pixrl values for a DotShape.qml instance
    var xPositionOnMap = currentXValue-(dotWidth/2);
    var yPositionOnMap = currentYValue-(dotHeight/2);

    // Creating DotShape.qml component
    var comp = Qt.createComponent("DotShape.qml");

    var dotComponent = comp.createObject(dotPositionOnMap,
                                           {
                                               "x": xPositionOnMap,
                                               "y": yPositionOnMap,
                                               "width": dotWidth,
                                               "height": dotHeight,
                                               "color": dotColor,
                                               "radius": dotRadius
                                           });
} // end for
} // end script
} // end Item

Finally DotShape.qml , which's just a small red dot plotted at x,y coordinate
import QtQuick 2.5

Rectangle
{
// Other properties are generated at runtime
id: dotShapeId;
objectName: "dotShapeId";
}


text:
Q: Centrally managing 100+ websites without bankrupting a small company I'm mainly interested in opinions on the trade-offs between having a single central server all the websites connect to as opposed to each website mirroring a subset of the master database with all the products in it. For example, will I run into severe performance issues (or even security issues, or restrictions) making queries to an offsite database? Will we hit scalability issues we can't handle early on from the sheer bandwidth required to maintain this? If we do go with something like a script that keeps smaller databases (each containing a subset of the central master data) in sync, what sorts of issues will we likely encounter there? I would really like the opinions of people far more knowledgeable than I am regarding the pros and cons of both setups and what headaches we are likely to encounter.
CLARIFICATION: This should not be viewed as a question about whether we should implement one database vs multiple databases. This question has been answered numerous times. The question is regarding the pros and cons for a deployment like this having the ability to manage all the websites centrally (one server) vs trying to keep them all in sync if they each have their own db (multiple servers).
REAL-WORLD EXAMPLE: We are a t-shirt company, and we have individual websites for our different kinds of t-shirts, but we're looking at a central order management integrated with our single shopping cart (which is ColdFusion + MySQL). Now, let's say we have a t-shirt that's on 10 of our websites and we change an image for it. Ideally we would change that in one place and the change would propagate, but how would we set this up?

A: It sounds like what you are asking about is database replication.  You'd set that up with your MySQL servers to replicate changes made to, say, a master product table over to product tables in the various databases for the individual sites.  Such replication can be done between databases on either the same physical server or different ones.
That said, doing so seems needlessly complex when you can just use one shared db for all the stores and just have the individual stores filter on those products it can display.  A master inventory control panel could be made to assign products to sites.  If traffic then becomes an issue, you can replicate the single master database to other database servers, and point read-only queries over to the replicated copy of the database (read from many, but only write to the master db).

A: The answer is for each Web app you need a different database because of the security reasons. Simply do not put all your eggs in one basket!. If somebody attach your DB then you lost everything.
There is no cost difference between 1 database or 100 databases!. Most of the hosting companies get a certain rate (something like <40$) so you will have unlimited data storage and the ability to create unlimited number of DBs.


text:
Q: Sorting an arraylist error I'm putting together code for sorting algorithms. It's meant to demonstrate the fastest method between different types of data sets. So far it compiles but I continue to receive the following error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.elementData(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at SortTestPractice.insertionSorty(SortTestPractice.java:152)
    at SortTestPractice.testSpeed(SortTestPractice.java:71)
    at SortTestPractice.main(SortTestPractice.java:17

What does this error mean and what can I do to rectify this?

A: ArrayIndexOutOfBoundsException means that your program is trying to access data out of bounds of the array. That is, the program is outside of the declared memory for its scope. Look at where you access arrays or ArrayList and you will find that the program is trying to manipulate data which is outside of the declared array or list.

A: ArrayIndexOutOfBoundsException: -1
Meaning: your code is trying to access the array element with index -1
It's very likely that you have a logical error at SortTestPractice.insertionSorty(SortTestPractice.java:152)


text:
Q: How to print list value as each row in csv using python? I would like to generate a csv something like below but my python code generating .cvs file like this -
names
delectus aut autem,quis ut nam facilis et officia qui,fugiat veniam minus,et porro tempora

I would like to print each name in a separate row, please find my python code below
test.py
import requests
import csv
my_list = []
for i in range(1, 10):

    url = 'https://jsonplaceholder.typicode.com/todos/'+str(i)
    response = requests.get(url)
    jsonResponse = response.json()
    my_list.append(jsonResponse['title'])

print(my_list)

fields = ['names']

# data rows of csv file
rows = [my_list]

with open('data.csv', 'w') as f:
    write = csv.writer(f)
    write.writerow(fields)
    write.writerows(rows)

Expected output -data.csv
names
delectus aut autem
quis ut nam facilis et officia qui
fugiat veniam minus
et porro tempora

A: Method 1 (Using CSV)
import requests
import csv

writer=csv.writer(open('data.csv','w'))

fields = ['names']
writer.writerow(fields)

my_list = []
for i in range(1, 10):
    url = 'https://jsonplaceholder.typicode.com/todos/'+str(i)
    response = requests.get(url)
    jsonResponse = response.json()
    my_list.append(jsonResponse['title'])
    writer.writerow([jsonResponse['title']])

print(my_list)

Method 2 (Using pandas)
import requests
import pandas as pd

my_list = []
for i in range(1, 10):
    url = 'https://jsonplaceholder.typicode.com/todos/'+str(i)
    response = requests.get(url)
    jsonResponse = response.json()
    my_list.append(jsonResponse['title'])

print(my_list)

df = pd.DataFrame({'names': my_list})
df.to_csv('data.csv', index=False)

Output in csv file
names
delectus aut autem
quis ut nam facilis et officia qui
fugiat veniam minus
et porro tempora
laboriosam mollitia et enim quasi adipisci quia provident illum
qui ullam ratione quibusdam voluptatem quia omnis
illo expedita consequatur quia in
quo adipisci enim quam ut ab
molestiae perspiciatis ipsa

--- Edit ---
Added method 2, which uses pandas library.

A: That's not a CSV file.  That's just a plain text file.
with open('data.txt','w') as f:
    print(fields, file=f)
    print('\n'.join(rows), file=f)


text:
Q: how to mask some text in radtextbox I need to mask a input string having Pan number format ex.(ABCDE1234F) to (######234F) .
I have tried using maskedtextbox but it didn't help.
using below code :-

A: Please check this code, you can modify this code as per the textbox values
var cardNumber = "ABCDE1234F";

var firstDigits = cardNumber.Substring(0, 5);
Console.WriteLine(firstDigits);

var lastDigits = cardNumber.Substring(cardNumber.Length - 5, 5);
Console.WriteLine(lastDigits);

var requiredMask = new String('#', cardNumber.Length - firstDigits.Length);
Console.WriteLine(requiredMask);

var maskedString = string.Concat(requiredMask, lastDigits);
Console.WriteLine(maskedString);

Output
ABCDE
1234F
#####
#####1234F

A: Add event OnTextChanged to your textbox with below code
private void textBox_TextChanged(object sender, EventArgs e)
{
    TextBox tb = sender as TextBox;
    if (tb != null && !string.IsNullOrWhiteSpace(tb.Text))
    {
        tb.Text = tb.Text.Remove(0, 6).PadLeft(10, '#');
    }
}


text:
Q: JW Player controls not working I have used JW Player plugin in my joomla website. We have a lot of videos to upload in our website, so we are using Amazon. In the desktop webbrowser the controls of player are working fine. But in mobile and safari webbrowser the controls are not shown properly.
This is the code I have added for amazon tag({amazon}{/amazon}).
<script type=\"text/javascript\">
jwplayer('{SOURCE}').setup({

    'playlist': [{
        sources: [{
        'file':'https://s3.amazonaws.com/qa-mp4format/{SOURCE}'
        },{
        'file':'rtmp://srzg2rz4587c9.cloudfront.net/cfx/st/mp4:{SOURCE}'
        }]
        }],
    'image': '{PLAYER_POSTER_FRAME_REMOTE}',
    'height': '{HEIGHT}',
    'width': '{WIDTH}',
    'autostart': '{PLAYER_AUTOPLAY}',
    'repeat': '{PLAYER_LOOP}',
    'primary': 'flash',
    'controls': '{JWPLAYER_CONTROLS}'
});

Please help me to solve this problem.

A: The JW controls will show up by default, so you can take that out of your configuration. Also if you are concerned about your mobile viewer experience, you will not want to force 'flash'.


text:
Q: Cloud Datastore metric baseline to be alerted In my company, there is a request to be alerted for the following metrics on a Cloud DataStore service configuration but they don't know which are the baselines for each of these metrics.
Do they have to be like a fixed count (ie: request_count > 100) or maybe an average.
api/request_count
index/write_count
entity/read_sizes
entity/write_sizes

I was checking free quota limits here but I'm not really sure which values can be the right ones to use for a baseline.


text:
Q: Combobox selection warns "This implementation does not support subelements" On my touchscreen computer, I get a warning when I use a simple Qt combobox (in PySide):
class MyComBox(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        comboxText=["Hi", "Bye", "Give me a warning"]
        self.comBox=QtGui.QComboBox(self)
        self.comBox.addItems(comboxText)
        self.comBox.move(20,40)
        self.setGeometry(100, 100, 200, 100)
        self.show()

When I create an instance of the GUI, the GUI looks as I expect, but when I press on the dropdown menu, I get the following warning in my shell:
QAccessibleWidget::rect: This implementation does not support subelements! (ID 1 unknown for QWidget)

While it is somewhat innocuous, I'd like to make this go away as it is distracting when it pops up every time someone clicks on a combobox. Google has not yielded much on the topic, except the following related discussion:
http://www.daz3d.com/forums/viewthread/6773/
I am on Windows 7 and Python 2.7, running under Anaconda. Note I am only getting this error on my Dell touchscreen laptop, but not my work desktops (neither of which are touch screen). All are Windows 7, but the touchscreen laptop is a Dell Inspiron 15z "downgraded" from Windows 8.
Because of the lack of people clamoring with me about this problem, it is clear this seems fairly localized to me. Hence I have submitted this as a bug report at the Qt Project site (https://bugreports.qt-project.org/browse/PYSIDE-242). I will update here if I hear anything back.

A: The thread http://niftools.sourceforge.net/forum/viewtopic.php?f=24&t=2147 indicates that it is a problem with Qt accessibility support on some touch/tablets. Can you try disabling the Tablet PC Components (or, in Vista, Tablet PC Optional Components) from Control Panel -> Program Features -> Turn Windows Features On or Off, as mentioned in the last post there and check if it works.
Also, if you just want to suppress the the warning, since it is innocuous, you can install your own message handler using QtCore.qInstallMsgHandler()
And, this is more likely a Qt issue than a PySide one.

A: I had the same problem on windows8. Stopping the service TabletInputService seemed to fix it for me


text:
Q: Xcode Image Asset Catelogue I would like to use backgroundimage on UIButton with little arrow at bottom.
In Assest catalogue  I have slice image but result is not what I want.

Result

is there anyway I can add another vertical line? I could use exact size but button size is changing at different place.

A: In the end I used excellent third party tool.
PaintCode
http://www.paintcodeapp.com/


text:
Q: is it possible to have a function inside a defined constant? According to https://www.tutorialspoint.com/php/php_constants.htm a normal costant is define by using define() function plus a value:
define('TEST', 123);

I think it would be interesting and useful if there were a way to define a constant with a function inside:
define ('ME', function($test){
   if($test == true){
       return "Whats up";
   }else{
       return "whats down";
   }
});

Then perhaps I could do something like this?
 if($I_Said === ME($val)){
     do something;
 }

Is there a such a way to do this?

A: There's no syntactical or other important difference on the caller side to:
function ME() {}

if ($I_Said === ME($val))

So, just do that.


text:
Q: How to add all the python libraries in spyder How can I add all the python libraries in Spyder IDE which I have already downloaded using Terminal and are present in the directory /home/{username}/.local/lib/python3.6/site-packages

A: I have found the answer, Just go to Tools -> PYTHONPATH Manager and add a path to these libraries and restart Spyder.


text:
Q: How to stop webpack from creating dist/main.js after upgrade to Webpack 5? I am using Webpack with Elixir/Phoenix. I recently upgraded to Webpack 5 from Webpack 4.
I think everything is working fine except that now for some reason a dist and main.js are always created at the project root dist/main.js when I run my tests. This file is mostly empty:
/*
 * ATTENTION: The "eval" devtool has been used (maybe by default in mode: "development").
 * This devtool is neither made for production nor for readable output files.
 * It uses "eval()" calls to create a separate source file in the browser devtools.
 * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/)
 * or disable the default devtool with "devtool: false".
 * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/).
 */
/******/ (() => { // webpackBootstrap
/******/    "use strict";
/******/
/******/
/******/ })()
;

In my mix.exs I have the following. This is the line of code that creates the dist/main.js
  defp compile_assets(_) do
    Mix.shell().cmd("./assets/node_modules/webpack/bin/webpack.js --mode development",
      quiet: false
    )
  end

My webpack.config includes:
    devtool: 'eval-source-map',
    entry: {
      'app': glob.sync('./vendor/**/*.js').concat(['./js/app.js']),
      'marketing': glob.sync('./vendor/**/*.js').concat(['./js/marketing.js']),
      'admin': glob.sync('./vendor/**/*.js').concat(['./js/admin.js']),
    },
    output: {
      filename: '[name].js',
      path: path.resolve(__dirname, '../priv/static/js')
    },

When I run this in IEx I get:
iex(1)> Mix.shell().cmd("./assets/node_modules/webpack/bin/webpack.js --mode development", quiet: false)
asset main.js 662 bytes [emitted] (name: main)

ERROR in main
Module not found: Error: Can't resolve './src' in '/Users/me/development/apps/my_app'
resolve './src' in '/Users/me/development/apps/my_app'
  No description file found in /Users/me/development/apps/my_app or above
  No description file found in /Users/me/development/apps/my_app or above
  no extension
    /Users/me/development/apps/my_app/src doesn't exist
  .js
    /Users/me/development/apps/my_app/src.js doesn't exist
  .json
    /Users/me/development/apps/my_app/src.json doesn't exist
  .wasm
    /Users/me/development/apps/my_app/src.wasm doesn't exist
  as directory
    /Users/me/development/apps/my_app/src doesn't exist

webpack 5.50.0 compiled with 1 error in 50 ms
1

Since I have specified the entry I would assume it should be fine. Any help would be greatly appreciated.
Update:
Showing entire webpack.config.js
const path = require('path');
const glob = require('glob');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader');
const webpack = require('webpack')
const Dotenv = require('dotenv-webpack');

module.exports = (webpackEnv, webpackOptions) => {

  const platform = process.env.PLATFORM
  if (platform == undefined) {
    throw "process.env.PLATFORM is undefined!"
  }
  dotEnvFile = `.env.${platform}`
  const mode = platform === 'production' ? 'production' : 'development';
  const minimize = platform === 'production' ? true : false;
  const cache = platform === 'production' ? false : { type: 'filesystem' };
  const vueProdDevtools = platform === 'production' ? false : true;

  return {
    cache: cache,
    mode: mode,
    optimization: {
      minimize: minimize,
      minimizer: [
        new TerserPlugin({
          parallel: true
        }),
        new CssMinimizerPlugin()
      ]
    },
    entry: {
      'app': glob.sync('./vendor/**/*.js').concat(['./js/app.js']),
      'marketing': glob.sync('./vendor/**/*.js').concat(['./js/marketing.js']),
      'admin': glob.sync('./vendor/**/*.js').concat(['./js/admin.js']),
    },
    output: {
      filename: '[name].js',
      path: path.resolve(__dirname, '../priv/static/js')
    },
    module: {
      rules: [
        {
          test: /\.vue$/,
          use: [
            {
              loader: 'vue-loader',
              options: {
                compilerOptions: {
                  compatConfig: {
                    MODE: 2
                  }
                }
              }
            }
          ]
        },      {
          test: /\.js$/,
          exclude: /node_modules/,
          use: [
            {
              loader: 'babel-loader'
            }
          ]
        },
        {
          test: /\.css$/,
          use: [
            MiniCssExtractPlugin.loader,
            'css-loader',
            'postcss-loader'
          ]
        },
        {
          test: /\.scss$/,
          use: [
            'vue-style-loader',
            'css-loader',
            'sass-loader'
          ]
        }
      ]
    },
    plugins: [
      new Dotenv({
        path: path.resolve(__dirname, '..', dotEnvFile)
      }),
      new MiniCssExtractPlugin({ filename: '../css/[name].css' }),
      new CopyWebpackPlugin({patterns:[{ from: 'static/', to: '../' }]}),
      new VueLoaderPlugin(),
      new webpack.DefinePlugin({
        __VUE_PROD_DEVTOOLS__: vueProdDevtools
      })
    ],
    resolve: {
      alias: {
        vue: '@vue/compat'
      },
      extensions: [ '*', '.js', '.vue', '.json' ],
    },
  }
};

Update 2:
Per the suggestion to turn filename into a function I updated it to:
    output: {
      filename: (pathData, assetInfo) => {
        console.log("******** pathData:", pathData)
        console.log("******** assetInfo:", assetInfo)

        return '[name].js'
      },
      path: path.resolve(__dirname, '../priv/static/js')
    }

The interesting bit is when I run
mix phx.server

The outputs are:
******** pathData: {
  hash: '449eeaf77670741a6887',
  runtime: 'app',
  chunk: Chunk {
    id: 'app',
    ids: [ 'app' ],
    debugId: 1000,
    name: 'app',
    idNameHints: SortableSet [Set] {
      _sortFn: undefined,
      _lastActiveSortFn: Symbol(not sorted),
      _cache: undefined,
      _cacheOrderIndependent: undefined
    },
    preventIntegration: false,
    filenameTemplate: undefined,
    _groups: SortableSet [Set] {
      [Entrypoint],
      _sortFn: [Function: compareChunkGroupsByIndex],
      _lastActiveSortFn: Symbol(not sorted),
      _cache: undefined,
      _cacheOrderIndependent: undefined
    },
    runtime: 'app',
    files: SetDeprecatedArray [Set] { '../css/app.css' },
    auxiliaryFiles: Set {},
    rendered: false,
    hash: '09da590258e85092531ee1a26f184db4',
    contentHash: [Object: null prototype] {
      'css/mini-extract': '4500f8bd1df6d9d548c3',
      javascript: 'a1a060a5ddfcebc58653'
    },
    renderedHash: '09da590258e85092531e',
    chunkReason: undefined,
    extraAsync: false
  },
  contentHashType: 'javascript'
}
******** assetInfo: {}
******** pathData: {
  hash: '449eeaf77670741a6887',
  runtime: 'marketing',
  chunk: Chunk {
    id: 'marketing',
    ids: [ 'marketing' ],
    debugId: 1001,
    name: 'marketing',
    idNameHints: SortableSet [Set] {
      _sortFn: undefined,
      _lastActiveSortFn: Symbol(not sorted),
      _cache: undefined,
      _cacheOrderIndependent: undefined
    },
    preventIntegration: false,
    filenameTemplate: undefined,
    _groups: SortableSet [Set] {
      [Entrypoint],
      _sortFn: [Function: compareChunkGroupsByIndex],
      _lastActiveSortFn: Symbol(not sorted),
      _cache: undefined,
      _cacheOrderIndependent: undefined
    },
    runtime: 'marketing',
    files: SetDeprecatedArray [Set] { '../css/marketing.css' },
    auxiliaryFiles: Set {},
    rendered: false,
    hash: 'e11f89b04d9e2d62877069c780bfd99c',
    contentHash: [Object: null prototype] {
      'css/mini-extract': '1218451d2cf9d01e4c35',
      javascript: '0bf8255fc0482a761bba'
    },
    renderedHash: 'e11f89b04d9e2d628770',
    chunkReason: undefined,
    extraAsync: false
  },
  contentHashType: 'javascript'
}
******** assetInfo: {}
******** pathData: {
  hash: '449eeaf77670741a6887',
  runtime: 'admin',
  chunk: Chunk {
    id: 'admin',
    ids: [ 'admin' ],
    debugId: 1002,
    name: 'admin',
    idNameHints: SortableSet [Set] {
      _sortFn: undefined,
      _lastActiveSortFn: Symbol(not sorted),
      _cache: undefined,
      _cacheOrderIndependent: undefined
    },
    preventIntegration: false,
    filenameTemplate: undefined,
    _groups: SortableSet [Set] {
      [Entrypoint],
      _sortFn: [Function: compareChunkGroupsByIndex],
      _lastActiveSortFn: Symbol(not sorted),
      _cache: undefined,
      _cacheOrderIndependent: undefined
    },
    runtime: 'admin',
    files: SetDeprecatedArray [Set] { '../css/admin.css' },
    auxiliaryFiles: Set {},
    rendered: false,
    hash: '6a55d7e6d1cc37be6087e1c464285cc2',
    contentHash: [Object: null prototype] {
      'css/mini-extract': '613df220ea4099b5fbf5',
      javascript: '90a7803cefe86244fd07'
    },
    renderedHash: '6a55d7e6d1cc37be6087',
    chunkReason: undefined,
    extraAsync: false
  },
  contentHashType: 'javascript'
}
******** assetInfo: {}

So, I see that it run one time for each entry point (makes sense). However, when in IEx and I do:
Interactive Elixir (1.12.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Mix.shell().cmd("./assets/node_modules/webpack/bin/webpack.js --mode development", quiet: false)
asset main.js 662 bytes [compared for emit] (name: main)

ERROR in main
Module not found: Error: Can't resolve './src' in '/Users/me/development/apps/my_app'
resolve './src' in '/Users/me/development/apps/my_app'
  No description file found in /Users/me/development/apps/my_app or above
  No description file found in /Users/me/development/apps/my_app or above
  no extension
    /Users/me/development/apps/my_app/src doesn't exist
  .js
    /Users/me/development/apps/my_app/src.js doesn't exist
  .json
    /Users/me/development/apps/my_app/src.json doesn't exist
  .wasm
    /Users/me/development/apps/my_app/src.wasm doesn't exist
  as directory
    /Users/me/development/apps/my_app/src doesn't exist

webpack 5.51.1 compiled with 1 error in 47 ms
1

So the console.log command isn't printing in IEx. Could that be related? Could be be that the command the test code is running, the one in IEx, is running a "different" webpack command? Is it perhaps not finding the webpack.config?

A: The reason dist/main.js is created is because when webpack is run it is unable to find a webpack.config.js and so dist/main.js is a default behavior.
I discovered this when I updated the filename to be a function. In it I then called console.log("test") and expected to see it in IEx. The console log never printed out.
I then ran the regular mix phx.server and I did get the new output.
In dev.exs there's:
    watchers: [
      node: [
        "node_modules/webpack/bin/webpack.js",
        "--mode",
        "development",
        "--progress",
        "--watch",
        "--watch-options-stdin",
        cd: Path.expand("../assets", __DIR__)
      ]
    ]

This all looks as expected but with a different implementation. (It is using cd: Path.expand but I'm only noticing this now.)
So, why is one not working while the other is fine?
When taking a closer look at
  defp compile_assets(_) do
    Mix.shell().cmd("./assets/node_modules/webpack/bin/webpack.js --mode development",
      quiet: false
    )
  end

I decided to see where I got this from (which was from the Wallaby documentation)
I went back to the documentation and noticed it had changed.
Here is the change:
https://github.com/elixir-wallaby/wallaby/commit/834bdb726228349f800837e470a0c77cd2f4a6bd
Now the code should be:
  defp compile_assets(_) do
    Mix.shell().cmd("cd assets && ./node_modules/.bin/webpack --mode development",
      quiet: true
    )

I don't know why we'd need to cd into assets vs what we had before, but now it works.


text:
Q: How can I group A horizontal Results set into a vertical one like below: Select * from Machines Where DayOfWeight = '2013-10-31'

RETURNS
MachineId   TotalValue  DayOfWeigh
1           290.70      2013-10-31
2           647.20      2013-10-31
3           2178.56     2013-10-31

How can I get it to return:
DayOfWeigh  1       2       3
2013-10-31  290.70  647.20  2178.56

This seems quite simple, but I cant find the right grouping statement or pivot perhaps?

A: select *
from machines
pivot (sum(TotalValue) for MachineID in ([1],[2],[3])) p

http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

A: This fixed it
SELECT *
FROM (
    SELECT
        DayOfWeigh ,MachineId, TotalValue
    FROM MachineTotals
) as s
PIVOT
(
    SUM(TotalValue)
    FOR MachineId IN ([1], [2], [3)
)AS p


text:
Q: Can't get the name and age of each student. Instead I get weird characters and age = 0? #include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct Student {
    char name[50];
    int age;
} student;

int main() {
    char name[50];
    int age;

    // Requirement values
    char stop[] = "stop";
    int check = 1;

    int countOfStudents = 0;

    // Array with students
    student* students = malloc(countOfStudents);

    while(check) {

        scanf("%s", &name);

        if(!strcmp(name, stop) == 0) {

            scanf(" %i", &age);
            struct Student student = {*name, age};

            strcpy(students[countOfStudents].name, student.name);
            students[countOfStudents].age = student.age;

            countOfStudents++;
        } else {
            printf("You wrote stop \n");
            check = 0;
        }
    }

    for (int i = 0; i < countOfStudents; ++i) {
        printf("Name = %s , Age = %i", students[i].name, students[i].age);
        printf("\n");
    }

    return 0;
}

I have an array with students. Each student is a struct, and has a name & age.
I have to register each student until the user write "stop".
Input:
test
12
stop

The output is like this:
You wrote stop
ogram Files (x86)
Name = t♀ , Age = 0

Why does this happen?

A: At least this problem
Wrong allocation
int countOfStudents = 0;
student* students = malloc(countOfStudents);

Allocates zero mmmeory.
Try
int countOfStudents = 0;
int Students_MAX = 100;
student* students = malloc(sizeof *students * Students_MAX);

and limit iterations:
while(countOfStudents < Students_MAX && check)

Better to use a width limit
char name[50];
...
// scanf("%s", name);
scanf("%49s", name);

struct Student student = {{*name, age}}; is not the needed initialization.

A: memory allocation is wrong.
the following code will work.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct Student
{
    char name[50];
    int age;
} student;

int main()
{
    char name[50];
    int age;

    char stop[] = "stop";
    int check = 1;

    int countOfStudents = 0;

    student* students = NULL;

    while(check)
    {
        scanf("%49s", name); // 49 + '\0' = 50
        if(!strcmp(name, stop) == 0)
        {
            scanf(" %i", &age);
            if(!students)
            {
                students = (student*) malloc(sizeof(student*)); // allocating for the first
            }
            else
            {
                students = (student*) realloc(students, sizeof(student*)); // allocating
            }
            strcpy(students[countOfStudents].name, name);
            students[countOfStudents].age = age;
            countOfStudents++;
         }
         else
         {
            printf("You wrote stop \n");
            check = 0;
         }
     }

    for (int i = 0; i < countOfStudents; ++i)
    {
        printf("Name = %s , Age = %i", students[i].name, students[i].age);
        printf("\n");
    }

    free(students);
    students = NULL;

    return 0;
}


text:
Q: Network printer loses connection, but not its fault tl;dr: What could cause a network printer to lose its connection besides the printer or router or cable between them?
I have had a Canon wired network laser printer for years with no issues, but after a point in time a new problem developed - sometimes when I or my husband tried to print (both PCs are Win7 if that matters) the printer driver would complain of a "network board error". Cycling power on the printer would fix it for the time being, but it would recur (usually the next day or so). After putting up with this for several months, we decided that the printer was dying and bought a new printer, a similar but newer model. But the new one did the same thing! I thought back and realized that it may have started happening at about the time I had simplified our home LAN from a wired router and a wireless access point to one robust wireless router (Netgear) that could do everything we needed. I tried a different network cable, but when that didn't solve it, I decided that the our Netgear router must be flaky. It was already out of warranty, so I bought yet another new router, this time a Buffalo. But... yup, you guessed it: The problem remains! It seems to happen after being idle for some time (a matter of hours, I think) - once we have printed something, we can print more with no issues.
The printer is on a fixed IP address (192.168.1.6) as is a NAS drive (192.168.1.3). The PCs are on DHCP, but the router is set to only assign addresses above 192.168.1.10, so as far as I know I'm not having address conflicts. I do have random interruptions to my internet connection (not obvious when just browsing, but enough to kill Skype and SSH), but that has been going on since long before the printer problem (the reason I changed the network layout was to try to fix that) and it shouldn't even be related to this anyway - the PCs and printer are simply on the internal LAN, and the printer is sitting on the shelf right above the router and is directly connected to one of its LAN ports with a short cable. I can't figure out what else to try! Any ideas?
EDITS: A suggested in the comments, I tested connecting the printer directly to my computer with a LAN cable for a week, and there were no problems, so it's definitely not the printer itself but something in the mysterious bowels of my LAN. I tried to use Wireshark as suggested in other comments, but it doesn't see the traffic between the router and printer (promiscuous mode doesn't work on Windows, apparently). The problem might be happening after some device goes to sleep and wakes up, or leaves the LAN and returns, but I haven't been able to identify a repeatable pattern.


text:
Q: How do I specify a USB device as a specific COM port? We are working on switching our POS registers to Ubuntu from Windows.  Our registers run in a WAN configuration so the POS software doesn't actually run on them but rather is running on a Windows server and is served to them through Citrix Receiver.  We have our devices set in the POS software on the server to specific COM ports. When a register connects the server maps up the COM ports/devices on that machine and talks to those devices on specific COM ports.  Specifically COM4 for receipt printer and COM5 for credit card reader.  Both are USB devices emulating COM ports.
I've already made the user part of the dialout group and found the tty devices in the /dev folder.
What do I need to do tell ttyAMC0 to identify itself as COM5?

A: You need to create a new UDEV rule to make sure the software always points to the correct port.
Go to /etc/udev/rules.d and create a file named "COM5.rules"
Edit the file and put the following line in it. The id's (067b) and (2303) must be replaced by the id's from your hardware.
SUBSYSTEM=="tty", ATTRS{idVendor}=="067b", ATTRS{idProduct}=="2303", SYMLINK+="COM5"

After reboot a device called @COM5 will be created in /dev
Set the software to go to /dev/COM5
Rebooting or taking out the port and installing it again even updating, upgrading and even major version upgrades of the whole system, it all stays persistent.


text:
Q: Иконки программы в зависимости от ОС Доброго времени суток!
Хотелось бы научится изменять иконку программы
в зависимости от операционной системы...
По типу как папки, скинул на флешку, а отображается
под разными ОС по-своему...
Нет идей как это запрограммировать до запуска программы?
A: Простого решения, разумеется нет, поскольку ваше приложение при открытии папки проводником должно автоматически предоставить ему некоторую иконку, которая будет им отрисована.
Соответственно, простой способ - до первого запуска хранить любую иконку, а после первого запуска патчить свой фрагмент .exe, куда и зашит ресурс иконки, заменяя ее на необходимую.
Сложный способ - вешать глобальный хук на соответствующий вызов получения иконки (готов допустить, что его, может быть, придется перехукивать и на уровне Native API) и опять же, на лету патчить ресурс, демонстрируя ту иконку, которая вам нужна. В этом способе даже в первый раз иконка будет показана правильная.
В общем, задачка интересная, но, естественно, ни один человек в здравом уме таким заниматься не станет :)
A: Можно воспользоваться тем, что иконку ищет проводник в ресурсах приложения. И для висты/7 поддерживаются большие иконки большого размера 256 на 256. А ХР их ещё не поддерживает. Конечно, это грязный хак, но по другому - только патчить проводник.
Но пользователь может зайти с TotalCommander или другой программы и приплыли...
а вот картинки папок отображаются по разному, потому что картинки для папок хранятся не на флешке, а в системных каталогах.
A: Я немного не понял вопрос, нужно программно менять иконки как иконки папок?
Если офф топ,то извин.
У Application есть вроде свойство Icon - её вроде и менять надо...
Давно этим занимался просто....


text:
Q: How to optimize a dictionary with multiple keys per distinct value? I have a relatively large set of data that lends itself very naturally to the c#'s dictionary object. Currently, I have 102400 key-value pairs that are being generated semi-dynamically when my program starts up. My problem is that I have to run a great number of lookup operations as fast as possible.
According to This Page the speed of the lookups is directly influenced by the number of key-value pairs in the dictionary. My data is a bit odd in that a great number of different keys lead to the same value. In fact, I have only 4900 distinct values... This means that I have an average of 20 key-value pairs for each distinct value.
My first instinct was to swap the keys for the values (as I only care about the distinct values in the data) then have the old keys in a list or array as the new values. This reduced my dictionary size to 4900 from 102400 key-value pairs, but I can't see any way to efficiently search all of the lists for a specific value to get the key by.
I know that my description probably got a bit dificult to follow as I switched the keys and values, so I've included a mock-up of my data to show you what I mean:
old method:
Key   Value
---   -----
1     1
2     2
3     3
4     1
5     3
6     2
7     2
8     1
9     3
10    2
11    3
12    1

New structure:
Key   Value
---   -----
1     {1,4,8,12}
2     {2,6,7,10}
3     {3,9,5,11}

In my program, I'm going to be given '11' and I'll need to return '3'. The first structure is a simple lookup, but is a huge list which seems to be slowing things down... the second adds so much logical overhead to track down which value list I'm looking for that I've only seen a reduction in speed trying to implement it.
Am I barking up the wrong tree here? Should I just accept the speed of the larger list, or is there some other way that I can store my data to increase the lookup speed?

A: If all keys are distinct and contiguous, then you should consider a simple array; if the keys aren't contiguous, then a hash map type of structure if they aren't.  This would be approaching O(1) if the hashing function is good, and if they are all integers, shouldn't take up much space.
Even then, for 102400 elements, a binary tree lookup would take at most log2(102400) operations per lookup which is 16.64 operations, not exactly slow.

A: Use a Lookup (.NET 3.5 and above).
From MSDN:

Lookup(Of TKey, TElement)
Represents a collection of keys each mapped to one or more values.

EDIT:
By the way, if all your keys are contiguous (ie 1, 2, 3, ...), use a simple array.

A: Using your parameters of a Dictionary<int, ulong>, 20 key/value pairs per unique value, a size of 102,400 total key/value pairs, and the code you linked to, I ran a test on a 102,400 count dictionary and one ten times that size:
    int entries = 102400;
    var full = new Dictionary<int, ulong>();
    var half = new Dictionary<int, ulong>();
    var both = new Dictionary<int, ulong>();

    for (int i = 0; i < entries * 10; i++)
    {
        full.Add(i, (ulong)(i % 20));
        if (i < entries)
        {
            both.Add(i, (ulong)(i % 20));
            half.Add(i, (ulong)(i % 20));
        }
    }

    const int m = 100;
    Stopwatch s1 = Stopwatch.StartNew();
    for (int i = 0; i < m; i++)
    {
        foreach (var key in both.Keys)
        {
            if (!full.ContainsKey(key))
            {
                throw new Exception();
            }
        }
    }
    s1.Stop();

    Stopwatch s2 = Stopwatch.StartNew();
    for (int i = 0; i < m; i++)
    {
        foreach (var key in both.Keys)
        {
            if (!half.ContainsKey(key))
            {
                throw new Exception();
            }
        }
    }
    s2.Stop();
    Console.WriteLine("{0},{1}, difference = {2}", s1.ElapsedMilliseconds, s2.ElapsedMilliseconds, s1.ElapsedMilliseconds - s2.ElapsedMilliseconds);

Both tests finished within 10 miliseconds of each other.
I don't think your lookup speed is the issue here.

A: A dictionary is the way to go if your keys are non-contiguous.  I'm not aware of any faster lookup method for that kind of data.  Your example shows contiguous, sequential data which could benefit from storing your values directly in an array and jumping directly to to correct index based off the key.  As long as the keys for your real data mimics your example keys I would go with an array.

A: One time you made your new strutcure, something like this, as much as I understood,
Dictionary<first, List<second>>, where  first and second are integers.
You can take care about a fact that the content of List<second> is an ordered.
Considering that you challenge is not fast composition of data, but fast access and recovery, having the List<second> will let you execute secure List,BinarySearch, the fastest possible way to find a data among the list items.


text:
Q: Android Activate Internet I create a new App with need access to the Internet.
I can check if some internet connection is on, but i try to get a new internet connection if no one is established.
public boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager)
        getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni!=null && ni.isAvailable() && ni.isConnected()) {
            return true;
        } else {
            return false;
        }
}

Can some one help me.
Thank you for the help.

A: The ConnectivityManager does this for you. If there is WiFi available, the ConnectivityManager will use it, if not, it will try to use the next best (4G, 3G, etc)..
So, what you have there is the extent of checking for connectivity. If your NetworkInfo object is null, you can't access the internet.


text:
Q: what is the size of windows semaphore object? How to find size of a semaphore object in windows?
I tried using sizeof() but we cannot give name of the sempahore object as an argument to sizeof. It has to be the handle. sizeof(HANDLE) gives us the size of handle and not semaphore.

A: This what is known as an "opaque handle.". There is no way to know how big it really is, what it contains or how any of the functions work internally.  This gives Microsoft the ability to completely rewrite the implementation with each new version of Windows if they want to without worrying about breaking existing code.  It's a similar concept to having a public and private interface to a class.  Since we are not working on the Windows kernel, we only get to see the public interface.
Update:
It might be possible to get a rough idea of how big they are by creating a bunch and monitoring what happens to your memory usage in Process Explorer.  However, since there is a good chance that they live in the kernel and not in user space, it might not show up at all.  In any case, there are no guarantees about any other version of Windows, past or future, including patches/service packs.

A: It's something "hidden" from you. You can't say how big it is. And it's a kernel object, so it probably doesn't even live in your address space. It's like asking "how big is the Process Table?", or "how many MB is Windows wasting?".
I'll add that I have made a small test on my Windows 7 32 bits machine: 100000 kernel semaphores (with name X{number} with 0 <= number < 100000)) : 4 mb of kernel memory and 8 mb of user space (both measured with Task Manager). It's about 40 bytes/semaphore in kernel space and 80 bytes/semaphore in user space! (this in Win32... In 64 bits it'll probably double)


text:
Q: API for Shapeless Extensible Records I am trying to learn Shapeless(2.3.2). I have created a very simple container for extensible records:
   case class Records[L <: HList](ps: L) {

  def get(k: Witness)(implicit selector: Selector[L, k.T]): selector.Out = selector(ps)

  def rm[V, Out <: HList](k: Witness)(implicit remover: Remover.Aux[L, k.T, (V, Out)]) =
    this.copy(ps = remover(ps)._2)

  def upd[F](f: F)(implicit updater: Updater[L, F]) = this.copy(ps = updater(ps, f))
}

Now I am trying to realise API method like:
def upsert[T](k: String, v: T) = ???

All of my attemps are finished with compile errors like:
could not find implicit value for parameter updater: shapeless.ops.record.Updater[L,T with shapeless.labelled.KeyTag[k.type,T]]

Could you please help me to understand how to build such APIs(not tightened to shapeless) and how to gather information to solve such issues ?

A: I figured, I'd make my comment an answer, so that it can be accepted.
From my experience working with shapeless, when compiler complains about missing implicit value, the first thing to do is to try and provide it to the relevant function via an implicit parameter, especially if the type in question is something from shapeless. Shapeless provides lots of those implicits, and there are very good chance adding implicit parameter will fix such error.
In this case, add the Updater (not sure about type parameters, but they should be in line with those from upd) implicit parameter to the upsert function.


text:
Q: undefined method 'id' - Section 5.12 Updating Posts I'm following the Getting Started tutorial for Rails 4.0.0, http://guides.rubyonrails.org/getting_started.html#updating-posts, and was having the same problem as the user who asked this question, UrlGenerationError on section 5.12 of Rails Guide.  However, after fixing the issue he had with post_path and removing the '}' that was throwing an error, I now get an undefined method 'id' error message when I try to edit a post.  I've been searching stackoverflow and google for a people with similar problems but have not been able to find a solution.  Any help is much appreciated.
Below is my Posts controller and my edit.html.erb file
posts_controller.rb:
class PostsController < ApplicationController
def new
    @post = Post.new
end

def create
  @post = Post.new(post_params)

  if @post.save
    redirect_to action: :show, id: @post.id
  else
    render 'new'
  end
end

def show
  @post = Post.find(params[:id])
end

def index
  @posts = Post.all
end

private
  def post_params
    params.require(:post).permit(:title, :text)
  end

def edit
  @post = Post.find(params[:id])
end

  def update
    @post = Post.find(params[:id])

    if @post.update(params[:post].permit(:title, :text))
      redirect_to @post
    else
      render 'edit'
    end
  end
end

edit.html.erb:

Editing post

<%= form_for :post, url: post_path(@post.id) ,
method: :patch do |f| %>
  <% if @post.errors.any? %>

<%= pluralize(@post.errors.count, "error") %> prohibited
      this post from being saved:

    <% @post.errors.full_messages.each do |msg| %>

<%= msg %>

    <% end %>

  <% end %>

    <%= f.label :title %>

    <%= f.text_field :title %>

    <%= f.label :text %>

    <%= f.text_area :text %>

    <%= f.submit %>

<% end %>

<%= link_to 'Back', posts_path %>

A: Start with moving You edit and update methods out of the private scope! And point to the line the error is appearing.


text:
Q: Android Application Project not showing under dropdown I was running Eclipse 4.2 from Google's ADT bundle and it was not starting properly so I decided to install Eclipse 4.3, the SDK and the ADT plugin separately, instead of using the ADT Bundle.
Now, when I was using Google's ADT bundle, in the dropdown menu for "File - New", you would see "Android Application Project". In my new install, Eclipse 4.3, it is nowhere to be found. You can only see it if you click on "Other" and then you will have to search for it under the "Android" folder.
Do you know how I can get it back in the dropdown, instead of having to find it every time under "Other"?

A: Go to Window -> Customize Perspective -> Menu visibility -> File -> New and check "Android Application Project" option:

A: This usually happens when you don't select any android SDK in "Preferences > Android". Some wired cases if you set the path also this problem may occurs. So solution to overcome it is,You just have to reset the perspective in eclipse, Windows > Reset Perspective.
Hope this is still helpful.


text:
Q: How to handle insufficient typing in external libraries? I like making use of the typing capabilities in Python along with a static type check e.g. pyright. Unfortunately, not all libraries are completely typed. For example some functions may be generated at runtime (therefore missing) or the function return type is not specified because it depends on the input parameters.
These type of functions obviously result in warnings. How do you resolve these types of warnings from your type checker?


text:
Q: Preserve comments in pip requirements file after regenerate it I have the following requirements file:
Flask==0.10.1
Flask-SQLAlchemy==2.0
Flask-WTF==0.10.3
itsdangerous==0.24
Jinja2==2.7.3
MarkupSafe==0.23
#MySQL-python==1.2.5
SQLAlchemy==0.9.8
Werkzeug==0.9.6
WTForms==2.0.1

But after I run pip freeze > requirements.txt the commented line (MySQL-python==1.2.5) is replaced
Flask==0.10.1
Flask-SQLAlchemy==2.0
Flask-WTF==0.10.3
itsdangerous==0.24
Jinja2==2.7.3
MarkupSafe==0.23
MySQL-python==1.2.5
SQLAlchemy==0.9.8
Werkzeug==0.9.6
WTForms==2.0.1

Is there any way to preserve comments?

A: You can run pip freeze -r requirements.txt which will preserve the order and contents of requirements.txt when pip is freezing the installed packages (including comments).
However, it seems that your virtualenv does have MySQL-python installed so you'll end up with both a commented and uncommented line for MySQL-python. I think you need to either uncomment the line or uninstall MySQL-python for "preserving comments" to make sense.


text:
Q: finding just full words in a python string Basically it all comes down to finding just the fullword, not matching also a substring thereof.
I have phrases like:
texto = "hello today is the first day of working week" and what I wanted to do is to split that phrase into words to see if any matched fullwords that I have obtained from a sql query, like this:
sql = "select keyword from keywords"
    try:
        cursor.execute(sql)
        # Fetch all the rows in a list of lists.
        results = cursor.fetchall()
        for result in results:
            keywords.append(result)

so there I have a tuple of keywords.
So, yes, of course, you would split the phrase like this:
for word in texto.split():
    if word in keywords.__str__():
        print ("keyword %s detected in texto" % (word))

but while that does indeed find me words, it also "finds" me things that I would have not wanted or expected (a substring of a word):
I know that in PHP you would do something like this:
if (preg_match("/\b$search\b/", texto)):
            {print "word found"}

and I ve read quite a few discussions on this at SO. Some people say that you just do split, (but that is what I have done), others say use this:
in isn't how it's done.
>>> re.search(r'\babc\b', 'abc123')
>>> re.search(r'\babc\b', 'abc 123')
<_sre.SRE_Match object at 0x1146780>

is this latest example the way to do it? according to the shell interpreter it would match the second row.

A: I dont't see why split() should not work. The issue is the .__str__() (which I don't see any need for). It creates one single string in which the keywords are searched - and then it will find substrings as well.
The following is working for me:
texto = "hello today is the first day of working week"
keywords = ["is", "day", "week", "work", "sun"]

for keyword in keywords:
    print("keyword", keyword, end=" ")
    if keyword in texto.split():
        print("found.")
    else:
        print("not found")

work and sun should not match, work is a substring in the text, sun is not in the text.
Output is
keyword is found.
keyword day found.
keyword week found.
keyword work not found
keyword sun not found


text:
Q: Inserindo uma PROCEDURE em query() no PHP Galera, estou há um tempo tentando integrar uma procedure juntamente com o PHP, mas ao chamá-la, o PHP continua apresentando erros:

Visão Geral:

$database = null;

 function Conecta($server, $user, $port, $bd){
  $GLOBALS['database'] = mysql_connect($server, $user, $port);
  mysql_select_db($bd);
  if ($GLOBALS['database']) {
   return $GLOBALS['database'];
  } else {
      aviso("ERRO!");
  }
 }

 function aviso($texto){
  ?>
   <script>
    alert("<?php echo $texto ?>");
   </script>
  <?php
 }

 function CadastrarFuncionario($nome_fun, $cargo_fun, $nascimento_fun, $cpf_fun, $rg_fun, $estado_fun, $salario_fun){
  $res = $GLOBALS['database']->query("SET @nomefun = '".$nome_fun."'");
  if ($res0) {
   aviso("foi");
  }
  $res .= $GLOBALS['database']->query("SET @cargofun = '".$cargo_fun."'");
  $res2 = $GLOBALS['database']->query("SET @nascimentofun = '".$nascimento_fun."'");
  $res3 = $GLOBALS['database']->query("SET @cpfun = '".$cpf_fun."'");
  $res4 = $GLOBALS['database']->query("SET @rgfun = '".$rg_fun."'");
  $res5 = $GLOBALS['database']->query("SET @estadofun = '".$estado_fun."'");
  $res6 = $GLOBALS['database']->query("SET @salariofun = '".$salario_fun."'");

  $sql = "CALL CadastrarFuncionario(@nomefun, @cargofun, @nascimentofun, @cpfun, @rgfun, @estadofun, @salariofun);";
  $res7 = $GLOBALS['database']->query($sql);
  if ($res7) {
   aviso("funcionário cadastrado com sucesso!");
  } else {
   aviso("erro!");
  }
 }

 function CadastrarDependente($nome_dep, $nascimento_dep, $funcionario_dep, $parentesco_dep, $conexao){
  $res = mysqli_query($conexao, "CALL CadastrarDependente ('".$nome_dep."', '".$nascimento_dep."', ".$funcionario_dep.", '".$parentesco_dep."')", MYSQLI_USE_RESULT);
  if ($res) {
   aviso("dependente cadastrado com sucesso!");
  } else {
   aviso("erro!");
  }
 }

Porém, não sei se o problema está no código ou na lógica de programação, mas esta procedure que foi chamada está programada esta maneira:

Tabelas e Procedures no MySQL:

CREATE TABLE funcionario (
 id INT PRIMARY KEY AUTO_INCREMENT,
 nome VARCHAR(100) NOT NULL,
 cargo VARCHAR(50) NOT NULL,
 nascimento DATE NOT NULL,
 cpf CHAR(20) NOT NULL,
 rg CHAR(20) NOT NULL,
 estado CHAR(50) NOT NULL,
 salario DOUBLE NOT NULL
);

CREATE TABLE dependente (
 id INT PRIMARY KEY AUTO_INCREMENT,
 nome VARCHAR(100) NOT NULL,
 nascimento DATE NOT NULL,
 funcionario_id INT NOT NULL,
 parentesco CHAR(50) NOT NULL,
 FOREIGN KEY (funcionario_id) REFERENCES funcionario (id)
);

# cadastrar

DELIMITER $$
CREATE PROCEDURE CadastrarFuncionario (IN nome_fun VARCHAR(100), IN cargo_fun VARCHAR(50), IN nascimento_fun DATE, IN cpf_fun CHAR(20), IN rg_fun CHAR(20), IN estado_fun CHAR(50), IN salario_fun DOUBLE)
BEGIN
 INSERT INTO funcionario VALUES (null, nome_fun, cargo_fun, nascimento_fun, cpf_fun, rg_fun, estado_fun, salario_fun);
END $$
DELIMITER ;

DELIMITER $$
CREATE PROCEDURE CadastrarDependente (IN nome_dep VARCHAR(100), IN nascimento_dep DATE, IN funcionario_dep INT, IN parentesco_dep CHAR(50))
BEGIN
 INSERT INTO dependente VALUES (null, nome_dep, nascimento_dep, funcionario_dep, parentesco_dep);
END $$
DELIMITER ;

E no servidor, o PHP está insistindo no mesmo erro:

Problema: Qual(is) são os erros que está fazendo o servidor retornar este aviso. E qual(is) seriam as boas práticas para criar uma procedure normal e chamá-la pelo PHP

A: Não está sendo feito o bind correto dos parâmetros, pode fazer assim:
// declara o sql
$sql = "CALL CadastrarFuncionario(@nomefun, @cargofun, @nascimentofun, @cpfun, @rgfun, @estadofun, @salariofun);";

// prepara a execucao da procedure
$res7 = $GLOBALS['database']->prepare($sql);

// passa os parametros
$res7->bindParam($nome_fun, $cargo_fun, $nascimento_fun, $cpf_fun, $rg_fun, $estado_fun, $salario_fun);

// executa
$res7->execute();


text:
Q: How do I vote on a map in CS:GO? Is it me being stupid, or do my keys not work while voting on a map in CS:GO?
I press 1 to 8 when the map vote appears at game end, nothing happens, sometimes I jumble keys to manage to get something happen, and a map gets really voted on, but then I don't know if I did it and how I did it.
Can somebody point me in the right direction?

A: As you said,by default you should be able to vote maps with number keys(1-8).
In game those keys are used to select your weapons,and as such can be binded to other keys.
So if you change the number 1(primary weapon) to lets say letter K...If you wanted to vote for the first map you will have to press K,pressing 1 wouldn't give your vote.
This is the default binding,if you want to vote maps with numbers 1-8 you should bind it correspondingly.


text:
Q: Stay DRY with DTO's Currently I'm creating a web interface for FreeRADIUS. It's just a small app, to simplify mutations for Shell- and SQL-lazy co-workers. I created a Entity Framework model for the database and want to encapsulate it by using the facade pattern. So I created a DTO class called Account. It stores data aggregated from three different tables. This is what Account.cs looks like:
public class Account
{
    public int? Id { get; set; }
    public string UserName { get; set; }
    public string Password { get; set; }
    public string GroupName { get; set; }
    public string IpAddress { get; set; }
    public string Route { get; set; }
}

This is the method I assemble and return a single Account-DTO.
Account Get(string userName)
{
    // Get the values from the database.
    var check = _entities.Checks.Single(x => x.UserName == userName);
    var userGroup = _entities.UserGroups.Single(x => x.UserName == userName);
    var ipReply = _entities.Replies.Single(x => x.UserName == userName && x.Attribute == "Framed-IP-Address");
    var routeReply = _entities.Replies.Single(x => x.UserName == userName && x.Attribute == "Framed-Route");

    // Populate the DTO
    var account = new Account
    {
        UserName = check.UserName,
        Password = check.Value,
        GroupName = userGroup.GroupName
    };

    if (ipReply != null) account.IpAddress = ipReply.Value;
    if (routeReply != null) account.Route = routeReply.Value;

    return account;
}

And this is the method to update the database by a user-submitted Account-DTO
void Update(Account account)
{
    // Get the values from the database. Again.
    var check = _entities.Checks.Single(x => x.UserName == account.UserName);
    var userGroup = _entities.UserGroups.Single(x => x.UserName == account.UserName);
    var ipReply = _entities.Replies.Single(x => x.UserName == account.UserName && x.Attribute == "Framed-IP-Address");
    var routeReply = _entities.Replies.Single(x => x.UserName == account.UserName && x.Attribute == "Framed-Route");

    // Update the possible attributes
    check.Value = account.Password;
    userGroup.GroupName = account.GroupName;
    ipReply.Value = account.IpAddress;
    routeReply.Value = account.Route;

    _entities.SaveChanges();
}

As you can see, I use the exact same code to retrieve data from the database. How can I DRY this code up?

A: Why not to simply extract shared code to local class
class AcccountFieldsByName {
// check, userGroup, ipReply, routeReply

    static AcccountFieldsByName Read(... _entities, string userName)
    {
    return new AcccountFieldsByName {
        check = _entities.Checks.Single(x => x.UserName == userName),
        userGroup = _entities.UserGroups.Single(x => x.UserName == userName),
        ipReply = _entities.Replies.Single(x => x.UserName == userName && x.Attribute == "Framed-IP-Address"),
        routeReply = _entities.Replies.Single(x => x.UserName == userName && x.Attribute == "Framed-Route"),
        }
    }
}


text:
Q: How can I perform perfect forwarding without using templates? I want perfect forwarding but I already know (and only accept) the type my function will take.
Here is a quick example I typed up:
class big_class
{
private:
    std::string m_somethingBig;
};

class testmove
{
public:

    void Add(big_class&& big)
    {
        std::cout << "Add via move\n";
        m_bigClasses.push_back(std::move(big));
    }

    void Add(big_class const& big)
    {
        std::cout << "Add via copy\n";
        m_bigClasses.push_back(big);
    }

private:

    std::vector<big_class> m_bigClasses;
};

int main()
{
    testmove tm;

    big_class big;
    tm.Add(big);

    tm.Add(big_class{});
}

Live Sample
Is it possible to do some form of implementation sharing between the two overloads of testmove::Add()? I want to optimize for move, and if someone does std::move() without my rvalue overload it will end up doing at least 1 copy before it is added to my vector.
Again, I realize I can solve this problem by making Add() a template function, and even using type traits and some template trickery. But I wanted to avoid this if possible. If you need to know why, I have a few reasons:

*

*I can't do implementation hiding with a template (restrict includes and symbol visibility to a single translation unit)

*Using a template here gives me more flexibility than I want (My contract requires I only use a big_class).

*Using a template would impact readability/maintainability for what should be a simple interface.

A: The approach suggested by Xeo (take the parameter by value) is the one I would strongly recommend. However, if for some reason you can't do that (e.g., moves are expensive but less so than copies), keep reading.
I think it's possible to satisfy all your criteria, but it's only worth it if the code is complicated enough so that duplicating it would be bad. The idea is to delegate to a template that will be explicitly instantiated only for big_class.
big_class.h:
// ...
public:
    void Add(big_class&& big)
    {
        Add_internal(std::move(big));
    }
    void Add(big_class const& big)
    {
        Add_internal(big);
    }
private:
    // not part of interface; defined in .cpp file
    template <typename T> void Add_internal(T&& big);

big_class.cpp:
// implementation of template
template <typename T> void big_class::Add_internal(T&& big) {
    // shared logic goes here
    m_bigClasses.push_back(std::forward<T>(big));
}
// explicit instantiation
template void big_class::Add_internal<big_class>(big_class&&);
template void big_class::Add_internal<big_class const&>(big_class const&);

A: if you really can't stand the idea of adding by value, you may provide one internal templated impl:
private:
    template<class X>
    auto add_impl(X&& x) {
        m_bigClasses.push_back(std::forward<X>(x));
    }

public:

    void Add(big_class&& big)
    {
        std::cout << "Add via move\n";
        add_impl(std::move(big));
    }

    void Add(big_class const& big)
    {
        std::cout << "Add via copy\n";
        add_impl(std::move(big));
    }

How can this work? you're moving a const ref!

Because std::move does not move anything. It merely casts an l-value reference to an r-value reference. So const T& becomes a const T&&, which no-one ever codes for. So it will decay to match the const T& or T that people do code for.


text:
Q: R data.table reverse a cumprod function to get rates of change Hi in the following example
library(data.table)
library(lubridate)
set.seed(1234)
a = data.table(date=seq(ymd('2001-6-30'),ymd('2003-6-30'),by='weeks'),a=rnorm(105),b=rnorm(105),c=rnorm(105))

I get output a little like
           date           a           b           c
  1: 2001-06-30 -1.20706575  0.16698928  0.41805782
  2: 2001-07-07  0.27742924 -0.89626463 -0.40023524
  3: 2001-07-14  1.08444118  0.16818539  1.49349310
  4: 2001-07-21 -2.34569770  0.35496826 -1.60708094
  5: 2001-07-28  0.42912469 -0.05210512 -0.41575179
 ---
101: 2003-05-31  0.41452353  0.76046236  1.47171869
102: 2003-06-07 -0.47471847  1.84246363  0.44366490
103: 2003-06-14  0.06599349  1.11236284 -0.42172187
104: 2003-06-21 -0.50247778  0.03266396 -0.04000163
105: 2003-06-28 -0.82599859 -1.11444896 -0.49227997

and I can cumulate it (if e.g it were rates of return) using
a[,(2:4):=lapply(.SD,function(x) cumprod(x/100+1)),.SDcols=2:4]

and get
           date         a         b         c
  1: 2001-06-30 0.9879293 1.0016699 1.0041806
  2: 2001-07-07 0.9906701 0.9926923 1.0001615
  3: 2001-07-14 1.0014134 0.9943618 1.0150988
  4: 2001-07-21 0.9779233 0.9978915 0.9987854
  5: 2001-07-28 0.9821198 0.9973716 0.9946329
 ---
101: 2003-05-31 0.8540733 1.0838999 1.1223825
102: 2003-06-07 0.8500188 1.1038704 1.1273621
103: 2003-06-14 0.8505798 1.1161495 1.1226078
104: 2003-06-21 0.8463058 1.1165140 1.1221587
105: 2003-06-28 0.8393153 1.1040711 1.1166346

My question is what do I do if I have the output and want to get back to the original rates of return?
b=(a[2:105,2:4,with=F]/a[1:104,2:4,with=F]-1)*100

followed by a merge seems clunky and I would have difficulty figuring out the merge operation.
Thanks

A: It's pretty much the same as for the cumprod:
a[,(2:4):=lapply(.SD,function(x) c(NA,(tail(x,-1)/head(x,-1)-1)*100)),.SDcols=2:4]


text:
Q: Discord.js ban duration I have been struggling with this issue for quite some time
I wanna see what options I have for a ban duration. However
the official discord documentation is barebones on this subject
guildMember.ban({ days: 7, reason: 'They deserved it' })
  .then(console.log)
  .catch(console.error);

This code bans a guildmember for 7 days
But aside from days are there minutes ? Hours ? Etc ?

A: It doesn't ban the member for 7 days. It just deletes 7 days of their messages. To actually ban them for ? days, ? minutes, ? hours, etc., you need to set a timer yourself (e.g. setTimeout, although the timer will be reset when you restart the bot).

A: Days is not the duration. Days specifies the days to delete messages in. Its like when you try to ban someone on discord, it gives you the option to select for how long you want to delete past messages. To implement a temp ban, you have to manually write code that unbans them.
Reference: https://discord.js.org/#/docs/main/stable/typedef/BanOptions


text:
Q: IOS 8 Default (Swift Xcode Tutorial) vs IOS 7 (Objective C Xcode Tutorial) I am currently trying to code using Swift for IOS8 (anyone else doing this?)
So far I found the tutorial for IOS7 linked here:
https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/FirstTutorial.html#//apple_ref/doc/uid/TP40011343-CH3-SW1
(if anyone has the IOS8 tutorial please do link me!)
In it, it says to go under the "Supporting Files" folder and "To look at the main.m source file" and erase 3 lines of code in order to prevent Xcode from displaying the default white blank screen.
In IOS8 however, they use Swift instead of Objective C, and there is only 1 file under Supporting Files: Info.plist.
Does anyone know what to do to stop XCode from showing its default screen every time I run my code, no matter what I write?

A: The tutorial doesn't say anything about deleting lines from main.m.
It says you should delete three lines from application:didFinishLaunchingWithOptions: in XYZAppDelegate.m to make it look like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    return YES;
}

If you've created a new project using the "Empty Application" template and Swift, then you need to delete lines from the application(didFinishLaunchingWithOptions:) method in AppDelegate.swift to make it look like this:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
    return true
}


text:
Q: How (can) I access the Microphone on the iOS the way Google Voice does? Apple hasn't approved Google Voice as an App so Google created a web "app". So somehow they are accessing the microphone thru the browser. The browser doesn't have access to the Mic so I'm wondering how they (and thus I) did that.
Only thing I can think of is something like PhoneGap or Titanium.

A: It's not possible to access the microphone or the camera from a web app running within Safari on iOS. It may be possible in a few years once the W3C finalizes HTML5, but it's a long way off. I believe Google Voice's servers actually call your phone and then the audio runs over your phone's voice connection.
If you're willing to make yourself a minimal native app, there is a solution that will let you do most everything as a web app, using native code only for the audio-related stuff:

*

*Create your app as a web app. Design and build everything so it looks great in Safari on the iPad.

*Create a new native app that will act as a shell for your website. It can just be a very basic Objective-C app with a web view in it.

*When your web app needs to open up an audio recording interface, make it request an url (via javascript or via the user clicking a link) like this one:
startaudio://whatever-variables-you-need-to-pass

*Implement the UIWebView delegate function webView:shouldLoadRequest: in your Objective-C code. Check each URI that the web view tries to load and intercept your custom "startaudio://" url. At this point, your app would bring up the audio interface in native Objective-C, perhaps over top of the website view.

*Upload recorded audio data to your server in Objective-C (probably) and then use [webView executeJavascript: ] to tell the browser that the audio recorder has been dismissed.
Hope that helps!


text:
Q: html objects don't float? I am building site using Amazon affiliate. Most of their widgets are <objects> and I populate appropriate <divs> on my site and then try to position this but without success. Is it impossible to float object containing divs??

<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab" id="Player_e3463c6b-61ad-4bdc-bf9a-ba74d3d1cbd2"  WIDTH="728px" HEIGHT="90px"> <PARAM NAME="movie" VALUE="http://ws.amazon.ca/widgets/q?ServiceVersion=20070822&MarketPlace=CA&ID=V20070822%2FCA%2Fcraigslist068-20%2F8009%2Fe3463c6b-61ad-4bdc-bf9a-ba74d3d1cbd2&Operation=GetDisplayTemplate"><PARAM NAME="quality" VALUE="high"><PARAM NAME="bgcolor" VALUE="#FFFFFF"><PARAM NAME="allowscriptaccess" VALUE="always"><embed src="http://ws.amazon.ca/widgets/q?ServiceVersion=20070822&MarketPlace=CA&ID=V20070822%2FCA%2Fcraigslist068-20%2F8009%2Fe3463c6b-61ad-4bdc-bf9a-ba74d3d1cbd2&Operation=GetDisplayTemplate" id="Player_e3463c6b-61ad-4bdc-bf9a-ba74d3d1cbd2" quality="high" bgcolor="#ffffff" name="Player_e3463c6b-61ad-4bdc-bf9a-ba74d3d1cbd2" allowscriptaccess="always"  type="application/x-shockwave-flash" align="middle" height="90px" width="728px"></embed></OBJECT> Amazon.ca Widgets

 Amazon.ca Widgets

CSS:
div#slidebar-main{ float:left; }

And no working as they are just one on top other. Please, help?? :)

A: Nowhere in that code does the div id slidebar-main exist.
Try changing it to
div#slidebar-primary { float: left; }

A: The CSS you've written doesn't match your HTML (there's no element called #slidebar-main). Does this not work?
#slidebar-primary, #recommend-right {float: left;}


text:
Q: R: Calculate the mean and variance of length N elements in a vector I'm new to R.
I'm trying to calculate the mean and variance of a vector.
However rather than simply calculating the mean and variance of the whole vector, I am trying to calculate the mean and variance of each "block of 10 elements".
For example
v <- c(1:100)
mean(v) # returns 50.5
var(v) # returns 841.6667

what I actually want is a new vector, with length 10, containing this:
mean(v[1:10]), mean(v[11:20]), ... , mean(v[91:100])

(and also the variance)
var(v[1:10]), var(v[11:20]), ... , var(v[91:100])

However I don't know how to accomplish this in a sensible way. Any help appreciated even if that is "go read this reference at [url]". I tried duckduckgo searching for this, but to no avail.
Seems like something that should be easy?

A: Create a grouping variable that increments 1 every 10 values
grp <- as.integer(gl(length(v), 10, length(v)))

and then use a group by operation
tapply(v, grp, mean)
tapply(v, grp, var)

Or this can be done in dplyr
library(dplyr)
tibble(v) %>%
    group_by(grp = as.integer(gl(n(), 10, n()))) %>%
    summarise(Mean = mean(v), Var = var(v), .groups = 'drop')


text:
Q: Is there a way to load a function with a Navigation Link in Swift? I'd like to know if there is way to call a function along with a NavigationLink in Swift. I have a detail view for a list of posts but in order to get all of the information for that detailed post view I need to call a fetcher function in order to load a bunch of extra information which I cannot make with the initial call as it would largely increase the time to make the initial request for posts. Something like the following, keep in mind this most definitely isn't how it would look just what I envision as how it would work.
List(self.posts) { result in
   NavigationLink(call: PostFetchingFunction(PostID: result.ID) -> destination: DetailedPostView(post: PostFetchingFunction.result)) {
       Text("Go to detailed post view")
   }
}

As I said, this, most definitely isn't correct Swift code, but just a code visualization of what I'd like to do might be helpful.

A: You could achieve this using a provider pattern conforming to ObservableObject
1. ContentView
struct ContentView: View {
    var body: some View {
        NavigationView {
            List(0...100, id: \.self) { (index) in
                NavigationLink("Show \(index)",
                    destination: NextView(provider: ItemProvider(id: index)))
            }
            .navigationBarTitle("List")
        }
    }
}

*

*Destination is NextView

*NextView requires something of type ItemProvider for it's initialization (we'll see this later)

2. NextView
struct NextView: View {
    @ObservedObject var provider: ItemProvider

    var body: some View {
        Text(provider.title)
            .navigationBarTitle("Item", displayMode: .inline)
            .onAppear {
                self.provider.load()
        }
    }
}

*

*ItemProvider is an @ObservedObject which makes it a listener for changes in order to update the view

*.onAppear is where we run a funtion, in this case self.provider.load() to get the provider to begin fetching

3. ItemProvider
class ItemProvider: ObservableObject {
    private var id: Int
    @Published var title: String = ""

    init(id: Int) {
        self.id = id
    }

    func load() {
        title = "Loading \(id)"

        DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [weak self] in
            guard let _weakSelf = self else { return }
            _weakSelf.title = "Loaded \(_weakSelf.id)"
        }
    }
}

*

*ItemProvider has to conform to ObservableObject in order to emit changes

*Any variables within that are marked @Published will emit a change signal

*ItemProvider has a load function that actually does the fetching and if it updates any @Published variables, the connected Views will be notified and will update automatically


text:
Q: Create a folder with the creation time as prefix (C++) For each execution of the program I need to create a new folder that contain the date and time of the creation of the folder as prefix.
for example if I execute the program at Date1Time1 the folder name will be Date1Time1_Folder,
after a few minute Date1Time2 the name will be Date1Time1_Folder
is there a way to do this stuff ?

A: First you need to get the date and time:
std::time_t t = std::time(nullptr);
std::tm tm = *std::localtime(&t);

Then you need to format it to a style you want, I went for displaying day of the month and minute of the hour. See here for how to format it.
// format date and time
std::ostringstream date_and_time_ss;
date_and_time_ss << std::put_time(&tm, "Date%dTime%M");

Finally you need to create the directory:
std::filesystem::create_directory(date_and_time_ss.str() + "_Folder");

Example output on 12th of November at 7:00pm:
Date12Time00_Folder


text:
Q: Python TKinter: frame and canvas will expand horizontally, but not vertically, when window is resized For some reason, I was able to get this TKinter frame (allValOuterFrame) to expand both vertically and horizontally when its window is resized, but however, it appears that the canvas that the frame holds, as well as the frame and vertical scrollbar inside that canvas, will only expand horizontally.  Could someone please explain why?
Here is my code:
# At first I only had "from X import *" but then discovered that
# it is bad practice, so I also included "import X" statements so
# that if I need to use something from tk or ttk explicitly, I can,
# but I had 2/3 of my code done at that point so I had to leave in the
# "import *" things.
try:
    from Tkinter import * #python 2
    import Tkinter as tk
    from ttk import *
    import ttk
    import tkMessageBox as msg
    import tkFileDialog as openfile
except ImportError:
    from tkinter import * #python 3
    import tkinter as tk
    from tkinter.ttk import *
    import tkinter.ttk as ttk
    from tkinter import messagebox as msg
    from tkinter import filedialog as openfile
import csv
# My stuff:
from extractor import Analysis
from extractor import createDictionariesAndLists as getRawData
from nitrogenCorrector import correct as nCorrect
from carbonCorrector import correct as cCorrect

( ... )

def createAllValWindow(self):

    allValWindow = Toplevel(self)
    allValWindow.grab_set()

    if self.element == "N":
        allValWindow.title("All Nitrogen Raw Data Values")
    elif self.element == "C":
        allValWindow.title("All Carbon Raw Data Values")
    else:
        allValWindow.title("All Raw Data Values")

    allValOuterFrame = tk.Frame(allValWindow,background="#00FF00")
    allValCanvas = Canvas(allValOuterFrame, borderwidth=0)
    allValInnerFrame = Frame(allValCanvas, borderwidth=5)

    def allValOnFrameConfigure(event):
        allValCanvas.configure(scrollregion=allValCanvas.bbox("all"))

    allValOuterFrame.grid_rowconfigure(0,weight=1)
    allValOuterFrame.grid_columnconfigure(0,weight=1)
    allValInnerFrame.grid_rowconfigure(0,weight=1)
    allValInnerFrame.grid_columnconfigure(0,weight=1)

    allValVertScrollbar = Scrollbar(allValOuterFrame, orient="vertical",command=allValCanvas.yview)
    allValHorizScrollbar = Scrollbar(allValOuterFrame, orient="horizontal",command=allValCanvas.xview)
    allValCanvas.configure(yscrollcommand=allValVertScrollbar.set, xscrollcommand=allValHorizScrollbar.set)
    allValVertScrollbar.grid(row=1,column=12,sticky=N+S)
    allValHorizScrollbar.grid(row=2,column=0,columnspan=12,sticky=E+W)

    allValCanvas.grid(row=1,column=0,columnspan=12,sticky=N+S+E+W)        allValCanvas.create_window((4,4),window=allValInnerFrame,anchor="nw",tags="allValInnerFrame")
    allValInnerFrame.bind("<Configure>",allValOnFrameConfigure)
    allValDoneButton = Button(allValWindow,text="Done",command=allValWindow.destroy)
    allValOuterFrame.pack(fill="both",expand=1)
    allValDoneButton.pack()

    textRows = [self.rawHeader]
    textLabels = [[]]
    numDiffAminos = len(self.analyses) - 1 # Ignore the "trash" list at the end
    for singleAminoAnalyses in self.analyses[0:numDiffAminos]: # Once again, ignoring the last list
        if len(singleAminoAnalyses) < 1:
            continue
        for analysis in singleAminoAnalyses:
            textRows.append([str(analysis.analysisID),
                             str(analysis.row),
                             str(analysis.identifier1),
                             str(analysis.identifier2),
                             str(analysis.comment),
                             str(analysis.peakNumber),
                             str(analysis.rt),
                             str(analysis.component),
                             str(analysis.areaAll),
                             str(analysis.ampl),
                             str(analysis.r),
                             str(analysis.delta)])
            textLabels.append([])
    for i in range(len(textRows)):
        if i == 0:
            listRow = i
        else:
            listRow = i+1
        for j in range(len(textRows[i])):
            if i == 0:
                textLabels[i].append(Label(allValInnerFrame,text=textRows[i][j],font=("Fixedsys",10,"bold")))
            else:
                textLabels[i].append(Label(allValInnerFrame,text=textRows[i][j]))
            if j == 9:
                textLabels[i][j].grid(row=listRow,column=j,sticky=W+E,padx=(4,10))
            else:
                textLabels[i][j].grid(row=listRow,column=j,sticky=W+E,padx=(4,4))
        if i == 0:
            separator = tk.Frame(allValInnerFrame, height=2, borderwidth=1, bg="black", relief=SUNKEN)
            separator.grid(row=1,column=0,columnspan=12,sticky=W+E)

A: It is because you give row 0 of AllValOuterFrame a weight of 1, but you put the canvas in row 1. If you move the canvas to row 0 or give row 1 a weight of 1, it will resize the way you expect.


text:
Q: Tallying columns using Countif with a variable number of rows I'm using Google Sheets for a spreadsheet I'm working on.
Basically, I'm counting the number of times some different items (items are all listed in columns) live inside of different application windows (all my windows are listed in rows).
I'm just plopping a checkmark to say yes when an item lives in a window.
I want to tally this, and I'm using Countif like this: =countif(C4:C38,"✔")
However, if I find a new item, or window, everything has to move and I have to update the formula's column or row number.
Is there a way to make the Countif's range dynamic?

A: To count the checkmarks in column C, irrespective of how many rows are in the sheet:
=COUNTIF(C:C,"✔")
To count the checkmarks from the fourth row down in column C, and not be affected by row insertion/deletion:
=COUNTIF(INDIRECT("C4:C"),"✔")
To count the checkmarks from the fourth row in column C, down to the row above where the formula is placed:
=COUNTIF(INDIRECT("C4:C"&(ROW()-1)),"✔")


text:
Q: How to add JavaScript dynamically to immediately above  tag? I have a piece of JavaScript code that is to be added at the end of <body> tag, that is  immediately above </body>. The JavaScript can not be added directly to the page. It is inserted to the browser end by an external tool. This js code is to be placed immediately above </body> tag as shown below.
<head>
something
</head>

<body>
some html/js
some html/js
........
my js code here
</body>

How can I do this ? Is there any way to accomplish this without coding in page but only as part of js code in external tool ? I am allowed to write only JavaScript in tool.
My basic question is how to insert script just before </body> tag when the script is to be written somewhere else ?

A: You can use do it like this:
document.body.appendChild(SCRIPT_NODE_HERE);

Also if you are using Ajax then you should put your code in the event that says the script loaded successfully and ready to be executed
One thing here though, if you want to load the script dynamically then there is no point of loading it just before the </body> tag because it gives you no benefit.
Developers usually put the script near the end of the body so that it reduces page load times, and delays script execution to some extent until the page has finished loading so it doesn't block other content and cause unpleasant experience to the client.
So when you load your script dynamically, your page would have already downloaded its resources and there will be no blocking.

A:  document.onreadystatechange = function () {
  if (document.readyState == "complete") {
    your js code here
  }
 }

load this into the page using your tool, I believe wherever it is loaded in the page, it will execute once the page's readystate changes and when the page is completely loaded your code will execute.