Q: How to remove the word "Data" at the top of Excel Pivot Table generated by C# with Interop.Excel? I have the following example raw data table:

And hope to make the following Pivot Table using C# and the Microsoft.Office.Interop.Excel library:

I have written the following code to generate both the original table and the pivot table:
            string fileTest = "test.xlsx";

            Excel.Application app;
            Excel.Worksheet sheet;
            Excel.Workbook book;

            app = new Excel.Application();
            book = app.Workbooks.Add();
            sheet = (Excel.Worksheet)book.Worksheets.get_Item(1);

            sheet.Cells[1, 1] = "Name";
            sheet.Cells[1, 2] = "Salary";
            sheet.Cells[1, 3] = "Hours";
            sheet.Cells[1, 4] = "Department";

            sheet.Cells[2, 1] = "Bill";
            sheet.Cells[2, 2] = 140000;
            sheet.Cells[2, 3] = 40;
            sheet.Cells[2, 4] = "IT";

            sheet.Cells[3, 1] = "Ann";
            sheet.Cells[3, 2] = 310000;
            sheet.Cells[3, 3] = 60;
            sheet.Cells[3, 4] = "Payroll";

            sheet.Cells[4, 1] = "Bob";
            sheet.Cells[4, 2] = 200000;
            sheet.Cells[4, 3] = 50;
            sheet.Cells[4, 4] = "IT";

            sheet.Cells[5, 1] = "Sam";
            sheet.Cells[5, 2] = 50000;
            sheet.Cells[5, 3] = 20;
            sheet.Cells[5, 4] = "Payroll";

            Excel.Range range = sheet.Range["A1", "D5"];

            Excel.Worksheet pivotSheet = (Excel.Worksheet)book.Worksheets.Add();

            pivotSheet.Name = "Pivot Table";

            Excel.Range range2 = pivotSheet.Cells[1, 1];

            Excel.PivotCache pivotCache = (Excel.PivotCache)book.PivotCaches().Add(Excel.XlPivotTableSourceType.xlDatabase, range);
            Excel.PivotTable pivotTable = (Excel.PivotTable)pivotSheet.PivotTables().Add(PivotCache: pivotCache, TableDestination: range2, TableName: "Summary");

            Excel.PivotField pivotField = (Excel.PivotField)pivotTable.PivotFields("Salary");
            pivotField.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
            pivotField.Function = Excel.XlConsolidationFunction.xlSum;

            Excel.PivotField pivotField3 = (Excel.PivotField)pivotTable.PivotFields("Hours");
            pivotField3.Orientation = Excel.XlPivotFieldOrientation.xlDataField;
            pivotField3.Function = Excel.XlConsolidationFunction.xlSum;

            Excel.PivotField pivotField2 = (Excel.PivotField)pivotTable.PivotFields("Department");
            pivotField2.Orientation = Excel.XlPivotFieldOrientation.xlRowField;

            Excel.PivotField dataField = pivotTable.DataPivotField;
            dataField.Orientation = Excel.XlPivotFieldOrientation.xlColumnField;

            pivotTable.TableStyle2 = "PivotStyleLight16";

            book.SaveAs(fileTest);
            book.Close();
            app.Quit();

However, my Pivot Table has an extra row in the Pivot Table Header with the word "Data" in it:

Is there a way I can remove this extra header? Thanks for any advice.


