text:
Q: Mapping images and their labels I have images in a folder(train) and csv file(train.csv) containing image names and labels.
how to map images in one folder and labels in another csv file
how can i create a data frame with image data and labels.
multiclass classification

A: import tensorflow as tf
from tensorflow import keras
import pandas as pd

class MyTrainingData(keras.utils.Sequence):
    def __init__(self, file, labels, batchSize):
        self.file = file
        self.label = labels
        self.batchSize = batchSize
        self.n_bathces = int(len(self.file) / self.batchSize)

    def on_epoch_end(self):  # it is called after every epoch
        self.file, self.label = shuffle(self.file, self.label)
        for i in range(50):
            print(self.file[i], self.label[i], 'file-label')

    def __len__(self):
        return self.n_bathces

    # called after every batch to get new batch or new 32 images and labels
    def __getitem__(self, idx):
        # this method calls by fit method with idx ranging from 0 to len(training_exmaples) / batch_size =
        batchX = self.file[idx*self.batchSize: (idx+1)*self.batchSize]
        batchY = self.label[idx*self.batchSize: (idx+1)*self.batchSize]
        imgFiles = [image.load_img(name, target_size=(224, 224, 3)) for name in batchX]   #loading 32 images
        imgFiles = [image.img_to_array(img) for img in imgFiles]   #preprocessing
        imgFiles = [img / 255 for img in imgFiles]        batchY = to_categorical(batchY, 4)    # 4 represent number of classes (4 in that case)
        return np.array(imgFiles), np.array(batchY)

def getfilePath(filenames):
    path = './train/'  # or any other path according to directory structure
    filePaths = []
    for name in filenames:
        filePaths.append(path + name)   # './train/' + 'img1.jpg' = './train/img1.jpg

    return filePaths

df = pd.read_csv()
img_names = df['img_names']
labels = df['labels']
img_names = ['img1.jpg', 'img2.jpg', -----]
img_names = getfilePath(img_names)
img_names = ['./train/img1.jpg', './train/img2.jpg', -----]
label = [3, 1, 2, 0, ----]

batch_size = 32

data = MyTrainingData(fileNames, labels, batchSize

model = defineModel()
sgd = SGD(learning_rate=0.0001, momentum=0.9, nesterov=True)
model.compile(optimizer=sgd, loss='binary_crossentropy', metrics=['accuracy'])
model.fit(data, epochs=10, verbose=1)

The above code does much more than mapping. In case of large dataset(to big to fit in RAM). this techniwue will help you to load, preprocess and generate input data dynamically. Hope you find it usefull. Give feedback so that i can further improve it.


text:
Q: Codeigniter Upload Image Choice I have a form including different inputs and file upload input. I want the users if they want to upload images then upload, but if they don't want to upload. Don't give an error.
if($_POST){
    $config['upload_path']          = 'images/tmp';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['max_size']             = 2048;
    $config['min_width']            = 480;
    $config['min_height']           = 360;

    $this->load->library('upload', $config);

    if (!$this->upload->do_upload('userfile')) {
        $error = array('error' => $this->upload->display_errors());
        //Sending this $error to view and if a user didnt upload image and just filled
        //the other inputs it shows error. but i dont want that.
    } else { }
} else {
    redirect(site_url());
}

A: You are on right track. Just delete or comment this line
$error = array('error' => $this->upload->display_errors());
You might be send your $error to view file like below:
$this->load->view('upload_form', $error);
So Don't send your value to view file. Just call your view when image successfully uploaded below:

            if ( ! $this->upload->do_upload('userfile') )
            {

                // $error = array('error' => $this->upload->display_errors());
                /*Delete or comment this line. Do your other stuff here if image not uploaded.*/

            }else{
                   $data = array('upload_data' => $this->upload->data());
                   $this->load->view('upload_success', $data);
                   /* This is example. You can do anything on successfully image upload.*/
            }

You can refer codeigniter manual  https://www.codeigniter.com/userguide3/libraries/file_uploading.html

A:     $config['upload_path']          = 'images/tmp';
    $config['allowed_types']        = 'gif|jpg|png';
    $config['max_size']             = 2048;
    $config['min_width']            = 480;
    $config['min_height']           = 360;
    $this->load->library('upload', $config);
       //$rand_str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
         //   $filename=md5(str_shuffle($rand_str.mt_rand()));
        //  $config['file_name']=$filename;

            $this->upload->initialize($config);

            if ( $this->upload->do_upload('userfile'))
            {
                    //$data = array('upload_data' => $this->upload->data());
                     //  $data["filename"]=$filename;
                    //  $data["ad_id"]=$lid;

                    // $data["filename"]=$rand_name;
                  //  $this->Ads_model->insert_image($data);

            }

A: I solved my problem changing the Upload class to give no error. I commented the lines including "no selected files".

redpajama_set_name: RedPajamaStackExchange


text:
Q: read txt file start from the botton My txt file is beeing read incorectly, when I send keys with my code it's only reading the last line of my txt file, instead of reading 1st line and then the next one
f = open('list.txt', 'r', encoding='utf-8').readlines()
    for word in f:
        if word == "\n":
            continue
        elif not 0 < len(word) < 280:
            continue
        print(word)

     driver.find_element_by_xpath(message_paste).send_keys(word)
        print(word)

Result : the code send the very last line of my txt file

A: I can't replicate this. Check indentation. The following snippet works for me.
f = open('list.txt', 'r', encoding='utf-8').readlines()
for word in f:
    if word == "\n":
        continue
    elif not 0 < len(word) < 280:
        continue
    print(word)


text:
Q: JQuery animate enhanced through webkit, inconsistent The following code controls a function for sliding various items across a bar. It is using a plugin called JQuery animate enhanced that uses CSS3 where possible on supporting browsers.
Without CSS3 the function works perfectly. However with CSS3 once all tabs have been selected the first one will no longer cooperate.
the fiddle: http://jsfiddle.net/cqBZz/3/
the code:
$(document).ready(function () {
    var bounceholder = 0;
    var delayact = 0;
    $('.bouncetabs a').click(function () {
        $('.bouncetabs a').removeClass('active');
        $(this).addClass('active');

        if ($(this).index('.bouncetabs a') < bounceholder) {
            var backwards = 1
        } else {
            var backwards = 0
        }

        bounceholder = $(this).index('.bouncetabs a');
        var bounceoffset = 0;

        if ($('.bounceholder ul:eq(' + bounceholder + ') li').length == 6) {
            var bounceoffset = 0;
        } else if ($('.bounceholder ul:eq(' + bounceholder + ') li').length == 5) {
            var bounceoffset = 72;
        } else if ($('.bounceholder ul:eq(' + bounceholder + ') li').length == 4) {
            var bounceoffset = 144;
        } else if ($('.bounceholder ul:eq(' + bounceholder + ') li').length == 3) {
            var bounceoffset = 216;
        } else if ($('.bounceholder ul:eq(' + bounceholder + ') li').length == 2) {
            var bounceoffset = 288;
        }

        $('.bounceholder ul:eq(' + bounceholder + ')').prevAll().each(function () {
            $('li', this).each(function () {
                $(this).delay(150).animate({
                    left: -200,
                    top: 0,
                    leaveTransforms: true
                }, {
                    duration: 400,
                    queue: true
                });
            });
        });
        $('.bounceholder ul:eq(' + bounceholder + ')').nextAll().each(function () {
            $('li', this).each(function () {
                $(this).delay(150).animate({
                    left: +1000,
                    top: 0,
                    leaveTransforms: true
                }, 600);
            });
        });

        if (backwards == 1) {
            bounceoffset = 800 - bounceoffset;
            $($('.bounceholder ul:eq(' + bounceholder + ') li').get().reverse()).each(function (i) {
                delay = (i + 1) * 100;
                $(this).delay(delay).animate({
                    left: +bounceoffset,
                    top: 0,
                    opacity: 0.6,
                    leaveTransforms: true
                }, {
                    duration: 400,
                    queue: true
                });
                bounceoffset -= 160;
            });
        } else {
            $('.bounceholder ul:eq(' + bounceholder + ') li').each(function (i) {
                delay = (i + 1) * (100 * delayact);
                $(this).delay(delay).animate({
                    left: +bounceoffset,
                    top: 0,
                    opacity: 0.6,
                    leaveTransforms: true
                }, {
                    duration: 400,
                    queue: true
                });
                bounceoffset += 160;
            });
        }
        delayact = 1;

        return false
    });

});

A: The best way to deal with hardware acceleration currently is using a combination of CSS3 transition for -moz-translate, -webkit-translate and -webkit-translate3d and jQuery animate. My personal experience with the above mentioned tool is rather bad. It caused multiple errors on my pages.
Also set translateZ(0px) for all elements you want to move as translate3d is only used for safari and chrome (enables hardware acceleration)
Here's something to get started with. You have to add checks for browsers to make it work.
if(browser.isFF) {
    function moveDOM(jQueryObj,x,y) {
        jQueryObj[0].style.cssText += '-moz-transform:translate('+x+'px,'+y+'px);';
    } // firefox does not know translate3d
} else if(browser.isAndroid) {
    function moveDOM(jQueryObj,x,y) {
        jQueryObj[0].style.cssText += '-webkit-transform:translate('+x+'px,'+y+'px);';
    } // most Android version currently don't know translate3d (U could add checks for the Android versions though -> caniuse.com
} else if(browser.isSafari || browser.isChrome) {
    function moveDOM(jQueryObj,x,y) {
        jQueryObj[0].style.cssText += '-webkit-transform:translate3d('+x+'px,'+y+'px,0px);';
    };
} else { // ie opera, others
    function moveDOM(jQueryObj,x,y) {
        jQueryObj.animate({'left':x,'top':y},500);
    };
}

// example run of the function, moving the element with the id myDiv to position (50,90)
moveDOM($("#myDiv"),50,90);

the delay for the css translates can be set via CSS3:
-webkit-transition: all 0.5s ease; -moz-transition: all 0.5s ease;

PS: you might wonder why i used default JS instead of jQuery's .css() functoin in 3 out of 4 cases... It's simply faster. If you want to increase speed even further, replace the += with = but that overwrites any other stlyes you might have added.


text:
Q: On a certain bijection of the multiplicative group modulo prime $p=2^k+1$. Let:
$G=\{1,\ldots,p-1\}$ be the multiplicative group of integers modulo prime $p=2^k+1$;
$v_2(a)$ be the exponent of $2$ in the prime factorization of $a$;
$\mu(a)=\max\{j\in[0,k]\ |\ x^{2^j} \equiv a\}$ for some $x\in\mathbb{G}$;
$A_i = \{a\in\mathbb{G}\ |\ v_2(a)=i\}$;
$B_i = \{a\in\mathbb{G}\ |\ \mu(a)=i\}$.
Now, couple questions:

*

*Prove that $a$-powers of the elements of $G$ are exactly $2^{v_2(a)}$-powers of the elements of $G$.

I prove this by introducing two sub-groups $G_1=\{x^a,x\in G\}$ and $G_2=\{x^{2^{v_2(a)}},x\in G\}$ and showing that $G_1\subseteq G_2$ and $G_2\subseteq G_1$. But could there be less laborious and more intuitive proof, which is often the case with simpler problems in number theory?

*Let $g$ be a primitive root modulo $p$ and $f$ be a map from $G$ to itself that sends $x$ to $g^x$ modulo $p$. Prove that $f$ is a bijection that sends $A_i$ to $B_i$ for each $i\in\{0,\ldots,k\}$.

This one I can't formally prove at all...


text:
Q: PFquery table view control show detail I'm looking for a way to transport data entered into the database from a view to another. I have a table view controller with university exams inserted every examination must show your card, calling its data from the data browser to Parse the current user through the
- (void) prepareForSegue: (uistoryboardSegue)

A: Then I try to explain as best as possible ...
I downloaded from the project parse.com PFQueryTableViewController.
I entered all the data perfectly recall the Databrowser ...
My cells are thus created:
#import "TableViewParse.h"
#import "CustomNav.h"
#import "ListaInAttesa.h"

@implementation TableViewParse
@synthesize TableViewInAttesa;

- (id)initWithCoder:(NSCoder *)aCoder {
    self = [super initWithCoder:aCoder];

        // Custom the table

        // The className to query on
        self.parseClassName = @"miaclasse";

        // The key of the PFObject to display in the label of the default cell style
        self.textKey = @"titolomio";

        // Whether the built-in pull-to-refresh is enabled
        self.pullToRefreshEnabled = YES;

        // Whether the built-in pagination is enabled
        self.paginationEnabled = YES;

        // The number of objects to show per page
        self.objectsPerPage = 5;

     [CustomNav NavBar];

    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.

    self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - Parse

- (void)objectsDidLoad:(NSError *)error {
    [super objectsDidLoad:error];

    // This method is called every time objects are loaded from Parse via the PFQuery
}

- (void)objectsWillLoad {
    [super objectsWillLoad];

    // This method is called before a PFQuery is fired to get more objects
}

// Override to customize what kind of query to perform on the class. The default is to query for
// all objects ordered by createdAt descending.
- (PFQuery *)queryForTable {
    PFQuery *query = [PFQuery queryWithClassName:self.parseClassName];
        [query whereKey: @"user" equalTo: [PFUser currentUser]];

    // If no objects are loaded in memory, we look to the cache first to fill the table
    // and then subsequently do a query against the network.
    if ([self.objects count] == 0) {
        query.cachePolicy = kPFCachePolicyCacheThenNetwork;
    }
    [query orderByAscending:@"createdAt"];

    return query;
}

// Override to customize the look of a cell representing an object. The default is to display
// a UITableViewCellStyleDefault style cell with the label being the first key in the object.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath object:(PFObject *)object {
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    }

    // Configure the cell
    cell.textLabel.text = [object objectForKey:@"titolomio"];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"Questo esame è previsto per il : %@", [object objectForKey:@"datamia"]];

    return cell;
}

