text:
Q: How to do a tooltip on an SVG generated by Raphael I'm doing a bit of a pedagogical exercise, converting XML to SVG with XSLT, Javascript and Raphael. I'm sure it's the hard way...but it's educational.
The problem I've run into is creating tooltips. So far, I've found three ways to do this:

*

*The first way is to use .attr({title: "blah"{) on an object. This works, but it's not supported by Raphael officially, and the content I want to put in the tooltip might be somewhat long, which is a problem when people's OS times out the tooltip before people have finished reading it.

*The second way I've found is the function here. It works OK for having a Raphael object popup when there is a mouseover, but, near as I can tell, getting a normal-looking tooltip to pop up isn't possible.

*Using the jquery Tooltip plugin. This just doesn't seem to work. I can't get Raphael to add the title attribute to an object AND get this to select that title. Not sure why.

So, what I'd like to know is, what's an easy and reliable way to add tooltips to Raphael objects such that they popup when people mouseover the object, and disappear when they mouseout (but not before)?

A: If you use [title] attributes, it will wrap the  elements with links  making it easy to use tooltip plugins like qtip.
var R = Raphael('canvas', 100, 100);
R.path(path).attr({ title: 'Fancy tooltip' });

$('#canvas a').qtip();

A: In case someone will seek for an example of tooltip over g Rapahel charts (I guess it could be easily used with plain Rapahel too) I did one that use dynamically created div (so no third part tooltip plugin needed) that acts as a tooltop over pie chart
Interactive Pie Chart with Tooltip
It uses mousemove and mouseout of raphael...
b.t.w I use the legend as a source of the tooltip - of course its not a must an could be replaced by any other text (just replace the this.label[1].attrs.text with some other text)

A: One way to do this is to use a div tag on top of the Raphael paper. Then use Jquery mousevents along with fadeIn() and fadeOut(). I created an example on jsFiddle. Have a look

A: I used qtip to add tooltips:
http://jsfiddle.net/chrisloughnane/h5WU9/


text:
Q: How to handle the end of layout animation My layout with animateLayoutChanges look like this:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/main_layout"
    android:orientation="vertical"
    android:animateLayoutChanges="true">

    <Button
        layout_width="wrap_content"
        layout_height="wrap_content"
        android:id="@+id/button"/>
</LinearLayout>

I would like to handle the moment when setVisibility aniamtion is eneded:
buttom.setVisibility(View.GONE);

How to do it?

A: You can probably use LayoutTransition and its listener
LayoutTransition mainLayoutTransition = mainLayout.getLayoutTransition();
mainLayoutTransition.addTransitionListener(new TransitionListener(){

    @Override
    public void endTransition(LayoutTransition arg0, ViewGroup arg1,
                    View arg2, int arg3) {
        button.setVisibility(View.GONE);
    }

    @Override
    public void startTransition(LayoutTransition transition,
                    ViewGroup container, View view, int transitionType) {

    }
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I display data in a table and allow users to copy selected data? I have a long list of data that I want to display in table format to users. The data changes when the user performs certain actions in my app, but it is not directly editable. So the user can create a reasonably big table of data, but he can't change individual cells' values.
However, I do want the data to be copy-able. So I want it to be possible for the user to select some or all of the cells, and do a ctrl+C to copy the data to his clipboard, and then a ctrl+V to paste the data to an external text editor.
At the moment, I'm displaying the data in a ListView with a GridView and this works perfectly, except that GridView doesn't allow one to copy data.
What other options can I try? Ours is a WPF app, coding in C#.

A: You can trythe DataGrid control of the WPF Toolkit. It allows you to copy the data on the grid and paste it anywhere (like notepad, word, etc.). You can bind a datasource there the way you do on DataGridView\DataGrid controls on .Net Win App and Web App application.


text:
Q: list index out of range I created a Telegram bot with MySQL database. The user can insert and retrieve the orders from MySQL. The telegram bot will display the order details from MySQL when the user inputs the /select command. I have attached the MySQL table with two orders.
from datetime import datetime
import mysql.connector
import telebot

bot_token = ''

mydb = mysql.connector.connect(
    host = "localhost",
    user = "root",
    passwd = "",
    database = "telegram",
)

my_cursor = mydb.cursor()

bot = telebot.TeleBot(token=bot_token)

@bot.message_handler(commands=['select'])

def select_order(event):
    try:
        my_cursor.execute("SELECT * FROM mysql")
        res = my_cursor.fetchall() # fetch all the results
        mydb.commit()

        if(res):
            text = create_message_select_query(res)
            bot.send_message(event.chat.id, text)

        else:
            bot.send_message(event.chat.id, "No orders found inside the database.")

    except Exception as e:
        print(e)
        bot.send_message(event.chat.id, "Something Wrong happened... Check your code!")

def create_message_select_query(ans):
    text = " "
    for i in ans:
        id = i[0]
        product = i[1]
        quantity = i[2]
        date_edited = i[3]
        text += ""+ str(id) +" | " + ""+ str(product) +" | " + ""+ str(quantity)+" | " + ""+ str(date_edited)+"\n"
    message = "Received   Information about orders:\n\n"+text
    return message

bot.polling()

I encountered an error list index out of range when I input the telegram command /select.
How do I fix the above error?


text:
Q: Magento place order button fails after PayPal express checkout is accepted I am doing a Magento build. I have just used a template and very basic extensions at this stage.
I get this error after testing with a PayPal payment.

app/code/core/Mage/Sales/Model/Resource/Order/Address.php on line 95

And if I don't use PayPal in advance and log in it just lets me press the "Place Order" button, says it is processing the order but then doesn't change pages. The order does not drop into the back end but it does reduce my stock levels for the item. Does anyone know what this is? I have checked my mbstring is turned on as one other site recommended that.


text:
Q: Winforms (with Python): Drag file object to Windows Explorer I am using WinForms with Python / pythonnet. I have a WinForm object and want to drag the underlying file data to Windows Explorer.
I basically do this:
def on_mouse_down(self, sender, event):
   print('Mouse down')
   file_list = List[str]()
   file_list.Add('C:\\somefolder\\myfile.txt')
   do = WinForms.DataObject(WinForms.DataFormats.FileDrop, file_list)
   self.DoDragDrop(do, WinForms.DragDropEffects.Copy)

Dragging this on the Windows Explorer invokes the "Copy-File"-Cursor. But when I release the mouse button, nothing happens. It does not copy the file. Do you have any ideas what I am doing wrong?
Below is the full code I use. You can drag and drop files on/from the label.
import time

import clr
clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Threading')
import System.Windows.Forms as WinForms
from System.Collections.Generic import List
from System.Threading import Thread, ThreadStart, ApartmentState

class Form(WinForms.Form):
    def __init__(self):
        lbl = WinForms.Label(self)
        lbl.Text ='Drag Me or Drop on me'
        self.Controls.Add(lbl)
        lbl.DragEnter += self.on_drag_enter
        lbl.DragDrop += self._on_drop
        lbl.MouseDown += self.on_mouse_down
        lbl.AllowDrop = True

    def _on_drop(self, sender, event):  # DROP
        print('drop')
        print([s for s in event.Data.GetData(WinForms.DataFormats.FileDrop)])

    def on_drag_enter(self, sender, event):  # DROP
        print('drag enter')
        event.Effect = WinForms.DragDropEffects.Copy

    def on_mouse_down(self, sender, event):
        print('Mouse down')
        file_list = List[str]()
        file_list.Add(r'C:\\somefolder\\myfile.txt')
        do = WinForms.DataObject(WinForms.DataFormats.FileDrop, file_list)
        self.DoDragDrop('dfdf', WinForms.DragDropEffects.Copy)

def create():
    app = WinForms.Application
    app.EnableVisualStyles()
    app.SetCompatibleTextRenderingDefault(False)
    Form().Show()
    app.Run()

thread = Thread(ThreadStart(create))
thread.SetApartmentState(ApartmentState.STA)
thread.Start()
thread.Join()

A: The problem was that I was passing the wrong datatype to the DataObject:
How not do it:
from System.Collections.Generic import List
def on_mouse_down(self, sender, event):
   file_list = Array[str](['C:\\myfolder\\myfile.zip'])
   file_list = List[str]()
   file_list.Add(String('C:\\myfolder\\myfile.zip'))
   do = WinForms.DataObject(WinForms.DataFormats.FileDrop, file_list)
   self.DoDragDrop(do, WinForms.DragDropEffects.All)

How to do it instead:
from System import Array
def on_mouse_down(self, sender, event):
   file_list = Array[str](['C:\\myfolder\\myfile.zip'])
   do = WinForms.DataObject(WinForms.DataFormats.FileDrop, file_list)
   self.DoDragDrop(do, WinForms.DragDropEffects.All)


text:
Q: How to restructure dataframe in R (rows to columns) I have a dataframe that consists of 3 columns (category name, month, and sum of units sold).
I would like to reformat my dataframe where category name and sum of units are my rows and each column represents the 12 months in the order I have specified (starting with Oct and ending with Sep).
How do I do this? My current df is structured as so:
`Category Name` Month   sum
   <fct>           <fct> <dbl>
 1 Diet Soda       Oct   34680
 2 Diet Soda       Nov   41589
 3 Diet Soda       Dec   31564
 4 Diet Soda       Jan   22635
 5 Diet Soda       Feb   34853
 6 Diet Soda       Mar   48583
 7 Diet Soda       Apr   33550
 8 Diet Soda       May   44991
 9 Diet Soda       Jun   34995
10 Diet Soda       Jul   33260
11 Diet Soda       Aug   46027
12 Diet Soda       Sep   33924
13 Diet Soda Can   Oct       0
14 Diet Soda Can   Nov       1
15 Diet Soda Can   Dec       0
16 Diet Soda Can   Jan       0
17 Diet Soda Can   Feb       0
18 Diet Soda Can   Mar       0
19 Diet Soda Can   Apr       0
20 Diet Soda Can   May       0

A: One option would be pivot_wider after creating a sequence column by group
library(dplyr)
library(tidyr)
df1 %>%
   group_by(Month, `Category Name`) %>%
   mutate(rn = row_number()) %>%
   pivot_wider(names_from = Month, values_from = sum)

NOTE: the group_by/mutate is not really required in this data but for a general case
The pivot_wider reshapes data from 'long' to 'wide' format
df1 %>%
    pivot_wider(names_from = Month, values_from = sum)
# A tibble: 2 x 13
#  `Category Name`   Oct   Nov   Dec   Jan   Feb   Mar   Apr   May   Jun   Jul   Aug   Sep
#  <chr>           <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
#1 Diet Soda       34680 41589 31564 22635 34853 48583 33550 44991 34995 33260 46027 33924
#2 Diet Soda Can       0     1     0     0     0     0     0     0    NA    NA    NA    NA

data
df1 <- structure(list(`Category Name` = c("Diet Soda", "Diet Soda",
"Diet Soda", "Diet Soda", "Diet Soda", "Diet Soda", "Diet Soda",
"Diet Soda", "Diet Soda", "Diet Soda", "Diet Soda", "Diet Soda",
"Diet Soda Can", "Diet Soda Can", "Diet Soda Can", "Diet Soda Can",
"Diet Soda Can", "Diet Soda Can", "Diet Soda Can", "Diet Soda Can"
), Month = c("Oct", "Nov", "Dec", "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan",
"Feb", "Mar", "Apr", "May"), sum = c(34680L, 41589L, 31564L,
22635L, 34853L, 48583L, 33550L, 44991L, 34995L, 33260L, 46027L,
33924L, 0L, 1L, 0L, 0L, 0L, 0L, 0L, 0L)), class = "data.frame",
row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20"))


text:
Q: stuck x-axis scrollbar in MSChart Chart [EDIT]
After a lot of trial and error, I realized a version of my tooltip code could scroll while the rest of the codes are unchanged.  The only difference between the two tooltip usage is that the pos.x value is shifted, instead of being exactly where the mouse is.
Which means instead of
/*X-axis Tooltip*/
tooltip.Show(Math.Truncate(xValue * 1000) / 1000 + unit_Converter(), this.chart1, pos.X, pos.Y - 15);

I did this
/*X-axis Tooltip*/
tooltip.Show(Math.Truncate(xValue * 1000) / 1000 + unit_Converter(), this.chart1, pos.X - 70, pos.Y - 15);

That was all the difference. Now I can click and drag the X-axis scroll bar around.  I suppose the reason why I always could scroll my Y-axis is it was shifted by 15 to begin with.
So if you set your tooltip position exactly where your mouse position is, then apparently you will be clicking on the tooltip itself, instead of the scrollbar when you attempt to scroll.
Answer provided by Josh W is equally valid, because using just "this" instead of "this.chart" automatically shifts the tooltip a little bit for some reason.  thanks for the help!

[Original Question]
I have a chart that has Y-axis and X-axis scroll bar.  For a while both my scrollbars worked.  As my code grow, the X-axis scrollbar now won't move, while the Y-axis scrollbar moves just fine.  I am puzzled. Any help would be appreciated.
I have referenced other answers such as
c# chart control, vertical scrolling problems with zoom ["Stuck Scroll bar"]
But X-axis scrollbar still stuck....
[EDIT]:
I realized that my tooltip on mouse move code is causing this.  If I disable my call to my mouse move code, the X-axis scrollbar would be functional again.  But how do I make it so that both can function?  I don't really know how the crossair tooltip would disable scrolling on the X-axis only, but not the Y-axis...
    void chart1_MouseMove(object sender, MouseEventArgs e)
    {
        var pos = e.Location;
        _point.X = e.Location.X;
        _point.Y = e.Location.Y;

        try
        {
            if ((chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.X) >= 0) && (chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.X) <= max))
            {
                //Crossair
                chart1.ChartAreas[0].CursorX.SetCursorPixelPosition(_point, true);

                //Tooltips
                double xValue = chart1.ChartAreas[0].AxisX.PixelPositionToValue(e.X);

                /*X-axis Tooltip*/
                tooltip.Show(Math.Truncate(xValue * 1000) / 1000 + unit_Converter(), this.chart1, pos.X, pos.Y - 15);
            }
        }
        catch (Exception exception)
        {

        }
}

My code to set series settings:
var series = chart1.ChartAreas[chart1.Series[iname].ChartArea];

//Line thickness
chart1.Series[iname].BorderWidth = 2;

series.AxisX.Minimum = 0;
series.AxisX.Maximum = max;
series.AxisY.Minimum = 0;
series.AxisY.Maximum = checkedListBox1.CheckedItems.Count * 3 - 2;
series.AxisX.MajorGrid.Interval = time_of_cycle;
series.AxisX.MajorGrid.LineDashStyle = ChartDashStyle.DashDotDot;
series.AxisY.MajorGrid.Interval = 2;
series.CursorX.Interval = 0;
series.CursorY.Interval = 0;

series.AxisX.ScaleView.SmallScrollSize = time_of_cycle /100 ;
series.AxisY.ScaleView.SmallScrollSize = 1;

//Disables Y axis lable
series.AxisY.LabelStyle.Enabled = false;

series.AxisX.LabelStyle.ForeColor = Color.White;
series.AxisY.LabelStyle.ForeColor = Color.White;
series.AxisX.LabelStyle.Format = label_Style_Converter();

series.AxisX.LabelStyle.Interval = time_of_cycle * 2;
series.AxisX.MajorGrid.LineColor = Color.DimGray;
series.AxisY.MajorGrid.LineColor = Color.DimGray;
series.AxisX.ScrollBar.BackColor = Color.LightGray;
series.AxisY.ScrollBar.BackColor = Color.LightGray;
series.AxisX.ScrollBar.ButtonColor = Color.LightGray;
series.AxisY.ScrollBar.ButtonColor = Color.LightGray;
series.AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.SmallScroll;
series.AxisY.ScrollBar.ButtonStyle = ScrollBarButtonStyles.SmallScroll;
series.AxisX.ScrollBar.Enabled = true;
series.AxisY.ScrollBar.Enabled = true;
series.AxisX.ScrollBar.IsPositionedInside = false;
series.AxisY.ScrollBar.IsPositionedInside = false;
series.AxisX.IsMarginVisible = true;
series.AxisY.IsMarginVisible = false;
series.AxisX.Name = "µs";
series.AxisX.ScaleView.Size = max - time_of_cycle / 100;
series.AxisY.ScaleView.Size = (checkedListBox1.CheckedItems.Count * 3 - 2) + 1 ;
series.BackColor = Color.Black;

//crosshair
var cursor_Y = chart1.ChartAreas["ChartArea1"].CursorY;
var cursor_X = chart1.ChartAreas["ChartArea1"].CursorX;
cursor_Y.LineWidth = 1;
cursor_Y.LineDashStyle = ChartDashStyle.Solid;
cursor_Y.LineColor = Color.DarkRed;
cursor_Y.SelectionColor = Color.LightGray;

cursor_X.LineWidth = 1;
cursor_X.LineDashStyle = ChartDashStyle.Solid;
cursor_X.LineColor = Color.DarkRed;

chart1.MouseMove += new MouseEventHandler(chart1_MouseMove);

A: At first I thought maybe your call to .Show() was blocking the GUI thread, but some quick and dirty code didn't seem to have that issue.  One odd thing I did notice with the tooltip though is that when you have something like your Chart subscribed to the MouseMove event, and your tool-tip is given a 'this.chart1' reference instead of just this, then if the tooltip is under your mouse, it continues to fire the event.
That is, even if the tooltip moves off the chart for example.
Here was some test code I just played with using a panel instead of a chart.
    private int Counter = 0;
    private void panel1_MouseMove(object sender, MouseEventArgs e)
    {
        Console.WriteLine(string.Format("X{0}, Y{1}\t Count = {2}", e.X, e.Y, Counter));
        Counter++;

        toolTip1.Show(
            string.Format("X{0}, Y{1}\t Count = {2}", e.X, e.Y, Counter),
            this.panel1,
            e.X - 75,
            e.Y -5);
    }

First you should also get rid of that try/catch statement as you aren't doing anything with the error... either handle errors, or let them bubble up to crash something (so that you can 'fix' it).  What you have there now might throw an error, but you'd never know, because you are catching it and ignoring it.
Second, the MouseMove event happens a LOT... perhaps use the MouseHover for showing the tooltip?
Other than that... it does not appear to be where your code is breaking, though it could be inside the unit_Converter() call or even on the math function... your try/catch may be hiding an exception on that line.


text:
Q: Notifications not showing Android I am trying to bring up a notification after set period of time using:
scheduleNotification(getNotification("Notification content..") differ);

and the following functions -
private Notification getNotification(String content) {
        Notification.Builder builder = new Notification.Builder(this);
        builder.setContentTitle("Scheduled Notification");
        builder.setContentText(content);
        builder.setSmallIcon(R.drawable.icon);

        return builder.build();
}

private void scheduleNotification(Notification notification, long delay) {

        Intent notificationIntent = new Intent(this, NotificationPublisher.class);
            notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
        notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        long futureInMillis = SystemClock.elapsedRealtime() + delay;
        AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}

After logging the delay value, I get 57580 which is roughly 57 seconds, but even after this period of time, I do not get any notification on status-bar.
Please help.

A: You need a BroadcastReceiver to get notifications from the system.
public static class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        getNotification(String content);
    }
}

And remember to declare the class in your AndroidManifest:
<receiver android:name=".AlarmReceiver" />


text:
Q: Creating an exponential average I've been searching across documentation and internet, but it seems there's nothing about.
In SQL SERVER we have a really powerful function which is the windows frame. I can have something like this
SELECT
     [YearMonth]
    ,[OrderQuantity]
    ,[RunningTotal] = SUM([OrderQuantity]) OVER (PARTITION BY [Year]
                                                ORDER BY [YearMonth]
                                                ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM [CTE_source]
ORDER BY [YearMonth];

In the OVER clause with the keyword ROWS I can filter the rows to apply my aggregate function.
With c#, according to documentation a can create a user defined aggregate function, but nowhere is there something window frame. Does someome have any idea or doc I could read? I would like to create an exponential average.
Thanks.


text:
Q: Echo multidimensional array fields in a for or foreach loop I built a multidimensional array to store some values, and I was able to remove duplicates.
What I want to do now is build a for or foreach loop to echo the subarray values by key, like [0], [1], etc because it seems to have put them in nice rows for me. Print_r shows the data exactly as I need it, but I need to iterate through to build some form buttons for each set.
I use a function I found to generate unique entries from multidimensional arrays, as follows:
function multi_unique($array) {
    foreach ($array as $k=>$na)
        $new[$k] = serialize($na);
    $uniq = array_unique($new);
    foreach($uniq as $k=>$ser)
        $new1[$k] = unserialize($ser);
    return ($new1);
}

Initializing the array:
$unique_array = array(
    'username'=>array(),
    'user_id'=>array(),
    'weeknumber'=>array()
    );

Building the array from within a while loop:
while($row = mysql_fetch_array($query))
{
$unique_array[] = array('username'=>$row['username'], 'user_id'=>$row['user_id'], 'weeknumber'=>$row['weeknumber']);
}

And finally, I need to make sure the array values are unique (there are duplicates entries as a result of database and query limitations), after the while loop I have:
print_r(multi_unique($unique_array));

Which produces output like this on the page with print_r, generated dynamically from the database with duplicate entries removed:
Array ( [username] => Array ( ) [0] => Array ( [username] => username1 [user_id] => 58 [weeknumber] => 1 ) [1] => Array ( [username] => username2 [user_id] => 21 [weeknumber] => 1 ) [3] => Array ( [username] => username3 [user_id] => 24 [weeknumber] => 1 )

Like I said, everything goes into the array swimmingly, I just need a good way to pull everything out once again, I need the username, user_id, and weeknumber to echo within a loop.
Any help is appreciated!
And yes, I know mysql is deprecated, but it's too late in the game to change that now + I'm working off existing code by someone else.

A: You can just loop through the array and each iteration of the loop will be the next array in the unique_array
foreach($unique_array as $row){
   // Format this as desired
   echo $row['username'] . $row['user_id'] . $row['weeknumber'];
}

A: Your initialization code is incorrect, it should be:
$unique_array = array();

To pull everything out, use:
foreach ($unique_array as $user) {
  echo "Username: " . $user['username'] . "\n";
  echo "UserID: " . $user['user_id'] . "\n";
  echo "Week Number: " . $user['weeknumber'] . "\n";
  echo "\n";
}


text:
Q: find optimal sum of elements in list of numbers that are > a given number I have a list of numbers, sorted descending, size of array is variable and any number can appear (typically less than 1000)
given an input number (x), I need to find the optimal combination of values in the list, that is larger than x by the smallest amount possible. I've been reading about the NP-optimization and sum subset type problems, but haven't found a solution yet. I've found some psuedocode for an approximate alogorithm, but i would like to find the exact optimal solution from the given list of numbers.
thanks

A: From your comments I understood that the input array has unsigned (integers).
This problem seems not much different from the subset sum problem with non-negative integers which can be solved in polynomial time.
I found this to be a reasonably well-performing algorithm that finds the optimal solution:
The algorithm in pseudo code
For each element of the array:
    select this element
    if sum of selected <= x:
        # Sum is too small, so add more (smaller) term(s)
        execute algorithm recursively for the remaining part of array
    else if < sum in best solution so far:
        # Sum is closer to target, so this is currently the best
        best solution = current selected terms
    # Back-track: remove this term from the sum
    unselect this element
return best solutiuon

When the algorithm is called recursively the previous selected terms remain selected, and in the loop one more term is selected. It can recurse again, etc. The total number of selected terms corresponds to the depth of the recursion.
There are two ways in which the recursion cuts many combinations:

*

*when a high value term is selected, the remaining value for crossing the target value becomes relatively small, reducing the possibilities of which other terms can contribute to a (better) solution;

*when a lower value term is selected, the remaining number of terms is relatively small (because of the order), and so also the possibilities are reduced.

This suggests that the time complexity is less than O(2n), which would be the complexity when all possible combinations would have to be investigated (or a constant fraction of it).
Implementation
Here is an implementation in JavaScript, so you can run it. It offers a randomize button so you can generate an array of any given length with random numbers, and a random target value.
The algorithm seems to run in the order of O(n.logn) time, by just looking at the number of combinations it checks on average. That is of course not a proof.
The comments in the code should give clarification.

// Main  algorithm
function solve(a /* array of int */, x /* int */) {
    // Initialise
    var best = {sum: a[0] * a.length, numSumsVerified: 0, numTerms: 0, terms: []};
    var current = {sum: 0, terms: []};

    function recurse(start) {
        var ok = start < a.length;
        for (var i = start; i  x + 1 && ok; i++) {
            // Use this term for the sum
            current.sum += current.terms[current.terms.length] = a[i];
            // Keep statistics of how many combinations we check
            best.numSumsVerified++;
            if (current.sum <= x) {
                // Sum is too small, so add more (smaller) term(s)
                ok = recurse(i+1);
            } else if (current.sum < best.sum) {
                // Sum is closer to target, so this is currently the best
                best.sum = current.sum;
                best.terms = current.terms.slice(0);
            }
            // Back-track: remove this term from the sum
            current.sum -= current.terms.pop();
        }
        return ok || i > start + 1;
    }

    // start the search, and capture errors
    try {
        recurse(0);
    } catch (ex) {
        best.error = 'Too much recursion!';
        best.sum = null;
        return best;
    }
    best.numTerms = best.terms.length;
    // if no solution, set error message
    if (!best.terms.length) {
        best.error = 'no solution';
        best.sum = null;
    }
    return best;
}

// Utility for randomizing
function createRandomNumbers(limit, count) {
    res = [];
    while (count--) res.push(Math.floor(Math.random() * limit));
    return res;
}

// I/O

var inputA = document.querySelector('#a');
var inputX = document.querySelector('#x');
var buttonSolve = document.querySelector('#solve');
var inputSize = document.querySelector('#size');
var buttonRandom = document.querySelector('#randomize');
var output = document.querySelector('pre');

buttonSolve.onclick = function() {
    // Get input
    var a = inputA.value.match(/\d+/g).map(Number);
    var x = Number(inputX.value);
    // Sort descending
    a.sort(function(a,b) { return b-a; });
    // Solve
    var result = solve(a, x);
    // Output
    inputA.value = a.join(' '); // just for reformatting
        // Reduce detail when many items
    if (result.terms.length > 100) result.terms = '(too many to display)';
    output.textContent = JSON.stringify(result, null, 4);
};

buttonRandom.onclick = function() {
    // Generate random input
    var size = Number(inputSize.value);
    var limit = size * 20;
    var a = createRandomNumbers(limit, size).sort((a,b) => b-a);
    var sum = a.reduce((a,b) => a+b);
    var x = createRandomNumbers(sum, 1).pop();
    // Populate the input boxes
    inputA.value = a.join(' ');
    inputX.value = x;
    // Trigger click on "solve" button
    setTimeout(buttonSolve.click.bind(buttonSolve), 0);
}
Enter list of integers: <input id="a" size="50" value="18 13 12 10 9 8 6 6 1 0">

Sum must be larger than: <input id="x" size="10" value="16">

<button id="solve">Solve</button>

Desired array size: <input id="size" size="6" value="50">
<button id="randomize">Random Input</button>

As this algorithm performs a recursive call for every term that is added to the combination, the recursion might go deep for large input arrays. At a certain point it may hit stack limits. In my browser that limit gets hit often near array sizes of 10,000 elements. Probably this algorithm can be rewritten without use of recursion if it needs to be used for such large arrays.

A: This sounds very much like a knapsack problem. If it is, then finding an exact solution is not going to be easy.
Why is that? It is because the best solution may be comprised of potentially any subset for your numbers. There are 2^N subsets, so that is an extremely large space to search for solutions.
How large is it?
Items | Search Space          | How this feels
16    | 65,536                | I can do it!
32    | 4,294,967,296         | Better go get lunch
40    | 1,099,511,627,776     | If I only had a supercomputer
50    | 1,125,899,906,842,624 | I will watch as the last stars day

There are tricks and things which can reduce the search space, but you'll still hit epicly large problems for low item counts.
Given this, you should:

*

*Choose only small problem sizes and use exhaustive search because it is easy to implement.

*Learn about branch-and-bound and other search space reducing techniques

*Approximate. Everyone does it.


text:
Q: VSTO project is it possible to add colors and items from windows forms In VSTO, I'm using VS 2012 with Excel 2013, and the Ribbon area I create with an addin looks so plain vanilla ( font is not able to be in bold etc..)  It would be great to extend the look and feel and functionality of this along with tying in Event handlers for status updates.
Does anyone have any experience with extending VSTO,  any samples, links that you found very useful ( yes I spent a lot of time on google already.)

A: The style of the Ribbon is controlled by Office. There is not anything you can do to change the format and styling of the fonts. The options you do have are size of the controls (e.g. buttons) & their icons.
It's also possible to use Office events to update the appearance of the ribbon.
If you have a specific scenario in mind, I'd be happy to help.
In the meantime, here are some helpful links:
Ribbon Extensibility Overview
How to: Customize the Ribbon
VSTO - Create a custom tab for the Office Ribbon in Excel (Visual Studio 2012)


text:
Q: Should using different unit cells lead to different band diagrams? I am interested in hexagonal (triangular) lattice i.e. the structure is metal rods at the center of each hexagon. Two different unit cells that I think can be used are shown in the figure. My question is:

*

*Are their Brillouin zones different (for the hexagonal unit cell, the brillouin zone is a hexagon rotated by 90 deg(w.r.t. the real space hexagon); will that be further rotated by any angle if I use the other unit cell?)?

*I tried to calculate photonic band structure using those two unit cells. They are giving slightly different band diagrams. If it is expected, why is so? I also observed the difference only for TE modes.


text:
Q: signal.alarm replacement in Windows [Python] I have a function that occasionally hangs.
Normally I would set an alarm, but I'm in Windows and it's unavailable.
Is there a simple way around this, or should I just create a thread that calls time.sleep()?

A: The most robust solution is to use a subprocess, then kill that subprocess.  Python2.6 adds .kill() to subprocess.Popen().
I don't think your threading approach works as you expect.  Deleting your reference to the Thread object won't kill the thread.  Instead, you'd need to set an attribute that the thread checks once it wakes up.

A: Here's how the original poster solved his own problem:
Ended up going with a thread.  Only trick was using os._exit instead of sys.exit
import os
import time
import threading

class Alarm (threading.Thread):
    def __init__ (self, timeout):
        threading.Thread.__init__ (self)
        self.timeout = timeout
        self.setDaemon (True)
    def run (self):
        time.sleep (self.timeout)
        os._exit (1)

alarm = Alarm (4)
alarm.start ()
time.sleep (2)
del alarm
print 'yup'

alarm = Alarm (4)
alarm.start ()
time.sleep (8)
del alarm
print 'nope'  # we don't make it this far

A: I realize this thread has been inactive for some time, but I faced a similar issue and hope that someone else may find this useful as well.
As @jfs mentioned in a useful comment, the standard threading module provides a Timer method that works really well for this (docs). It is just a subclass of threading.Thread, but it makes this very simple and clean. It can also be canceled using the inherited cancel method.
import threading
delay_time = 3   # delay time in seconds
def watchdog():
  print('Watchdog expired. Exiting...')
  os._exit(1)

alarm = threading.Timer(delay_time, watchdog)
alarm.start()
my_potentially_never_ending_call()
alarm.cancel()

A: You could - as you mentioned - just kick off a new thread that sleeps for that number of seconds.
Or you can use one of Windows' multimedia timers (in Python, that'd be in windll.winmm). I believe timeSetEvent is what you're looking for. Incidentally, I found a piece of code that uses it here.


text:
Q: How to serialize everything but the checkbox elements in jQuery.serialize()? is there a way to serialize all form elements using serialize() function except the checkboxes?

A: From the docs:

The .serialize() method can act on a
  jQuery object that has selected
  individual form elements, such as
  <input>, <textarea>, and <select>.

You could do this:
var s = $('#post-form').find('input, textarea, select')
                       .not(':checkbox')
                       .serialize()

A: You can combine the :input, :not() and :checkbox selectors:
var serialized = $(":input:not(:checkbox)").serialize();


text:
Q: Analyzing revenue and historical data to estimate profit What is the approach to solve such a question, given that I need to simply analyze a dataset and
express findings I find?
Problem:
I am given a dataset of everyday revenue for three children companies of ABC for the period of January 1, 2014 to March 31, 2014.
I am also given revenue and profit for the three children companies for last five quarters of the above period, i.e Q4 2012, Q1 2013, Q2 2013, Q3 2013, and Q4 2013.
My aim is:
Based on the everyday revenue data for the period of January 1, 2014 to March 31, 2014 (Q1 2014) and the historical data (revenue and profit) to come up with an estimate for the profit that ABC will report as their Q1 2014 profit.
How should I approach this problem?


text:
Q: How to troubleshoot this duplicate sources warning in installing newest Google Chrome Debian? I am updating my Google Chrome from 53.x to 56.x, by having google-chrome-stable in apt this time.
I did not do anything to the old Google Chrome version because unsure how to handle it.
My /etc/apt/sources.list in Debian 8.5
#

deb http://ftp.fi.debian.org/debian/ jessie main
#deb http://ftp.us.debian.org/debian/ jessie main
deb-src http://ftp.fi.debian.org/debian/ jessie main
#deb-src http://ftp.us.debian.org/debian/ jessie main

deb http://security.debian.org/ jessie/updates main contrib
deb-src http://security.debian.org/ jessie/updates main contrib

# jessie-updates, previously known as 'volatile'
deb http://ftp.fi.debian.org/debian/ jessie-updates main contrib
#deb http://ftp.us.debian.org/debian/ jessie-updates main contrib
deb-src http://ftp.fi.debian.org/debian/ jessie-updates main contrib
#deb-src http://ftp.us.debian.org/debian/ jessie-updates main contrib

# jessie backports
deb http://http.debian.net/debian jessie-backports main contrib non-free

# Debian 8 "Jessie"
deb http://httpredir.debian.org/debian/ jessie main contrib

deb http://cran.wu.ac.at/bin/linux/debian jessie-cran3/

In doing apt-get update
Reading package lists... Done
W: Duplicate sources.list entry http://dl.google.com/linux/chrome/deb/ stable/main amd64 Packages (/var/lib/apt/lists/dl.google.com_linux_chrome_deb_dists_stable_main_binary-amd64_Packages)
W: You may want to run apt-get update to correct these problems

I installed the new Google Chrome as root by
# http://askubuntu.com/questions/510056/how-to-install-google-chrome
wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list'
apt-get update
apt-get install google-chrome-stable

OS: Debian 8.5
Linux kernel: 4.7
Hardware: Asus Zenbook UX303UB

A: The following command :
sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list'

will add a new entry google-chrome.list to your /etc/apt/sources.list.d . Check it withe ls /etc/apt/sources.list.d then remove the dplicate entry.
If you have a single entry , you should check the google-chrome.list file then comment the duplicates URLs under /etc/apt/sources.list.d/google-chrome.list


text:
Q: PHP Function to devide an array of N elements in N sub array Let say I have an array of N elements. I want to divide it as much as possible equally into M sub arrays to make M columns.
Do you know how I could do that in PHP ?
I've tried array_chunk, but it's not quite what I'm looking for.
Here is two example :
$array = range(1, 10);
$number_of_split = 3;

The array should be split into 3 sub arrays of 4 elements for the first sub array and 3 elements for the two other sub arrays.
$array = range(1, 27);
$number_of_split = 5;

The array should be split into 5 sub arrays of 6 elements for the two first sub arrays and 5 elements for the three other sub arrays.

A: Try this function from php.net.
function partition($list, $p) {
    $listlen = count($list);
    $partlen = floor($listlen / $p);
    $partrem = $listlen % $p;
    $partition = array();
    $mark = 0;
    for($px = 0; $px < $p; $px ++) {
        $incr = ($px < $partrem) ? $partlen + 1 : $partlen;
        $partition[$px] = array_slice($list, $mark, $incr);
        $mark += $incr;
    }
    return $partition;
}

Use it like this:
$array = array();
$array = range(1, 10);
$number_of_split = 3;
$chunks = partition($array, $number_of_split);
print_r($chunks);


text:
Q: Calculating how many products to load from server based upon view-size I am working on a Spring-MVC application. In this, there are products in the database which I would like to load using a Ajax request. While doing so, I have to check for the view-size of the users device, and then compute how many products it can see in immediate view and with some fair amount of scrolling. For example : It is normal on a PC or a laptop to load 30/40 products, but on a mobile around 10-15 products also would suffice
I currently have the client side functionality to get the view-size of the screen. I would like to know how to calculate the optimal number of products to load from server depending upon screen-size. I am posting my ajax function incase it helps.
Ajax function : The 1 in listallproducts/1 is the page number
$(document).on('click','.product-image', function(event){
                $.ajax({
                 url: '../listallproducts/1',
                 type: 'POST',
                 success: function(response){
                         var newElement = $.parseHTML(response);
                         $(newElement).find(".products").css("display", "none");
                         $(newElement).find(".products").addClass("loadedProduct");
                                $("#freewall").append($(newElement).find(".products"));
                                initializeFreewall();
                                $("#freewall").find('.products').fadeIn(500);
                 },
                                error: function(xhr, status, error){
                                        alert("Da ist etwas schiefgelaufen" + xhr.responseText );
                                }
         });
        });

Any pointers are welcome. Thank you.

A: You could simply calculate the amount of products in javascript too, right? Like:
var productsView = 20;
if(screenSize<SCREENSIZEHERE){
     productsView = 10;
}

Then just send the offset number of current shown products + the productsView with the AJAX request. (I advice to use an offset number instead of page number in case a screen size changes.) Along with 'url:', 'type:' and 'succes:' put in:
data: { productsView: productsView, offset: offset },

I hope this helps..


text:
Q: How to close the Modal using Selenium WebDriver? I have a dropdown list, when I click on any of the dropdown value then a modal get opens, When I click outside the modal, it will get close. How to handle it with Selenium WebDriver?
here is my Modal Code

You click on Dropdown hover Option

I have tried with below code
driver.switchTo().defaultContent();

and
driver.switchTo().alert().dismiss();

But both are not working.

A: If you don't want to hit the Esc key you can click on div that has been created to cover the rest of the page using the following:
    driver.get("https://demo.stqatools.com/MouseHover.php");
    WebElement hoverButton = driver.findElement(By.cssSelector(".dropbtn"));
    WebElement linkOne = driver.findElement(By.cssSelector(".dropdown-content > a"));

    //Activate modal dialogue
    Actions action = new Actions(driver);
    action.moveToElement(hoverButton).perform();
    wait.until(ExpectedConditions.visibilityOf(linkOne));
    action.moveToElement(linkOne).click().perform();

    //Dismiss modal dialogue
    driver.findElement(By.cssSelector(".show")).click();

A: The most easy way - it's click on some static text on page.
Try click on page title (if exist).

A: This is not an alert, it's just a normal piece of DOM which looks like a modal popup due to CSS styling
So all you need to do is to locate the element using, for instance it's text, the relevant XPath locator would be something like:
//div[contains(text(),'You click on Dropdown hover Option')]

It would be also good to "wait" until popup presence/intractability via WebDriverWait like:
new org.openqa.selenium.support.ui.WebDriverWait(driver, 10)
        .until(
                ExpectedConditions.elementToBeClickable(
                        By.xpath("//div[contains(text(),'You click on Dropdown hover Option')]")))
        .click();


text:
Q: On representability of $\underline{Hom}_k(\mathbb A^1_k, \mathbb A^1_k)$ Let $F:k\text{-Sch} \rightarrow \text{Set}$ be the following functor:
$$F(X)=\text{Hom}_{X-\text{sch}}(\mathbb A^1_X, \mathbb A^1_X).$$
I would like to show that such functor is not representable.
I am able to show that is not representable by an affine scheme. Indeed, suppose $X=\text{Spec }R$ represents such functor and let $p(x)\in \text{Hom}_{X-\text{sch}}(\mathbb A^1_X, \mathbb A^1_X)=R[x]$ the universal object. If $A$ is a $k$-algebra and $a(x)\in A[x]$, then it should exist a morphism of $k$-algebras $R\rightarrow A$, such that the induced morphism $R[x]\rightarrow A[x]$ maps $p(x)$ to $a(x)$. If the degree of $p(x)$ is smaller than the one of $a(x)$, then it is impossible. Such argument could be extented to prove that such functor it is not representable by a quasi-compact scheme, but I'm not able to do the general case.
Any hints or ideas?


text:
Q: Merging Multiple TextViews onto a Bitmap - should i use canvas? I have found that you can add or merge textviews onto a bitmap. I have 4 textviews that I would like to merge onto the top of the image.
Here is a screenshot of what I would like to achieve (although at the minute this is textviews at the top separate to the image):
the image is below the textviews. Image header in top right is for what image No it is

So what I am trying to do is once I click the send button it "prints" or merges these Textviews onto the image bitmap below so that I can then save or send the image(with the textviews in it) as one file to my server/device.
So far I have used Canvas.draw() method although it seems to overwrite each other and I am trying to keep the same layout as the screenshot.
Can anyone help?

A: Try this...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    >
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottomLayID"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="vertical"
        >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="2"
            android:padding="8dp"
            >
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Detail work order"
                android:textStyle="bold"
                android:gravity="center"
                android:layout_weight="0.5"
                />
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Image"
                android:textStyle="bold"
                android:gravity="center"
                android:layout_weight="1.5"
                />
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:weightSum="2"
            android:padding="8dp"
            >
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:gravity="center"
                android:layout_weight="0.5"
                />
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textStyle="bold"
                android:gravity="center"
                android:layout_weight="1.5"
                />
        </LinearLayout>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/bottomLayID"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_alignParentBottom="true"
        >
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Open Camera"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Send Image"
            android:background="#99d72e"/>
    </LinearLayout>
</RelativeLayout>

Give background as transparent color and border to textviews.
You can set bitmap to imageview by
ImageView mImg;
mImg = (ImageView) findViewById(R.id.(your xml img id));
mImg.setImageBitmap(img);


text:
Q: BeautifulSoup to dataframe This is a follow up to this POST. I have managed to extract and write the data in excel. This is my current code:
import csv
import os
import pandas as pd
import requests
import datetime
from bs4 import BeautifulSoup

url_list = ["https://www.dell.com/community/Inspiron-Desktops/7700-AIO-failed-on-start-up/m-p/8303065#M36274",
            "https://www.dell.com/community/Inspiron-Desktops/Inspiron-7700-AIO-win-10/m-p/8303066#M36275"]
for i in url_list:
    result = requests.get(i)
    soup = BeautifulSoup(result.text, "html.parser")

    date = '11-16-2022'
    comments = []

    #Fiscal Week#
    date_object = datetime.datetime.strptime(date, '%m-%d-%Y').date()
    year, week_num, day_of_week = date_object.isocalendar()

    comments_section = soup.find('div', {'class':'lia-component-message-list-detail-with-inline-editors'})
    comments_body = comments_section.find_all('div', {'class':'lia-linear-display-message-view'})

    for comment in comments_body:
        if date in comment.find('span',{'class':'local-date'}).text:
            comments.append({
                'FW': week_num,
                'Date': comment.find('span',{'class':'local-date'}).text.strip('\u200e'),
                'Board': soup.find_all('li', {'class': 'lia-breadcrumb-node crumb'})[1].text.strip(),
                'Sub-board':soup.find('a', {'class': 'lia-link-navigation crumb-board lia-breadcrumb-board lia-breadcrumb-forum'}).text,
'Title of Post': soup.find('div', {'class':'lia-message-subject'}).text.strip(),
                'Main Message':  soup.find('div', {'class':'lia-message-body'}).text.strip(),
                'Post Comment': comment.find('div',{'class':'lia-message-body-content'}).text.strip(),
                'Post Time' : comment.find('span',{'class':'local-time'}).text,
                'Username': comment.find('a',{'class':'lia-user-name-link'}).text,
                'URL' : str(i)
            })

    df1 = pd.DataFrame(comments)
    print(df1)

    with open('output.csv', 'a', newline = '') as f:
        df1.to_csv(f, mode='a', header=f.tell()==0, index = False)

This gives me 10 columns in my sheet. However, I dont want 'main message' as a separate column. I want it in the 'Post Comment column itself (provided it was made on the given date). How do i do this as they both have different tags?


text:
Q: Kendo UI Menu Doesn't work in IE (Touch) Kendo UI Menu doesn't work in IE on Tablets running Windows 8 (IE 10 & IE 11). The menu drop down doesn't work. The menu works in Google chrome on the same Windows tablet.

A: It would be easier if you posted a code example.
By far the most common problem I have with things not working on IE is with trailing commas in arrays. For example:
menuItems=[12,33,44,2,7,];

Runs just fine in chrome but IE breaks.

A: Upgrade to a newer version of Kendo. They fixed this in their Q2 2013 release 2013.2.918.
Kendo Link

A: The latest version from KendoUIWeb (2013.3.1119) does now also solve this issue.


text:
Q: How to use an xcode game on unity3d I have a game built on xcode using objective c. this game needs to be integrated with another game developed in unity3d as a part of it. how can i do this? what plugins are available to achieve this??
The thing is that.. i have a unity3d game and i have few other games inside the main game(games inside one game). these small games are already built on xcode.. now i have to use these games inside the main unity game.. something like if i chose to play one of the games it has to load that particular xcode game.. how can i achieve this?? also if this is achieved.. can i build it on unity-android and expect it to work? or do i have to do it differently for android? Please guide..

A: Have a look at the following resources about mixing Unity3D code with Objective-C native code:

*

*Mixing Unity generated code with Objective-C in iOS?

*iPhone & Unity3D: Integrating 3rd Party Static Libraries in Unity3D Generated XCode Projects

*Unity Native Plugins: OS X
If both application modules need interact on a high frequency, I recommend a polling approach instead of SendMessage, because of a perfomance lack in the latter case.


text:
Q: insert excel vba function values into access I have been puzzling over this problem and can't seem to work it out by myself. I wrote an Excel tool that will calculate a specific amount of money. I have to do this for 10,000 different cases and have to store the results in Access. I haven't been able to figure out how, though. The function I need to use looks something like this:
> Public Function Assets(TG As Integer, t As Integer, n As Integer,
> Tarif As String, j As Integer)
>
> Assets = ...
>
> End Function

In the same module, I have a macro that combines a few procedures and should also insert the results into my Access database. I have two columns in this database: the case number and the value of the result.
> Sub Results()
>
> Dim n As Integer Dim Tarif As String Dim TG As Integer Dim t As
> Integer Dim i As Integer Dim j As Integer Dim dbfile2 As String Dim
> dbe2 As Object    ' As DAO.DBEngine Dim db2  As Object    ' As
> DAO.Database Dim rs2 As Object     ' AS DAO.Recordset
>
>
> n = ... Tarif = ... TG = ...
>
> For j = 1 To 10000
>
>     'Opens the Access database
>     dbfile2 = "\\r74efc11\PR_GDV_TRA\Transparenz_2016_2017\20_TP_F\02_Arbeitspakete\CRK_Berechnung\Beispiel-Hochrechnung\Hochrechnung_Ablaufvermögen_Test.accdb"
>     Set dbe2 = CreateObject("DAO.DBEngine.120")
>     Set db2 = dbe2.OpenDatabase(dbfile2)
>
>     db2.Execute "INSERT INTO Tabelle1 (Nr, [Value])VALUES(" & j & "," & Assets(TG,n,n,j) & ")"
>
>     db2.Close
>     Set db2 = Nothing
>     Set dbe2 = Nothing
>
> Next j
>
> End Sub

This code works fine without the Assets-function and the Assets-function runs correctly in Excel as well. I just want to insert the result in my Access database.
Can anyonle help me with this? All I could find online was how to insert worksheet functions but this doesn't apply in my case. I've tried to modify that but without any luck.

A: You shouldn't replace but convert. Although solved by now, in the future you may benefit from this function which does exactly that:
' Converts a value of any type to its string representation.
' The function can be concatenated into an SQL expression as is
' without any delimiters or leading/trailing white-space.
'
' Examples:
'   SQL = "Select * From TableTest Where [Amount]>" & CSql(12.5) & "And [DueDate]<" & CSql(Date) & ""
'   SQL -> Select * From TableTest Where [Amount]> 12.5 And [DueDate]< #2016/01/30 00:00:00#
'
'   SQL = "Insert Into TableTest ( [Street] ) Values (" & CSql(" ") & ")"
'   SQL -> Insert Into TableTest ( [Street] ) Values ( Null )
'
' Trims text variables for leading/trailing Space and secures single quotes.
' Replaces zero length strings with Null.
' Formats date/time variables as safe string expressions.
' Uses Str to format decimal values to string expressions.
' Returns Null for values that cannot be expressed with a string expression.
'
' 2016-01-30. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function CSql( _
    ByVal Value As Variant) _
    As String

    Const vbLongLong    As Integer = 20
    Const SqlNull       As String = " Null"

    Dim Sql             As String
    Dim LongLong        As Integer

    #If Win32 Then
        LongLong = vbLongLong
    #End If
    #If Win64 Then
        LongLong = VBA.vbLongLong
    #End If

    Select Case VarType(Value)
        Case vbEmpty            '    0  Empty (uninitialized).
            Sql = SqlNull
        Case vbNull             '    1  Null (no valid data).
            Sql = SqlNull
        Case vbInteger          '    2  Integer.
            Sql = Str(Value)
        Case vbLong             '    3  Long integer.
            Sql = Str(Value)
        Case vbSingle           '    4  Single-precision floating-point number.
            Sql = Str(Value)
        Case vbDouble           '    5  Double-precision floating-point number.
            Sql = Str(Value)
        Case vbCurrency         '    6  Currency.
            Sql = Str(Value)
        Case vbDate             '    7  Date.
            Sql = Format(Value, " \#yyyy\/mm\/dd hh\:nn\:ss\#")
        Case vbString           '    8  String.
            Sql = Replace(Trim(Value), "'", "''")
            If Sql = "" Then
                Sql = SqlNull
            Else
                Sql = " '" & Sql & "'"
            End If
        Case vbObject           '    9  Object.
            Sql = SqlNull
        Case vbError            '   10  Error.
            Sql = SqlNull
        Case vbBoolean          '   11  Boolean.
            Sql = Str(Abs(Value))
        Case vbVariant          '   12  Variant (used only with arrays of variants).
            Sql = SqlNull
        Case vbDataObject       '   13  A data access object.
            Sql = SqlNull
        Case vbDecimal          '   14  Decimal.
            Sql = Str(Value)
        Case vbByte             '   17  Byte.
            Sql = Str(Value)
        Case LongLong           '   20  LongLong integer (Valid on 64-bit platforms only).
            Sql = Str(Value)
        Case vbUserDefinedType  '   36  Variants that contain user-defined types.
            Sql = SqlNull
        Case vbArray            ' 8192  Array.
            Sql = SqlNull
        Case Else               '       Should not happen.
            Sql = SqlNull
    End Select

    CSql = Sql & " "

End Function


text:
Q: Sharp Regression Discontinuity (RD) for one part of the sample, RCT for another? I have a study where schools' 4th graders are randomized into treated and controls (at the school level, i.e. there are treatment and control schools). Within each treated school, treatment follows a sharp cut-off rule which also allows for a sharp regression discontinuity (RD) approach. In contrast, among 3rd graders, there are only treatment schools, but the RD approach can still be used: In any treated school, half of the students don't receive the program, strictly following assignment along a forcing variable.
I know how to set this up to exploit the RCT for 4th graders, the RD for 3rd graders, and to estimate everything in one go. I'm interested in doing that to increase power. However, this strategy mushes together the (4th grade) ATE and the (3rd grade) local RD estimate. Do you know of any literature that already discusses the properties of such a "combined" estimator, that uses an RCT for some part of the sample and an RD for another part? If not, what would be your arguments against such an approach?


text:
Q: Swift observe(_:options:changeHandler:) newValue always nil I have this setup to observe value changes for AVCaptureDevice deviceWhiteBalanceGains:
@objc dynamic var videoDevice:AVCaptureDevice?
private var deviceWBGainsObservation: NSKeyValueObservation?

And then in the code,
deviceWBGainsObservation = videoDevice?.observe(\.deviceWhiteBalanceGains,
                     options: [.old, .new]) {[unowned self] (object, change) in

    NSLog("\(change)")
}

Problem is change oldValue and newValue is always nil. This is not the case if I use the traditional key-value observing method observeValue(forKeypath:...). What am I doing wrong?


text:
Q: Running 3-6V motors with 7.2V I'm using the popular DIY motor:

Which his operating voltage is claimed to be between 3-6V.
I'm using a battery of 7.2V. I know that running the motor outside the recommended voltage range might shorten it's lifespan. I'm planning to use it for the next couple of months, about 10 hours of total usage. Will it be safe to say that the motor will still be able withstand this voltage?

A: No. Why should it? You're operating outside the manufacturer's ratings so you can expect it to fail.

simulate this circuit – Schematic created using CircuitLab
Figure 1. Two-diode voltage dropper.
Wire two silicon diodes in series with the circuit. They will drop 0.6 to 0.8 V each and run the motor at about 5.8 V.

A: Over driving the motor will affect it's life by an unknown amount. It may live for a year, a month, a day, or immediately burn itself out. It also depends on how often you turn the motor on, and for how long each time. Longer periods of time mean more heat buildup.
A quick fix is to lower the voltage, through the use of two diodes in series. Standard 1n400x should be fine. At 0.7V per diode, that's 1.4 volt drop from the nominally 7.2V battery, giving you 5.8 volts at the pager motor.

A: You should not use any component outside of it's absolute maximum ratings. The effects are not to be underestimated.
A very common way to protect components from overvoltage is the proper use of suppressor diodes or zener diodes. They are used in all kind of devices. They are wired in parallel with the component to be protected. If the voltage applied is higher than the breakdown voltage of the suppressor diode, it will "breakdown" and conduct so that the voltage will drop and the component is protected.
For more information click here
However, these diodes are for transient overvoltages, not continuous! So the solution would be to adjust the input voltage. Is the motor directly driven from the battery without any electronics? Then you should use at least two normal diodes in series with the motor. Watch out for the maximum current that is drawn.
You could also switch to a 5V Battery-Pack, witch are getting really common with the USB Powerbanks these days.


text:
Q: Creating an empty array of functional interfaces I have a method which returns an empty array of Function<T,V>
public <T, V> Function<T, V>[] foo() {
    ...
    return (Function<T, V>[]) new Object[0];
    ...
}

But I catch java.lang.ClassCastException at runtime.
Is it possible to return an empty array of functional interfaces?

A: The closest thing you can do is
return (Function<T, V>[]) new Function[0];

This has nothing to do with functional interfaces, and everything to do with arrays and generics not interacting well.

A: You can't cast an Object[] to another type, simply because it's not that type. This applies even if the array size is 0.
Why don't you simply return an array of 0 Functions?
return new Function[0];

This may give an "unchecked cast" warning, but it will still work, since there's no difference at runtime between the type Function[] and the parameterized type Function<T, V>[] due to type erasure. In this case, you can safely use @SuppressWarnings("unchecked").


text:
Q: GA event tracking doesn't work I have the following code:
<input type="submit" name="button" id="button" value="Submit"/>

I also tried:
<input onclick="ga('send','event','contactform','submit');" type="submit" name="button" id="button" value="Submit"/>

When the submit button is clicked I can't see anything in (realtime) Google Analytics. I fear I've done something wrong with the implementation.

A: try wrapping it in a function something like
function test(){

    ga('send', 'event', 'Videos', 'play', 'Fall Campaign');

}

then doing .
Though I think the issue maybe with the implementation of your GA code. Are you using a plugin to place Google Analytics code on the website?


text:
Q: Spring MVC: Load jars to classpath from external folder along with WEB-INF\lib I have a Spring MVC Application(with Maven) that will be deployed to the tomcat server. All its libs goes to WEB-INF\lib.
I have a custom jar which contains spring services, i want to load this to classpath from external folder. This custom jar may not present all times. If it copy it to WEB-INF\lib manually, it works. But, that is not an ideal solution as new war deployment will erase this jar.
I have tried setting its path in setenv.sh using CLASSPATH, but the Autowired classes in the internal classes are not working.
Is there any way we can set the external folder as classpath along with WEB-INF\lib?
Any help would be appreciated.


text:
Q: What is the process of star formation? What is the process of star formation and what happens to stars after their death?

A: The process of star formation (which is known as stellar evolution) changes a star over time. The mass of a star makes an impact on its lifetime. So depending on the mass, a lifetime of a star can vary from a few million years to a trillion years.

All stars are formed from collapsing clouds of gas and dust, often called nebulae or molecular clouds. These very first baby stars are known as protostars. Over time, maybe million years, these protostars settle down and become main-sequence stars.
Nuclear fusion gives power to stars in their formation, evolution, and the rest of their lifetime. Initially, this power generated by a fusion of hydrogen atoms at the core of main-sequence stars. Lately, these atoms become Helium. According to the mass of the star, the process of evolution varies after this stage.

*

*stars like the Sun begin to fuse hydrogen along a spherical shell surrounding the core.
This causes a gradual increase in the size of stars passing through the subgiant stage until it reaches the red giant phase of stars.

*

*Stars with at least half the mass of the Sun can also begin to generate energy through the fusion of helium at their core, whereas more massive stars can fuse heavier elements along with a series of concentric shells. Once a star like the Sun has exhausted its nuclear fuel, its core collapses into a dense white dwarf and the outer layers are expelled as a planetary nebula.

*Stars with around ten or more times the mass of the Sun can explode in a supernova as their iron cores collapse into an extremely dense neutron star or black hole. The smallest red dwarfs reach the end of their existence, they will slowly become brighter and hotter before running out of hydrogen fuel and becoming low-mass white dwarfs.


text:
Q: Estimating sample size for Mann Whitney U test I'm trying to estimate the required sample size for 80% power in an A/B testing, comparing user ratings with the Mann Whitney U test, and I'm having a problem with the power estimation.
I'm using this code to generate a dataset:
def sim_ratings(n, p):
    return np.random.choice(np.arange(5) + 1, size = (n,), p = p)

which I then compare. For example, I check the Type-1 error rate, and get this:
a = np.asarray([0.15, 0.15, 0.15, 0.15, 0.4])

N_TRIALS = 10000

for N_SAMPLES in [10, 50, 100, 500]:
    p_values = np.asarray([mannwhitneyu(sim_ratings(N_SAMPLES, a), sim_ratings(N_SAMPLES, a), alternative = 'greater')[1]
                           for _ in range(N_TRIALS)])

    print(N_SAMPLES, np.sum(p_values < 0.05) / len(p_values))

which gives the expected output
10 0.0416
50 0.0508
100 0.0525
500 0.0523

But then when I try to calculate power, I run into a problem:
a = np.asarray([0.15, 0.15, 0.15, 0.15, 0.4])
b = np.asarray([0.1, 0.15, 0.15, 0.15, 0.45])

N_TRIALS = 200
N_REPEAT = 10
ss = []
vv = []
for i in range(N_REPEAT):
    s = []
    v = []
    for N_SAMPLES in range(20, 2400, 20):
        p_values = np.asarray([mannwhitneyu(sim_ratings(N_SAMPLES, b), sim_ratings(N_SAMPLES, a), alternative = 'greater')[1]
                       for _ in range(N_TRIALS)])

        s.append(N_SAMPLES)
        v.append(np.sum(p_values < 0.05) / len(p_values))

    ss.append(s)
    vv.append(v)

plt.figure(figsize=(14,7))
for s,v in zip(ss, vv):
    plt.plot(s, v)

which renders the below graph.

Note the sudden dips to zero once the number of samples reaches a certain level. Is this a bug in my code or in the mannwhitneyu function from scipy? Is this a reasonable way to approximate the samples needed for a particular power level?
For what it's worth, I'm using Python 3.5 with SciPy 0.17.0.


text:
Q: How can I define a function which bind only xvalue OR prvalue but not both Is there a way to define a function which handle only xvalue or prvalue (or is here a exclusive or)  ?
For instance suppose I have a method f(foo&& f), how can I declare f to bind xvalue type and reject prvalue type and vice versa ?
struct Foo{};
void xvalue(/*what put here ?*/){}
void prvalue(/*what put here ?*/){}

void main()
{
  Foo foo;

  prvalue(Foo());//compile
  prvalue(std::move(foo)));//fail at compilation

  xvalue(std::move(foo)); //compile
  xvalue(Foo());//fail at compilation
}