Q: Formik component changing an uncontrolled input of type text to be controlled I am using Formik with an array, where the items are being passed from a parent and retrieved like this:
updateState (){
    this.state.choices = this.props.choices
    this.state.questionId = this.props.questionId
  }
  render() {
    this.updateState()
    var choices = this.state.choices
    console.log(choices)
    return ( ...

I am originally initializing the values as empty or 0:
  constructor(props){
    super(props);
    this.state = {
      choices : [],
      questionId: 0
    };
  }

While this seems like it should work, I am getting the error that a component is changing an uncontrolled input of type text to be controlled.  understand this is due to my use of this.state but I'm unsure how to actually fix this.
What I have done so far, since I am using Formik, is change my export to look like this:
  export default withFormik({
  mapPropsToValues: (props) => ({
    choices: [{
    id: '',
    value: '',
    weight: '',
    impact: ''}]
  }),
})(Choices)

It's unclear if I should be mapping props at all, or if I should be using something more like:
export default withFormik({
  mapPropsToValues: (props) => ({

    id: '',
    value: '',
    weight: '',
    impact: ''
  }),
})(Choices)

All I know is that I am unable to click to push a new object onto the array that I am working with, so the functionality is basically frozen until I can figure out the state of the un/controlled input element.
Any idea where I am going wrong?

A: Fixing the HTML and the {choices[index].id} bits cleared this error.
E.g.:

                        {choices[index].id}
                        <Field name={choices[index].id} placeholder={choices[index].value} type="text"/>
                        <ErrorMessage name={choices[index].id} component="div" className="field-error" />


Q: can't see properties of viewcontoller I want to change the value of a label in my default view controller from a different class.

*

*So I start a simple 'Single View Application' iOS project (Xcode5)

*This automatically generates a ViewController for me (which I
understand is the root view controller)

*I now add a label in my View and connect it to the ViewController (via IBOutlet mechanism)

*I call this outlet 'gameStateLabel', so it looks like this in the ViewController.h file
@property (weak, nonatomic) IBOutlet UILabel *gameStateLabel;

Next, I have a completely separate class which has the logic for my code, and based on a condition in the logic I want to change the UIlabel.
So I try to do this from my other class:

*

*Get an instance of the root view controller like this:
UIViewController * uvc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];

I think I now have an instance of the rootviewcontroller in uvc and should be able to reach in and change gameStateLabel.
BUT: I CANNOT do this uvc.gameStateLabel simply does not show up as a property even though it is clearly declared as a property and I've added the @synthesize for it also.
Any help will be greatly appreciated - I've been going nuts over this.
(For ref. I'm used to doing something similar on the Mac side where I'd declare a label as a property of the AppDelegate, get the instance of the Appdelegate and simply refer to the label property and change its text]
Here's the ViewController. Note that gameStateLable is a property
#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *gameStateLabel;

@end

@implementation ViewController
@synthesize gameStateLabel;
- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

And here is my class cls1 (which inherits from NSObject)
#import "cls1.h"
#import "ViewController.h"

@implementation cls1

-(void) dummy{

UIViewController * uvc = [[[[UIApplication sharedApplication] delegate] window] rootViewController];

// uvc does NOT show gameStateLabel in intellisense, i.e. uvc.gameStateLabel does NOT work

}

A: Add #import "mainRootVC.h" in you CustomClass.m file
And create object of mainRootVC such like,
mainRootVC *obj = [[mainRootVC alloc] init];
// Now you can access your label by
obj.gameStateLabel...

A: Do like this...
YourViewController *rootController =[(YourViewController*)[(YourAppDelegate*)
        [[UIApplication sharedApplication]delegate] window] rootViewController];

A: Try the following too:
ViewController *controller = (ViewController*)self.window.rootViewController;

It will return the initial view controller of the main storyboard.

A: For sending information from a viewController to other viewController you have:

*

*Delegates:Definiton and examples

*NSNotificationCenter:  Apple Documentation
NSString *label = @"label text";
[[NSNotificationCenter defaultCenter] postNotificationName:NAVIGATETO object:label userInfo:nil];
You can found tons of examples about those two. I recommend you use one of those.
Hope this helps a bit.

A: OK. I found two issues.

*

*I had copied the code over from my Mac project and modified it. Something seems to have gone wrong.

I retyped the entire function and it solved most of the problem

*

*uvc should be of the type ViewController* - not UIViewController* as I was doing

Thanks everyone for your replies - much appreciated.


Q: C# Newbie: Change Entity Framework DataBound DataGrid created with WPF drag-and-drop I'm new to C# and I created a WPF GUI using Visual Studio 2010 Ultimate (Windows 7 x64).
I used drag-and-drop technology to databind a datagrid to an SQL Server 2008 database table using Entity Framework technology.
This all works very well, despite my lack of C# skills.
I was able to hide columns using statements like:
dataGridInputEmails.Columns[0].Visibility = Visibility.Hidden;

And I cleared the datagrid using:
dataGridInputEmails.Columns.Clear();

Now I want to populate the datagrid with a string that I created by reading in a text file and using:
string[] parts = slurp.Split(delimiters,StringSplitOptions.RemoveEmptyEntries);

But, I cannot figure out how to populate the datagrid.
TIA

A: Try this:
dataGridInputEmails.ItemsSource = parts;

You shouldn't have to do dataGridInputEmails.Columns.Clear(); first.


Q: Pandas maximum difference of values with day-to-day intervals Continuation of previous previous question
df

                    Timestamp  Spot DK1  Spot DK2  Ubalance DK1  Ubalance DK2
0   2020-01-01T00:00:00+01:00     33.42     33.42         34.00         34.00
1   2020-01-01T01:00:00+01:00     31.77     31.77         34.00         34.00
2   2020-01-01T02:00:00+01:00     31.57     31.57         34.00         34.00
3   2020-01-01T03:00:00+01:00     31.28     31.28         34.00         34.00
4   2020-01-01T04:00:00+01:00     30.85     30.85         26.00         26.00
5   2020-01-01T05:00:00+01:00     30.14     30.14         25.00         25.00
6   2020-01-01T06:00:00+01:00     30.17     30.17         24.00         24.00
7   2020-01-01T07:00:00+01:00     30.00     30.00         24.00         24.00
8   2020-01-01T08:00:00+01:00     30.63     30.63         24.00         24.00
9   2020-01-01T09:00:00+01:00     30.59     30.59         25.00         25.00
10  2020-01-01T10:00:00+01:00     30.27     30.27         25.00         25.00
11  2020-01-01T11:00:00+01:00     30.34     30.34         25.00         25.00
12  2020-01-01T12:00:00+01:00     30.59     30.59         30.59         30.59
13  2020-01-01T13:00:00+01:00     30.04     30.04         30.04         30.04
14  2020-01-01T14:00:00+01:00     30.60     30.60         30.60         30.60
15  2020-01-01T15:00:00+01:00     31.09     31.09         31.09         31.09
16  2020-01-01T16:00:00+01:00     31.53     31.53         31.53         31.53
17  2020-01-01T17:00:00+01:00     31.78     31.78         33.50         33.50
18  2020-01-01T18:00:00+01:00     31.64     31.64         33.50         33.50
19  2020-01-01T19:00:00+01:00     31.44     31.44         31.44         31.44
20  2020-01-01T20:00:00+01:00     31.35     31.35         31.35         31.35
21  2020-01-01T21:00:00+01:00     31.07     31.07         31.07         31.07
22  2020-01-01T22:00:00+01:00     30.96     30.96         25.00         25.00
23  2020-01-01T23:00:00+01:00     30.61     30.61         21.00         21.00
24  2020-01-02T00:00:00+01:00     30.78     30.78         20.00         20.00
25  2020-01-02T01:00:00+01:00     30.64     30.64         20.00         20.00
26  2020-01-02T02:00:00+01:00     30.43     30.43         20.00         20.00
27  2020-01-02T03:00:00+01:00     28.79     28.79         23.00         23.00
28  2020-01-02T04:00:00+01:00     28.42     28.42         22.73         22.73
29  2020-01-02T05:00:00+01:00     28.75     28.75         23.00         23.00
30  2020-01-02T06:00:00+01:00     33.38     34.16         22.50         22.50
31  2020-01-02T07:00:00+01:00     31.79     42.07         22.28         22.28
32  2020-01-02T08:00:00+01:00     31.83     44.89         22.50         22.50
33  2020-01-02T09:00:00+01:00     31.74     45.26         23.00         23.00
34  2020-01-02T10:00:00+01:00     31.63     45.57         24.00         24.00
35  2020-01-02T11:00:00+01:00     31.32     45.09         25.00         25.00
36  2020-01-02T12:00:00+01:00     31.07     45.16         25.00         25.00
37  2020-01-02T13:00:00+01:00     31.06     44.90         25.00         25.00
38  2020-01-02T14:00:00+01:00     31.07     44.06         26.00         26.00
39  2020-01-02T15:00:00+01:00     31.26     44.84         26.00         26.00
40  2020-01-02T16:00:00+01:00     31.41     44.40         27.50         27.50
41  2020-01-02T17:00:00+01:00     31.40     46.05         26.00         46.05
42  2020-01-02T18:00:00+01:00     31.10     46.72         26.00         26.00
43  2020-01-02T19:00:00+01:00     30.75     45.26         25.32         25.32
44  2020-01-02T20:00:00+01:00     30.47     39.32         20.25         20.25
45  2020-01-02T21:00:00+01:00     30.10     30.10         16.50         16.50
46  2020-01-02T22:00:00+01:00     29.71     29.71         16.50         16.50
47  2020-01-02T23:00:00+01:00     24.99     24.99         15.00         15.00
48  2020-01-03T00:00:00+01:00     18.93     18.93         15.00         15.00
49  2020-01-03T01:00:00+01:00      9.98      9.98          9.98          9.98

I want to generate a separate series of values in which the maximum difference of each day's values are in. Preferably able to choose of which columns to include.
Therefore, the first value in the series should be 12.5, since the largest and lowest values of the first day are 33.5 and 21.00, respectively.
Expected outcome:
       Day          Max diff
0   2020-01-01       12.50
1   2020-01-02       31.72

So far, I've tried this - but this gives me a rolling, 24-hour interval, crossing days, which is what I try to avoid:
cols = ['Spot DK1','Spot DK2','Ubalance DK1','Ubalance DK2']
N = 24

battery['dif'] = (battery[cols].stack(dropna=False)
                     .rolling(len(cols) * N)
                     .agg(lambda x: x.max() - x.min())
                     .groupby(level=0)
                     .max())

A: Idea is aggregate minimal and maximal values per days, so possible get max and min by max and min levels in df1 and last subtract to new df2:
df['Timestamp'] = pd.to_datetime(df['Timestamp'])

cols = ['Spot DK1','Spot DK2','Ubalance DK1','Ubalance DK2']

df1 = (df.set_index('Timestamp')[cols]
         .groupby(pd.Grouper(freq='D', level='Timestamp'))
         .agg(['min','max']))

s1 = df1.xs('max', level=1, axis=1).max(axis=1)
s2 = df1.xs('min', level=1, axis=1).min(axis=1)

df2 = s1.sub(s2).rename_axis('Day').reset_index(name='Max diff')
print (df2)
                        Day  Max diff
0 2020-01-01 00:00:00+01:00     13.00
1 2020-01-02 00:00:00+01:00     31.72
2 2020-01-03 00:00:00+01:00      8.95

Details:
print (df1)
                          Spot DK1        Spot DK2        Ubalance DK1        \
                               min    max      min    max          min   max
Timestamp
2020-01-01 00:00:00+01:00    30.00  33.42    30.00  33.42        21.00  34.0
2020-01-02 00:00:00+01:00    24.99  33.38    24.99  46.72        15.00  27.5
2020-01-03 00:00:00+01:00     9.98  18.93     9.98  18.93         9.98  15.0

                          Ubalance DK2
                                   min    max
Timestamp
2020-01-01 00:00:00+01:00        21.00  34.00
2020-01-02 00:00:00+01:00        15.00  46.05
2020-01-03 00:00:00+01:00         9.98  15.00


Q: Generic JQuery Function? I'm using Jeditable to edit dozens of fields such as first_name, last_name, birthday, etc.
My problem is that I'm drowning in detail: I keep having to create a new selector such as $('#edit_first_name').editable or $('#edit_birthday').editable to making the field editable as well as create a bunch of SQL commands specific to each field to insert them once they're edited.
My question is: Is there a way I can create something generic or OO in JQuery so that I don't don't have to endlessly create code that essentially does the same thing?
My guess is I can create some "generic" function that will create $('#edit_someField').editable on the fly by feeding some JSON array, which was created by doing a SELECT on all field names I'm interested in. I imagine that's exactly what JQuery plugins do.
Any direction on how I can accomplish this would be much appreciated.
EDIT
One solution I have come up with is to put the table, column name and id in the id value of whatever I want to edit.
For example, if I want to edit the first_name of id=6 on table Person, then in the id I will put myFirstName. When I send the id to my save.php file, I use a preg_split to insert my data into the table.

A: Mark all your editable input fields with the class "editable". (Change to suit.)
$('.editable').each(function() {
  $(this).editable('mysaveurl.php');
});

That's all you need for the basic functionality. Obvious improvements can be made, depending on what else you need. For example, if you are using tooltips, stick them in the title attribute in your HTML, and use them when you call editable().
Your actual PHP/Ruby/whatever code on the server is just going to look at the id parameter coming in, and use that to save to the appropriate field in the database.

A: Just use a class to make them all editable, and using their id (or a attribute that you have attached to the tag) you can specify the field you are updating.
Then just pass the field and the value to your DB.
i don't know the plugin you are using
but, assuming it has some sort of event handling in it...
something like this maybe?
$(".editable").editable({
      complete : function() {
            var _what = $(this).attr("id");
            var _with = $(this).val();
            $.post("yourPostPage.php",{what:_what, where:_where});
       }
});

Without knowing more about your environment I wouldn't be able to help further.

A: The jQuery way of assigning some common code to a bunch of objects is to either give all the objects the same class so you can just do this:
$(".myEditableFields").editable("enable");

This will call the editable add-on method for all objects in your page with class="myEditableFields".
If you just have a list of IDs, you can just put them all in the single selector like this and they will each get called for the editable jQuery method:
$("#edit_first_name, #edit_birthday, #edit_last_name, #edit_address").editable("enable");

Sometimes, the easy way it to create a select that just identifies all editable fields within a parent div:
$("#editForm input").editable("enable");

This would automatically get all input tags inside the container div with id=editForm.
You can of course, collect common code into your own function in a traditional procedural programming pattern and just call that when needed like this:
function initEditables(sel) {
    $(sel).editable("enable");
    // any other initialization code you want here or event handlers you want to assign
}

And, then just call it like this as needed:
initEditables("#edit_first_name");

To help further, we would need to know more about what you're trying to do in your code and what your HTML looks like.


Q: No funciona el if Cuando estoy por ejecutar el código, en la parte del if pregunto que si la Var1 es mayor o igual que 402.336; el caso es que cuando el resultado es mayor, por ejemplo:
Que en el programa puse un 5 cuando pedí la velocidad, la variable Var1 obtendrá el valor 579.36384; el problema en todo esto es que cuando se imprime el resultado de el método LoLogro me imprime "No logro romper su récord". En pocas palabras no logra dar la respuesta correcta cuando debe darlo, aún no sé cómo corregir el problema y llevo mucho rato probando sin éxito.
class Programa4
{
    static void Main()
    {
        double Tiempo;
        string respuesta;

        Console.Write("Escribe cuanto tiempo tardo en segundos: ");
        respuesta = Console.ReadLine();
        Tiempo = double.Parse(respuesta);

        Arrancon A1 = new Arrancon();

        Console.WriteLine("____________________________________________________________");
        Console.WriteLine(A1.Lologro());
        Console.WriteLine("Su velocidad fue de: "+A1.Velocidad(Tiempo));
    }
}

public class Arrancon
{
    double Var1;
    public double Velocidad(double Tiempo)
    {
        Var1 = ((402.336 * 2)/1000)/(Tiempo/3600);
        return Var1;
    }
    public string Lologro()
    {
        string respuesta;
        if (Var1 >= 402.336)
        {
            respuesta = "Si logro romper su record";
        }
        else
        {
            respuesta = "No logro romper su record";
        }
        return respuesta;
    }
}```

A: Simplemete llame al método Velocidad antes del Lologro:
class Programa4
{
    static void Main()
    {
        double Tiempo;
string respuesta;

Console.Write("Escribe cuanto tiempo tardo en segundos: ");
respuesta = Console.ReadLine();
Tiempo = double.Parse(respuesta);

Arrancon A1 = new Arrancon();

Console.WriteLine("____________________________________________________________");
var time=A1.Velocidad(Tiempo);
Console.WriteLine(A1.Lologro());
Console.WriteLine("Su velocidad fue de: " +time);
Console.ReadKey();
    }
}

public class Arrancon
{
    double Var1;
    public double Velocidad(double Tiempo)
    {
        Var1 = ((402.336 * 2)/1000)/(Tiempo/3600);
        return Var1;
    }
    public string Lologro()
    {
        string respuesta;
        if (Var1 >= 402.336)
        {
            respuesta = "Si logro romper su record";
        }
        else
        {
            respuesta = "No logro romper su record";
        }
        return respuesta;
    }
}

Esto porque la velocidad debe calcularse antes de llamar el método Lologro sino nunca va a dar el resultado correcto

A: El pasar variables a un constructor se hace justamente para evitar este tipo de problemas. Tu clase Arranco no tiene sentido si Var1 no está seteada, por eso debe ir en el constructor.
class Programa4
{
    static void Main()
    {
        decimal Tiempo;
        string respuesta;

        Console.Write("Escribe cuanto tiempo tardo en segundos: ");
        respuesta = Console.ReadLine();
        Tiempo = Convert.ToDecimal(respuesta);
        Arrancon A1 = new Arrancon(Tiempo );

        Console.WriteLine("____________________________________________________________");
        Console.WriteLine(A1.Lologro());
        Console.WriteLine("Su velocidad fue de: "+A1.Velocidad);
    }
}

public class Arrancon
{

    public decimal Velocidad {get;set;}
    public Arrancon(decimal tiempo){
       Velocidad = ((402.336m * 2)/1000)/(tiempo/3600);
    }
    public string Lologro()
    {
        if (Velocidad >= 402.336m)
        {
            return "Si logro romper su record";
        }
        return "No logro romper su record";
    }
}

A: tu error esta en que nunca usas la variable var1, por lo tanto nunca se validara tu condicion, la forma de solucionarlo seria mandando el dato por tu constructor:
Arrancon(double dat){
 var1=dat;
}

A: Únicamente debes de llamar primero la velocidad y luego llamar el método de logro, hice una variable para el tiempo y una de la respuesta consumiendo los métodos segun el orden y finalemente agregue un ReadKey para deteter el programa ya que se cerraba de una, hice lo siguiente:
Arrancon A1 = new Arrancon();
double Tiempo2 = A1.Velocidad(Tiempo);
string Respuesta = A1.Lologro();

Console.WriteLine("____________________________________________________");
Console.WriteLine(Respuesta);
Console.WriteLine("Su velocidad fue de: " + Tiempo2);
Console.ReadKey();


Q: jQuery - Exclude an li from this function? I have a ul list of 8 li's on the last li it has the id #search - I don't want the dropdown applid to this, how can I exclude it? here's my code..
$(document).ready(function () {
  $('#navigation li').hover(function () {
    // Show the sub menu
    $('ul', this).stop(true,true).slideDown(300);
  },
  function () {
  //hide its submenu
   $('ul', this).stop(true,true).slideUp(200);
  });
});

Thanks

A: Use jQuery's .not()
$('#navigation li').not("#search").hover(function () {
   // Show the sub menu
   $('ul', this).stop(true,true).slideDown(300);
},
function () {
  //hide its submenu
  $('ul', this).stop(true,true).slideUp(200);
});


Q: Shift a column in R Suppose that I have a dataframe like the following:
library(tidyverse)

df <- tibble(x = c(1,2,3), y = c(4,5,6))

# A tibble: 3 x 2
      x     y
  <dbl> <dbl>
1     1     4
2     2     5
3     3     6

And I would like to shift a column, adding a column like:
# A tibble: 3 x 3
      x     y shifted_x
  <dbl> <dbl>     <dbl>
1     1     4        NA
2     2     5         1
3     3     6         2

Basically, I want to work with timeseries, so I would like to get previous values and use them as feature. In python I know I can do:
for i in range(1,11):
    df[f'feature_{i}']=df['sepal_length'].shift(i)

Where df is a pandas Dataframe.
Any equivalent code for doing this in R?

A: An equivalent in R tidyverse is dplyr::lag.  Create the column in mutate and update the object by assigning (<-) back to the same object 'df'
library(dplyr)
df <- df %>%
    mutate(shifted_x = lag(x))

or if we need to use the shift, there is shift in data.table
library(data.table)
setDT(df)[, shifted_x := shift(x)]

Also, if we need to create more than one column, shift can take a vector of values in n
setDT(df)[, paste0('shifted', 1:3) := shift(x, n = 1:3)]

A: We can also use the flag function from the collapse package.
library(collapse)

df %>%
  ftransform(shifted_x = flag(x))
# # A tibble: 3 x 3
#       x     y shifted_x
# * <dbl> <dbl>     <dbl>
# 1     1     4        NA
# 2     2     5         1
# 3     3     6         2


Q: BCP error "Unable to open BCP host data-file" I've just create a new table in my sqlserver name exporttable
 now I'm trying to push out using cmd bcp but om getting this following error:

SQLState = S1000, NativeError = 0 Error = [Microsoft][ODBC Driver 13
  for SQL Server]Unable to open BCP host data-file

Here is my path:
C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop" -C -T

anyone can help ?
After trying Shnugos suggestion to add a filename I got this error:

SQLState = S0002, NativeError = 208 Error = [Microsoft][ODBC Driver 13
  for SQL Server][SQL Server]Invalid object name
  'Testing.bdo.ExportTable'. SQLState = 37000, NativeError = 11529 Error
  = [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]The metadata could not be determined because every code path results in an error;
  see previous errors for some of these. –

A: From the error I take, that the data file cannot be opened:
C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop\MyFile.txt" -C -T

I think, you have to add a filename behind the \Desktop. Desktop is an existing directory and cannot be opened as file ...
And - btw - it might be necessary to add -S Servername...
UPDATE
Found this here

Whenever I get this message, it's because of one of three things:
1) The path/filename is incorrect (check your typing / spelling)
2) The file does not exist. (make sure the file is where you expect it
  to be)
3) The file is already open by some other app. (close the other app to
  release the file)
For 1) and 2) - remember that paths are relative to where bcp is
  executing. Make sure that bcp.exe can access the file/path from it's
  context.
/Kenneth

A: If you are running BCP through xp_cmdshell, run the following-->
xp_cmdshell 'whoami';
GO
--Make sure whatever user value you get back has full access to the file in question

A: Run: EXEC master..xp_cmdshell 'DIR C:\Users\Serge\Desktop', this will show if you have access to the path.
Remember if you are accessing SQL remotely or over a network, the output ie. "C:\Users\Serge\Desktop" will be the C drive on the SQL Server, not your remote PC you are working on.

A: I know this is old, but you also appear to have the schema spelled wrong.
C:\Users\Serge>BCP Testing.bdo.Exporttable out "C:\Users\Serge\Desktop" -C -T
s/b
C:\Users\Serge>BCP Testing.dbo.Exporttable out "C:\Users\Serge\Desktop" -C -T


Q: Logtalk : Load a file with camelcase naming on Windows With logtalk 3.1.2, under OS X and Linux, no problem to load a file with a camelcase name, but an exception is thrown on Windows (ERROR : file does not exist).
logtalk_load(mypath(myFileNameInCameCase))

What's wrong ?

A: Some backend Prolog compilers, such as SWI-Prolog when running on Windows, down-case file names when expanding file paths into absolute file paths. This caused a failure in the Logtalk compiler when going from the file argument in the compilation and loading predicates to an absolute file path and its components (directory, name, and extension). A workaround have been found and committed to the current git version. Thanks for the bug report.


Q: Appending javascript value to gridview hyperlink. Any ideas why my code doesn't work? We have a javascript that takes start date and end date, calculates the difference between them and stores the value in a variable called hourDiff.
Here is relevant part of the js.
To avoid a scope issue, a gobal variable called hourDiff is defined at top of the javascript outside any function"
var hourDiff = 0;

//Calulate the time difference and store the value in hourDiff
hourDiff = endDate - startDate;

The idea is to eventually appendd hourDiff to the gridview hyperlink control below and pass the name-value pairs as querystring to another page called Reseve.aspx
<asp:HyperLink ID="siteId" class="js_siteid" style="color:#111" runat="server" navigateurl='<%# String.Format("Reserve.aspx?id={0}&groupsize={1}&facilityFees={2}&extrahour={3}&depoitAmt={4}&cancelAmt={5}&keydeptAmt={6}", Eval("siteId"), Eval("capacity"),Eval("RentalFeeAmount"),Eval("ExtraHourAmount"),Eval("DepositAmount"),Eval("CancellationAmount"),Eval("KeyDepositAmount")) %>' Text='Select' />

Since the hyperlink is not exposed to the javascript until after search button is clicked, I have another javascript below that is used to apend hourdiff to the hyperlink and passed to another page.
This javascript is placed at the bottom of the html page:

Each time I compile my code and clic the Select link, hourDiff always displays the value of 0 rather than the difference between start date and end date.
Any ideas what I am doing wrong?
Protected Sub ValidateDuration(ByVal sender As Object, ByVal args As ServerValidateEventArgs)
  Dim validator As Control = DirectCast(sender, Control)
  Dim row As Control = validator.NamingContainer

  Dim startHour As Integer = Integer.Parse(DirectCast(row.FindControl("startHour"), DropDownList).SelectedValue)
  Dim startMinutes As Integer = Integer.Parse(DirectCast(row.FindControl("startMinutes"), DropDownList).SelectedValue)
  Dim startAmPm As String = DirectCast(row.FindControl("startAmPm"), DropDownList).SelectedValue

  Select Case startAmPm
    Case "AM"
        If startHour = 12 Then
            startHour = 0
        End If

    Case "PM"
        If startHour <> 12 Then
            startHour += 12
        End If

    Case Else
        args.IsValid = True
        Return
  End Select

  Dim endHour As Integer = Integer.Parse(DirectCast(row.FindControl("endHour"), DropDownList).SelectedValue)
  Dim endMinutes As Integer = Integer.Parse(DirectCast(row.FindControl("endMinutes"), DropDownList).SelectedValue)
  Dim endAmPm As String = DirectCast(row.FindControl("endAmPm"), DropDownList).SelectedValue

  Select Case endAmPm
    Case "AM"
        If endHour = 12 Then
            endHour = 0
        End If

    Case "PM"
        If endHour <> 12 Then
            endHour += 12
        End If

    Case Else
        args.IsValid = True
        Return
  End Select

  Dim hoursDiff As Integer = endHour - startHour
  If endMinutes < startMinutes Then
    hoursDiff -= 1
  End If

  args.IsValid = hoursDiff >= 2

End Sub

A: Update 2015-02-27 ~13:40 EDT: Appending hiddenfield to hyperlink serverside
I'm using GridView1 as I do not know the name of your gridview.
In the GridView1 RowDatabound Event (note the addition of "&hourDiff={7}" to the end of the format string and the addiition of the hiddenfield value in the parameter list):
Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
  If e.Row.RowType = DataControlRowType.DataRow Then
    dim hl as HyperLink = if(e.Row.FindControl("siteId"), Nothing)
    If hl IsNot Nothing then
      hl.NavigateURL = String.Format("Reserve.aspx?id={0}&groupsize={1}" & _
          "&facilityFees={2}&extrahour={3}&depoitAmt={4}&cancelAmt={5}" & _
          "&keydeptAmt={6}&hourDiff={7}",
          DataBinder.Eval("siteId"),
          DataBinder.Eval("capacity"),
          DataBinder.Eval("RentalFeeAmount"),
          DataBinder.Eval("ExtraHourAmount"),
          DataBinder.Eval("DepositAmount"),
          DataBinder.Eval("CancellationAmount"),
          DataBinder.Eval("KeyDepositAmount"),
          hf1.Value )
    End If
  End If
End Sub

Problem 1: Each time I compile my code and click the Select link
the Select link in a Gridview is going to cause a postback and therefore hourDiff is going to be 0 everytime since a postback is going to force all js to be re-evaluated
Problem 2:
Be aware that every control that causes a postback is going to reset your page javascript.  One way to get around that is to save to and restore from hidden field controls (<asp:HiddenField ID="hf1" runat="server" ClientIDMode="Static"...>). then you can access like this: $('#hf1').val(3.14); and the value is preserved between postbacks.
Cookies or local storage are other options
Also, is there any reason that the calculation must occur clientside?  because you have another problem once you redirect to a new page.  Be aware that redirecting, even to the same page, is not a postback.
Update 2015-02-26 14:30 EDT
I cannot see your search code so I'm going to make an assumption that no matter how the user picks a start/end date/time there is a Search button that causes a postback with four fields (assuming asp:TextBox's) of Search data, I'll call them: StartDate, StartTime, EndDate, EndTime.
The Search Button is going to cause a postback which should make the search fields available for use in the code behind.
Build 2 DateTime variables (S, E) and use the DataDiff() function to determine the difference you need.
In your case it would be something like this:
' At class level define the variable:
Dim hourDiff as DateTime = nothing

' In the gridview databinding event do your calculation
Private Sub GridView1_DataBinding(sender As Object, e As System.EventArgs) Handles GridView1.DataBinding
  Dim S as New DateTime( <replace with relevant parameters> )
  Dim E as New DateTime( <replace with relevant parameters> )

  hourDiff = DataDiff(DateInterval.Hour, S, E)
End Sub

' Then in the row databound event append the difference to the hyperlink
Private Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
  If e.Row.RowType = DataControlRowType.DataRow Then
    dim hl as HyperLink = if(e.Row.FindControl("siteId"), Nothing)
    If hl IsNot Nothing then
      hl.NavigateURL = <build your Hyperlink and Append hourDiff>
    End If
  End If
End Sub

Amended 2015-02-26 18:06EDT

i would have preferred the option of using hiddenField if you could
  explain how to tie hf1 to hourdiff.

Add a hidden field to your page like this:
<asp:HiddenField ID="hf1" runat="server" ClientIDMode="Static">

to js add this:
// define hourDiff
var hourDiff;

// Using jquery place an object reference to the hidden field into hourDiff
hourDiff = $("#hf1");

// Do your time calculations and assign results to hourDiff
hourDiff.val( time_calc_results );

// The above places the results in the hidden field Value property
// which will be available in the code behind as as `hf1.Value` after postback

I am spending more time trying to fix errors on the code you just posted.

Well that's to be expected as it's mostly from memory and is partially pseudo code.

With regards to your latest code, does that mean that I try the javascript
  I posted at the top or use both?

The intent was that the search criteria could be selected Clientside or Serverside, the choice is yours.  But you have to be careful of problem 1. you need a way to preserve the calculation between posts.  Hence my suggestion for the Hidden Field.
Worst case Scenario: 5+ postbacks
In the worst case scenario you post back every time a user selects a time and date so at minimum you have 5 postbacks, one for each start and end date and time and then clicking search.  Posting back like this makes it pointless to do the calculations client side.  I hope you understand why.  Ideally, in this situation the user has made all the selections prior to selecting Search and then you calculation once server side.
Scenarios 2: 1 Postback
In this scenario you have js or jQ code picker that allow the user to select times and dates WITHOUT posting back to the server.  This is a great way to collect data.

*

*If Clientside, you need to make sure the calculation is complete and stored in the Hidden Field before you post back

*If Serverside you need to grab the four field and do the calculation in the Search button click event or in the Gridview DataBinding event.

In either case you need to modify the Hyperlink href.  This could be done client side...maybe.  It depends, if you cause a postback before getting a chance to update the href of the select link.
To me it looks like you added your own hyperlink to each row.  If that is so then you should be able to modify all the hyperlinks with a bit jquery code after you calc hourDiff
// Assuming hourDiff is defined as
var hourDiff = $('#hf1');

... (other stuff)

// and you calc and assign to hourDiff as this:
hourDiff.val( endDate - startDate);

... (maybe more other stuff)

// then you modify your hyperlinks like this
$( "#GridView1 a.js_siteid" ).each( function( i, e ) {
    this.href += "&diff=" + hourDiff.val();
} );

Also, I don't understand:
  Dim E as New DateTime( <replace with relevant parameters> )

It's the VB equivalent of what you are doing in the js code with the Date objects.  There are over a dozen ways to instantiate one so I just left it up to you to pick one that works for you.


Q: Showing that two Matrices are not similar over GL$_n(\mathbb{F}_2)$
Problem: Show that $$ \begin{pmatrix} 0 & 1 \\ 1 & 0  \end{pmatrix}, \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} $$
  Are not similar over GL$_n ( \mathbb{F}_2)$

Note: We write $ \mathbb{F}_2= \text{GF}(2)$ the Galois Field, just in case people use a different notation.
I assume that this problem is ridiculously easy, but I couldn't find a satisfying way to show the statement as above. I have read a couple of similar problems on this website and found this great comment by @J.M.  on How do I tell if matrices are similar?

"The simplest test you can make is to see whether their characteristic polynomials are the same. This is necessary, but not sufficient for similarity (it is related to having the same eigenvalues)."

So I did this for the above and got two characteristic polynomials that differ in their sign, hence they would not be similar. My problem now is, that with this approach I did not even make use of the statement that my invertible Matrix, lets call it $P$ has to be in $\mathbb{F}_2$.
So my most naive approach was to define a general Matrix $P$ as follows: $$P
:= \begin{pmatrix} a & b \\ c & d \end{pmatrix} $$ and use $A=P^{-1}BP \implies PA=BP$ where $A$ is the first Matrix on the left as stated in the problem and $B$ the latter. My next naive step was to perform the calculations $$PA=BP \iff \begin{pmatrix} b & a \\ d & c \end{pmatrix} = \begin{pmatrix} a & b \\ -c & -d \end{pmatrix}  $$ Well and my last thought was that two matrices are equal if and only if their entries are equal. This gave me $b=a, d=-c$ and these entries have to be in $\mathbb{F}_2$, so I don't see how this could be a contradiction.
I would have said that now $$P = \begin{pmatrix} a & a \\ -d & d  \end{pmatrix} $$
and next looked at the special case that all the entries are $1$, which would work considering the Mathematica output for P.A == H.P

A: The fact we're in $\Bbb F_2$ is very relevant. The problem with the characteristic polynomial approach is that $+1=-1$ are the same element of $\Bbb F_2$. Now consider the invertibility of your $P$ in $\Bbb F_2$....

A: You already did it. Because you are in $GF(2)$, $-x=x$ for any element. So your $P$ looks like
$$
\begin{bmatrix}a&a\\ d&d\end{bmatrix}
$$
and now you can use a variety of methods to show that such $P$ is not invertible.


Q: Custom legend text on ASP.NET Chart bound by DataBindCrossTable I'm binding an ASP.NET Chart control with DatabindCrossTable and everything works well, except the legend text that is applied.
My table looks like this:
Year     Week     Value
2015     1        530
2015     2        680
...
2016     1        887
2016     2        991
...
2017     1        990
2017     2        1021
...

I'm binding my Chart control this way:
chrtValuesByWeekByYear.DataBindCrossTable(myTable.Rows, "Year", "Week", "Value", "")

My problem is that the legend text is displaying "Year - YYYY", like the image below. How can I just display "YYYY" in the legend?

A: There's plenty of opportunity to configure your Legend and Series, but when you call DataBindCrossTable, you're delegating everything to this method. The only thing you're left with is to overwrite whatever you want after the fact.
So, right after you call DataBindCrossTable, you can for instance, simply do:
foreach (Series s in chrtValuesByWeekByYear.Series)
    s.Name = s.Name.Remove(0, 7);


Q: A function like: ng-click="alert('Clicked')" For a mockup I need a simple mechanism like
ng-click="alert('Clicked')"

but the code above is not working, can someone help me? I don't want to touch the Controller..

A: Refer to previous answer, ng-click = "alert('Hello World!')" will work only if $scope points to window.alert i.e
$scope.alert = window.alert;

But even it creates eval problem so correct syntax must be:
HTML

Click me

Controller
$scope.alert = function(arg){
    alert(arg);
}

A: As far as I know, ng-click works only within your $scope. So you would only be able to call functions, defined in your $scope itself. To use alert, you may try accessing the window element, just by using window.alert('Clicked').
EIDT: Thanks to Ibrahim. I forgot. You shouldn't be able to use window.alert, as far as you won't define:
$scope.alert = window.alert;

In this case, using alert('Clicked') in your ng-clicked directive should work. But at the end, this method would not solve your problem of not touching your controller.

A: You can use
onclick="alert('Clicked')"

for debugging purposes

A: As Neeraj mentioned, the accepted answer does not work. Add something like this to your controller to avoid an Illegal Invocation error:
$scope.alert = alert.bind(window);


Q: Powerbuilder 12 classic version Scc option Unavailable I can't perform any of the source control options in powerbuilder classic version 12. They are just greyed out. at startup i get standard message Connection to source control established. objects under pbl shows sign of out of syc. but i can't use option Get Latest Version as its greyed out. we are using Microsoft Team Foundation Server fo Souce control. operating system is Windows 7 32 bit.

A: Verify that you have this registry key:
HKLM\SOFTWARE\SourceCodeControlProvider\InstalledSCCProviders
I've seen some source control tools either not use it, or remove it, and PowerBuilder looks there for the SCC vendors.  If there are none there, then PB won't show the SCC options as available.

A: Another thing to check - Make sure the workspace file (*.pbw) is not read-only.  Right click on the file and verify that the *.pbw file does not have the Read-Only attribute checkbox selected.


Q: Windows Clipboard, Store Image Using MS Forms Data Object - VBA I want to put an image on the Windows clipboard using VBA. I currently do this for text essentially as described here using the DataObject in the MS Forms 2.0 Library.
I want to do the same thing using an image file, putting the image on the clipboard instead of text.
My working code used for text is below, I have tried using the image file path as the variable but just stores the text. Also tried "SetImage" as a method but throws error as below.
Dim DataObj As MSForms.DataObject
Set DataObj = New MSForms.DataObject

DataObj.SetText str1   <--------------- works for string variable
DataObj.SetImage strImageFilePath <----------- Error Method not available

DataObj.PutInClipboard


Q: If matter was compressed at big bang was time more and more compressed too in the past for us now (opposite expansion for time going in the past)? If everything was smaller or compress in the past, did this compress time?
In the foundation of Big bang theory, all is expanding now, galaxies expand space between. Then they must had been closer or compress in the past. This compress space and time.
Did time run slower and slower in the past? (More and more compress)
Observer in each reference frame will only see futur expansion of space time since they follow time. Time relative to our frame would be compress compare to us, as space. Each frame being smaller than the previous. All frame having still one unit, unless compare externally.


Q: AWS Connect - Getting permission error on Wisdom:getContent I am implementing Connect Wisdom in my CCP UI. I am able to search for content and suggestions appear for documents I had previously uploaded but when i click on a suggestion it fails to load and upon checking the api call I see the error:
{"errorCode":"AccessDeniedException","message":"User: arn:aws:sts::xxxxxxxxx:assumed-role/AWSServiceRoleForAmazonConnect_Of0Wxxxxxxba/_<connect-username> is not authorized to perform: wisdom:GetContent on resource: arn:aws:wisdom:us-east-1:xxxxxxxxx:content/xxxxx-xxxxx-xxxxx-xxxx-xxxxx/xxxxx-xxxxx-xxxxx-xxxx-xxxxx"}
It being an assumed role and set by AWS means I cannot change what is already there. I have enabled Wisdom in the agent Security Profile this account is using.
I am thinking it could be an issue with how I registered content. I didnt create a Salesforce or Service Now integration but rather registered a knowledge base and uploaded content via .txt files to the knowledge base. The fact that suggestions appear when i search indicates i've done something right, its just the retrieving full document that is the problem.


Q: Error in Loading UITableView - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.nameList.count;

}
-(UITableViewCell *)tableview:(UITableView *)tableview cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier=@"Cell";

    UITableViewCell *cell=[tableview dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell==nil) {

        cell=[[UITableViewCell alloc]initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
        //cell = [[UITableViewCell alloc]
        //   initWithStyle:UITableViewCellStyleDefault
        // reuseIdentifier:CellIdentifier];

    }
    //Setup the cell
     NSString *cellValue=[ListofItems objectAtIndex:indexPath.row];
    cell.text=cellValue;
    cell.textLabel.text = [self.nameList              objectAtIndex: [indexPath row]];

    return cell;

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

Hi guys,
I have these codes and I cant see my values in my tableview.?And it says this:'program received signal sigabrt'
Can you help me where is my mistake?

A:  return self.nameList.count;

which is the value of nameList.count when tableview numberOfRowsInSection is called? Try to set it to a fixed value just to test. Maybe you are not setting namelist properly.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;

}


Q: Android TextView width I already searched internet for the solution, but none of them works for me...
I have 3 EditText's and 2 TextViews. I can't figure out how I can trim those TextViews (space after '+' and '=').

there is my .xml file:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TableRow android:layout_marginTop="40dp" >

        <EditText
            android:id="@+id/num1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="4"
            android:inputType="number" />

        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <EditText
            android:id="@+id/num2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:ems="4" />

        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="="
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <EditText
            android:id="@+id/wynik"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="4"
            android:inputType="text" >

            <requestFocus />
        </EditText>

    </TableRow>
 </TableRow>

A: android:paddingRight="0dp" should work

A: Change the layout by setting weight like this. This will do the trick for you.

<TableRow android:layout_marginTop="40dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="8">

    <EditText
        android:id="@+id/num1"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:layout_height="wrap_content"
        android:ems="4"
        android:inputType="number" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="+"
         android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/num2"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="4" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="="
         android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/wynik"
        android:layout_width="0dp"
        android:layout_weight="2"
        android:layout_height="wrap_content"
        android:ems="4"
        android:inputType="text" >

        <requestFocus />
    </EditText>

</TableRow>


Q: comparing strings to pointers? Comparing strings in C So this is my code for an assignment for school, and right now my problem is in my inputID function. Where the comment says "If the same!!!!!!!!!!!!!!!!!!!!!!!!!!!", I try to compare a string given by the user and a string stored in my array of strings "IDArray". I try using the strcmp function however I keep getting an error. Any help with this would be much appreciated. The contents of the text file it reads from is shown below the code. Thank You
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_RECORDS 1000
#define MAX_INPUT 40

void writeFile();
void inputPass();
void inputID();
void userInput();
void printDB();
void readFile();
void inputInit();
void DBInit();
void init();

FILE *fp;

char **IDArray;
char **passwordArray;

char *IDInput;
char *passInput;

int main()
{
    init();
    readFile();

    printf("\n\n\tWelcome to CPS_633, Lab 1\t\n\n");

    userInput();
    writeFile();
    printDB();

    return 0;
}

void writeFile()
{
    fp = fopen("Database_Table.txt", "w");
    int i;
    for (i = 0; i < MAX_RECORDS; i++)
    {
        if (IDArray[i][0] != '\0')
        {
            fprintf(fp, "%s\t%s\n", IDArray[i], passwordArray[i]);
        }
        else
        {
            break;
        }
    }
    fclose(fp);
}

void printDB()
{
    printf("\nUsername\tPassword\n");
    int i;
    int databaseLength = 0;

    for (i = 0; i <= MAX_RECORDS; i++)
    {
        if (IDArray[i][0] != '\0')
        {
            printf("%s\t\t%s\n", IDArray[i], passwordArray[i]);
        }
        else
        {
            break;
        }
    }
}

void inputPass()
{
    int correct = 1, strLength;

    printf("Please Enter Your Password (no special characters): ");
    fgets(passInput, MAX_INPUT, stdin);
    strLength = strlen(passInput) - 1;

    if (strLength > 0 && passInput[strLength] == '\n')
    {
        passInput[strLength] = '\0';
    }

    while (correct)
    {
        int k;
        int specialCase = 1;
        for (k = 0; k <= strLength; k++) //Searches for special characters
        {
            switch (passInput[k])
            {
            case '~':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '!':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '`':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '@':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '#':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '$':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '%':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '^':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '&':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '*':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '(':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case ')':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '-':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '_':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '=':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '+':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '[':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case ']':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '{':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '}':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '|':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '\\':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case ':':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case ';':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;

            case '"':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case ',':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '<':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '.':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '>':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '?':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            case '/':
                printf("Special Character(s) Found\n");
                specialCase = 0;
                break;
            }
            if (specialCase == 0)
                break;
        }
        if (specialCase != 0)
        {
            if (strLength > 12) //Password longer than 12 characters
            {
                printf("This password is too long, the characters after the 12th has been cut off\n");
                int i;
                for (i = 0; i < MAX_RECORDS; i++)
                {
                    if (passwordArray[i][0] == '\0')
                    {
                        strncpy(passwordArray[i], passInput, 12);
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
                correct = 0;
            }
            else //Password shorter than 12 characters
            {
                int i, j;
                for (j = strLength; j <= 12; j++) //Pads password with "-"
                {
                    passInput[j] = '-';
                }

                for (i = 0; i < MAX_RECORDS; i++) // Traverses array for first empty slot
                {
                    if (passwordArray[i][0] == '\0') //If empty insert
                    {
                        strncpy(passwordArray[i], passInput, 12);
                        break;
                    }
                    else // If not empty continue
                    {
                        continue;
                    }
                }
                correct = 0;
            }
        }
        else
        {
            printf("Please Enter Your Password (no special characters): ");
            fgets(passInput, MAX_INPUT, stdin);
            strLength = strlen(passInput) - 1;

            if (strLength > 0 && passInput[strLength] == '\n')
            {
                passInput[strLength] = '\0';
            }
        }
    }
}