/*
 // Override if you need to change the ordering of objects in the table.
 - (PFObject *)objectAtIndex:(NSIndexPath *)indexPath {
 return [objects objectAtIndex:indexPath.row];
 }
 */

// Override to customize the look of the cell that allows the user to load the next page of objects.
// The default implementation is a UITableViewCellStyleDefault cell with simple labels.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForNextPageAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"NextPage";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = @"Visualizza ancora ....";

    return cell;
}

#pragma mark - Table view data source

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {

        PFObject *object = [self.objects objectAtIndex:indexPath.row];
        [object deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            [self loadObjects];
        }];
    }
}

// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}

// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"Esamiinattesa"])
    {
       // NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
       // ListaInAttesa *destViewController = segue.destinationViewController;
       // destViewController.title = [self.postController objectInListAtIndex:indexPath.row];
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
   // [self performSegueWithIdentifier:@"Esamiinattesa" sender:indexPath];

}

@end

Now I need that when the user clicks on a current exam placed in the cell Tableview is sent to a specific viewcontroller where inside are called the results of the examination the time the user selected current ...
I know that it is "prepareForSegue" but I can not figure out where I'm wrong, maybe I'm wrong just the procedure to obtain the required result.
P.S.I realized just now that I connected with the user's findanzato because I changed my pc and I kept doing the same id logout ... Sorry ... We are working on this project in two App


text:
Q: PHP difference between notice and warning When writing code errors, warnings and notices can occur. I know the idea behind errors. I suppose a warning is there to inform you about something that can cause an error, but isn't a notice exaclty the same? I suppose a notice is not a message of something doing right ;).
It's just a bit confusing to me. Can anybody tell the difference between those two and the way these messages should be treated.

A: A notice is an advisory message meaning "You probably shouldn't be doing what you're doing, but I'll let you do it anyway"
A warning is a message saying "You are doing something wrong and it is very likely to cause errors in the future, so please fix it."
Both notices and warnings will not halt execution of your script, although I would encourage you to take them seriously and strive to have not even one notice in your apps.

A: *

*NOTICE:
    this is a short message for saying what to do or what not to do.

*WARNING:
    occcurs at run time. Code execution continues.

*ERROR:
    this also occurs at run time, execution terminates.

A: I won't re-iterate the specific meanings, which have been thoroughly covered by other answers.
Warnings and notices indicate different "badness" levels for things you might be doing wrong, but I'm with the PEAR/Zend guides on this: you should always code to E_STRICT, which means you shouldn't ever raise either warnings or notices.
If you follow E_STRICT compatibility, the distinction between notices and warnings is kind of redundant if both are considered "Non-fatal errors that you should make sure don't happen" - they're both essentially warnings.

A: Differences are explained here: http://www.php.net/manual/en/errorfunc.constants.php
Specifficaly:
Errors:

Fatal run-time errors. These indicate
  errors that can not be recovered from,
  such as a memory allocation problem.
  Execution of the script is halted.

Warnings:

Run-time warnings (non-fatal errors).
  Execution of the script is not halted.

Notices:

Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.

A: *

*NOTICE: It is a message for saying what you should do and what you should not do.

*WARNING: It occurs at run time.But it do not interrupt Code execution.

*ERROR: It also occurs at run time, but program execution is not continued it terminates.

A: According to PHP Manual:

*

*WARNING - Run-time warnings (non-fatal errors). Execution of the script is not halted.

*NOTICE - Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script.

Personally I think, that notices indicate some code parts, which potentially can lead to some problems, but which were introduced intentionally. In such cases programmer is considered to "know what he is doing" and to know about some particular PHP features (type casts, default initialization values etc).


text:
Q: save data from api to dataframe I have the following output when getting data from an API:
{'Textbook': [{'Type': 'Chapters', 'Case': 'Ch09', 'Rates':
[{'Date': '2021- 04-23T00:00:00', 'Rate': 10.0}, {'Date': '2021-04-26T00:00:00', 'Rate': 10.0},
{'Date': '2021-04-27T00:00:00', 'Rate': 10.5}, {'Date': '2021-04-28T00:00:00', 'Rate': 10.5},
{'Date': '2021-04-29T00:00:00', 'Rate': 10.5}, {'Date': '2021-04-30T00:00:00', 'Rate': 10.0}]}]}

I am trying to get the following output in a dataframe:
Date                           Rate
2021- 04-23T00:00:00          10.0
2021-04-26T00:00:00           10.0
2021-04-27T00:00:00           10.5

etc
I tried the following code:
l=parsed ###this is the output from API
df=pd.DataFrame()
for i in l:
   d1 = {}
   reportDate = []
   price = []
   for j in i['Chapters']:
      reportDate.append(j['Date'])
      price.append(j['Rate'])
   d1['Date'] = reportDate
   d1['Rate'] = price
df = df.append(pd.DataFrame(d1))
df['Date'] = pd.to_datetime(df['Date'])

However, I get the following error: string indices must be integers for the line for j in i['Chapters']:

A: Below fix on your code will solve your issue. Although the answer by Andreas is a pythonic way!
import ast

# Data setup
raw_data="""
{'Textbook': [{'Type': 'Chapters', 'Case': 'Ch09', 'Rates':
[{'Date': '2021- 04-23T00:00:00', 'Rate': 10.0}, {'Date': '2021-04-26T00:00:00', 'Rate': 10.0},
{'Date': '2021-04-27T00:00:00', 'Rate': 10.5}, {'Date': '2021-04-28T00:00:00', 'Rate': 10.5},
{'Date': '2021-04-29T00:00:00', 'Rate': 10.5}, {'Date': '2021-04-30T00:00:00', 'Rate': 10.0}]}]}
"""
val=ast.literal_eval(raw_data) # eval to dictionary

the fix would be(pls review the comment section)
l=val ###this is the output from API, added val in this example
reportDate = [] # moved out of loop to collect the data
price = [] # moved out of loop to collect the data
#df=pd.DataFrame() build the dataframe once all the data is ready
for i in l: # this is dictionary
    #d1 = {} not needed

    for j in l[i][0]['Rates']:
        reportDate.append(j['Date'])
        price.append(j['Rate'])
    #d1['Date'] = reportDate
    #d1['Rate'] = price
#df = df.append(pd.DataFrame(d1))
#df['Date'] = pd.to_datetime(df['Date'])
df=pd.DataFrame({'Date':reportDate,"Rate":price})

A: You can try this:
d = {'Textbook': [{'Type': 'Chapters', 'Case': 'Ch09', 'Rates':
[{'Date': '2021- 04-23T00:00:00', 'Rate': 10.0}, {'Date': '2021-04-26T00:00:00', 'Rate': 10.0},
{'Date': '2021-04-27T00:00:00', 'Rate': 10.5}, {'Date': '2021-04-28T00:00:00', 'Rate': 10.5},
{'Date': '2021-04-29T00:00:00', 'Rate': 10.5}, {'Date': '2021-04-30T00:00:00', 'Rate': 10.0}]}]}

pd.DataFrame(d.get('Textbook')[0].get('Rates'))