Maybe by using std::enable_if and the fact that decltype(e) is a rvalue reference type for xvalues and non-reference type for prvalue ?

A: Using the code from this answer it should be trivial.
#include <type_traits>
#include <iostream>
#include <utility>

template <typename T>
bool is_xvalue()
{
    if (std::is_lvalue_reference<T>::value)
        return false;
    else if (std::is_rvalue_reference<T>::value)
        return true;
    return false;
}

template <typename T>
bool is_prvalue()
{
    if (std::is_lvalue_reference<T>::value)
        return false;
    else if (std::is_rvalue_reference<T>::value)
        return false;
    else
        return true;
    return false;
}

struct Foo {};

int main()
{
    std::cout << std::boolalpha;
    std::cout << is_prvalue<decltype(Foo())>() << "\n"; // true
    std::cout << is_prvalue<decltype(std::move(Foo()))>() << "\n"; // false
    std::cout << is_xvalue<decltype(Foo())>() << "\n"; // false
    std::cout << is_xvalue<decltype(std::move(Foo()))>() << "\n"; // true
    return 0;
}

Unfortunately, you have to explicitly instantiate the templates, or else it doesn't work for some reason.
struct Foo {};

template <typename T, typename = typename std::enable_if<is_prvalue<T>(), void>::type>
void prvalue(T&& t)
{
}