void inputID()
{
    int correct = 1, strLength;

    printf("Please Enter Your Username ID: ");
    fgets(IDInput, MAX_INPUT, stdin);
    strLength = strlen(IDInput) - 1;

    if (strLength > 0 && IDInput[strLength] == '\n')
        IDInput[strLength] = '\0';

    while (correct)
    {
        if (strLength > 32) //If longer than 32 characters
        {
            printf("This Username ID is longer than 32 characters\n");
            printf("Please Enter Your Username ID: ");
            fgets(IDInput, MAX_INPUT, stdin);

            strLength = strlen(IDInput) - 1;

            if (strLength > 0 && IDInput[strLength] == '\n')
                IDInput[strLength] = '\0';
        }
        else if (strLength < 4) //If shorter than 4 characters
        {
            printf("This Username ID is shorter than 4 characters\n");
            printf("Please Enter Your Username ID: ");
            fgets(IDInput, MAX_INPUT, stdin);

            strLength = strlen(IDInput) - 1;

            if (strLength > 0 && IDInput[strLength] == '\n')
                IDInput[strLength] = '\0';
        }
        else //If acceptable length
        {
            int i;
            for (i = 0; i < MAX_RECORDS; i++)
            {
                if (IDArray[i][0] != '\0') //If element occupied, compare
                {
                    if (strcmp(IDArray[i], inputID) == 0) // If the same!!!!!!!!!!!!!!!!!!
                    {
                        printf("Found Match");
                        correct = 0;
                        break;
                    }
                    else //If not the same
                    {
                        continue;
                    }
                }
                else //If element empty, insert
                {
                    strcpy(IDArray[i], IDInput);
                    break;
                }
            }
            correct = 0;
        }
    }
}