#                    Date  Rate
# 0  2021- 04-23T00:00:00  10.0
# 1   2021-04-26T00:00:00  10.0
# 2   2021-04-27T00:00:00  10.5
# 3   2021-04-28T00:00:00  10.5
# 4   2021-04-29T00:00:00  10.5
# 5   2021-04-30T00:00:00  10.0

A: Possible solutions to your question
You could read a documentation here: https://www.activestate.com/resources/quick-reads/how-to-save-a-dataframe/
or you could try this code
d = {'Textbook': [{'Type': 'Chapters', 'Case': 'Ch09', 'Rates':
[{'Date': '2021- 04-23T00:00:00', 'Rate': 10.0}, {'Date': '2021-04-26T00:00:00', 'Rate': 10.0},
{'Date': '2021-04-27T00:00:00', 'Rate': 10.5}, {'Date': '2021-04-28T00:00:00', 'Rate': 10.5},
{'Date': '2021-04-29T00:00:00', 'Rate': 10.5}, {'Date': '2021-04-30T00:00:00', 'Rate': 10.0}]}]}

pd.DataFrame(d.get('Textbook')[0].get('Rates'))

Code doesn't work? Please comment below.. any other questions, I'll be glad to talk.


text:
Q: Custom labels and custom labels deployments How to use custom labels in apex any syntax??
I have created more than 100 custom labels on my developer sandbox and added a translation text. when I create a change-set, add the custom labels to the change-set and deploy on production, only english text is deployed but translation text are not deployed.
Please let me know is there a better method to do this?

A: When using change sets, translations are specified through Language Translation. Any translations you have set for Custom Labels, Custom Objects, Custom Fields, etc. in the Change Set will automatically be sent along for the languages you select:

When using a package based Metadata api deployment, the translations for Custom Labels are under translations, as opposed to custom object translations.

A: *

*How to use custom labels in apex any syntax??
Try Label.**YourLabelName**. Refer using custom labels.

*Deploy translations
You can do it by change set itself. Add Language Transition for doing that. When you deploy please make sure that both the language translation and the component being translated must be included in the change set. Refer deploy translations


text:
Q: MS Access VBA & SQL Server - ODBC Call Failed on .Update of Recordset I have an MS Access application that I'm converting to SQL Server Backend (still Access FE), with SQL Server Management Studio (SSMS).
The application stores HR information and there is a function that is supposed to build probation schedule due dates based on employment date and probation period.
Here's the function:
Private Sub BtnBuildSked_Click()
    Const SUB_NAME As String = "BtnBuildSked_Click"
    On Error GoTo ErrCond
    Dim ThisReport, myresponse, MyStyle As Integer
    Dim MYDB As Database
    Dim Myrst, PdRec As DAO.Recordset
    'Dim Myfrm As Form
    Dim PdStr As String
    Dim s, strsql As String
    Dim t As TTracking

    If Me.PaysrID.Value = "ON LEAVE" Then
        MsgBox ("Record is marked ON LEAVE. Cannot proceed.")
        Exit Sub
    End If

    'Set Myfrm = Screen.ActiveForm
    Set MYDB = CurrentDb
    s = "SELECT * FROM tblProbationReports"
    Set Myrst = MYDB.OpenRecordset(s, dbOpenDynaset, dbSeeChanges)
    MyStyle = vbOKOnly + vbExclamation

    If IsNull(Me.PaysrID) Then
        MsgBox ("Cannot process for empty Employee ID")
        Exit Sub
    End If

    If (IsNull(Me.ApptDate)) Then
        myresponse = MsgBox("Appointment Date field is empty ", vbCritical)
        Exit Sub
    End If

    '----- Check that Probation Term ID is not blank
    If (Me.ProbationTermId.Value < 1 Or Me.ProbationTermId.Value > 7 Or IsNull(Me.ProbationTermId)) Then
        myresponse = MsgBox("You must select a probationary period to be able to build a schedule", MyStyle)
        Exit Sub
    End If

    '----- Warning that any existing records for this employee will be deleted
    myresponse = MsgBox("Warning!! This will delete any current probation schedule records for this Employee and Line No. combination. Do you want to proceed  ?", vbYesNo)
    Debug.Print myresponse
    If myresponse = 7 Then
        Exit Sub
    End If

    '------ Delete previous Probationary records for employee ; Keys = SS# and Line#
    strsql = "DELETE tblProbationReports.* " & _
             "FROM tblProbationReports " & _
             "WHERE tblProbationReports.LineNo= '" & Me.LineNo & "' and tblProbationReports.PaysrID = '" & Me.PaysrID & "' "

    DoCmd.SetWarnings False
    DoCmd.RunSQL (strsql)
    DoCmd.SetWarnings True

    '----- Point to the approp recoird in Probation Data
    PdStr = "SELECT * " & _
            "FROM [tblProbationData] " & _
            "WHERE [ProbationTermID] = " & Me.ProbationTermId.Value

    'Set PdRec = MYDB.OpenRecordset("SELECT * FROM [tblProbationData] WHERE [ProbationTermID] = & me.ProbationTermID.Value & ")
    Set PdRec = MYDB.OpenRecordset(PdStr)
    If Not PdRec.EOF Then
        For ThisReport = 1 To PdRec("ProbationReports")

        'With Myrst
            Myrst.AddNew
            Myrst.Fields("LineNumber") = Me.LineNo
            Myrst.Fields("SSNO") = Me.SSNo
            Myrst.Fields("PaysrID") = Me.PaysrID
            Myrst.Fields("ReportNo") = ThisReport
            Select Case ThisReport
                Case 1
                    Myrst.Fields("FromDate") = Me.ApptDate
                    Myrst.Fields("ToDate") = Me.ApptDate + (PdRec("Report1weeks") * 7) '-1
                    Myrst.Fields("DueDate") = Me.ApptDate + (PdRec("Report1weeks") * 7) - 1 - 14
                    Myrst.Fields("SentDate") = Me.ApptDate + (PdRec("Report1weeks") * 7) - 1 - 28
                Case 2
                    Myrst.Fields("FromDate") = Me.ApptDate + (PdRec("Report1weeks") * 7)
                    Myrst.Fields("ToDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks")) * 7) '- 1
                    Myrst.Fields("DueDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks")) * 7) - 1 - 14
                    Myrst.Fields("SentDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks")) * 7) - 1 - 28
                Case 3
                    Myrst.Fields("FromDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks")) * 7)
                    Myrst.Fields("ToDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks")) * 7) '- 1
                    Myrst.Fields("DueDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks")) * 7) - 1 - 14
                    Myrst.Fields("SentDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks")) * 7) - 1 - 28
                Case 4
                    Myrst.Fields("FromDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks")) * 7)
                    Myrst.Fields("ToDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks")) * 7) '- 1
                    Myrst.Fields("DueDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks")) * 7) - 1 - 14
                    Myrst.Fields("SentDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks")) * 7) - 1 - 28
                Case 5
                    Myrst.Fields("FromDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks")) * 7)
                    Myrst.Fields("ToDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks")) * 7) '- 1
                    Myrst.Fields("DueDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks")) * 7) - 1 - 14
                    Myrst.Fields("SentDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks")) * 7) - 1 - 28
                    Myrst.Fields("SentDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks")) * 7) - 1 - 42
                    Myrst.Fields("SentDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks")) * 7) - 1 - 56
                Case 6
                    Myrst.Fields("FromDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks")) * 7)
                    Myrst.Fields("ToDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks") + PdRec("Report6weeks")) * 7) '- 1
                    Myrst.Fields("DueDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks") + PdRec("Report6weeks")) * 7) - 1 - 14
                    Myrst.Fields("SentDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks") + PdRec("Report6weeks")) * 7) - 1 - 28
                    Myrst.Fields("SentDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks") + PdRec("Report6weeks")) * 7) - 1 - 42
                    Myrst.Fields("SentDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks") + PdRec("Report6weeks")) * 7) - 1 - 56
                Case 7
                    Myrst.Fields("FromDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks")) * 7)
                    Myrst.Fields("ToDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks") + PdRec("Report6weeks")) * 7) '- 1
                    Myrst.Fields("DueDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks") + PdRec("Report6weeks")) * 7) - 1 - 14
                    Myrst.Fields("SentDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks") + PdRec("Report6weeks")) * 7) - 1 - 28
                    Myrst.Fields("SentDate") = Me.ApptDate + ((PdRec("Report1weeks") + PdRec("Report2weeks") + PdRec("Report3weeks") + PdRec("Report4weeks") + PdRec("Report5weeks") + PdRec("Report6weeks")) * 7) - 1 - 56
            End Select
            Myrst.Fields("Received") = False
            Myrst.Update

        'End With
        Next ThisReport

     End If

        'set up tracking manually
        t.Comment = "Build New Schedule"
        t.FieldName = "LineNo"
        t.ItemID = Me.LineNo
        t.NewValue = "New Schedule Built"
        t.OldValue = ""
        t.TableName = "tblProbationReports"
        t.TrackingType = TR_TYPE_NEW
        SaveTrans t

     Myrst.Close
     PdRec.Close

'Myfrm.SetFocus
Me.Recalc
MsgBox ("Probation dates created")

Exit Sub
ErrCond:
    EventLogging AppSession.UserName, MSG_TYPE_ERROR, Err.Number, Err.Description, MOD_NAME & "." & SUB_NAME, AppSession.AppSilent
End Sub

The first several blocks are checks for properly formatted employeeID, and active status.
Code warns that any new schedule will delete previous values.
Then the application is supposed to build the new schedule based on probation period (the various Case statements) and employment date.
But when the code drops to .Update, it fails with "ODBC Call Failed".
Here's a rundown of notes and troubleshooting thus far:

*

*Nothing wrong with the connection to the BE. I'm able to create, update, and delete employee records without issue. I can see data in the tables when opening via Access FE. I can run reports.

*"Probation Reports" table did not have a primary key, which I needed to add in order to create Audit triggers in SSMS (I know table should have primary key, but I wasn't the original developer).

*I made "RecordID" Primary Key in "Probation Reports" table and made it "Identity" in order to increment the unique identifier automatically.

*When making RecordID "Identity" to increment sequentially in SSMS, Access errored out on Recordset.Open of "Probation Reports" ... "table with identity needs dbSeeChanges on open of Recordset"

*Trying Recordset.Open ("name", ,dbSeeChanges) still errored out, "table with identity needs dbSeeChanges on open of Recordset". Access was not reading "dbSeeChanges" Option value

*I needed to add an open "Type" (although optional) in order for Access to read the open "Options" value of "dbSeeChanges".

*I've tried every value for Open "Type" learn.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/database-openrecordset-method-dao  (even ones that didn't make sense). This is where the .Update breaks with "ODBC Connection Failed"