template <typename T, typename = typename std::enable_if<is_xvalue<T>(), void>::type>
void xvalue(T&& t)
{
}

prvalue<decltype(Foo())>(Foo());
// prvalue<decltype(std::move(Foo()))>(std::move(Foo())); - compile error
xvalue<decltype(std::move(Foo()))>(std::move(Foo()));
// xvalue<decltype(Foo())>(Foo()); - compile error


text:
Q: Can't boot into Windows 10 anymore I currently dual booting between Ubuntu and Windows 10. However, whenever I try to boot from Windows 10 in grub it simply restarts and brings me right back to grub again.
I used boot-repair to create a pastebin:
http://paste.ubuntu.com/p/pzJqP55FVV/
It's too long to paste it here.
But I have no idea what anything in the pastebin really means or how to fix grub. I have tried updating grub but the same problem occurs.
I ran sudo ntfsfix -b -d /dev/sda1
 and got
Mounting volume... Failed to load runlist for $MFT/$DATA.
highest_vcn = 0x32cfb, last_vcn - 1 = 0x4027f
Failed to load $MFT: Input/output error
FAILED
Attempting to correct errors... Failed to load runlist for $MFT/$DATA.
highest_vcn = 0x32cfb, last_vcn - 1 = 0x4027f
Failed to load $MFT: Input/output error
FAILED
Failed to startup volume: Input/output error
Checking for self-located MFT segment... OK
Failed to load runlist for $MFT/$DATA.
highest_vcn = 0x32cfb, last_vcn - 1 = 0x4027f
Failed to load $MFT: Input/output error
Volume is corrupt. You should run chkdsk.