void userInput()
{
    inputID();
    inputPass();
}

void readFile()
{
    fp = fopen("Database_Table.txt", "r");

    char line[MAX_INPUT];
    if (fp == NULL)
    {
        perror("Error in opening file");
    }
    else
    {
        int i = 0;
        while (!feof(fp))
        {
            if (fgets(line, sizeof(line), fp) == NULL)
            {
                break;
            }
            else
            {
                sscanf(line, "%s\t%s", IDInput, passInput);
                strcpy(IDArray[i], IDInput);
                strcpy(passwordArray[i], passInput);
                i++;
            }
        }
    }
    fclose(fp);
}

void inputInit()
{
    IDInput = (char *)malloc(sizeof(char) * MAX_INPUT);
    passInput = (char *)malloc(sizeof(char) * MAX_INPUT);
}

void DBInit()
{
    IDArray = (char **)malloc(sizeof(char *) * MAX_RECORDS);
    passwordArray = (char **)malloc(sizeof(char *) * MAX_RECORDS);

    int i, j;
    for (i = 0; i < MAX_RECORDS; i++)
    {
        IDArray[i] = (char *)malloc(sizeof(char) * MAX_INPUT);
        passwordArray[i] = (char *)malloc(sizeof(char) * MAX_INPUT);
        for (j = 0; j < MAX_INPUT; j++)
        {
            IDArray[i][j] = '\0';
            passwordArray[i][j] = '\0';
        }
    }
}