*I tried adding LockEdit value option of "dbOpenOptimistic" and still getting the "ODBC Call Failed" error ...
I'm at a loss of where to go from here...

UPDATE - based on feedback in comments, I tried adding values to the table directly and received the following error (screenshot)

A: To define recordsets (both in access, and when using sql server).
Dim rst      AS DAO.Reocdset

you can leave out the DAO. but you should not.
For ANY linked sql server table?
That table MUST have a PK defined. If you open the access linked table in design mode (ignore the ready only warning), then check TWO things:
First, be 100% if not 200% sure you see a PK defined.
Second: while you at this, check the data types for datetime columns. If they are text in place of date time, you MUST STOP NOW and fix that issue.
If the datetime columns are seen as text, then  you have two choices:
Change the sql server column data types from datetime2 (the new default) to datetime and then re-link tables. Now check again with table in design as per aobve - check the column data types.
You can also consider installing the newer ODBC Native 11 or later drivers - they support datetime2 - the built in legacy ODBC driver does NOT!!! - it see those columns as text. But, the downside is that you have to install the native 11 (or later driver - now at verison 17) on EACH workstation. So, it up to you which is less hassle (install native drivers on each workstation, or flip the sql server column times back to datetime and NOT use datetime2).
Next issue.
Access open a table:
Dim  rst   AS DAO.RecordSet

set rst = currentdb.OpenReocrdSet(" table name or sql goes here")

Access open a linked table to sql server.
   Dim rst             As DAO.Recordset
   Dim strSQL          As String

   strSQL = "SELECT * FROM tblInvoice where InvoiceNum = " & InvoiceNumber

   Set rst = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset, dbSeeChanges)

So, you ALWAYS include dbOpenDynaset, dbSeeChanges
If you just done a access to sql server migration? Then I find EVEN in a relative large application, using global search and replace, (with ,dbOpenDynaset,dbSeeChanges in my paste buffer? It should not take more then say about 5 minutes of time. so go change all VBA reocrdset code that NOW operates on linked tables.
So, you have to add/have/include the two extra parms on recordset open like this:
Set rst = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset, dbSeeChanges)

A few more got ya's
All bit fields MUST HAVE a default value set (say 0) for false in the sql server table designs.
If you are receiving the dreaded "someone else has updated" the record errors? Then you need to add a timestamp column to that table (do NOT confusing timestamp with a date time - the timestamp is what we call a row-version column - has zero to do with date-time, and you never touch or edit or change that row-version column.

A: The culprit is/was actually one of the fields in this db (and subsequent code above): "LineNo"
"LineNo" is a RESERVED WORD in SQL Server.
After implementing all sorts of suggestions, this one crept up from ....I don't even remember where but here's an article of reserved words in SQL Server for future reference for others:
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql?view=sql-server-ver15
Changing ALL references to this field from "LineNo" to "LineNum" resolved all errors.


text:
Q: Why am I getting this LINQ error inside my api controller? I'm working on an ASP.NET Core app primarily using Razor Pages updated from 2.2 to 3.0 trying to implement jQuery Autocomplete on a textbox
Inside my api controller there is a search method which searches for a user's Full Name given letters entered in a textbox. When testing with postman, I get this exception:

The LINQ expression 'Where<>(\r\n    source: DbSet<>, \r\n
  predicate: (i) => i.FullName.ToUpper().Contains((Unhandled parameter:
  __ToUpper_0)))' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly
  by inserting a call to either AsEnumerable(), AsAsyncEnumerable(),
  ToList(), or ToListAsync()

Note I use a different name than <user>
Is the LINQ query wrong in some way or did I miss something when upgrading from .NET Core SDK 2.2 to 3.0?
API Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using <project name>.Data;
using <project name>.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace <project name>.Controllers
{

    [Route("api/[controller]")]
    [ApiController]
    public class SearchUserController : ControllerBase
    {
        // instance variables

        private readonly UserManager<<user>> _userManager;
        public SearchUserController(UserManager<<user>> userManager)
        {

            _userManager = userManager;
        }
        [Produces("application/json")]
        [HttpGet("Search")]
        public async Task<IActionResult> Search()
        {
            try
            {
                string term = HttpContext.Request.Query["term"].ToString();
                //var userFound = await _userManager.Users.FirstOrDefaultAsync(t => t.FullName.Contains(term));

                var UserList = await _userManager.Users
                    .Where(u => u.FullName.ToUpper().Contains(term.ToUpper()))
                    .OrderBy(u => u.FullName)
                    .ToListAsync();
                return Ok(UserList);
            }
            catch (Exception ex)
            {
                return BadRequest();
            }
        }
    }
}

Here is the ConfigureServices and Configure methods from Startup.cs
// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<InTandemUser, IdentityRole>(config =>
            {
                config.SignIn.RequireConfirmedEmail = false;
            })
                .AddDefaultUI()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
            services.AddTransient<IEmailSender, EmailSender>();
            services.Configure<AuthMessageSenderOptions>(Configuration);
            services.AddControllers();
            // deprecated code
            /*services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            }).AddRazorPagesOptions(options =>
            {
                options.Conventions.AddPageRoute("/Events/Index", "");
            });*/
            services.AddRazorPages()
                .AddRazorPagesOptions(options =>
            {
                options.Conventions.AddPageRoute("/Events/Index", "");
            });
            services.AddSession();
            services.AddScoped<IAuthorizationHandler, RegisterAuthorizationHandler>();
            services.AddScoped<IAuthorizationHandler, ManagerAuthorizationHandler>();

            services.AddScoped<UserService>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            CreateRoles(serviceProvider).Wait();

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseAuthentication();
            app.UseSession();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });
        }

Thanks in advance for the help!
EDIT: After removing .ToUpper I had to work on it giving me an error for using .Contains and wrote this code referring to here
        public async Task<IActionResult> Search()
        {
            try
            {
                string term = HttpContext.Request.Query["term"].ToString();
                var users = await (from u in _userManager.Users
                                      select u).ToListAsync();

                if (!String.IsNullOrEmpty(term))
                {
                    users = users.Where(u => u.FullName.Contains(term)).ToList();
                }
                return Ok(users);
            }
            catch (Exception ex)
            {
                return BadRequest();
            }
        }

Any way to make users = users.Where(u => u.FullName.Contains(term)).ToList(); async?


text:
Q: Apppend and Delete Rows to Grid with GridTableBase I am having trouble appending and deleting rows. My table changes a lot and must be rebuilt often so this has been a little tricky. All of my information comes from an SQL database. I am loading the results into a pandas DataFrame and then using it to populate the GridTableBase class. I am now trying to Append and Delete rows, but am having trouble overriding the class. I have been able to somewhat get it to work, but it behaves weird. For some reason, self.table.AppendRows(row) doesn't work and throws an error. The original was self.table.AppendRow(row), but AppendRow isn't a method. So I had to use a different method. I have to change a value in order to get the GridTableMessage to realize there has been a change, which is what I am doing here data.iloc[data.shape[0]-1,0] = str(val)
Ideally, I would add/delete the row from the table itself, but I can't figure out how to do that. I have derived most of my code from here https://github.com/wxWidgets/Phoenix/blob/master/demo/Grid_MegaExample.py but a lot of that will not work properly for me.
As of now, I can append a row, but for some reason, it appends 2 even though only one has been added to the DataFrame and GetNumberRows is returning the correct count. I assume it has something  to do with the way I am accessing the table class. Can anyone provide some clarity?
def rowPopup(self, row, evt):
        """(row, evt) -> display a popup menu when a row label is right clicked"""
        appendID = wx.Window.NewControlId()#wx.NewId()
        deleteID = wx.Window.NewControlId()#wx.NewId()
        x = self.GetRowSize(row)/2
        if not self.GetSelectedRows():
            self.SelectRow(row)
        menu = wx.Menu()
        xo, yo = evt.GetPosition()
        menu.Append(appendID, "Append Row")
        menu.Append(deleteID, "Delete Row(s)")

        def append(event, self=self, row=row):#event, self=self, row=row
            global data
            #print("Append")
            #self.table.AppendRows(row)
            dlg = wx.TextEntryDialog(self,'Enter a new Key ID to insert into the ' + str("'") + data.columns[0] + str("'") + ' column.', 'Insert New Record')
            dlg.SetValue("")
            if dlg.ShowModal() == wx.ID_OK:
            #print('You entered: %s\n' % dlg.GetValue())
                val = dlg.GetValue()
                #data[~pd.isnull(data).all(1)].fillna('')
                #data['tables_id'].apply('(g)'.format)
                data.loc[data.iloc[-1].name + 1,:] = ""
                data.iloc[data.shape[0]-1,0] = str(val)
                self.Reset()
                #print(data)
            #data = data.append(pd.Series(dtype='object'), ignore_index=True)
            #self.data = DataTable(data)
            #data[~pd.isnull(data).all(1)].fillna('')
            #self.data = DataTable(data)

        def delete(event, self=self, row=row):#event, self=self, row=row
            global data

            rows = self.GetSelectedRows()
            data.drop(data.index[rows],inplace=True)
            print (data)
            self.Reset()

            #self.table.DeleteRow(row)
            #print(row)
            #print(rows)

        #EVT_MENU(self, appendID, append)
        #EVT_MENU(self, deleteID, delete)
        self.Bind(wx.EVT_MENU, append, id=appendID)
        self.Bind(wx.EVT_MENU, delete, id=deleteID)
        self.PopupMenu(menu, wx.Point(round(x), round(yo)))
        menu.Destroy()