A: Attempt to repair the NTFS drive from linux. Per this solution, do the following:

Install ntfs-3g with sudo apt-get install ntfs-3g . Then run the
  ntfsfix command on your NTFS partition

sudo ntfsfix -b -d /dev/sdaX

if ntfsfix won't or can't fix your drive, you will have to run chkdsk from windows. You can boot from Hiren's miniXP boot disk and use the command line there to run chkdsk.


text:
Q: How do I sync my users connections PHP I have a class in PHP called cUser:
class cUser {
    var $m_email;//The users email adresse(String)
    var $m_password;//His password(String)
    var $m_username;//His username(String)
    var $m_active;//If the user have been activate (By following a link send to him via is email)(Bool)

    function __construct($p_username, $p_password, $p_email, $p_active) {
        $this->m_username = $p_username;
        $this->m_password = $p_password;
        $this->m_email = $p_email;
        $this->m_active = $p_active;
    }

    //this is the important part...
    function connexion() {
        include "Config.php";//include all the parameters needed to connect to the DB

        $cn = new cConnexion($ConnexionDBHost, $ConnexionDBName, $ConnexionDBLogin, $ConnexionDBPassword);//Initiate a connection to the DB

        if($cn->DBConnexion())//If it is connected {
            $parameters = array('username'=>$this->getUsername(), 'password'=>$this->getPassword());//create an array with the username and the password
            $getConnexion = $cn->SecureSelect("SELECT username, password, email, active FROM user WHERE BINARY username = :username AND BINARY password = :password", $parameters);//selecte the user in the DB (for DB description see below code)

            if($getConnexion != null) { //if there is no error in the query.
                $resultSet = $getConnexion->fetch();//fetch the results
                if($resultSet != null) { //if there is a match
                    //assigne the DB field values to this instance of cUser
                    $this->setUsername($resultSet['username']);
                    $this->setPassword($resultSet['password']);
                    $this->setEmail($resultSet['email']);
                    $this->setActive($resultSet['active']);

                    if($this->getActive() == 1) {
                        //If the user has been activate already return success
                    }
                    else {
                        //Else send an activation email to the user.Dont connecte him and return an error message
                    }
                }
                else {
                    //Send an error message
                }
            }
            else {
                //send an error message
            }
        }
        else {
            //send an error message
        }
    }

    //this are not important for the question but I put them there so you can see what kind of operation the class is doing.
    function delete(){//Delete this instance of cUser from de DB}
    function insert(){//Insert this instance of cUser from the DB}
    function update($p_email, $p_username, ...){//Update this instance of cUser with the new parameters}
    function activateAccount(){//Activate this instance of cUser}
    //And all the getters and setters associate with the class attributes.
}

Here is the MySQL Table containing the field for the cUser class (roughly coded):
USER
    varchar email,
    varchar password,
    varchar username,
    tiny int activate,//1 or 0
    tiny int connected//1 or 0

Question:
How can I implement or change the function connection so one instance of a user is connected  at the same time?
Note:
I already know I can just check if the DB connected field is set to 1 but if two user access the DB at the same time it would create a problem (race condition or something like that).
Is there something like a mutex or semaphore I can use to sync the access of the DB field connected??
Example:
David fill the HTML form and submit it with user name and password ("Dav1", "ThisIsPassword"), a process page create the cUser instance and connect to check if Dav1 already existe then give him access to the rest of the web-app.
Now Davos fill the form and submits it with the same user-name and password that David used because Davos and David are friend and they shared the same account and shared there password.
With the existing code both David and Davos can then access the web application at the same time with the same account what I want is that when David connect Davos get an error message that tell him that the user is either already connected or the user-name/password doesn't match.

A: Use a transaction.
In MySql you can also use SELECT FOR UPDATE statement.
Pseudocode:
$transaction = db->beginTransaction();
try {
    $user = User::getByUsername($username);

    if ($passwordImcorrect)
        throw new Exception('invalid credentials');

    if (user->loggedIn)
        throw new Exception('already logged in');

    user->loggedIn = 1;
    user->save();

    $transaction->commit();
}
catch (Exception $e) {
    echo $e->getMessage();
    $transaction->rollback();
}


text:
Q: Detect decimal number in Swift string I'd like to detect a number in a given String.
Examples are:

*

*1

*1.2

*1,2

*1.2kg

*100mg

Please note that it is safe to assume the string always starts with the number, the number can be an integer or a decimal and the decimal separator can be a dot or a comma. Also you can assume a string does not contain multiple numbers.
As you can see from the examples a string can also contain a unit. I'd like to be able to get the range of the found number in order to get the remaining substring and to match that with a list of known units. However that range should be relative to a much bigger string. The string parsed here is only one token of a much larger string and I'd like to be able to get the range of the quantity in that larger string. Therefore the goal would be a function looking like this:
func scanQuantity(in string: String) -> (NSNumber, Range<String.Index>)?

Here is what I have. It kind of works however I am not sure how to a) get the range of the quantity inside of that larger string and
b) how to handle both decimal separator as scanDouble only works for one.
To make things clearer that is what I want to achieve:
I'd like to have 4kg bananas

Tokens:
- I'd
- like
- to
- have
- 4kg
- bananas

I'd like to have 4kg bananas
                 ↑⇧⇧
↑: quantityRange
⇧: unitRange

func detect(in string: String) {
    let matches = string.matches(of: pattern)
    for match in matches {
        let token = match.output.0
        print("Scanning token: \(token)")
        if let quantity = scanQuantity(in: String(token), of: match.range) {
            print("Found quantity: \(quantity.value)")
        }
    }
}

private func scanQuantity(in token: String, of range: Range<String.Index>) -> Quantity? {
    let scanner = Scanner(string: token)
    #warning("this does not work for both comma and dot decimal separator")
    guard let quantity = scanner.scanDouble() else {
        return nil
    }

    if !scanner.isAtEnd {
        let unitSubstring = token[scanner.currentIndex...]
        print("Scanning for unit of quantity")
        print("Unit: \(unitSubstring)")
        #warning("how to get the range of the quantity in the whole string (relative to the range parameter)")
        return Quantity(value: NSNumber(value: quantity), range: range, unit: .piece)
    } else {
        return Quantity(value: NSNumber(value: quantity), range: range, unit: .piece)
    }
}

A: You can use the new Regex functionality in swift
The pattern used is
let regex = /((\d+(\.|,?)\d*)([a-z]*))/

and then to evaluate the regex
someString.firstMatch(of: regex)

Example
let inputs = ["1", "1.2", "1,2", "1.2kg", "100mg", "I'd like to have 4kg bananas"]

for input in inputs {
    if let result = input.firstMatch(of: regex) {
        print((result.2, result.4))
    }
}

Output

("1", "")
("1.2", "")
("1,2", "")
("1.2", "kg")
("100", "mg")
("4", "kg")


text:
Q: Why does Ubuntu's installer fail with an error made of question marks? I bought a Toshiba KIRAbook. It has Windows 8. I tried to install Ubuntu from USB driver 16.04 but it gave an awkward error in the "Preparing to install Ubuntu" step. The error consisted of question marks separated by a space:

??? ???

*

*I tried the 32-bit and 64-bit versions.

*I tried the 16.04 and 17.04 version.

*And I tried to install from "Try Ubuntu" option.

It is not about the USB drive because I has installed on another desktop before a couple weeks ago, and it worked.
Does anyone have any idea?
The error looks like this:


text:
Q: How to create object of Activity how to create object of activity and call its life cycle method like a normal java class.
for example,
In Android
class ABC extends Activity{}

new ABC().onCreate(null);

A: If you are looking to start a new activity (like from your main activity to ABC activity), you do it this way
Intent i = new intent(this, ABC.class);
startActivity(i);

if you looking for passing data, use putExtra() method with the intent.
if your data is much larger, you can always use SharedPreferences or SqlLite database, depending on your need.
Hope it helps


text:
Q: Missing new line when downloading a text file using python's request package I am using the following code for downloading a csv file from a remote http server:
with contextlib.closing(requests.get("http://some_url/file.csv", stream= True)) as response, open('/tmp/archivo.csv', 'wb') as output_file:
        for chunk in response.iter_lines(chunk_size=1024*8):
            if chunk:
                print(chunk)
                output_file.write(chunk)

Everything seems to work, the output on the screen is:
b'Code,Description'
b'"1","Some"'
b'"2","Few"'
b'"3","human"'
....

But the file is:
$ cat /tmp/archivo.csv
Code,Description"1","Some""2","Few""3","human"...

I think that the issue is related to the new line encoding between Windows, GNU/Linux and Mac, but I don't know how to specify that in the code just showed.
The problem is not related to opening the file in 'wb' mode, is I made the changes needed
with contextlib.closing(requests.get("http://some_url/file.csv", stream= True)) as response, open('/tmp/archivo.csv', 'w') as output_file:
        for chunk in response.iter_lines(chunk_size=1024*8):
            if chunk:
                print(chunk.decode('utf-8'))
                output_file.write(chunk.decode('utf-8'))

The output on the screen changes,
'Code,Description'
'"1","Some"'
'"2","Few"'
'"3","human"'
...

but the file doesn't
Any ideas?

A: You are seeing newlines because print() automatically terminates every output with a newline. Compare your output to
print(chunk.decode('utf-8'), end='')

which specifically does not terminate with newlines.
To correctly insert newlines into output_file you can use
output_file.write(chunk.decode('utf-8') + '\n')

or iterate over chunks instead of lines using
for chunk in response.iter_content(chunk_size=1024*8):
    if chunk:
        output_file.write(chunk)


text:
Q: base plot glm multivariate logistic regression in R I have the following model :
model_ <- glm( response ~ var_1 + var_2, family = "binomial" )

which gives me the following results :
Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.07418    0.05484 -56.053   <2e-16 ***
var_1        0.19238    0.13547   1.420    0.156
var_2        2.07090    0.23579   8.783   <2e-16 ***
---

The only way I figured out how to plot with the base graphic functions the two probability curves was by running two different models :
model_1 <- glm( response ~ var_1, family = "binomial" )
model_2 <- glm( response ~ var_2, family = "binomial" )

and create two predicted curves :
curve( predict( mod_1, data.frame( var_1=x ), type="resp" ))
curve( predict( mod_2, data.frame( var_2=x ), type="resp" ))

Which once plotted look like the following graphs :

But of course the coefficients are then not the same than with my initial model_.
          coef(model_)    coef(model_1)    coef(model_2)
var_1         0.192            0.165           ---
var_2         2.071***          ---           2.065***

I would like to plot the two probability curves corresponding to each variable from the multivariate model model_and not from the two submodels model_1and model_2.

*

*Is there a more or less simple way to show those two curves directly from model_ without having to run other submodels which give slightly different coefficients ?

*How would it work with 4 probability curves corresponding to the variables var_1, var_2, var_3and var_4 with a formula such as response ~ var_1 + var_2 + var_3 + var_4 ?

There are some examples on the net, but either using automatic functions from ggplot (which i don't want to use) or running univariate models.

A: I came out with this last night :
# intercept & beta coefficients
intercept <- as.numeric( coef( model )[1] )
beta_var_1 <- as.numeric( coef( model )[2] )
beta_var_2 <- as.numeric( coef( model )[3] )
...

# range of variables
range <- seq( 0, 10, .01 )

# log odds
logodds_var_1 <- intercept + beta_var_1 * range
logodds_var_2 <- intercept + beta_var_2 * range
...

# probabilities
prob_var_1 <- exp(logodds_var_1) / (1+exp(logodds_var_1))
prob_var_2 <- exp(logodds_var_2) / (1+exp(logodds_var_2))
...

# curves
plot( x=range, y=prob_var_1, type="l" )
plot( x=range, y=prob_var_2, type="l" )
...

This produces two (or more) curves which look more coherent to what i am looking for. I hope i am not misunderstanding the principles of such a logit model.


text:
Q: Xcode 6 doesn't auto generate code I have a strange problem with Xcode 6. I am not exactly sure if it was this way from the beginning or only lately, but when I add new class that inherit from UITableViewController and such, Xcode does not add the pre-generated methods as it usually does. On top of that, when I add a new class and choose Swift, the file imports Cocoa on default instead of UIKit, so I have to change it manually every time.
As it doesn't prevent me from creating classes etc., it is a bit annoying to deal with that every time. I would appreciate some help with that issue, searching for an answer led me nowhere so far. Thanks!


text:
Q: Is there a way to invoke a goal of a particular version of a Maven plugin? I would like to invoke a goal of a particular version in a Maven plugin from the command line.
How can this be achieved?
I'm looking for something along the lines of:
mvn org.foo:my-plugin:1.2.3-SNAPSHOT:do-something

A: Your first guess is correct. The scheme for such a command is
mvn groupid:artifactid:version:goal

Example:
mvn org.apache.maven.plugins:maven-compiler-plugin:3.0:compile


text:
Q: Why use a recursive function rather than `while true do` in F#? Whilst watching a Pluralsight course by Tomas Petricek (who I assume knows what he is talking about), I saw code like the following...
let echo =
  MailboxProcessor<string>.Start(fun inbox ->
    async {
      while do true
        let! msg = inbox.Receive()
    printfn "Hello %s" msg
    })

Ignore the fact that this was to demo agents, I'm interested in the inner function, which uses while do true to keep it running indefinitely.
Whilst looking around for other example of agents, I saw that many other people use code like this...
let counter =
  MailboxProcessor.Start(fun inbox ->
    let rec loop n =
      async { do printfn "n = %d, waiting..." n
        let! msg = inbox.Receive()
        return! loop(n+msg) }
    loop 0)

Code copied from Wikibooks.
The inner function here is recursive, and is started off by calling it with a base value before the main function declaration ends.
Now I realise that in the second case recursion is a handy way of passing a private value to the inner function without having to use a mutable local value, but is there any other reason to use recursion here rather than while do true? Would there be any benefit in writing the first code snippet using recursion?
I find the non-recursive version much easier to read (subjective opinion of course), which seems like a good reason to use that whenever possible.

A: In many cases it depends on how you like to code. Like in your example.
Everything you can write recursiv you can also write with a loop, but sometime like with recursive data structures it is easier to write the in a recursive style.
At university I learned that with recursive programming you only have to look at your next step which is pretty handy!
You might be interested in this question as it explains my answer a bit further:
recursion versus iteration

A: Talking about MailboxProcessor specifically, I think the choice depends on what exactly you are doing. In general, you can always use while loop or recursion.
Recursion makes it easier to use immutable state and I find while loop nicer if you have no state or if you use mutable state. Using mutable state is often quite useful, because MailboxProcessor protects you from concurrent accesses and you can keep the state local, so things like Dictionary (efficient hash table) are often useful.
In general:

*

*If you don't need any state, I would prefer while

*If you have mutable state (like Dictionary or ResizeArray), I'd go for while

*If you have some immutable state (like functional list or an integer), then recursion is nicer

*If your logic switches between multiple modes of operation then you can write it as two mutually recursive functions, which is not doable nicely with loops.

A: In F# for and while loop expressions lacks capabilities common in other languages:

*

*continue - Skip the rest of the loop and restart from the top of loop expression.

*break - Stop the loop prematurely.

If you want continue and break don't do what I did in the beginning a write a very complex test expression for while loops. Instead tail recursion is the best answer in F#:
let vs : int [] = ...
let rec findPositiveNumberIndex i =
  if i < vs.Length then
    if vs.[i] > 0 then
      Some i
    else
      findPositiveNumberIndex (i + 1)
  else
    None
match findPositiveNumberIndex 0 with
| Some i -> printfn "First positive number index: %d" i
| None   -> printfn "No positive numbers found"

In code like this F# applies something call tail-call optimization (TCO) which transforms the code above into a while loop with break. This means that we won't run out of stack space and the loop is efficient. TCO is a feature that C# lacks so we don't want to write code like above in C#.
Like others are saying with tail recursion you can sometimes avoid mutable state but that's not all.
With tail recursion your loop expressions can return a result which is nice.
In addition, if you like to iterate fast in F# over types like int64 or with increment other than 1 and -1 you have to rely on tail recursion. The reason is that F# only does efficient for expressions for ints and increments of 1 and -1.
for i in 0..100 do
  printfn "This is a fast loop"

for i in 0..2..100 do
  printfn "This is a slow loop"

for i in 0L..100L do
  printfn "This is a slow loop"

Sometimes when you are hunting for performance a trick is to loop towards 0 (saves a CPU register). Unfortunately the way the F# generates for loop code this doesn't perform as well one would hope:
for i = 100 downto 0 do
  printfn "Unfortunately this is not as efficient as it can be"

Tail recursion towards 0 saves the CPU register.
(Unfortunately the F# compiler don't merge the test and the loop instruction for tail-recursion so it's not so good as it could be)


text:
Q: How do I discard modified content in git submodules? I recently ran a git submodule init and update commits in my staging branch. This led to git downloading a bunch of changes from submodules that I do not want to put into staging and wish to discard completely.
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
  (commit or discard the untracked or modified content in submodules)
        modified:   path-to/submodule1 (modified content)
        modified:   path-to/submodule2 (new commits,modified content)
    …

no changes added to commit (use "git add" and/or "git commit -a")

I'd like to discard all of these changes and and not add anything to my current branch. How do I do this?

A: Since each submodule is its own Git repo, you can reset each one individually.

*

*Get rid of any local changes that are not committed: go into each submodule, and run git reset --hard

*Make sure each submodule is on the commit that the top-level Git repo wants, by running git submodule update at the top level.


text:
Q: Noob C++/OpenMP: Why do I get this compile time error? variable in 'reduction' clause must be shared in enclosing context  1 int result = 0;
 2 int b = 0;
 3 #pragma  omp for reduction(+:result) private(b)
 4 for(int i = 0; i < size; i++) {
 5    ifile >> b;
 6    if(b== 100)
 7      result++;
 8 }

Why do I get this error?
(3) error C3037: 'result' : variable in 'reduction' clause must be shared in enclosing context
I tried googling btw... all the examples look like this. I am also coding this in visual studios 2012 if that matters. I hate asking a question like this, but it is blocking me from continuing.
Fixed: add parallel
#pragma  omp parallel for private(buffer) reduction(+:result)

A: You're missing the "parallel" tag from the reduction clause:
#pragma  omp for reduction(+:result) private(b)

should be
#pragma omp parallel for reduction(+:result) private(b)


text:
Q: PyUSB backend not accessible hey i am trying to run the simple script available in the tutorial;. the usb is getting imported but when i try to search the device i get the following error,please help
>>> dev=usb.core.find()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\usb\core.py", line 819, in find
    raise ValueError('No backend available')
ValueError: No backend available

A: You need to install libusb-1.0, libusb-0.1, or openusb as a backend to pyusb.  Is this a Windows machine?
If so, you can download a simple installer here: http://www.craftedge.com/products/libusb.html


text:
Q: "java.lang.NoClassDefFoundError: Lfacade/UserDAOLocal;" error in EJB I have the following error on deployment of my EJB app. This may be caused by adding "L" to class path - package name is "facade", then I don't know where this "L" come from. Anybody knows where it can be added?

A: This is from the JVM specification. Take a look here: http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.3.2

The characters of BaseType, the L and ; of ObjectType, and the [ of ArrayType are all ASCII characters.

It defines how fields are stored, for ObjectType it is L<ClassName>;


text:
Q: Trying to remove an element with data-value equal to a previously created variable? When I click on a "trash" button I want to delete the message block. There are multiple message blocks but they all have unique data-values. The id of the targeted block I want to delete is stored in the data-value of .send-message-button.
I tried making a variable that I could pass onto the targeted .messageblock element. I checked with an alert to see if the variable gets the proper number, which it does. However when I alert the whole thing, it gives [object object] (without the .remove, of course).
How can I do this?
var trashid = $(".send-message-button").attr("data-value");
$('.message-block').attr("data-value", trashid).remove();

A: If you want to retrieve an element using the value of one of its attributes you need to use the attribute selector, not the setter of the attr() method.
There's two main ways to do this. Firstly if the data attribute is present in the DOM then you can use an attribute selector:
var trashid = $(".send-message-button").data('value');
$('.message-block[data-value="' + trashid + '"]').remove();

Alternatively if the data attribute is held in jQuery's cache (as will be the case if you use data() as a getter/setter, as you should be) then you can use filter() instead:
var trashid = $(".send-message-button").data('value');
$('.message-block').filter((i, e) => $(e).data('value') === trashid).remove();


text:
Q: How to increase size of font in MessageBox c++ builder *I'm using c++ builder (bcb6)
I would like enlarge font size of message box without creating custom message box.
I searched over google and find that it's possible to use by WM_SETFONT.
I tried doing:
HWND hWnd = CreateWindowEx(0,"WC_DIALOG","Questions!", WS_OVERLAPPEDWINDOW | WS_VISIBLE,400, 100, 100, 100,NULL, NULL, NULL, NULL);
HFONT hFont=CreateFont (30, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, "Arial");
SendMessage (hWnd, WM_SETFONT, WPARAM (hFont), TRUE);
MessageBox(hWnd,message.c_str(),"Info",MB_OK | MB_ICONINFORMATION);

And it dorsn't work..
Any suggestions please?
Your help is very appreciated.

A: There is nothing specific in C++Builder for changing font in a MessageBox. Your options are:

*

*Make a custom dialog

*Use window hooks to change the default MessageBox, via the Windows API.

Both of these are described in more detail with linked examples on this thread.  If you have tried something from that thread and it didn't work then post the code that you tried as a new question.