void init()
{
    DBInit();
    inputInit();
}

ID11    PASSWORD1
ID22    PASSWORD2
ID33    PASSWORD3
ID44    PASSWORD4
ID55    PASSWORD5
ID55    PASSWORD5

A: You have a typo in line 325 (the line with that comment): it's IDInput you want to compare with, not inputID which is the name of the function it's in.


Q: Группировка ListView с виртуализацией C# UWP Windows 10
Необходимо выводить список из нескольких десятков тысяч записей в группированном виде. Сейчас это реализовано как в примере MSDN через CollectionViewSource который является источником данных для ListView. Работает это очень хорошо, но проблема в том что сначала нужно эти записи загрузить в память из базы SQLite, что само по себе занимает очень много времени. Я нашел примеры как реализовать ISupportIncrementalLoading, что полностью решило бы мою проблему, но он не работает с группировкой.
Какие есть варианты решения подобной задачи?


Q: Matlab filter2 and opencv sobel produce different image gradients I need to implement histogram of oriented gradients for patches in an image (one HOG feature vector per patch, not one HOG for the whole image). I have been using the Matlab code at this link and translating the code to opencv python. I have made some changes to fit it for my purpose, one of the main difference between the Matlab and Python codes is in the way I get the gradient of each cell, while in Matlab I am using filter2 as was used in the above link, in Opencv I use Sobel operator. My problem is that the gradients that these two methods produce are different and I had a hard time fixing it. I tried changing both the image and kernel numerical representations. I also tried using filter2D in opencv, also imfilter in Matlab, but basically none of them worked. Here is the Matlab code for calculating the gradient using filter2:
blockSize=26;
cellSize=floor(blockSize/2);
cellPerBlock=4;
numBins=9;
dim = [444,262];
RGB = imread('testImage.jpg');
img= rgb2gray(RGB);