class DataTable(gridlib.GridTableBase):
    def __init__(self, data):

        gridlib.GridTableBase.__init__(self)
        self.headerRows = 1
        if data is None:
            data = pd.DataFrame()
        self.data = data
        print("Instance")
        #Store the row and col length to see if table has changed in size
        self._rows = self.GetNumberRows()
        self._cols = self.GetNumberCols()

        self.odd=gridlib.GridCellAttr()
        self.odd.SetBackgroundColour((217,217,217))
        self.even=gridlib.GridCellAttr()
        self.even.SetBackgroundColour((255,255,255))

    def GetAttr(self, row, col, kind):
        attr = [self.even, self.odd][row % 2]
        attr.IncRef()
        return attr

    def GetNumberRows(self):
        #print("# Rows:",len(self.data))
        return len(self.data)# - 1

    def GetTypeName(self, row, col):
        #print(wx.grid.GRID_VALUE_STRING)
        return wx.grid.GRID_VALUE_STRING

    def GetNumberCols(self):
        #print("# Cols:",len(self.data.columns)+ 1)
        return len(self.data.columns) + 1
        #return len(self.data.columns) #+ 1

    def IsEmptyCell(self, row, col):
        return False

    def GetValue(self, row, col):
        if col == 0:
            try:

                return self.data.index[row]

            except:
                print("Row,Col(",row,col,")","OOB")
                return ""
        else:
            try:

                return str(self.data.iloc[row, col - 1])

            except:
                print("Row,Col(",row,col,")","OOB")
                return ""

    def GetColLabelValue(self, col):
        if col == 0:
            if self.data.index.name is None:
                return 'Index'
            else:
                return self.data.index.name
        return self.data.columns[col - 1]

    def ResetView(self, grid):
        """
        (wxGrid) -> Reset the grid view.   Call this to
        update the grid if rows and columns have been added or deleted
        """
        print('Old::' , self._rows, self._cols)
        print('New::' , self.GetNumberRows(),self.GetNumberCols())
        print(data)

        grid.BeginBatch()
        for current, new, delmsg, addmsg in [
            (self._rows, self.GetNumberRows(), gridlib.GRIDTABLE_NOTIFY_ROWS_DELETED, gridlib.GRIDTABLE_NOTIFY_ROWS_APPENDED),
            (self._cols, self.GetNumberCols(), gridlib.GRIDTABLE_NOTIFY_COLS_DELETED, gridlib.GRIDTABLE_NOTIFY_COLS_APPENDED),
        ]:

            if new < current:
                msg = gridlib.GridTableMessage(self,delmsg,new,current-new)
                #grid.ProcessTableMessage(msg)
                self.GetView().ProcessTableMessage(msg)
                print("OvN:",self._rows,self.GetNumberRows())
                return True
            if new > current:
                msg = gridlib.GridTableMessage(self,addmsg,new-current)
                self.GetView().ProcessTableMessage(msg)
                grid.ProcessTableMessage(msg)
                #self.UpdateValues(grid)

                msg = gridlib.GridTableMessage(self, gridlib.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
                grid.ProcessTableMessage(msg)
                print("OvN:",self._rows,self.GetNumberRows())
        grid.EndBatch()

        self._rows = self.GetNumberRows()
        self._cols = self.GetNumberCols()
        # update the column rendering plugins
        #self._updateColAttrs(grid)

        # XXX
        # Okay, this is really stupid, we need to "jiggle" the size
        # to get the scrollbars to recalibrate when the underlying
        # grid changes.
        h,w = grid.GetSize()
        grid.SetSize((h+1, w))
        grid.SetSize((h, w))
        grid.ForceRefresh()

        def UpdateValues(self, grid):#self, grid
            """Update all displayed values"""
            # This sends an event to the grid table to update all of the values
            msg = gridlib.GridTableMessage(self, gridlib.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
            grid.table.ProcessTableMessage(msg)

class DataGrid(gridlib.Grid):
    def __init__(self, parent, data, lc, tc): # data
        gridlib.Grid.__init__(self, parent, - 1) #,colnames,-1 # data

        self.lc = lc
        self.tc = tc
        self.table = DataTable(data)

        self.SetTable(self.table, True)
        self.Bind(gridlib.EVT_GRID_LABEL_RIGHT_CLICK, self.OnLabelRightClicked)
        self.Bind(gridlib.EVT_GRID_CELL_RIGHT_CLICK, self.OnCellRightClick)
        self.Bind(gridlib.EVT_GRID_CELL_CHANGED, self.onCellChanged) #wx.grid

    def Reset(self):
        """reset the view based on the data in the table.  Call
        this when rows are added or destroyed"""
        self.table.ResetView(self)

    def OnCellRightClick(self, event):
        print ("OnCellRightClick: (%d,%d)\n" % (event.GetRow(), event.GetCol()))

    def OnLabelRightClicked(self, evt):
        row, col = evt.GetRow(), evt.GetCol()
        if row == -1: print("col")#self.colPopup(col, evt)
        elif col == -1: self.rowPopup(row, evt)

    def rowPopup(self, row, evt):
        """(row, evt) -> display a popup menu when a row label is right clicked"""
        appendID = wx.Window.NewControlId()#wx.NewId()
        deleteID = wx.Window.NewControlId()#wx.NewId()
        x = self.GetRowSize(row)/2
        if not self.GetSelectedRows():
            self.SelectRow(row)
        menu = wx.Menu()
        xo, yo = evt.GetPosition()
        menu.Append(appendID, "Append Row")
        menu.Append(deleteID, "Delete Row(s)")

        def append(event, self=self, row=row):#event, self=self, row=row
            global data
            #print("Append")
            #self.table.AppendRows(row)
            dlg = wx.TextEntryDialog(self,'Enter a new Key ID to insert into the ' + str("'") + data.columns[0] + str("'") + ' column.', 'Insert New Record')
            dlg.SetValue("")
            if dlg.ShowModal() == wx.ID_OK:
                val = dlg.GetValue()
                #data[~pd.isnull(data).all(1)].fillna('')
                #data['tables_id'].apply('(g)'.format)
                data.loc[data.iloc[-1].name + 1,:] = ""
                data.iloc[data.shape[0]-1,0] = str(val)
                self.Reset()
                #print(data)
            #self.data = DataTable(data)

        def delete(event, self=self, row=row):#event, self=self, row=row
            global data

            rows = self.GetSelectedRows()
            data.drop(data.index[rows],inplace=True)
            print (data)
            self.Reset()

        self.Bind(wx.EVT_MENU, append, id=appendID)
        self.Bind(wx.EVT_MENU, delete, id=deleteID)
        self.PopupMenu(menu, wx.Point(round(x), round(yo)))
        menu.Destroy()
class MainFrame(wx.Frame):
    def __init__(self, parent, data): # (self, parent, data):
        wx.Frame.__init__(self, parent, -1, "Varkey Foundation") #, size=(640,480))
        #Create a panel
        self.p = wx.Panel(self)
        self.Maximize(True)

        #Create blank dataframe
        data = pd.DataFrame() #pd.DataFrame(np.random.randint(0,100,size=(200, 5)),columns=list('EFGHD')
        #data.reset_index(drop=True, inplace=True)
        self.data = DataTable(data)

        self.nb = wx.Notebook(self.p)
        self.p.SetBackgroundColour( wx.Colour( 0, 0, 0 ) ) # 38,38,38
        self.nb.SetBackgroundColour(wx.Colour(58, 56, 56) )
        #self.SetBackgroundColour( wx.Colour( 255, 255, 56 ) )

        #create the page windows as children of the notebook
        self.page1 = PageOne(self.nb)
        self.page2 = PageTwo(self.nb)
        self.page3 = PageThree(self.nb)

        # add the pages to the notebook with the label to show on the tab
        self.nb.AddPage(self.page1, "Data")
        self.nb.AddPage(self.page2, "Analyze")
        self.nb.AddPage(self.page3, "Change Log")

        #CreateFonts
        self.b_font = wx.Font(14,wx.ROMAN,wx.NORMAL,wx.BOLD, True)
        self.lbl_font = wx.Font(14,wx.ROMAN,wx.NORMAL,wx.NORMAL, True)
        self.cb_font = wx.Font(11,wx.SCRIPT,wx.ITALIC,wx.NORMAL, True)
        self.h_font = wx.Font(18,wx.DECORATIVE,wx.ITALIC,wx.BOLD, True)

        #Create username textcontrol <<<<<<<<<<<< Passed to grid class
        self.tc_user =wx.TextCtrl(self.p,value='cmccall95',size = (130,25))
        self.tc_password =wx.TextCtrl(self.p,value='Achilles95', style=wx.TE_PASSWORD | wx.TE_PROCESS_ENTER,size = (130,25))
        self.tc_password.Bind(wx.EVT_TEXT_ENTER,self.onLogin)
        self.tc_user.SetFont(self.cb_font)
        self.tc_password.SetFont(self.cb_font)

        #Create Change log lstCtrl <<<<<<<<<<<< Passed to grid class
        self.lc_change = wx.ListCtrl(self.p,-1,style = wx.TE_MULTILINE | wx.LC_REPORT | wx.LC_VRULES)
        self.lc_change.InsertColumn(0,"User ID")
        self.lc_change.InsertColumn(1,"Status")
        self.lc_change.InsertColumn(2,"Description")
        self.lc_change.InsertColumn(3,"Date/Time")
        #Set column widths
        self.lc_change.SetColumnWidth(0, 75)
        self.lc_change.SetColumnWidth(1, 75)
        self.lc_change.SetColumnWidth(2, 450)
        self.lc_change.SetColumnWidth(3, 125)

        #Create the grid and continue layout
        self.grid = DataGrid(self.page1, data, self.lc_change, self.tc_user)

#More layout code...

def onLoadNewData(self, event): #This is how I'm replacing the data in my table class
        global data

        self.Freeze()
        if self.combo_table.GetValue():
            #Connect to db
            self.connect_mysql()

            #Determine db table
            self.getTable()

            #Get new data
            sql_query = "SELECT * FROM " + tbl
            self.cursor.execute(sql_query)
            temp = pd.read_sql(sql_query, con=self.db_con)
            temp.reset_index(drop=True, inplace=True)
            data = temp[~pd.isnull(temp).all(1)].fillna('')

            #Create title #if data:
            if not data.empty:
                self.title.SetLabel(str(self.combo_table.GetValue()))
                print(str(self.combo_table.GetValue()))
                self.grid.Destroy()
                self.grid = DataGrid(self.page1, data, self.lc_change, self.tc_user)
                #self.grid.HideCol(0)
                self.grid.AutoSizeColumns()

                #Insert grid into existing sizer
                self.p1_sizer.Insert(1,self.grid,1,wx.RIGHT| wx.LEFT|wx.EXPAND, 20)
                self.p1_sizer.Layout()
            #RESIZE
            else:
                print("Error:Dataframe is empty")
            self.close_connection()
        else:
            print('CANT BE BLANK')
        self.Thaw()

if __name__ == '__main__':
    import sys
    app = wx.App()
    frame = MainFrame(None, sys.stdout) # (None, sys.stdout)
    frame.Show(True)
    app.MainLoop()


text:
Q: Keyboard shortcut in VSCode for Markdown links? from other text editors I'm used to adding Markdown links by

*

*selecting the word I want to be linked,

*pressing cmd-K on my Mac's / iPad Pro's keyboard, which puts square brackets around the marked word, appends a pair of normal parenthesis () and places the cursor right in beetween those two parenthesis so that I can

*just paste the URL I have in my clipboard into the right place by pressing cmd-V.

So, select -> cmd-K -> cmd-V is a nice and short sequence for adding links in a Markdown document and cmd-K has become some kind of pseudo standard for adding links in several writing apps.
However, in VSCode that's not possible. But I'd love to make it possible. Any ideas? cmd-K is (hard-wired?) bound to listen for a next key press.
But it doesn't have to be cmd-K. I can learn another keystroke. But I need to be able to put additional text (square brackets and parenthesis) into the text and move the cursor to the right position. How's that done?
Thanks so much!

A: This extension Markdown All In One looks like it does what you want in one step.

Paste link on selected text

Just select your link and hit Ctrl+V and it creates the link and inserts the clipboard link.
If for some reason you don't want to use this extension, it would be pretty easy to create a snippet to do what you want.

A: Adding another answer that doesn't use the extension Markdown All In One I mentioned in the other answer and because a couple of commenters requested a different way.  @MarcoLackovic

*

*First Method: keybinding in keybindings.json, then manually paste

{
  "key": "alt+w",                  // use whatever keybinding you wish
  "command": "editor.action.insertSnippet",
  "args": {
    "snippet": "[${TM_SELECTED_TEXT}]($0)"
  },
  "when": "editorHasSelection && editorLangId == markdown "
}

Select the link text and, trigger your keybinding - the cursor will be placed where you want it and paste.

*

*Second Method: use a macro to insert the snippet and paste in one step

You will need a macro extension like multi-command to run multiple commands in series.  Then this keybinding:
{
  "key": "alt+w",
  "command": "extension.multiCommand.execute",
  "args": {
    "sequence": [
      {
        "command": "editor.action.insertSnippet",
        "args": {
          "snippet": "[${TM_SELECTED_TEXT}]($0)"
        }
      },
      "editor.action.clipboardPasteAction"
    ]
  },
  "when": "editorHasSelection && editorLangId == markdown "
}

Demo of second method:


text:
Q: Fontcustom Less template to generate custom icon fonts Im looking for a fontcustom template to generate less, rather than scss. Are there any out there?
http://fontcustom.com/

A: You can use the CSS template (By default, Font Custom will generate css and preview files for you.) and import that into your Less project.
Save the CSS templates as yourfont.css and than in your Less code:
@import (css) "yourfont.css";

See also: http://lesscss.org/features/#import-directives-feature


text:
Q: Is there a way to jump back and forth between the header and the source file in Android Studio? If I'm in the header, I'd like to switch to the source, and vice versa. Something like the XCode keyboard shortcut Ctrl + Cmd + up arrow (I'm on Mac).
Thanks!


text:
Q: If Then Else Statements I am trying to translate the below statement into Python but struggle with a reoccuring error.
hours = input (prompt1)
        ^
IndentationError: expected an indented block

A worker gets paid an hourly wage, when working up to 40 hours per week. When the time at work goes above 40 hours in a week, the worker is being paid overtime rate, which is 1.5 times the hourly wage. Given the hours worked per week, and the hourly wage, compute the weekly salary of the worker.
prompt1 = 'How many hours did you work?\n'

try:
hours = input (prompt1)

prompt2 = 'What is your hourly rate?\n'

rate = input (prompt2)

hours = float(hours)

rate = float(rate)

print float(hours) * float(rate*1.5)

except:
print('Error, Please enter a number')

I really appreciate your help.

A: In Python there are no {} or begin +end it works using identation. You code should look like:
prompt1 = 'How many hours did you work?\n'

try:
   hours = input (prompt1)
   prompt2 = 'What is your hourly rate?\n'
   rate = input (prompt2)
   hours = float(hours)
   rate = float(rate)
   if(hours > 40):
      rate = rate * 1.5
   print float(hours) * float(rate*1.5)

except:
   print('Error, Please enter a number')


text:
Q: How the socket server knows the client transform data over In the socket level, when the connection is built, the server will continue read data from the socket,  my question is how the server  will knows the client won't send any data?

A:
how the server will knows the client won't send any data

It doesn't. One option is to scan for pre-agreed-upon "end of message" byte sequence. When server sees this byte sequence, it considers message fully received. If there's more data in the buffer, it belongs to another message.
Or the client must advertise its message length ahead of time. "I'm going to send you X bytes now. Here they are: ..." The server then reads only X bytes from the socket and considers message fully received.
Take a look at redis protocol for an example of the second scheme. It's very simple and fully functional. It is so simple, in fact, that a full client can be implemented in only 20 lines of ruby.


text:
Q: IntelliJ Idea: Red lines in dependency viewer I started experimenting with the different diagram views that intellij offers and stumbled upon the dependency view. In one of my projects I've encountered that besides the blue arrows indicating dependencies there are some dependencies that are shown using a red line. What is IntelliJ trying to tell me here. Does it hint at a possible or maybe definite issue?

A: It looks like dependencies with a red line are conflicting or unsatisfied dependencies.
There is any explanation here.
https://www.jetbrains.com/help/idea/2016.3/working-with-maven-dependencies.html
I was just looking at one of my projects and it looks like I have Guava conflict. I am bringing in version 15 but Guice is bringing in version 16.0.1. Need to fix that.


text:
Q: Can I do RegAsm of .Net2 dll with .Net4 RegAsm.exe? Can I do RegAsm to a .NET 2 dll with .Net4 RegAsm.exe?
I have only .NET 4 installed on my machine and I need to do RegAsm to a .NET 2 file.

A: Yes, you can. The RuntimeVersion value written to the registry will be set according to the CLR header (that is, even if you register the 2.0 DLL with 4.0 RegAsm, it will 'know' that it's a 2.0 DLL and register it accordingly).


text:
Q: IPTables Block IP specific IP addresses I have been searching  for hours to find a solution to this question, so I apologize if its already been answered..  I have a strong Pix/ASA background, and I am getting lost with iptables...
I am running DD-WRT on a linksys router.  I have the DD--WRT "WAN" port plugged into my LAN so its external IP address is on my internal network and uses my normal gateway as its egress.  The WiFi is setup essentially as a guest network which I do not want to be able to access my internal network.  But in its current configuration, all traffic is passed through the Wifi vlan/network to the WAN interface so the "guests" can scan/access my internal network since my "internal" is on the DD-WRT's WAN interface.
I want to apply an IPTables rule (or other type of rule) to prevent communication to every IP address other than my Internal networks gateway (which is the DD-WRT's External egress).
DD-WRT's Internal Network (linksys routers WAN) = eth0 192.168.1.1/24 gw: 192.168.1.2
WiFi = ath0 Subnet 192.168.200.2/24  (only have 1 interface (2.4ghz) enabled on this for "guest" access)
Does anyone have a recommendation for how to apply an IP tables rule to prevent all communication from ath0 to eth0 with a source of 192.168.200.0/24 to IP addresses 192.168.1.3 - 192.192.168.1.255?
Any advice would be greatly appreciated...
Thank you!

A: I was re-reading my question after posting to make sure it was accurate and came up with an idea...  It worked.
I adjusted the DD-WRT's external interfaces Subnet mask to a /30 or 255.255.255.252 so all of its external traffic would be sent to its egress and be dropped/ignored...
The DD-WRT WAN/External interface is now configured with
Address: 192.168.1.1
Netmask: 255.255.255.252 = 30
Wildcard = 0.0.0.3
Network = 192.168.1.0/30
Broadcast = 192.168.1.3
First IP = 192.168.1.1
Last IP = 192.168.1.2
Usable hosts = 2
(source: https://www.adminsub.net/ipv4-subnet-calculator )
While this is not using ANY IPTable rules, this will work for what I am trying to accomplish since communication from the external IP on the DD-WRT router will be sent to the wrong IP address (aka: bit bucket) for anything going to my actual internal network.
Keep in mind that this will NOT prevent communication to other subnets/vlans that your main/internal router can communicate/route to (Ex: DMZ, VPN, etc).  With that said (and since I didn't mention it) I just added FW rules to prevent communication from the DD-WRT's external IP (192.168.1.1) to those networks and now the only networks my "guests" can access are in the public IP space.
While I figured it out on my own I am going to keep this post active incase anyone else can benefit from this solution since I was struggling for so long...
I welcome anyone to still post IPTable solutions since my solution may not be the best for everyone....


text:
Q: Setar dificuldade para uma questão e ao selecionar a dificuldade buscar somente aquelas questões Boa tarde!
Estou finalizando um Quiz em C# feito em Unity. A dúvida que tenho é, tenho várias questões que gero via um Asset. Porém eu preciso setar as dificuldades para cada uma das questões. E ao clicar no menu na dificuldade Fácil, quero que ele carregue somente aquelas questões que estão com a dificuldade selecionada. Porém ando tendo dificuldade. Vou colocar aqui o código da minha classe que cria a pergunta.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

[CreateAssetMenuAttribute]

public class QuizQuestion : ScriptableObject {
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    //Campos que receberão dados do arquivo .xml ou .json
    [SerializeField]
    private string pergunta;
    [SerializeField]
    private string[] respostas;
    [SerializeField]
    private int respostaCorreta;

    //Métodos para buscar as perguntas, opções, resposta correta e dificuldade
    public string Pergunta { get { return pergunta; } }
    public string[] Respostas { get { return respostas; } }
    public int RespostaCorreta { get { return respostaCorreta; } }

    //public int Dificuldade {  get { return dificuldade; } }

    public bool Asked { get; internal set; }

    //Validar a resposta
    private void OnValidate()
    {
        if (respostaCorreta > respostas.Length)
        {
            respostaCorreta = 0;
        }

       RenomearObjetoDeAcordoComPerguntaResposta();
    }

    private void RenomearObjetoDeAcordoComPerguntaResposta()
    {
        string desiredName = string.Format("{0} [{1}]",
            pergunta.Replace("?", ""),
            respostas[respostaCorreta]);

        string assetPath = AssetDatabase.GetAssetPath(this.GetInstanceID());
        string shouldEndWith = "/" + desiredName + ".asset";
        if (assetPath.EndsWith(shouldEndWith) == false)
        {
            Debug.Log("Want to rename to " + desiredName);
            AssetDatabase.RenameAsset(assetPath, desiredName);
            AssetDatabase.SaveAssets();
        }
    }
}

Agradeço desde já!

A: Tudo bem?
Você pode criar referência para as questões, com números, por exemplo. Vamos supor que na lista há 30 questões e estão divididos nas 3 dificuldades: fácil(1), médio(2) e difícil(3).
Então o jogador escolhe a dificuldade, logo (pseudo-código):
 \\aqui é a variavel que recebe a escolha da dificuldade
 int escolha_do_jogador = escolha;

  \\aqui analisa a escolha, no caso, a escolha é 1, logo, é a dificuldade facil.
 if(escolha do jogador == 1)
    {
       for(int i = 0; i <= 10;i++)
       {
          \\as questões faceis, neste caso, são as 10 primeiras da lista
          exibirQuestao = questao[i];
       }
    }
     \\dificuldade media
 if(escolha do jogador == 2)
    {
       for(int i = 0; i <= 10;i++)
       {
           \\aqui, a dificuldade media está de 10 a 20
          exibirQuestao = questao[i+10];
       }
    }
 if(escolha do jogador == 3)
    {
       for(int i = 0; i <= 10;i++)
       {
          \\aqui, a dificuldade esta no dificil, de 20 a 30
          exibirQuestao = questao[i+20];
       }
    }

É um código de exemplo, adapte seu código a esse pensamento.


text:
Q: ProcessStartInfo returning The directory name is invalid when invoking from SQL Job I have a SQL Job that's running on a DB Server and on one of the steps it calls an application server to run an exe "cmd Exec step type"
the exe application "C#" is invoked properly and does all its intended tasks, as a final step it runs cmd.exe to merge couple of files.
** When running the exe application manually, it's working as intended, but when invoking through SQL Job it's returning the below error:
Error in MergeFiles() Method : System.ComponentModel.Win32Exception (0x80004005): The directory name is invalid
   at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
   at System.Diagnostics.Process.Start()
   at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
   at _700CreditBillingScheduler.Billing700C.MergeFilesInPath()

Worth saying everything is running on E:\ drive
Here is my code:
    string filePath = "E:\\HomeFolder\\ApplicationFolder"; // where merged file will be created
    string sourcePath = "E:\\HomeFolder\\ApplicationFolder\\Transaction.Indiv.Files\\*.csv"; // to be merged
    string commandLine = String.Format("/c copy /b {0} {1}", sourcePath, "mergedFileName");
    var cmd = new ProcessStartInfo("cmd.exe", commandLine);
    cmd.WorkingDirectory = filePath;
    cmd.UseShellExecute = false;
    Process.Start(cmd);

A: Try to remove the line where you specify the working dir ?

A: I found the issue, it has to do with the UNC path.
The command was trying to merge the files on DB Server using the UNC path of the file, and UNC isn't supported through cmd.exe, so instead it ran on DB Server where the directory doesn't exist.
I switched to merge the files on application server using the C# application itself.


text: Q: has anyone figured out a way to use the back-facing camera on android in any browser with getusermedia? I can't seem to find the settings anywhere. I also tried searching the phone to set front-facing as default but had no luck. I'm using an xiaomi 1s if that helps.sorry ,my english is poor


text:
Q: Create new array basis on any key of current array I want to create Array basis on Key of idClient, Right now my array look like this :
Array
(
    [0] => Array
        (
            [idClient] => 101
            [Month] => 01
            [monthTotal] => 900.00
        )

    [1] => Array
        (
            [idClient] => 101
            [Month] => 02
            [monthTotal] => 100.00
        )

    [2] => Array
        (
            [idClient] => 102
            [Month] => 02
            [monthTotal] => 400.00
        )

    [3] => Array
        (
            [idClient] => 103
            [Month] => 03
            [monthTotal] => 300.00
        )

    [4] => Array
        (
            [idClient] => 103
            [Month] => 01
            [monthTotal] => 100.00
        )

    [5] => Array
        (
            [idClient] => 103
            [Month] => 02
            [monthTotal] => 200.00
        )

)

I want to create a new array in this way. please, Can anyone help me?
Array
(
    [101] => Array
        (
          [01] => 900.00
          [02] => 100.00
        )

    [102] => Array
        (
            [02] => 400.00
        )

    [103] => Array
        (
          [01] => 100.00
          [02] => 200.00
          [03] => 300.00
        )
)

Here: [101], [102] & [103] are idClient of array,
And [01], [02], [03] are Month number.
And 900, 100, 400 and so an amount of monthTotal according to the month number.

A: First Do array_column,To fetch only idClient
$ClientIds = array_unique(array_column($records, 'idClient'));//$records will be your array

Then Use this loop
foreach($ClientIds as $id){
    foreach($records as $row){
           if($id = $row['idClient']){
              $data[$id][$row['Month']] = $row['monthTotal'];
           }
    }
}
echo var_dump($data);die;

A: Input
$array = array
(
array
    (
        "idClient" => 101,
        "Month" => "01",
        "monthTotal" => "900.00",
    ),

array
    (
        "idClient" => 101,
        "Month" => "02",
        "monthTotal" => "100.00",
    ),

array
    (
        "idClient" => 102,
        "Month" => "02",
        "monthTotal" => "400.00",
    ),

array
    (
        "idClient" => 103,
        "Month" => "03",
        "monthTotal" => "300.00",
    ),

array
    (
        "idClient" => 103,
        "Month" => "01",
        "monthTotal" => "100.00",
    ),

array
    (
        "idClient" => 103,
        "Month" => "02",
        "monthTotal" => "200.00",
    )

);

PHP Script
$narray = array();
if ($array) {
foreach($array as $key => $value){
    if(!array_key_exists($value['idClient'],$narray)){
        $narray[$value['idClient']] = array();
    }
    $narray[$value['idClient']][$value['Month']] = $value['monthTotal'];
}
}
print_r($narray);

Output
Array
(
[101] => Array
    (
        [01] => 900.00
        [02] => 100.00
    )

[102] => Array
    (
        [02] => 400.00
    )

[103] => Array
    (
        [03] => 300.00
        [01] => 100.00
        [02] => 200.00
    )

)


text:
Q: How can I create a large file with random but sensible English words? I want to test my wordcount software based on MapReduce framework with a very large file (over 1GB) but I don't know how can I generate it.
Are there any tools to create a large file with random but sensible english sentences?
Thanks

A: A simple python script can create a Pseudo-random document of words. I have the one I wrote up for just a task a year ago:
import random

file1 = open("test.txt","a")
PsudoRandomWords = ["Apple ", "Banana ", "Tree ", "Pickle ", "Toothpick ", "Coffee ", "Done "]

index = 0
#Increase the range to make a bigger file
for x in range(150000000):
   #Change end range of the randint function below if you add more words
   index = random.randint(0,6)
   file1.write(PsudoRandomWords[index])
   if x % 20 == 0:
      file1.write('\n')`

Just add more words to the list to make it more random and increase the index of the random function. I just tested it and it should create a document named test.txt at exactly one gigabyte. This will contain words from the list in a random order separated by a new line every 20 words.

A: I wrote this simple Python script that scrape on Project Gutenberg site and write the text (encoding: us-ascii, if you want to use others see http://www.gutenberg.org/files/) in a local file text. This script can be used in combination with https://github.com/c-w/gutenberg to do more accurate filtering (by language, by author etc.)
from __future__ import print_function

import requests
import sys

if (len(sys.argv)!=2):
        print("[---------- ERROR ----------] Usage: scraper <number_of_files>", file=sys.stderr)
        sys.exit(1)

number_of_files=int(sys.argv[1])
text_file=open("big_file.txt",'w+')

for i in range(number_of_files):
    url='http://www.gutenberg.org/files/'+str(i)+'/'+str(i)+'.txt'
    resp=requests.get(url)
    if resp.status_code!=200:
        print("[X] resp.status_code =",resp.status_code,"for",url)
        continue
    print("[V] resp.status_code = 200 for",url)
    try:
        content=resp.text

        #dummy cleaning of the text
        splitted_content=content.split("*** START OF THIS PROJECT GUTENBERG EBOOK")
        splitted_content=splitted_content[1].split("*** END OF THIS PROJECT GUTENBERG EBOOK")
        print(splitted_content[0], file = text_file)
    except:
        continue

text_file.close()


text:
Q: Scheme - using foldr inside map and making the foldr proc use the current element given from the map iteration I'm trying to write the following function which gets 2 lists of lists and returns the cartesian product of those lists.
here's what I wrote:
;; Signature: mix-rows(rows1 rows2)
;; Purpose: returns a list of rows of the cartesian product of both rows
;; Type: [ List(Row) * List(Row) -> List(Row) ]
;; Tests:
;; (mix-rows (list '(10 11) '(20 21)) (list '('u 'v) '('p 'q)))
;; ==> ((10 11 'u 'v)
;;      (10 11 'p 'q)
;;      (20 21 'u 'v)
;;      (20 21 'p 'q))
(define mix-rows
  (lambda (rows1 rows2)
    (map (lambda (row1)
           (foldr (lambda (row2)
                  (append row1 row2))
                  '()
                rows2))
         rows1)))

for some reason the last lambda won't recognize row1 which was given from the function map iterating through rows1.
I want the last lambda to iterate through rows2 and append each element to row1 and after all rows2 elements were appended row1 will change to the next element in rows1.
why wan't the lambda recognize row1?
thanks.

A: First, if all you want is a cartesian-product function, you can use cartesian-product from racket/list.
> (cartesian-product
   (list '(10 11) '(20 21))
   (list '('u 'v) '('p 'q)))
'(((10 11) ('u 'v)) ((10 11) ('p 'q)) ((20 21) ('u 'v)) ((20 21) ('p 'q)))

Your test case is slightly different from this, because your test case splices the inner lists and this doesn't. But, if that's what you need you can easily fix it with (map append* ...). The append* function flattens a list of lists one level down.
> (define (mix-rows rows1 rows2)
    (map append* (cartesian-product rows1 rows2)))
> (mix-rows
   (list '(10 11) '(20 21))
   (list '('u 'v) '('p 'q)))
'((10 11 'u 'v) (10 11 'p 'q) (20 21 'u 'v) (20 21 'p 'q))

Although if you want to design it from scratch, the problem with your implementation is that foldr expects a function (X Y -> Y), a two-argument function, but you gave it a function (Row -> Row), a one argument function. You could fix that, but from what I can see, you don't really need a foldr at all there. You probably meant a map there too.
(define mix-rows
  (lambda (rows1 rows2)
    (map (lambda (row1)
           (map (lambda (row2)
                  (append row1 row2))
                rows2))
         rows1)))

Although, this still fails your test case, producing
> (mix-rows
   (list '(10 11) '(20 21))
   (list '('u 'v) '('p 'q)))
'(((10 11 'u 'v) (10 11 'p 'q)) ((20 21 'u 'v) (20 21 'p 'q)))

To get rid of that extra layer of nested lists, you can use append* to flatten that list of lists one level down.
;; Signature: mix-rows(rows1 rows2)
;; Purpose: returns a list of rows of the cartesian product of both rows
;; Type: [ List(Row) * List(Row) -> List(Row) ]
;; Tests:
;; (mix-rows (list '(10 11) '(20 21)) (list '('u 'v) '('p 'q)))
;; ==> ((10 11 'u 'v)
;;      (10 11 'p 'q)
;;      (20 21 'u 'v)
;;      (20 21 'p 'q))
(define mix-rows
  (lambda (rows1 rows2)
    (append*
     (map (lambda (row1)
            (map (lambda (row2)
                   (append row1 row2))
                 rows2))
          rows1))))

However, if you want a real Cartesian product, without splicing the rows, you can fix it by changing (append row1 row2) to (list row1 row2).
(define mix-rows
  (lambda (rows1 rows2)
    (append*
     (map (lambda (row1)
            (map (lambda (row2)
                   (list row1 row2))
                 rows2))
          rows1))))

Then it matches what cartesian-product does.


text:
Q: php fopen fails to open a file for writing in Mac OS X I'm running php script updreading.php locally on my laptop (with Mac OS X 10.6.7).
Here's the contents of updreading.php
<?php
    $outFile = "examples-output.txt";
    $out = fopen($outFile, 'w') or die("can't open write file");
?>

When I run it, I get "can't open write file" error message. I think it should have something to do with permissions. I've made myself (arman) an owner of /Library/WebServer/Documents/ with Read&Write permissions and 'applied settings to enclosed items'. My script and file I'm writing to (examples-output.txt) is located in /Library/WebServer/Documents/wabun/. Here are the permissions for files in /Library/WebServer/Documents/wabun/:
-rw-r--r--@ 1 arman  admin         0 May  1 01:03 examples-output.txt
-rw-r--r--@ 1 arman  staff      1657 May  1 01:04 updreading.php

I was trying to resolve the issue for the last 4 hours trying different permissions without luck. Any ideas how to resolve this issue, guys? Thanks!

A: I was having this exact same problem. I had to make sure the permissions were correct for all of the parent folders as well. For instance, if (in OSX) trying to write to the directory
~/foo/bar/baz, I solved it with the command chmod -R 777 ~/foo.

A: I bet the issue is that your webserver or PHP instance is not running under the same user (arman), you can check this using the get_current_user() function. You can either configure apache to run with your privileges (ask in ServerFault) or give the folder more generous permissions, like 0777.
Another thing, are you sure $outFile maps to an absolute path? Try doing:
var_dump(is_file($outfile));

A: you need to make apache (assuming apache is server you are using) the owner or put in group (and give group write access) or give write access to all or etc.. IOW apache is the one actually executing the script, not you.


text:
Q: ejabberd: mom_mam throws error I've just installed ejabberd from the sources (18.04) with MySQL support and changed the configuration file respectively. Basically everything works: ejabberd starts, I can register users, users can connect and send messages. I also see all users in the database so I assume the setup is so far correct.
Now I want to use the mod mod_mam to archive all messages. For this I added to the ejabberd.yaml file the following lines:
modules:
  ...
  mod_mam:
    db_type: sql
    default: always
  ...

However, when I sent an offline message, I get the following error -- actually two similar errors for two functions using both the offline message hook:
[error] <0.541.0>@ejabberd_hooks:safe_apply:383 Hook offline_message_hook crashed when running mod_mam:offline_message/1:
** Reason = {error,function_clause,[{mod_mam,offline_message,[{file,"src/mod_mam.erl"},{line,366}],[ok]},{ejabberd_hooks,safe_apply,[{file,"src/ejabberd_hooks.erl"},{line,380}],4},{ejabberd_hooks,run_fold1,[{file,"src/ejabberd_hooks.erl"},{line,364}],4},{ejabberd_sm,route,[{file,"src/ejabberd_sm.erl"},{line,143}],1},{ejabberd_local,route,[{file,"src/ejabberd_local.erl"},{line,73}],1},{ejabberd_router,do_route,[{file,"src/ejabberd_router.erl"},{line,368}],1},{ejabberd_router,route,[{file,"src/ejabberd_router.erl"},{line,93}],1},{ejabberd_c2s,check_privacy_then_route,[{file,"src/ejabberd_c2s.erl"},{line,823}],2}]}

With an older installation (17.01) everything worked fine. But I don't know if additional MySQL tables are required. When I look into my current database, I actually all messages (including offline message) get stored in table archive.

A: Do you use only the modules included in ejabberd, or did you install any of the contributed, or other custom modules?
Notice that offline_message_hook changed in 17.03 from "run" (without accumulator) to "run_fold" (with accumulator), which means that the result of a function call is passed to the next one, until all finish or one stops the hook.
See commit: https://github.com/processone/ejabberd/commit/e564f9ae31d2c5345be4eed66e70037ba8145dc1
and hook docs: https://docs.ejabberd.im/developer/guide/#hooks


text:
Q: Spring Integration Message Routing By Type of Part of Payload I've this class:
public interface ProcessMessage<T extends ProcessData, C, D> {
    T getProcessData();
    C getOperation();
    D getDetail();
}

I'm flowing this message between channels. At some point I need to use a router based on the type of processData field.
I've some concrete classes that implement ProcessData interface and I need to route ProcessMessage instance to some channel.
I've implemented something like below but if there is a better solution I'll be glad to hear.
<int:router input-channel="processMilestonePassChannel" expression="payload.processData.class.name">
    <int:mapping value="some.pkg.XProcessData" channel="channelX"/>
    <int:mapping value="some.pkg.YProcessData" channel="channelY"/>
</int:router>

A: Actually, your router looks good. PayloadTypeRouter isn't for you, because you want to determine a type of some part of your payload. SpEL in this case is OK.
You have only one component - router, and don't have any Java code lines - SpEL does the stuff for you! Keep her steady!


text:
Q: Php date difference with month wise days calculation $a = strtotime('June 3, 2011');
$b = strtotime('June 3, 2012');

i want this date in every month format and date diff can be in remaining days of month. like 3 Jun 2011 to 30 Jun 2011 & then start again from 1 July 2011 to 31 July 2011 & finally 1 jun 2012 to 3 jun 2012 (with no of days diff in jun 2012). All are start with 1 to 30 or 31 of month (Month start and Month End date)format with days calculate in every month. So how we can do this..
Please help me. Thanks in advance.


text:
Q: Bizarre integer behavior in cython I'm running into a strange issue with some integer manipulation in cython. When I compile this cython code ...
test.pyx
from libc.math cimport abs

cdef int c = 2047
cdef int b = 1009
print('%d'%(-(abs(b)&c)))

...like this
#!python
from subprocess import check_output

CFLAGS = check_output('python-config --cflags'.split()).decode('utf-8').strip()
LDFLAGS = check_output('python-config --ldflags'.split()).decode('utf-8').strip()

check_output('cython test.pyx'.split())

compile_call = ('clang -c test.c %s'%(CFLAGS)).split()
check_output(compile_call)

link_call = ('clang test.o -o test.so -shared %s'%(LDFLAGS)).split()
check_output(link_call)

import test

...I get 2130706744, but the right answer is -1009.

A: Looks like this might be a bug in Cython. The relevant line in test.c is
__pyx_t_2 = __Pyx_PyInt_From_unsigned_int((-(__pyx_t_1 & __pyx_v_4test_c)));

Clearly interpreting our number as unsigned gives a wrong answer. However if I remove the abs call, then I get
__pyx_t_1 = __Pyx_PyInt_From_int((-(__pyx_v_4test_b & __pyx_v_4test_c)));

and the result is correct. If I add a cast to int like print('%d'%(-(<int>abs(b)&c))) then I also get the right answer.
Cross posted to the Cython github page
Update: Here is the response to my github issue:

Basically, a signed int is not large enough to hold abs(-MAX_INT-1),
  so the result was changed to return an unsigned value. On the other
  hand, I agree that using an unsigned value is quite confusing as well,
  especially as promotion of equally ranked integers is to the unsigned
  type so it's contagious. Unclear what the best course of action is
  here...


text:
Q: How to open System Profiler.app on Mac OS X using a Java application? I have to show system information for my Mac OS X from my Java application.
I have created a button and trying to execute following:
private static String[] sysInfoPathMac =
    {"/usr/bin/open", "'/Applications/Utilities/System Profiler.app'"};

In the click event of the button I execute following command:
Runtime.getRuntime().exec(sysInfoPathMac);

I am not getting anything once button is clicked. It does not throw any error and neither does it run the system profiler.
What exactly I am doing wrong and how to get it done?

A: Remove the single-quotes. When you run the command from the shell the quotes are needed because the argument has a space in it. This isn't an issue when starting the process from Java because each element of the array is treated as a separate argument regardless of whether it contains spaces.
String[] command = {"/usr/bin/open", "/Applications/Utilities/System Profiler.app"};
Process proc = Runtime.getRuntime().exec(command);
int resultCode = proc.waitFor();
if (resultCode != 0) {
    throw new Exception("failed to open system profiler");
}

Note that in general when using Runtime.exec() you'll want to consume the stdout and stderr streams to avoid deadlock (although in this case it's not an issue since the 'open' command doesn't produce much output). For more on the subject check out Michael C. Daconta's article "When Runtime.exec() Won't"
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html


text:
Q: Bootstrap buttons with same height and vertically-centered text I have 3 Bootstrap buttons side-by-side, but one of them has a line break (I'm modifying them with white-space: normal). I need them all to have the same height, and vertical-centered text.
I have them like this:

And I need them like this:

I can't figure out how to do this. Any ideas?

A: would something like this work for you?

.option-button {
    height:100%;
}

.media-object {
    height: 100px;
}

    <button class="btn btn-info option-button">A</button>
    <button class="btn btn-primary option-button">A
B
C</button>
    <button class="btn btn-info option-button">A</button>

<link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

you can use height: 100%; on the buttons but with that, you need to set the height of the containing div. hope this helps!