img = imresize(img, [262,444], 'bilinear', 'Antialiasing',false);

%operators
hx = [-1,0,1];
hy = [-1;0;1] ;

%derivatives
dx = filter2(hx, double(img));
dy = filter2(hy, double(img));

% Remove the 1 pixel border.
dx = dx(2 : (size(dx, 1) - 1), 2 : (size(dx, 2) - 1));
dy = dy(2 : (size(dy, 1) - 1), 2 : (size(dy, 2) - 1));

% Convert the gradient vectors to polar coordinates (angle and magnitude).
ang = atan2(dy, dx);
ang(ang < 0) = ang(ang < 0)+ pi;
mag = ((dy.^2) + (dx.^2)).^.5;

And this is the Python OpenCV version that I wrote using Sobel operator:
blockSize=26
cellSize=int(blockSize/2)
cellPerBlock=4
numBins=9
dim = (444,262)
angDiff=10**-6
img = cv2.imread('3132 2016-04-25 12-35-43-53991.jpg',0)
img = cv2.resize(img, dim, interpolation = cv2.INTER_LINEAR)

sobelx = cv2.Sobel(img.astype(float),cv2.CV_64F,1,0,ksize=1)
sobelx = sobelx[1 : np.shape(sobelx)[0] - 1, 1 : np.shape(sobelx)[1] - 1]

sobely = cv2.Sobel(img.astype(float),cv2.CV_64F,0,1,ksize=1)
sobely = sobely[1 : np.shape(sobely)[0] - 1, 1 : np.shape(sobely)[1] - 1]

mag, ang = cv2.cartToPolar(sobelx, sobely)
ang[ang>np.pi+angDiff]= ang[ang>np.pi+angDiff] - np.pi

Edit: I have followed the post HERE, using bilinear method in Matlab and cv2.INTER_LINEAR in OpenCV, as well as deactivating Antialiasing in Matlab, but still the two resized images do not exactly match. Here is a part of the resized image for a test image in Matlab:

And this is the same part from OpenCV:

2nd Edit: It turns out the way rounding happens causes this difference. So, I changed my OpenCV code to :
img = cv2.resize(img.astype(float), dim, interpolation = cv2.INTER_LINEAR)

and the Matlab:
imresize(double(img), [262,444], 'bilinear', 'Antialiasing',false);

And now both give me the same result.

I think the problem is caused by the derivative methods. I have checked cv2.filter2D in OpenCV, but still the results are different. I hope someone can give me a hint on what possibly could have caused the problem.


Q: Do you have any personal visual clue in your code for other user and not the compiler? i use certain suffix in my variable name, a combination of an underscore and a property. such as :
$variable_html = variable that will be parse in html code.

$variable_str = string variable

$variable_int = integer variable

$variable_flo = float variable.

Do you have other visual clues? Maybe something you write for variable, function name, class strucure, or other stuff that helps others to read and not only for compiler ?

A: You're describing Hungarian Notation: Do people use the Hungarian Naming Conventions in the real world?
There's lots of discussion on Stack Overflow about people's feelings on the topic.

A: It nearly is Hungarian Notation, but when you use Hungarian Notation it is more common to use a prefix instead of a suffix.


Q: MethodInfo.Invoke Works only in Debug Mode for Prism EventAggregator I have a extension method for Prism's EventAgregator to publish an event using reflection. The implementation is as follows:
MethodInfo raiseMethod = typeof(Extensions).GetMethod("Raise", BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(obj.GetType());
raiseMethod.Invoke(null, new object[] {eventAggregator, obj, eventType});

This method calls an extension method which requires a typed parameter. This code, and the eventing work fine, but only in Debug mode. When switching to a Release build the event never arrives at the subscriber.
I have tried using the optional parameter during subscription keepSubscriberReferenceAlive but that does not fix the problem.
Any idea on how to fix this issue?
Update
I found that the issue is not releated to the above. It seems there is a filter in place which only allowed event from within the same assembly. But this really doesn't explain why the code worked while in debug mode.


Q: Probability - An urn with twenty balls (10 are black/ other 10 are red) pick three. Urn with ten red balls and ten black balls, what is the probability that you will get balls of both colors if you draw three times without replacement?
I created a tree with all the possible combinations (BBR, BRB, and etc.). There are eight variables and only two of them would not work BBB/RRR. So wouldn't be the answer be 75%?

A: Since you are drawing without replacement, the $8$ events you are thinking about are not all equally likely.  If, for example, you have drawn $2$ balls, and gotten BB, the probability the next one is a B is slightly lower than if your first two balls were AA, or AB. Your reasoning would be perfectly correct if the drawing were done with replacement.
I would probably attack the problem like this. The probability of BBB is $\frac{10}{20}\cdot\frac{9}{19}\cdot\frac{8}{18}$.
By symmetry the probability of RRR is the same. So the probability you will get a monochrome set of balls is $q=2\cdot\frac{10}{20}\cdot\frac{9}{19}\cdot\frac{8}{18}$.
The probability there will be some colour variation is $1-q$.

A: The key here is 'without replacement'.  To pick the three balls, the scheme will always be two of one color and one of the other.  Thus, we have probability
$$\frac{10\cdot{9}\cdot{10}}{20\cdot{19}\cdot{18}}$$
There are 6 out of 8 ways to do this so the answer is
$$6\times\frac{10\cdot{9}\cdot{10}}{20\cdot{19}\cdot{18}}=\frac{60}{76}$$


Q: How to fix a value error when i fit my Machine learning model Hi there, I am learning how to write code for the fist time. I am following a video on Youtube which asks me to write the following code:
tf.random.set_seed(42)
model = tf.keras.Sequential([tf.keras.layers.Dense(1)])
model.compile(loss=tf.keras.losses.mae,optimizer=tf.keras.optimizers.SGD(), # sgd is short for stochastic gradient descentmetrics=["mae"])
model.fit(X, y)

And below is what I see when I try to run it:
ValueError                                Traceback (most recent call last)<ipython-input-42-c251d8a2cc59> in <module>1314 # 3. Fit---> 15 model.fit(X, y)
1 frames/usr/local/lib/python3.8/dist-packages/keras/engine/training.py in tf__train_function(iterator)13                 try:14                     do_return = True---> 15                     retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)16                 except:17                     do_return = False
ValueError: in user code:
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1249, in train_function  *
        return step_function(self, iterator)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1233, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1222, in run_step  **
        outputs = model.train_step(data)
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1023, in train_step
        y_pred = self(x, training=True)
    File "/usr/local/lib/python3.8/dist-packages/keras/utils/traceback_utils.py", line 70, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "/usr/local/lib/python3.8/dist-packages/keras/engine/input_spec.py", line 250, in assert_input_compatibility
        raise ValueError(

    ValueError: Exception encountered when calling layer 'sequential_9' (type Sequential).

    Input 0 of layer "dense_9" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)

    Call arguments received by layer 'sequential_9' (type Sequential):
      • inputs=tf.Tensor(shape=(None,), dtype=float64)
      • training=True
      • mask=None

Can someone please help me figure out what the problem is. Thank you
Didn't try any solution as I didn't know what to do.


Q: How to force root categories to be collapsed by default when adding new product on Magento 1.7 Is it possible to have the category tree collapsed when adding new products?
Now the root categories are expanded.
Subcategories are collapsed (this is ok).
How to force root categories to be collapsed by default?
Thank you!

A: In /app/design/adminhtml/default/default/template/catalog/product/edit/categories.phtml there is a commented line "//tree.expandAll();". Change that line with tree.collapseAll();
Make sure you don't comment the new added line.


Q: How to integrate cognito identity pool with another AWS account for API Gateway access I have a working project in AWS Account A which authenticates users using cognito user pool. Have successfully limited access to certain API Gateway endpoints (using AWS_IAM authorizers) by using fine grained roles, policies, and identity pool. This is all working fine. Now, I am trying to figure how to get API Gateway end point in another AWS account (Account B) to use these same credentials (AccesskeyId, SecretAccessKey and SessionToken) from Account A to be able to hit the API Gateway end point in account B without creating an identity pool id etc in Account B.
I tried one approach where I added another resource to existing policy in Account A for one of the policies which is attached to a role to which a user is attached. Like this
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "execute-api:Invoke",
            "Resource": [
                "arn:aws:execute-api:us-east-1:<Account A id>:<api gateway resourceId account A>/*/*/*",
                "arn:aws:execute-api:us-east-1:<Account B id>:<api gateway resourceId account B>/*/*/*"
            ]
        }
    ]
}

so by adding the second resource arn:aws:execute-api:us-east-1:<Account B id>:<api gateway resourceId account B>/*/*/* my end points in Account B seems to work when a user who authenticates in Account A, gets the credentials (AccesskeyId, SecretAccessKey and SessionToken) and using the same credentials can access the endpoints in Account B. To make this work, on Account B api gateway, I had to enable AWS_IAM authorizer as well.
So was wondering if this is a valid approach for cross account authorization? Are there any other ways where we don't have to manually update these policies specifically? Any thoughts?

A: IMO approach is valid, make sure that APIs resource policy allows only assumed identity role to perform actions (assuming this is your use case).
You can also change the authorization type to Cognito and use the Cognito user access token and scopes to authorize access. Then you do not need to manage policies, see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-cross-account-cognito-authorizer.html.


Q: GIT: For http/https cloned repos only: git push failure shows password in clear text We are using https to clone a repo as following through Jenkins build:
git clone https://${repo_username}:${repo_password}@internalgit.com/scm/project/repo.git -b ${branch_name} $tmp

In above command: ${repo_username} & ${repo_password} are Jenkins variables passed as secrets so they are not logged as clear text.
However, this adds the user credentials to the git remote URL and in case of any push failure it shows the credentials in clear text in the following error:
[ERROR] To https://user:password@internalgit.com/scm/project/repo.git
[ERROR]  ! [remote rejected] master -> master (pre-receive hook declined)
[ERROR] error: failed to push some refs to 'https://user:password@internalgit.com/scm/project/repo.git'

There can be a number of valid reasons for a push failure, however, printing credentials on screen is not acceptable.
Is there a way either to:

*

*mask the above error message.

*updating the remote URL to lose the password, without the password once again being prompted during push.

Following work arounds work but NOT acceptable in our use case:

*

*Store password in credential cache (using credential.helper)

*Using ssh clones instead of https.

A: Assuming that output is visible but input is not:
git clone https://${repo_username}:${repo_password}@internalgit.com/scm/project/repo.git -b ${branch_name} $tmp | sed "s/${repo_password}/<redacted>/g"
 should do what you want.
I misread the question; for this answer to work you'd have to run it on each push (i.e. git push 2>&1 | sed "s/${repo_password}/<redacted>/g". I also missed that git prints this to stderr, so unless you want to use process substition, it will be difficult to redirect output.
You should escape the password in case it contains any special regex characters (as otherwise sed may match more or less than you mean too). This answer has some ready solutions for escaping strings to use with sed.


Q: ReactJS apolloClient Could not find "client" in the context or passed in as an option I am not getting why it is firing me this problem, and it was worked same way before in my another application. I just tried last 3 days, i coulndt figure out this issue yet.
I found this solution on stackoverflow: React Apollo Error: Invariant Violation: Could not find "client" in the context or passed in as an option
But it is not solved my problem
Can anyone help me in this case?
THis is my App.js
import EmpTable from './components/empTable';
import { ApolloProvider } from '@apollo/react-hooks';

import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
  uri: 'http://localhost:8000/graphql/',
  cache: new InMemoryCache(),
});

function App() {
  return (
    <ApolloProvider client={client}>
        <EmpTable />
    </ApolloProvider>
  );
}

export default App;

and this is my EmplyeeTable
import { gql, useQuery } from "@apollo/client";

function EmpTable() {

  const GET_EMPLOYEE = gql`
    query getEmp($id: String) {
      employeeById(id: $id) {
        id
        name
        role
      }
    }
  `;

  const {refetch} = useQuery(GET_EMPLOYEE)

  return (
    <div className="row">
      {/* some div  */}
    </div>
  );
}

export default EmpTable;

I am getting following error with this code:
Could not find "client" in the context or passed in as an option. Wrap the root component in an <ApolloProvider>, or pass an ApolloClient instance in via options.
new InvariantError
src/invariant.ts:12
   9 | export class InvariantError extends Error {
  10 |   framesToPop = 1;
  11 |   name = genericMessage;
> 12 |   constructor(message: string | number = genericMessage) {
  13 |     super(
  14 |       typeof message === "number"
  15 |         ? `${genericMessage}: ${message} (see https://github.com/apollographql/invariant-packages)`
View compiled
invariant
src/invariant.ts:27
  24 |   message?: string | number,
  25 | ): asserts condition {
  26 |   if (!condition) {
> 27 |     throw new InvariantError(message);
  28 |   }
  29 | }
  30 |

The error is too long i just puted few of them here. Can anyone please let me know what exactly the issue?

A: Try importing ApolloProvider from @apollo/client
import { ApolloProvider } from '@apollo/client';


Q: How do I get rid of this TypeError, and why is it occurring given that I am simply reassigning a value in a list? Code:
http://pastie.org/1961455
Trackback:
Traceback (most recent call last):
  File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 149, in <module>
    main ()
  File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 144, in main
    move = computer_move(computer, board, human)
  File "C:\Users\COMPAQ\Desktop\NoughtsCrosses.py", line 117, in computer_move
    board[i] = computer
TypeError: 'str' object does not support item assignment

As you can see for in my tic-tac-toe program, the board[i] = computer line in the computer_move function is the one (if I am reading this right) causing the error. But if I know this right, item assignment is allowed in lists, and I create a local copy of "board" for my function so that I can reassign values and whatnot within the function...
Any input at all would be greatly appreciated. This is my first serious piece of code, so if the function in question looks too mangled

A: The problem is here:
def computer_move (computer, board, human):
    best = (4,0,8,2,6,1,3,5,7)
    board = board [:]
    for i in legal_moves(board):
        board[i] = computer
        if winner(board) == computer:
            return i
        board = EMPTY

At the end of the function, you assign EMPTY to board, but EMPTY is an empty string, as defined on line 4. I assume you must have meant board[i] = EMPTY.

A: In line 120, you reassign board to EMPTY (ie an empty string). So from that point on, board is no longer a list, so you can't assign board[i]. Not quite sure what you meant to do there.
Generally, your code would greatly benefit from using object-orientation - with Board as a class, keeping track of its member squares.

A: Looks like board is a string. I get the same error when I do this:
>>> s = ''
>>> s[1] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment


Q: Why can Scala compiler not infer Stream type operations? Lets say I want to have a Stream of squares. A simple way to declare it would be:
scala> def squares(n: Int): Stream[Int] = n * n #:: squares(n + 1)

But doing so, yields an error:
<console>:8: error: overloaded method value * with alternatives:
  (x: Double)Double <and>
  (x: Float)Float <and>
  (x: Long)Long <and>
  (x: Int)Int <and>
  (x: Char)Int <and>
  (x: Short)Int <and>
  (x: Byte)Int
 cannot be applied to (scala.collection.immutable.Stream[Int])
       def squares(n: Int): Stream[Int] = n * n #:: squares(n + 1)
                                            ^

so, why can't Scala infer the type of n which is obviously an Int? Can someone please explain what's going on?

A: It's just a precedence issue.  Your expression is being interpreted as n * (n #:: squares(n + 1)), which is clearly not well-typed (hence the error).
You need to add parentheses:
def squares(n: Int): Stream[Int] = (n * n) #:: squares(n + 1)

Incidentally, this isn't an inference problem, because the types are known (i.e., n is known to be of type Int, so it need not be inferred).


Q: How to create a dynamic model for days of week names in schedule? For the gym schedule, I need to create a model with which I will get a list of seven days names. The list will be updated daily, so in the first place will always be the current day of the week. Every day the list will be shifted to one day, so, for example, in the cell in which the word “Wednesday” stands today, tomorrow the word “Thursday” will appear, the day after tomorrow - “Friday” and so on. The names of the days should then be retrieved into the view and passed to the template.
I tried to do it like this:
import calendar
import datetime
from datetime import *
from django.db import models
from django.utils.translation import ugettext as _

class DayOfWeekSchedule(models.Model):
    """General dynamic schedule for a week"""

    DOW_CHOICES = (
        (1, _("Monday")),
        (2, _("Tuesday")),
        (3, _("Wednesday")),
        (4, _("Thursday")),
        (5, _("Friday")),
        (6, _("Saturday")),
        (7, _("Sunday")),
    )
    day_of_week = models.PositiveSmallIntegerField(
        choices=DOW_CHOICES,
        verbose_name=_('Day of week')
        )

    def days_of_week(self):
        my_date = date.today()
        current_day_name = calendar.day_name[my_date.weekday()]
        index1 = DOW_CHOICES.index(current_day_name) #from Monday=0 (i.e. Friday=4)
        list_daynames = list(DOW_CHOICES[index1:] + DOW_CHOICES)[:7] #list of names, current is first
        list_index = (2, 3, 4, 5, 6, 7, 1) #to compensate systems difference
        list2 = list(list_index[index1:] + list_index)[:7]
        context_days = dict(zip(list_keys, list_daynames))
        return context_days

But
DOW_CHOICES.index (current_day_name)
and
list_daynames = list (DOW_CHOICES [index1:] + DOW_CHOICES) [: 7]
, as expected, do not work, because .index () is not applicable to tuples of this type.
And how to do it, I do not know.

A: Maybe you're overthinking this. If I understand what you want correctly, you could just do something like this:
 from datetime import datetime, timedelta

 days = {
    '1': _('Monday'),
    '2': _('Tuesday'),
    '3': _('Wednesday'),
    '4': _('Thursday'),
    '5': _('Friday'),
    '6': _('Saturday'),
    '7': _('Sunday')
}

DOW_CHOICES = []

today = datetime.today()
for i in range(7):
    day_number = (today + timedelta(days=i)).isoweekday()
    day = days[str(day_number)]
    DOW_CHOICES.append((day_number, day))

This gets the today's date and creates a list of tuples with day number and day. The result will be:
[
    (3, 'Wednesday'),
    (4, 'Thursday'),
    (5, 'Friday'),
    (6, 'Saturday'),
    (7, 'Sunday'),
    (1, 'Monday'),
    (2, 'Tuesday')
]


Q: Shape 1 of numpy array Consider
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])

In Python's view, x has shape (4, 3) and v shape (3, ). Why didn't Python view v as having shape (, 3). Also, why do v and v.T have the same shape (3, ). IMHO, I think if v has shape (3, ) then v.T should have shape (, 3)?

A: (3,) does not mean the 3 is first. It is simply the Python way of writing a 1-element tuple. If the shape were a list instead, it would be [3].
(, 3) is not valid Python. The syntax for a 1-element tuple is (element,).
The reason it can't be just (3) is that Python simply views the parentheses as a grouping construct, meaning (3) is interpreted as 3, an integer.

A: As you know, numpy arrays are n-dimensional. The shape tells dimensions in the order. If it is 1-D you will see only 1st dimension, 2-D only 2 dimensions and so on.
Here x is a 2-D array while v is a 1-D array (aka vector). That is why when you do shape on v you see (3,) meaning it has only one dimension whereas x.shape gives (4,3). When you transpose v, then that is also a 1-D array. To understand this better, try another example. Create a 3-D array.
z=np.ones((5,6,7))
z.shape
print (z)


Q: Error 1004 at the line d = Worksheets(A(i)).Cells(B(j), l) + d I am getting error at this command
d = Worksheets(A(i)).Cells(B(j), l) + d

Where I have stored the name of the sheets in Array A(i) Array B(j) is having integer values. I have already declared both the arrays along-with d as integer.
Thanks in advance,
Please find the code below
Sub checksum()
    Dim A(50) As String
    Dim B(5) As Integer
    Dim i As Integer, j As Integer, d As Integer, k As Integer, p As Integer, l As Integer, s As Integer
    s = 1
    A(1) = "TREND M S&G"
    A(2) = "TREND M RAZORS"
    A(3) = "TREND M RZ ACC"
    A(4) = "TREND M GROOM"
    A(5) = "TREND BODY GROOM"
    A(6) = "TREND Multi"
    A(7) = "TREND BRDM"
    A(8) = "TREND PRCSN"
    A(9) = "TREND M H CLIP"
    A(10) = "TREND PTB&A"
    A(11) = "TREND rch"
    A(12) = "TREND batt"
    A(13) = "TREND refills"
    A(14) = "TREND BABY"
    A(15) = "TREND BREAST FEED"
    A(16) = "TREND breast pad"
    A(17) = "TREND breast pumps"
    A(18) = "TREND REUSABLE"
    A(19) = "TREND DISPOSABLE"
    A(20) = "TREND TODDLER"
    A(21) = "TREND TODDLER C&P"
    A(22) = "TREND FEED ACCESS"
    A(23) = "TREND SOOTHING"
    A(24) = "TREND P&H"
    A(25) = "TREND TEETHERS"
    B(1) = 3
    B(2) = 6
    B(3) = 9
    B(4) = 12

    ThisWorkbook.Sheets.Add After:=Sheets(Worksheets.Count), Count:=1, Type:=xlWorksheet

    For i = 1 To 25
         Worksheets(Worksheets.Count).Cells(i, 1) = A(i)

         For j = 1 To 4
             d = 0

             If i > 10 Then k = 54 And p = 70
             If i < 11 Then k = 56 And p = 66

             For l = k To p
                 d = Worksheets(A(i)).Cells(B(j), l) + d
             Next l

             If d = 100 Then Worksheets(Worksheets.Count).Cells(i, j + 1) = "Fine"
             If d <> 100 Then Worksheets(Worksheets.Count).Cells(i, j + 1) = "Error"

         Next j
    Next i
End Sub

A: This does not work; the And Operator cannot be used this way:
If i > 10 Then k = 54 And p = 70
If i < 11 Then k = 56 And p = 66

Change it to:
If i > 10 Then
    k = 54
    p = 70
Else
    k = 56
    p = 66
End If

A: I don't know what's in the cell that you're referencing, but based on what I can see here, I'm guessing it contains an integer. If so, then you need to access the value of the cell:
d = Worksheets(A(i)).Cells(B(j), l).Value2 + d

You'll need to do the same with your last couple of lines
If d = 100 Then Worksheets(Worksheets.Count).Cells(i, j + 1).Value2 = "Fine"
If d <> 100 Then Worksheets(Worksheets.Count).Cells(i, j + 1).Value2 = "Error"


Q: Question about probability Could someone explain me how I would solve such as:

A bag contains 6 black marbles and 2 red marbles.
   3 marbles are picked out the bag without replacement.
   How likely is it that you picked exactly 2 black marbles?

I know the answer is:  $0.54$ (rounded on 2 decimals).
But how would I solve questions like above?

A: Hint: Assume $3$ blanks and find the combinations, eg: B,B,R and you will get two more.
For BBR, you get $\frac{6*5*2}{8*7*6}$. Find the remaining combinations. Add them up.
This should be easy.

A: This is a hypergeometric distribution problem:
$\frac{{6 \choose 2}*{2 \choose 1}}{{8 \choose 3}}=0.5357$
From the 6 black marbles find all combinations of the picking 2 multiplied by choosing 1 red marble from the 2 available. Then divide by the total number of combinations of selecting 3 marbles from the 8 total marbles that can be chosen.

A: I think that i've found an easy way for this:

Prob(Black, Black) = (6/8)(5/7) = 0.54 (rounded)
  (6/8)(5/7) = (total black / total marbles) * (total black - 1/ total marbles - 1)
  the more precise definition would be (total black / total marbles) * (total black - n / total marbles - n)
  where n would be the number left of each
  this only works without replacement, since you're removing items from the stack, so to speak


Q: Calculate in dynamic created textbox How can I add values in my dynamically created texbox in another textbox ? For example I have 6 textbox named from TextBox0 to TextBox6 and I want to add the values in TextBox0 to TextBox5 then set that values in TextBox6. How can I do that?
This is my code for create dynamic textbox:
static int column = 0;
private void button1_Click(object sender, EventArgs e)
{
    int i = 0;
    if (column > 0)
    {
        do
        {
            TextBox tb = new TextBox();
            tb.Text = "";
            tb.Name = "TextBox" + (i + column * 6);
            TextBox t = (TextBox)Controls["TextBox" + i.ToString()];
            Point p = new Point(15 + (column * 125), 5 + (i * 25));
            tb.Location = p;
            this.Controls.Add(tb);
            i++;
        } while (i <= 5);
    }
    else
    {
        do
        {
            TextBox tb = new TextBox();
            tb.Text = "";
            tb.Name = "TextBox" + i;
            TextBox t = (TextBox)Controls["TextBox" + i.ToString()];
            Point p = new Point(15, 5 + (i * 25));
            tb.Location = p;
            this.Controls.Add(tb);
            i++;
        } while (i <= 5);
    }
    column++;
}

A: private const string _textBoxName = "TextBox";

The method count textboxes sum by given range of text box ids. Be aware this will throw exception if the text box texts / name id are not intgeres or
   private int Count(int from, int to)
            {
                int GetIdFromTextBox(TextBox textBox) => int.Parse(new string(textBox.Name.Skip(_textBoxName.Length).ToArray()));

                var textBoxes = Controls.OfType<TextBox>().ToList();
                var textBoxesWithIds = textBoxes.Select(textBox => (textBox: textBox, id: GetIdFromTextBox(textBox))).ToList();

                var sum = textBoxesWithIds.Where(x => x.id >= from && x.id <= to).Sum(x => int.Parse(x.textBox.Text));

                return sum;
            }