text:
Q: node.js, testing a mongodb save and load Perhaps I'm just having trouble figuring out the callbackyness, but I can't figure out a way to test a save and load in node.js.
My test is this:
vows.describe('Saving').addBatch({
    'Single item can be saved':{
        topic:function () {
            myStore.saveItems(1, [{id:3,name:'squat'}]);
            myStore.getItems(1, this.callback);
        },
        'saved item is returned by getItems':function (err, items) {
            assert.equal(items.length, 1);
            assert.equal(items[0].deviceId, 1);
            assert.equal(items[0].id, 3);
        }
    }
}).export(module);

With this being tested:
exports.saveItems = function (deviceId, items) {
    var itemsCollection = db.collection('items');

    itemsCollection.find({deviceId:deviceId}).toArray(function (err, existingItems) {
        _.each(items, function (item) {
            item['deviceId'] = deviceId;
            var existingItem = _.find(existingItems, function (existingItem) {
                return existingItem.id === item.id
            });
            if (typeof(existingItem) === 'undefined') {
                itemsCollection.save(item);//callback here?
            } else {
            }
        });
    });
};

exports.getItems = function (deviceId, callback) {
    var itemsCollection = db.collection('items');
    itemsCollection.find({deviceId:deviceId}).toArray(callback);
};

Is there a way I can pass a callback to saveItems in such a way that getItems isn't called until all mongo saves are complete?

A: Try this :)
vows.describe('Saving').addBatch({
    'Single item can be saved':{
        topic:function () {
          var topicThis = this;
          // NEW: having a callback here
          myStore.saveItems(1, [{id:3,name:'squat'}], function(err, results){
              myStore.getItems(1, topicThis.callback);
          });
        },
        'saved item is returned by getItems':function (err, items) {
            assert.equal(items.length, 1);
            assert.equal(items[0].deviceId, 1);
            assert.equal(items[0].id, 3);
        }
    }
}).export(module);

// https://github.com/caolan/async
var async = require('async');
// NEW: having a callback here
exports.saveItems = function (deviceId, items, cb) {
    var itemsCollection = db.collection('items');

    itemsCollection.find({deviceId:deviceId}).toArray(function (err, existingItems) {
        var tasks = [];
        // here you are iterating over each item, doing some work, and then conditionally doing an async op
        _.each(items, function (item) {
            item['deviceId'] = deviceId;
            var existingItem = _.find(existingItems, function (existingItem) {
                return existingItem.id === item.id
            });
            if (typeof(existingItem) === 'undefined') {
                // so this is async, b/c it's talking to mongo
                // NEW: add it to our list of tasks, when are later run in parallel
                tasks.push(function(nextTask){
                    itemsCollection.save(item, nextTask);
                });
            }
        });
        // NEW: run it all in parrallel, when done, call back
        async.parallel(tasks, function(err, results) {
            cb(err, results);
        })
    });
};

A: Use the node.js mongo db driver:
http://mongodb.github.com/node-mongodb-native/api-articles/nodekoarticle1.html
Both the insert and update functions is defined with callbacks. I only use the update function because it works as insert as well (if the first argument below does not fetch any record).
itemsCollection.update({_id: itemId}, item, {upsert:true, safe:true}, function (err, result) {
  // callback here
});


text:
Q: Stylesheet path incorrect after asp.net page postback in IE7, IE8 I got a dropdownlist doing autopostback in aspx page.
The stylesheet loaded correctly when first load with path: http://localhost/test/theme/style/mystyle.css
When dropdownlist is selected and postback happened, the stylesheet loaded path become this: http://localhost/theme/style/mystyle.css
The loading sequence in IE7/IE8 load the wrong stylesheet path at first, and it load the correct path later. But my page using the stylesheet seems like style-less, every things are messed up.
Everything is working in Chrome, Safari, FireFox, IE9, it just went wrong in IE7, IE8.
Is there anyway to resolve this? It only happen to one page.
All stylesheets are included directly into aspx  section.

A: If your vitual folder is test then please use the below in the master page to include the stylesheet
<link href="~/theme/style/mystyle.css" rel="stylesheet" type="text/css" />

A: Managed to resolve the problem by adding the virtual folder directly into stylesheet link as below:
<link href="/test/theme/style/mystyle.css" rel="stylesheet" type="text/css" />

Now it works on IE7, IE8.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access a non-static property from another class I have a non-static property inside a non-static MainForm class:
public string SelectedProfile
{
    get { return (string)cbxProfiles.SelectedItem; }
    set { cbxProfiles.SelectedItem = value; }
}

I would like to get the value of this property, from another non-static class. Using MainForm.SelectedProfile gives an error saying "An object reference is required for the non-static field, method or property".
Usually I would solve this problem by making SelectedProfile static, but I can't, since cbxProfiles (a ComboBox control) can't be made static.
So how do I access the property's value without making it static?

A: You access non-static members the same way you always do: by using a reference to an instance of the object.
So whatever code you want to be able to use that property, you need to pass it a reference to a MainForm object.

A: As said in the compilation error, you need to have a reference of the existing MainForm instance to act on it.
// You surely do this somewhere in your code
MainForm mainForm = new MainForm();
// ...
// Use the reference to your mainForm to access its public properties
String selectedProfile = mainForm.SelectedProfile;

A: I might be late to the party but my solution might help someone someday down the road. You can directly access an open form's controls (even private ones) using Application.OpenForms[n]...
For example, let's assume you have created a MainForm and then created a comboBox such that it is inside MainForm => Tab (named tabControl) => TabPage (named tabPageMain) => Panel (named pnlMain) => ComboBox (named cmbSeconds). Then you can access this last control as follows:
ComboBox combo = Application.OpenForms[0].Controls["tabControl"].Controls["tabPageMain"].Controls["pnlMain"].Controls["cmbSeconds"] as ComboBox;
string SelectedProfile = (string)combo.SelectedItem;

// OR

bool isMaximized = Application.OpenForms[0].WindowState == FormWindowState.Maximized;

i.e. you've got to traverse the path from the top-level form down to that particular control. Document Outline view of Visual Studio (View menu => Other Windows => Document Outline) might help you in this bcoz you might be overlooking some transparent containers in between.
Use it cautiously. For example, if the handles of any of the referenced controls are not yet created, you might see runtime exceptions.


text:
Q: Difference between application/vnd.xls and application/vnd.ms-excel In my c#.NET MVC application you can download an excel file (with the Nuget EPPlus). To send the file to user I set content type as it follows:
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.xls";

What is the difference with:
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

Which one should I use?


text:
Q: Prevent Chrome to cache JS file When I'm connected too long in my back office and tried to log in again I'm rejected so I should clear my browser (Chrome,FF,Edge) every time to get access .
So i noticed that when the file named login.js is load from disk cache I can't access. here is a video that explain the issue.
I'm using PS on 3 websites with different version 1.7.6.5 and 1.7.6.6 aldo 1.7.6.7 on a VPS Linux Centos and 7.1 php version and I don't use any cache module as Nginx or Memcached.
Even on the mobile I should switch to desktop version or clear files to get access .
How can I prevent chrome to cache this file login.js on the browser setting or from the php file
Regards
https://www.prestashop.com/forums/uploads/monthly_2020_07/2020-07-28_05-41-14.mp4.f2a7a6c6fa765bb12f2c4a4d56d0d508.mp4

A: <script src="script.js?v=1"></script>

Change v value when you need (v=1, v=2...)
Or use PHP
<script src="script.js?v=<?php echo(rand(10,100)); ?>"></script>


text:
Q: how to update the textfield value in ios I have one textfield value like 100,000 using NSNumberFormatter, now I want to edit my textfield, to add one more 0 . After I Want to Change like the text like 1,000,000 but my textfield value is changed as 0

A: try like this,
 int x=[textfield.text intValue];

you can get the correct value.....

A: Try this code. It may help you
  NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [numberFormatter setFormat:@"#,###"];
    NSNumber *averageResponseTime = [NSNumber numberWithInt:[textfield.text intValue]];

//If you print text

 [NSString stringWithFormat: @"%@ms",[numberFormatter stringForObjectValue:averageResponseTime]];

A: numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle: NSNumberFormatterNoStyle];
[numberFormatter setGroupingSize:3];
[numberFormatter setGroupingSeparator:@","];
[numberFormatter setUsesGroupingSeparator:YES];
number= [NSNumber numberWithInt:[textFieldString intValue]];
NSString *numberString = [NSString stringWithFormat:@"$%@",[numberFormatter stringForObjectValue:number]];

try this


text:
Q: Water comprises/composes/combines/consists two hydrogen atoms and one oxygen atom
Possible Duplicate:
When do you use what word to express that something consists of something else?
Does a whole "compose" its parts?
Correct use of "consist"

Water comprises/composes/combines/consists two hydrogen atoms and one oxygen atom.

Can anyone let me know the correct usage in this sentence?

A: There are several possible correct usages.
You can say "Water comprises two hydrogen molecules and one oxygen molecule".
You can say "Water consists of two hydrogen molecules and one oxygen molecule".
You can say "Water is composed of two hydrogen molecules and one oxygen molecule".
You can probably say "Water is a combination of two hydrogen molecules and one oxygen molecule", though it sounds a bit off to me.
Note that they all have different structure, and subtly different semantics.

A: The last time I had water, there were a lot more than two hydrogen atoms involved, and very many oxygen atoms.  For this to make sense, you have to make it clear that you're talking about a single molecule of water, not water in general.
My preference for how to express this is the following.

A molecule of water consists of two hydrogen atoms and one oxygen atom.

A: For clarity use composed of, perhaps.  Comprise can be seen in two opposite senses--whether the whole comprises its parts, or the parts comprise the whole.
OED under 4b:

The house comprises box-room, nine bed-rooms, bath-room, etc.

but under 8b:

These essays together with those contained in this volume comprise the total of C. S. Lewis's essays on literature.


text:
Q: Express.js - Multer File Filter Not Working I want to filter the files while uploading them to the server but the Multer fileFilter method is not working.
Backend
destination and filename methods are working as well, but fileFilter is not working.
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/images/");
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + path.extname(file.originalname));
  },
  fileFilter: function (req, file, callback) {
    console.log("Hello Word"); // This doesn't work either

    var ext = path.extname(file.originalname);
    if (!['.jpg', '.jpeg'].includes(ext)) {
      return callback(new Error('Only images are allowed'));
    }

    callback(null, true);
  },
});

app.use(
  multer({ storage: storage }).fields([
    { name: "logo", maxCount: 1 },
    { name: "favicon", maxCount: 1 },
  ])
);

Frontend
<form action="" method="post" enctype="multipart/form-data">

                Logo

                    <input type="file" name="logo" accept="image/jpeg, image/jpg"/>

                Favicon

                    <input type="file" name="favicon" accept="image/x-icon" />

</form>

A: Your filterMethod works fine. This can be checked by changing the value in input accept="image/*" Then when we try to load a file other than ico or jpg we will get an error : Only images are allowed.
Your code needs some tweaking, additionaly i used the ejs module, here is my suggestion for a solution:

Folder & File project structure:

app.js - With Your fileFilter code.
const path = require("path");
const express = require("express");
const multer = require("multer");
const app = express();

app.use(express.static(path.join(__dirname, "public")));
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/views"));

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./images");
  },
  filename: function (req, file, cb) {
    console.log(req.file);

    cb(null, new Date().toUTCString() + " - " + file.originalname);
  },
});

const upload = multer({
  storage: storage,
  fileFilter: function (req, file, callback) {
    console.log("Hello, World! Works fine;-)");

    var ext = path.extname(file.originalname);
    if (![".jpg", ".ico"].includes(ext)) {
      return callback(new Error("Only images are allowed"));
    }

    callback(null, true);
  },
});

app.post(
  "/post",
  upload.fields([
    { name: "logo", maxCount: 1 },
    { name: "favicon", maxCount: 1 },
  ]),
  (req, res, next) => {
    const files = req.files;
    if (!files) {
      const error = new Error("Please upload a file");
      error.httpStatusCode = 400;
      return next(error);
    }
    res.send(files);
    console.log("Success", req.files);
  }
);

app.get("/post", (req, res) => {
  res.render("post");
});

app.listen(3000, () => {
  console.log(`Example app listening at http://localhost:3000/post`);
})

post.ejs - With Your frontend form code and my additional input submit:
<form action="" method="post" enctype="multipart/form-data">

        Logo

          <input type="file" name="logo" accept="image/jpeg, image/jpg" />

        Favicon

          <input type="file" name="favicon" accept="image/x-icon" />

  <input class="submit" type="submit" value="Upload File" />
</form>

http://localhost:3000/post route output in browser:

Output after submit - Upload File. Files specified in fields name logo and favicon.

Output on server side and in images folder:

Tested with: node v16.13.0 "ejs": "^3.1.6","express": "^4.17.2","multer": "^1.4.4"


text:
Q: jquery как присвоить переменной содержимое соседнего элемента Есть много одинаковых кусков html, нужно в переменную get_spanText "положить" текст из class_2_1 varSpan, подскажите пожалуйста как это правильно сделать через this. Делал как внизу - в переменной ничего нет - пустая строка

$('.class_1').click(function(){

  var get_spanText = $(this).next(".class_2").cildren(".class_2_1").find("span").text();
  console.log(get_spanText);
  $('.someClass').html(get_spanText+' ');

 });

Title varSpan

someText

A:

$('.class_1').click(function() {
  var get_spanText = $(this).next(".class_2").find(".class_2_1 span").text();
  console.log(get_spanText);
});

Title varSpan

someText


text:
Q: Adding Points on a Graphic I have three questions about the following code:
Plot[{1/2 - 3/2 \[Lambda], Min[1/2 - 3/2 \[Lambda], Sqrt[\[Lambda]]]}, {\[Lambda], 0, 1/9}, AxesLabel -> {\[Lambda], \[Gamma]}, PlotStyle -> Black, Filling -> {1 -> {{2}, White}, 2 -> {Axis, Red}},  AxesStyle -> {Directive[Black], Directive[Blue]}, Epilog -> {Text[Style["FULLY ATTRACTIVE", 36], Scaled[{0.6, 0.25}]], Red}]

*

*How can I plot a series of given points on the plot obtained by code shown? For example suppose I have the following series of points:
{{0.000297159,0.029389}, {0.00114653,0.0566384}, {0.00249252,0.082004},{0.00428816,0.105703} (* etc. *)}

*Is there a more effective way to write the text "FULLY ATTRACTIVE" in the red region of the plot?

*How can I change the axes dimension?
Thanks.

A: First thing let's plot the points
points = {{0.000297159, 0.029389}, {0.00114653,
    0.0566384}, {0.00249252, 0.082004}, {0.00428816, 0.105703}(*etc.*)};

For that you can keep using Epilog while paying attention to make all its content a valid Graphics element:
plot = Plot[{1/2 - 3/2 \[Lambda],
  Min[1/2 - 3/2 \[Lambda], Sqrt[\[Lambda]]]}, {\[Lambda], 0, 1/9},
 AxesLabel -> {\[Lambda], \[Gamma]}, PlotStyle -> Black,
 Filling -> {1 -> {{2}, White}, 2 -> {Axis, Red}},
 AxesStyle -> {Directive[Black], Directive[Blue]},
 Epilog -> {Orange, PointSize[.02], Point[points]}]

The result is

Your text can be fit into the red shape by making it a little smaller, but let's assume you don't want to manually find the good fit. A possibility is to use WordCloud to find a good layout for you (with the caveat that it's not preserving the ordering of the words, so this method is not valid in general for multi-words labels).
We need to define the appropriate mask:
mask = Binarize[
  Plot[{1/2 - 3/2 \[Lambda],
    Min[1/2 - 3/2 \[Lambda], Sqrt[\[Lambda]]]}, {\[Lambda], 0, 1/9},
   AxesLabel -> {\[Lambda], \[Gamma]}, PlotStyle -> Black,
   TicksStyle -> Transparent, AxesStyle -> Black,
   Filling -> {2 -> {Axis, White}}, Background -> Black]]

Now we can compute the layout (Erosion is used to leave a little margin)
text = WordCloud["FULLY ATTRACTIVE", Erosion[mask, 5],
  ColorFunction -> Black];

and use Overlay to compose it with the original plot without worrying too much about the coordinates
Overlay[{plot, text}]

A: Plot[{1/2 - 3/2 \[Lambda],
  Min[1/2 - 3/2 \[Lambda], Sqrt[\[Lambda]]]}, {\[Lambda], 0, 1/9},
 AspectRatio -> 1,
 AxesLabel -> {\[Lambda], \[Gamma]},
 PlotStyle -> Black,
 Filling -> {1 -> {{2}, White}, 2 -> {Axis, Red}},
 AxesStyle -> {Directive[Black], Directive[Blue]},
 Epilog ->
  {Text[Style["FULLY ATTRACTIVE", 26], Scaled[{0.6, 0.25}]],
   PointSize@0.02, Red, Point[{{0.00114653, 0.0566384},
     {0.00114653, 0.0566384}, {0.00249252, 0.082004}, {0.00428816, 0.105703}}]}

(1) Some points added
(2) Change axes-dimension with AspectRatio


text:
Q: Linear Algebra w/ matrix + linear system question True or False?
Let $A$ be an $m \times n$ matrix. If $m > n$ , then the linear system $Ax=b$ is inconsistent for at least one vector $b$ in $\mathbb{R}^n$

A: The set of all $b$ for which $Ax=b$ has a solution is the image of $A$. Which is the maximum dimension of the image of an $m\times n$ matrix?


text:
Q: How APIs works and get datas? First, I'm sorry if it's not the good place to ask this question, but I think it's related with programming.
I'm going to create a website, and this website needs soccer data like scores, players ... etc, I search on the net and I found a lot of APIs that you need to buy for it.
but I'm really confused how this APIs works ? it there are a companies who have employs and watched games and add data manually, or this use other method ? that can I create my own API ? If yes, how can I get the data ?


text:
Q: AutoLayout for Views Generated Programmatically Having two views headerView and footterView. I want the views to be placed one below another.
i mean to say  headerView on top and footerView below headerView.
UIView *mainview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    headerView =  [[[NSBundle mainBundle] loadNibNamed:@"BaseHeader" owner:self options:nil] objectAtIndex:0];
    footterView = [[[NSBundle mainBundle] loadNibNamed:@"BaseFotter" owner:self options:nil] objectAtIndex:0];

 self.view = mainview;
 [mainview  addSubview:headerView];
 [mainview  addSubview:footterView];

I have tried adding constraint as below
NSDictionary *viewsDictionary =
NSDictionaryOfVariableBindings(headerView,footterView);

NSLayoutConstraint *constraint = [[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[headerView]-[footterView]|" options:0 metrics:nil views:viewsDictionary] objectAtIndex:0];

NSLayoutConstraint *mconstraint = [[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[headerView(==footterView)]|" options:0 metrics:nil views:viewsDictionary] objectAtIndex:0];

[mainview addConstraint:constraint];
[mainview addConstraint:mconstraint];

But always the footerView alone is displayed in screen.
If i add View in below order , always HeaderView is displayed.
[mainview  addSubview:footterView];
[mainview  addSubview:headerView];

AutoLayout is checked in both xib (BaseHeader.xib & BaseFotter.xib ). do i need to do any more in xib?

A: Change your constraints adding code to:
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[headerView]-[footterView]|" options:0 metrics:nil views:viewsDictionary];
NSArray *mconstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[headerView(==footterView)]|" options:0 metrics:nil views:viewsDictionary];
[mainview addConstraints: constraints];
[mainview addConstraints:mconstraints];


text:
Q: How to deal with promoted conflicting branches on jenkins The idea is:

*

*all devs work on their feature branches and push them to github

*jenkins starts builds (triggered by "push on github") on job test to run unit tests on those feature branches

*Once they pass the test, manager goes to github to do code review.

*If code review is fine, then this build is promoted(promote build plugin) manually to "Pass QA, Ready for prod", in "actions" section, we set "trigger/call builds on other projects" to trigger a separate job test-prod only to merge this feature branch to master on remote repo.

job test promote build config:

job test-prod SCM config:

So 2 questions here:

*

*on step 4, we have situations like 2 conflicting feature branches both passed code review,  the first branch that is promoted will be fine, but the second will have conflicts and failure, is there a way to detect conflict before?  I know 'merge before build' can avoid conflict but that requires the former branch already been merged to remote master

*in no-conflict cases, whenever the second job is triggered by the manually promotion, there is always an extra build caused by: "Legacy code started this job. No cause information is available", I have no idea how that happens.
Also, dont know whether the idea is correct in terms of whole pipeline, any suggestions are welcome!

A: Disclaimer: I know nothing about git.
According to this, the best practice is to use rebase. As I am not familiar with git, I can't tell you how to setup rebase on Jenkins.
There is another poster here that also has issues with git and "Legacy code started this job" triggering extra builds: Legacy code started this job. No cause information is available.


text:
Q: How can I exclude files from PHP glob function, that contain a specific word and number in the filename I hope someone can help me with this problem.
I have a directory with some php files and a subdirectory which contains php files with the same name, but with a number before them. This number is used elsewhere for sorting the files. Like this:
folder
├── subfolder
|   ├── 001_file.php
|   └── 002_anotherfile.php
|   └── 003_onemorefile.php
├── file.php
├── anotherfile.php
├── onemorefile.php

What I would like to do is to include a random file from the subdirectory into a file from the root directory, but the included file can not contain the same name.
This is my code:
$excludefile = glob($_SERVER['DOCUMENT_ROOT'].
'/folder/subfolder/*' . basename(__FILE__));

$files = glob($_SERVER['DOCUMENT_ROOT'].
'/folder/subfolder/*.php');

$fileswithexclusion = array_values(array_diff($files, $excludefile));

$file = array_rand($fileswithexclusion);

include $fileswithexclusion[$file];

When I do not try to dynamically generate the excludefile, it works. Like this:
$excludefile = glob($_SERVER['DOCUMENT_ROOT'].
'/folder/subfolder/001_file.php');

So to solve my problem I would need a way to correctly generate the $excludefile (with the number)
Thanks a lot!

A: <?php

$sortedDir = __DIR__ . DIRECTORY_SEPARATOR . 'subfolder';

$files = glob($sortedDir . DIRECTORY_SEPARATOR . '*.php');

$filteredFiles = array_filter($files, function($file) {
    return false === strpos($file, basename(__FILE__));
});

$fileToInclude = $filteredFiles[array_rand($filteredFiles)];

print $fileToInclude;

A: Shoud work, "index.php" as sample file to exclude
$files = array_filter(glob($_SERVER['DOCUMENT_ROOT'] . '/folder/subfolder/*.php'), function($v) {
    return false === strpos($v, 'index.php');
});

Update
To get filename dynamically you can use code below
$info = pathinfo($file);
$file_name =  basename($file,'.'.$info['extension']);

A: Change the code to following:
$excludefile = glob($_SERVER['DOCUMENT_ROOT'].
'/folder/subfolder/[0-9]*' . basename(__FILE__));

$files = glob($_SERVER['DOCUMENT_ROOT'].
'/folder/subfolder/*.php');

$fileswithexclusion = array_values(array_diff($files, $excludefile));

$file = array_rand($fileswithexclusion);

include $fileswithexclusion[$file];

The reason your code is not working is because you are using * which matches everything in
$excludefile = glob($_SERVER['DOCUMENT_ROOT']. '/folder/subfolder/*' .basename(__FILE__));


text:
Q: DFSR specific folder specific server I'm considering using DFSR to speed up a slow link between a branch office.
I want to know if it is possible to exclude a specific folder from the replication, so that when the branch office accesses it, the data is read/written to the main server?
I would like this to be transparent to the user i.e. both offices see the same set of files.
I have a folder with several access databases, and i read that using access and DFSR makes bad things happen, so i want to limit the access databases to the main server.
My original plan was to use branch cache, but i don't have the option of upgrading to enterprise, so i'm looking for other ways to accomplish caching

A: Have you deployed DFS-N as well as DFS-R? DFS-N will allow people to see all the content inside a linked folder while DFS-R can be used to replicate the content you need replicated to the remote site.
Here is an overview of DFS-N
https://msdn.microsoft.com/en-us/library/cc730736(v=ws.11).aspx

A: As yagmoth555 mentioned, you can exclude the folder (or file types)...
Your concern is valid, as this will create dissociated files that will be out of sync. Users going to one referral path will see different data from the others.
Since you have an entire folder structure that contains these files, it might suffice to exclude the folder (and in branch site) create a shortcut within that jumps to the hub/desired server via UNC share.


text:
Q: How can I make a "browse for file.." button in VB.net? I'm trying to build a simple FTP uploader. How can I make it so the user can select a file to upload? See, what I want is to have a button (which I do) that a user can click, and it shows the OpenFileDialog (which I have), but then when they select a file, I want its path to be shown in a text box. How can I do that?

A: Try the following code
Dim dialog As New OpenFileDialog()
If DialogResult.OK = dialog.ShowDialog Then
  TextBox1.Text = dialog.FileName
End If

A: One way is to convert the filename to a FileInfo which contains all sorts of information about the file including the path. This opens the dialog and displays the path of the selected file.
If OpenFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
    Dim fi As New System.IO.FileInfo(OpenFileDialog1.FileName)
    TextBox1.Text = fi.DirectoryName
End If

A: You want to get the OpenFileDialog's property Filename property. See OpenFileDialog's class members here on MSDN.
Hope this helps

A: Add a OpenFileDialog And Add This Code
If YourOpenFileDialogName.ShowDialog = YourOpenFileDialogName.OK Then
 textBox1.Text = YourOpenFileDialogName.FileName
End If


text:
Q: labeled tableView is not found in my View Controller or UIView I have a View controller with 2 tableviews.  Originally I only had 1 and things worked fine but now I have to add a second due to some changes.
Basically, in XCode I re-labeled my first tableview to tableView1 and the second to tableView2.  In my delegate methods, in order to distinguish between the two tableviews I have an if/else clause like so...
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
   if(tableView == self.tableView1)
       return @"Ingate Options";
   else if(tableView == self.tableView2)
       return @"Outgate Options";
}

The problem is that tableView1 is not found in my view controller, but I don't know the syntax or what changes I need to make to let it see it.  I also tried self.view.tableView1 but it produces the same issue just in the UIView.  All I have done so far to these tables is change the 'label' value under the 'Change Identity Inspector' tab in xcode.  What else needs to be done?
Thanks

A: If you added your second instance of UITableView via IB, I suggest do remove that and create it programmatically:
self.tableView2 = [[UITableView alloc] initWithStyle:UITableViewStylePlain];
//do things... Note that this implementation leads to a memory leak, if not handled correctly (Use ARC or release it)


text:
Q: How to check if there is a `\0` character in a filename using C? I'd like to write a function like this:
int validate_file_name(char *filename)
{
    //...
}

which will:

*

*return 1 if there was no \0 character in the filename,

*0 otherwise.

I thought it may be achieved using a simple for(size_t i = 0; i < strlen(filename); i++), but I don't know how to determine how much characters I've got to check?
I can't use strlen() because it will terminate on the first occurrence of a \0 character.
How should I approach this problem?

Clarification:
I am trying to apply these guidelines to a filename I receive. If you should avoid putting a \0 in a filename, how could you validate this if you've got no size parameter.
Moreover, there are strings with multiple \0 characters, like here: http://www.gnu.org/software/libc/manual/html_mono/libc.html#Argz-and-Envz-Vectors. Still, I had no idea that it is impossible to determine their length if it is not explicitly provided.

Conclusion:
There is no way you can determine the length of string which is not NULL-terminated. Unless you know the length of course or you deploy some dirty hacks: Checking if a pointer is allocated memory or not.

A: You are trying to solve a problem that does not need to be solved.
A file name is a string. In C, a "string" is by definition "a contiguous sequence of characters terminated by and including the first null
character".
It is impossible to have a string or a file name with a null character embedded in it.
It's possible to have a sequence of characters with an embedded null character. For example:
char buf[] = "foo\0bar.txt";

buf is an array of 12 characters; the characters at positions 3 and 11 are both null characters. If you treat buf as a string, for example by calling
fopen(buf, "r")

it will be treated as a string with a length of 3 (the length of a string does not include the terminating null character).
If you're working with character arrays that may or may not contain strings, then it makes sense to do what you're asking. You would need to keep track of the size of the buffer separately from the address of the initial character, either by passing an additional argument or by wrapping the pointer and the length in a structure.
But if you're dealing with file names, it's almost certainly best just to deal with strings and assume that whatever char* value is passed to your function points to a valid string. If it doesn't (if there is no null character anywhere in the array), that's the caller's fault, and not something you can reasonably check.
(Incidentally, Unix/Linux file systems explicitly forbid null characters in file names. The / character is also forbidden, because it's used as a directory name delimiter. Windows file systems have even stricter rules.)
One last point: NULL is (a macro that expands to) a null pointer constant. Please don't use the term NULL to refer to the null character '\0'.

A: The answer is that you can't write a function that does that if you don't know the length of the string.
To determine the length of the string strlen() searches for the '\0' character which if is not present will cause undefined behavior.
If you knew the length of the string then,
for (int i = 0 ; i < length ; ++i)
 {
    if (string[i] != '\0')
        continue;
    return 1;
 }
return 0;

would work, if you don't know the length of the string then the condition would be
for (int i = 0 ; string[i] != '\0' ; ++i)

which obviously means that then searching for the '\0' makes no sense because it's presence is what makes all other string related functions to work properly.

A: If the string is not NULL-terminated, what else it is terminated by? And if you don't know that, what is it length? If you know the answer to these problems, you know the answer to your question.


text:
Q: PostgreSQL incremental dates? I have a database table that contains the following data:
ID | Date       | Bla
1  | 2013-05-01 | 1
2  | 2013-05-02 | 2
3  | 2013-05-03 | 3
4  | 2013-05-05 | 4

Note that there is a date missing: 2014-05-04. How should I alter the following query:
SELECT *
FROM table
where DATE >= '2013-05-01' AND DATE <= '2013-05-05'

So that I would end up with the following output:
ID   | Date       | Bla
1    | 2013-05-01 | 1
2    | 2013-05-02 | 2
3    | 2013-05-03 | 3
null | 2013-05-04 | null
4    | 2013-05-05 | 4

Is this possible?

A: You can join with a generate_series output:
select
    '2013-05-01'::date + g.o AS "date with offset"
from
    generate_series(0, 30) AS g(o)

Output:
"2013-05-01"
"2013-05-02"
"2013-05-03"
...
"2013-05-29"
"2013-05-30"
"2013-05-31"

Or... an easier method after defining a new stored procedure :)
CREATE OR REPLACE FUNCTION generate_series(date, date) RETURNS
SETOF date AS $$
SELECT $1 + g.s
FROM generate_series(0, ($2 - $1)) AS g(s);
$$ LANGUAGE SQL IMMUTABLE;

Just call it like this:
SELECT * FROM generate_series(start_date, end_date);

A: select *
from
    (
        select generate_series(
            '2013-05-01'::date, '2013-05-05', '1 day'
            )::date
    ) s("date")
    left join
    t using ("date")

Replace both "date" with the actual column name.

A: You need to outer join your table against a "list of dates":
with all_dates (some_date) as (
    select date '2013-05-01' + i
    from generate_series(0, 10) i  -- adjust here to the range of dates you need.
)
select t.id,
       ad.some_date, -- you need to take the actual date from generated ones
       t.bla
from all_dates ad
  left join the_table t on ad.some_date = t.date
where ad.some_date between date '2013-05-01' and date '2013-05-05';

Btw: date is a horrible name for a column. Apart from the fact that it is a reserved word it also tells nothing about what kind of "date" that is.


text:
Q: can t import HTTP module on client in meteor 1.3 i use react on meteor 1.3 and want to directly upload big files from the client to a file storage API (www.backblaze.com)
importing HTTP on the server works,
but it does not work on the client
import { HTTP } from 'meteor/http';

i get the error message on the client:
"Uncaught Error: Cannot find module 'meteor/http'" on install.js:78
but it works on the server (if the client API calls are commented out), where i import it the same way and make successful API calls.
the documentation indicates that it can be used client and server side:
http://docs.meteor.com/api/http.html
i use (osx chrome Version 50.0.2661.102) on the client side
any ideas?

A: after re-installing the HTTP package, the import works for client and sever.


text:
Q: type="number" causing form field to shrink Using iOS 4.2.1 on iPad/iPhone, when I view a specific web page with type="number" for a text field, the text input space is slightly shorter than when it's type="text". And when I enter 3 digits, the first one gets cutoff, while it does not get cutoff with type="text". This problem does not happen on iOS 3.x on iPad/iPhone. The input field input area is identical, and it works fine.
Has anyone noticed this problem? Is there anything I can do to fix it? Thanks.

A: It's probably to do with the device browser's default style sheet. If you just apply styles the same styles to the text and number input fields it should render the same.
input[type=text], input[type=number] {
    width: 100px;
    padding: 1px 0;
    ...etc...
}

A: You need to set the unit when styling width and height.
<input syle="width: 45px; padding: 1px 0;" name="mname" type="text" value="" autofocus />

or preferred:
input[type=number] {
width: 45px;
}


text:
Q: What does the image of the integer lattice under a norm look like? The question that I shall ask here has arisen in the context of Diophantine approximation. I find it rather interesting, and I have no idea how to answer it. Any help, advice, or suggestions for references would be much appreciated.
Let $S$ be a countably infinite subset of $\mathbb{R}_{>0}$ that satisfies the following conditions. Let $n$ be an arbitrary element of $\mathbb{Z}_{\geq 2}.$
1) For any integer $k \geq 1,$ we have $k \cdot S \subseteq S.$ (In particular, $S$ is unbounded.)
2) There exists a (necessarily unique) strictly increasing sequence $t_\bullet = (t_k)_{k \geq 1}$ such that $\{t_k : k \geq 1\} = S.$ Moreover, there exists a constant $C > 0$ such that for any $k \geq 1,$ we have $0 < t_{k+1} - t_k \leq C.$ (Notice that we clearly have $\lim_{k \to +\infty} t_k = +\infty$, in light of 1) above.)
3) There exists a constant $D > 0$ such that $$\limsup_{T \to +\infty} \frac{\mathrm{card}\{ k \in \mathbb{Z}_{\geq 1} : t_k \leq T\}}{T^n} \leq D.$$
Is it necessarily true that there exists a norm $\eta$ on $\mathbb{R}^n$ such that $\eta(\mathbb{Z}^n) - \{0\} = S$? (Clearly conditions 1), 2), and 3) are necessary in order for this to be true; I am wondering whether they are also, in fact, sufficient.)

A: I doubt that there is a simple characterization.
In any case conditions (1,2,3) are not sufficient.
For example, if $n=2$ then $S$ cannot be ${\bf Z}_{\geq 100}$,
and there are similar counterexamples for every $n \geq 2$,
as a consequence of the following observation.
Proposition. If $\eta$ is a norm on ${\bf R}^n$, and
$t_1$ is the smallest element of $\eta({\bf Z}^n)$,
then for any $M>0$ there are at most $(2M+1)^n$ integer vectors $v$
with $\eta(v) \leq M t_1$.
Proof: Consider the $\eta$-balls of radius $t_1/2$ centered on
all such $v$.  They have disjoint interiors, and are all contained in the
$\eta$-ball of radius $(2M+1)t_1/2$ about $0$.  Therefore their total volume
is no larger than the volume of the ball of radius $(2M+1)t_1/2$.
But the volume of a ball of radius $r$ is proportional to $r^n$.
Hence the total number of radius $t_1/2$ balls is at most
$\left[ ((2M+1)t_1/2) \left/ \, (t_1/2) \right. \right]^n = (2M+1)^n$, Q.E.D.
Equality is attained when $\eta$ is the sup norm and $M$ is an integer.  (Then we get a perfect packing of cubes.)


text:
Q: How do I make multiple fetch calls without getting 429 error? I came across a problem in a book which I can't seem to figure out. Unfortunately, I don't have a live link for it, so if anyone could help me with my approach to this theoretically, I'd really appreciate it.
The process:

*

*I get from a fetch call an array of string codes (["abcde", "fghij", "klmno", "pqrst"]).

*I want to make a call to a link with each string code.
example:

fetch('http://my-url/abcde').then(res => res.json()).then(res => res).catch(error => new Error(`Error: ${error}`)); // result: 12345
fetch('http://my-url/fghij').then(res => res.json()).then(res => res).catch(error => new Error(`Error: ${error}`)); // result: 67891
...etc

*

*Each of the calls is going to give me a number code, as shown.

*I need to get the highest number of the 5 and get its afferent string code and make another call with that.

"abcde" => 1234
"fghij" => 5314
"klmno" => 3465
"pqrst" => 7234 <--- winner
fetch('http://my-url/pqrst').then(res => res.json()).then(res => res).catch(error => new Error(`Error: ${error}`));

What I tried:
let codesArr = []; // array of string codes
let promiseArr = []; // array of fetch using each string code in `codesArr`, meant to be used in Promise.all()
let codesObj = {}; // object with string code and its afferent number code gotten from the Promise.all()

fetch('http://my-url/some-code')
.then(res => res.json())
.then(res => codesArr = res) // now `codesArr` is ["abcde", "fghij", "klmno", "pqrst"]
.catch(error => new Error(`Error: ${error}`);

for(let i = 0; i < codesArr.length; i++) {
      promiseArr.push(
         fetch(`http://my-url/${codesArr[i]}`)
            .then(res => res.text())
            .then(res => {
               codesObj[codesArr[i]] = res;
                        // This is to get an object from which I can later get the highest number and its string code. Like this:
                        // codesObj = {
                        //  "abcde": 12345,
                        //  "fghij": 67891
                        // }
               })
              .catch(error => new Error(`Error: ${error}`));
               // I am trying to make an array with fetch, so that I can use it later in Promise.all()
}

Promise.all(promiseArray) // I wanted this to go through all the fetches inside the `promiseArr` and return all of the results at once.
      .then(res => {
         for(let i = 0; i < res.length; i++) {
            console.log(res[i]);
            // this should output the code number for each call (`12345`, `67891`...etc)
            // this is where I get lost
         }
      })

*

*One of the problems with my approach so far seems to be that it makes too many requests and I get 429 error. I sometimes get the number codes all right, but not too often.

A: Like you already found out the 429 means that you send too many requests:

429 Too Many Requests
The user has sent too many requests in a given amount of time ("rate
limiting").
The response representations SHOULD include details explaining the
condition, and MAY include a Retry-After header indicating how long to
wait before making a new request.
For example:
HTTP/1.1 429 Too Many Requests
Content-Type: text/html
Retry-After: 3600

    <title>Too Many Requests</title>

Too Many Requests

I only allow 50 requests per hour to this Web site per
    logged in user. Try again soon.

Note that this specification does not define how the origin server
identifies the user, nor how it counts requests. For example, an
origin server that is limiting request rates can do so based upon
counts of requests on a per-resource basis, across the entire server,
or even among a set of servers. Likewise, it might identify the user
by its authentication credentials, or a stateful cookie.
Responses with the 429 status code MUST NOT be stored by a cache.

To handle this issue you should reduce the amount of requests made in a set amount of time. You should iterate your codes with a delay, spacing out the request by a few seconds. If not specified in the API documentation or the 429 response, you have to use trial and error approach to find a delay that works. In the example below I've spaced them out 2 seconds (2000 milliseconds).
The can be done by using the setTimeout() to execute some piece of code later, combine this with a Promise to create a sleep function. When iterating the initially returned array, make sure to await sleep(2000) to create a 2 second delay between each iteration.
An example could be:

const fetch = createFetchMock({
  "/some-code": ["abcde", "fghij", "klmno", "pqrst"],
  "/abcde": 12345,
  "/fghij": 67891,
  "/klmno": 23456,
  "/pqrst": 78912,
});

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
(async function () {
  try {
    const url = "https://my-url/some-code";
    console.log("fetching url", url);
    const response = await fetch(url);
    const codes = await response.json();
    console.log("got", codes);

    const codesObj = {};
    for (const code of codes) {
      await sleep(2000);

      const url = `https://my-url/${code}`;
      console.log("fetching url", url);
      const response = await fetch(url);
      const value = await response.json();
      console.log("got", value);

      codesObj[code] = value;
    }

    console.log("codesObj =", codesObj);
  } catch (error) {
    console.error(error);
  }
})();

// fetch mocker factory
function createFetchMock(dataByPath = {}) {
  const empty = new Blob([], {type: "text/plain"});

  const status = {
    ok:       { status: 200, statusText: "OK"        },
    notFound: { status: 404, statusText: "Not Found" },
  };

  const blobByPath = Object.create(null);
  for (const path in dataByPath) {
    const json = JSON.stringify(dataByPath[path]);
    blobByPath[path] = new Blob([json], { type: "application/json" });
  }

  return function (url) {
    const path = new URL(url).pathname;
    const response = (path in blobByPath)
      ? new Response(blobByPath[path], status.ok)
      : new Response(empty, status.notFound);
    return Promise.resolve(response);
  };
}

A: In this case... You should run and wait each fetch run finish before run new fetch by using async/await
runFetch = async (codesArr) => {
  for(let i = 0; i < codesArr.length; i++){
    const rawResponse = await fetch(`http://my-url/${codesArr[i]}`);
    const codeResponse = rawResponse.json();
    console.log(rawResponse);
    codesObj[codesArr[i]] = codeResponse;
  }
}

hope that help you.


text:
Q: Pygame window crashing on run I am trying to make a hangman game that has a window which shows the hangman being drawn every time you make a wrong guess.. i am using pygame library for it but when i run the program it opens the window and then crashes. How to fix?
Here's the code:
import pygame

def wait():
    result=None
    import msvcrt
    result=msvcrt.getch()
    return result

window=pygame.display.set_mode((600, 600))
window.fill((0, 0, 0))

running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
    if running==False:
        pygame.quit()

    print ("Press any key to start a game")
    wait()

    Wrong=0
    Word=list(input("Give the hidden word"))
    Hidden=[]
    Guess=input("Guess a letter or the word")

    for j in range(len(Word)):
        Hidden.append("_")

    if Guess in Word:
        for i in range(len(Word)):
            if Guess==Word[i]:
                Hidden.pop(i)
                Hidden.insert(i,Guess)
                print (Hidden)
    else:
        Wrong+=1

    if Wrong==1:
        White=pygame.draw.circle(window, (255, 255, 255),[300, 80], 50, 3)
        pygame.display.update()
    elif Wrong==2:
        Blue=pygame.draw.line(window, (0, 0, 255),[300, 130],[300, 350], 3)
        pygame.display.update()
    elif Wrong==3:
        Green=pygame.draw.line(window, (0, 255, 0),[300, 200],[400, 300], 3)
        pygame.display.update()
    elif Wrong==4:
        Red=pygame.draw.line(window, (255, 0, 0),[300, 200],[200, 300], 3)
        pygame.display.update()
    elif Wrong==5:
        Cyan=pygame.draw.line(window, (0, 255, 255),[300, 350],[200, 500], 3)
        pygame.display.update()
    elif Wrong==6:
        Yellow=pygame.draw.line(window, (0, 255, 255),[300, 350],[400, 500], 3)
        pygame.display.update()
    elif Wrong==7:
        print ("You Lost")

A: *

*Every pygame program needs pygame.init() at the beginning

*Use pygame.display.update() only once at the end of the program

*Your program freezes because input() breaks the main loop of your program

Pygame start file:
import pygame
from sys import exit

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

    #Your code...

    pygame.display.update()
    clock.tick(FPS)

You can solve this by adding an input box to the pygame window: https://stackoverflow.com/a/46390412/15500012
I hope it will help you, Adam


text:
Q: "hg log" command is taking hours instead of seconds on new machine The Jenkins mercurial plugin runs an hg log command at the beginning to determine which commits are new for that build.  Here's an example:  hg log --template "<changeset node='{node}' author='{author|xmlescape}' rev='{rev}' date='{date}'><msg>{desc|xmlescape}</msg><added>{file_adds|stringify|xmlescape}</added><deleted>{file_dels|stringify|xmlescape}</deleted><files>{files|stringify|xmlescape}</files><parents>{parents}</parents></changeset>\n" --rev pcdmis2015:0 --follow --prune 4e2c98f139772300206e87349c4d7b63e1a17d05 --encoding UTF-8 --encodingmode replace
On my old, out of warranty win7 machines, this command takes between 20 and 90 seconds to complete, depending on the machine.
But on my new win10 virtual machines, which have shown to be faster in every other regard so far, this same command in the same repository takes about 4.5 hours.
Why might this be?  What could be happening that takes so long?
Is there any way overcome or ameliorate this problem?

A: *

*It can be different Mercurials (standalone vs "for Pythons")

*It can be different versions|configurations of Pythons (if used)

*It can be damaged repo (check hg verify)

hg log --debug --time --profile will show you main time-eaters (as last resort)

A: Does you new machine have a virus scanner running?  They intercede in all file access and a log accesses a lot of files.


text:
Q: Best way to edit a nested protobuf field in react-admin? For our admin page, we are using the basic
<SimpleForm>
  <TextInput>
  ...
</SimpleForm>

pattern.
One of our fields, however, is a nested protobuf object. Although it's nested, most of the fields of this protobuf object are fairly basic. I tried using dot notation like
<TextInput
  label="nestedField"
  source="ProtobufObject.nestedField"
/>

but that doesn't seem to work. Is there a more straightforward way of handling this other than creating a custom input?

A: I don't know anything about ProtobufObject other than what I just read on the google site. I have an api that returns JSON below. To show the event name, source="event.eventName". If your payload isn't JSON, you'll need to convert it in your data provider.
[
  {
    "competitionName": "XYZ",
    "competitionStatus": "SCHEDULED",
    "id": 107,
    "createdAt": "2018-08-30T03:53:37.000Z",
    "updatedAt": "2018-08-30T03:53:37.000Z",
    "event": {
      "eventName": "XYZ",
      "eventDesc": "Something",
      "startDate": "2018-09-13T07:00:00.000Z",
      "startTime": "2018-08-30T01:00:58.482Z",
      "endTime": "2018-08-30T03:00:58.484Z",
      "eventLocation": "Gym",
      "competitionId": 107,
      "createdAt": "2018-08-30T03:53:37.000Z",
      "updatedAt": "2018-08-30T03:53:37.000Z",
    }
  }
]


text:
Q: Disable the selected value in drop down menu I have this drop down menu.It stores month, Jan-Dec. User can choose any value of the drop down menu but just one time only. Meaning, lets say previously he choose Jan, the next time if he logged in/ enter new record, he cannot choose Jan anymore or maybe remove the month permanently. Once he select the month, it will be store in session to other page. So, if you guys have any idea,suggestions, or plans, dont hesitate to leave ur answer here. Thank you.

A: Here are three working examples of what you're looking for:
Using jQuery:
http://jsfiddle.net/wLNZX/
With plain JavaScript:
http://jsfiddle.net/wLNZX/1/
Coded inline with the <select> tag:
http://jsfiddle.net/wLNZX/2/


text:
Q: In Python I'm trying to convert all files in directory from PDF to CSV, then edit csv with Pandas before saving to new folder I have a directory C:/Users/Desktop/folder/. I want to convert each file from a PDF to a CSV, make changes to the newly converted file using Pandas and NumpPy, then save it to a child directory
I have this working when it is just one file, but when adding code to get it working on all files in a directory, it doesn't work. Code, as is, does nothing. When I run it, it completes with nothing process and no errors.
import numpy as np
import pandas as pd
import tabula
import glob
from pathlib import Path

files = glob.glob("C:/Users/Desktop/folder/*.pdf")
childfolder = Path("C:/Users/Desktop/folder/childfolder/")

for file in files:
    # convert PDF into CSV
    tabula.convert_into(file, "Convert.csv", output_format="csv", pages='all')

    # read newly converted csv
    df = pd.read_csv("Convert.csv")

    # add empty row in 0th position
    df = pd.DataFrame([[np.nan] * len(df.columns)], columns=df.columns)
    df1 = df.append(df, ignore_index=True)

    # name columns added
    df1.rename(columns={ df.columns[0]: "Record"}, inplace = True)
    df1.rename(columns={ df.columns[1]: "Field"}, inplace = True)
    df1.rename(columns={ df.columns[2]: "FieldValue"}, inplace = True)
    df1.rename(columns={ df.columns[3]: "Reason"}, inplace = True)
    # df1.drop(df.columns[1], axis = 1)

    # drop empty rows to clean up
    new_df = df1.dropna(how='any',subset = ['Record'])

    # output
    new_df.to_csv(ChildFolder)

How do I convert all files in a directory, make edits, then save them to a different directory?

A: The argument to new_df.to_csv() must be a filename, not a folder name. Join the filename to the folder name to get the output file.
new_df.to_csv(os.path.join(ChildFolder, file.replace(".pdf", ".csv"))


text:
Q: Angular 2 ng2-scroll-to not working I'm trying to use ng2-scroll-to in my app, but it doesn't seem to be working and I can't figure out what is wrong.
I've imported it in my app.module.ts
import { ScrollToModule } from 'ng2-scroll-to';

and imported it in @NgModule
ScrollToModule.forRoot()

then in my app.component.html
Scroll to Div

//more content in here

Hello

Not sure why it wouldn't be working and I'm not getting any errors in the console. Any help?

A:

Hello

Little correction in your code


text:
Q: Авто обновление чтение файла php Подскажите пожалуйста, получаю данные из текстового фала вот таким кодом:

<?php echo file_get_contents('textfile.txt')
?>

После в этот txt файл заноситься новая информация, как получить новые данные из этого файла безе перезагрузке страницы?
Спасибо.


text:
Q: JAVA:the first output is difficult to understand [![enter image description here][1]][1]In my opinion,the first output should be "hello",but why the first output is "world" ?
    public static void main(String[] args) {
        System.out.println("hello");
        test();
    }
    public static void test() {
        System.out.println("world");
        main(null);
        System.out.println("!");
    }
   }

  [1]: https://i.stack.imgur.com/SXSHY.png

A: The main method is run by default. It is run first. Inside the main method, it:

*

*prints "hello"

*calls the test() method

In the test() method, it:

*

*prints "world"

*calls the main() method

And the process repeats, resulting in a StackOverflowError.
The main method was run first, so the order of events is as so:

*

*prints "hello"

*calls the test() method

*prints '"world"`

*calls the main() method

Therefore it prints "hello" first.


text:
Q: Angular pagination using PrimeNG I'm trying to paginate a table in my Angular project.
Doing the following:
app.module.ts
import { PaginatorModule } from 'primeng/paginator';

component.html

<ng-template pTemplate="header" let-columns>

            {{bookCol.header}}

</ng-template>

<ng-template pTemplate="body" let-book let-columns="bookCols">

                {{book[bookCol.field]}}

</ng-template>

Pagination is working fine, but the entire experience is reduced on simple blue numbers image here, not at all something that the official page is providing here
What am I missing?

A: include in angular.json
"styles": [
  "node_modules/primeicons/primeicons.css",
  "node_modules/primeng/resources/themes/omega/theme.css",
  "node_modules/primeng/resources/primeng.min.css",

],

A: Your angular.json file should be like that
"styles": [
  "node_modules/primeicons/primeicons.css",
  "node_modules/primeng/resources/themes/nova-light/theme.css",
  "node_modules/primeng/resources/primeng.min.css",

],

A: It is in .angular-cli.json file. Best practise is to add the style details
 "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.css",
        "../node_modules/font-awesome/css/font-awesome.min.css",
        "../node_modules/primeng/resources/primeng.min.css",
        "node_modules/primeicons/primeicons.css",
        "../node_modules/primeng/resources/themes/nova-light/theme.css",
        "styles.scss"  //external style sheet
      ],


text:
Q: Did this stormtrooper in "The Force Awakens" have a name? In The Force Awakens when the protagonists reach Maz Kanata's castle and are abruptly attacked by the Kylo Ren and the First Order, an unnamed Stormtrooper has a scuffle with Finn, showing off his bad-ass riot control baton and taking down Finn in the process, who was armed with the lightsaber. He is unfortunately killed by Han moments later.

For some reason this has turned into a meme, with many dubbing him TR-8R, or Tray Tor because of what he says to Finn. Does he actually have a real name?

A: Not in the current canon.

*

*He's not credited specially as far as I know by name
(the only 2 credited are  Michael Giacchino's FN-3181, and  Nigel Godrich's FN-9330; neither of them is described by anyone as being in that scene. One was supposedly the one arresting Poe, another one was supposedly  the one Han shot first on Starkiller base later)

*He has no name in the Foster's novelization

*There's no specific trooper mentioned as excelling with melee weapon in the prequel novel "Before the Awakening".
There's a chance that (based on him yelling "Traitor") he's one of Finn's close chums in the prequel book. Since Slip (FN-2003) was presumably - at least based on how he was described in the prequels - the one who got himself killed off on Jakku (and even if not, the one Finn always helped before so I don't see him insulting Finn and trying to kill him), that leaves:

*

*FN-2199, aka Nines (UPDATE: Starwars.com confirmed that this was Nines, hat/tip @AlfredoHernández)

*FN-2000, aka Zeros

A: Update: The Starwars.com website have officially named this character as FN-2199, one of the stormtrooper trainees who served with Finn in the star wars prequel novel Before the Awakening

MEET FN-2199, A.K.A. TR-8R:
His name is FN-2199. But his friends call him "Nines." As detailed in
  Greg Rucka's excellent book Before the Awakening, Nines trained and
  served on a squad with Finn (then FN-2187) in the First Order. That
  explains why he seems just a little extra angry upon seeing Finn
  during the attack on Maz's Castle. You can see FN-2199 in the image
  below by Phil Noto from Before the Awakening — he's the trooper seated
  in the background with red hair. Who'd have thought?

Hat tip to @AlfredoHernández

There's not been a character name released for him yet. The official Star Wars Databank refers to him as...

"Riot Control Stormtrooper"

and the screenplay just refers to him as "Stormtrooper"

FINN SURPRISES A STORMTROOPER WITH THE LIGHTSABER, then another!
  Untrained, he's athletic, brave, impressive. One Stormtrooper has a
  MACE --
STORMTROOPER: Traitor!
FINN and the TROOPER WITH THE MACE battle. The Mace Trooper KNOCKS
  FINN DOWN! The Stormtrooper is about to end him, when THE STORMTROOPER
  IS SHOT AND FALLS!

He's not named in the film's junior novelisation

The troopers were as startled as Finn when he sliced through armor,
  bone, and flesh. Two he cut down immediately. The third trooper
  dropped his rifle and brandished a melee weapon of his own, a riot
  control baton that crackled with blue electricity. Finn swung at him,
  but the trooper ducked and shoved Finn backward, off his feet. The
  trooper had raised his baton to finish Finn when a blaster bolt
  finished the trooper instead.

Nor in the Official Novelisation

A third came at him with a close-quarters weapon and the two locked in
  combat. Despite lack of any training with a lightsaber, Finn was
  athletic and courageous. In tandem with such traits, the saber made
  him a formidable fighter.
The trooper who had engaged Finn was big, strong, and agile. Finn
  realized the fight would have long since been over if not for the
  trooper's regard for the lethal potential of the lightsaber. That
  didn't stop him from finally knocking Finn to the ground and raising
  his own weapon for a killing strike—only to fall backward, shot before
  he could deliver the blow.

Nor in any of the film's official merchandise

A: Nines has apparently been confirmed as the squadmate who dies and streaks blood on Finn's mask. Zeros is a strong melee focused trooper who seems to have always had a beef with Finn. Nothing is for sure, but the good betting money is that "TR-8R" is actually FN-2000. Plus, if you see the guy he looks pretty awesome with his helmet off, with a big face scar and everything, so personally I'd love it to be him.


text:
Q: swap div's position from top div's I am trying to swap a div's position from top on and when I click another div then top div can be swap.
HTML

    <input type="text" value="div1" class="textbox " />

    <input type="text" value="div2" class="textbox " />

    <input type="text" value="div3" class="textbox " />

jQuery
(function ($) {
        $(".wrap").on("click", function () {
            if ($(this).index() == 0) {
            } else {
                $(this).insertBefore($(this).prev());
            }
        });
    }(jQuery));

The fact is I don't want to remove the div which I click instead want to swap the positions around.
How Can I do this using jQuery itself?

A: I would suggest using css to position the top div and just swap the class as follows:
(function ($) {
        $(".wrap").on("click", function () {
            if ($(this).index() == 0) {
            } else {
                $(".wrap").removeClass("top");
                $(this).addClass("top");
            }
        });
    }(jQuery));

A: this will swap whatever you click with the first element.
$(".wrap").on("click", function () {
  var $this = $(this);
  if ($this.index() == 0) {
  } else {
    var first = $this.siblings('.wrap').first();
    first.insertBefore($this);
    $this.prependTo($this.parent());
  }
});

if you just want to move the clicked element to the top, you can simply do
$this.prependTo($this.parent());

A: To swap the two DOM elements using jQuery, you could use something like this: -

 (function($) {
   $(".wrap").on("click", function(event) {
     var index = $(event.target).index();
     var first = $(".wrap").first();

     if (index > 0) {
       $(first).swapWith(this);
     }
   });
 }(jQuery));

 jQuery.fn.swapWith = function(to) {
   return this.each(function() {
     var copy_to = $(to).clone(true);
     var copy_from = $(this).clone(true);
     $(to).replaceWith(copy_from);
     $(this).replaceWith(copy_to);
   });
 };
.wrap {
  height: 100px;
  width: 200px;
  margin: 10px 10px 10px 10px;
  background-color: #2d8cd0;
}
h2 {
  color: white;
  text-align: center;
  padding-top: 20px;
  pointer-events: none;
}

1

2

3

4


text:
Q: Regression vs Classifier predict_proba Just a quick question, if I want to classify objects into either 0 or 1 but I would like the model to return me a 'likeliness' probability for example if an object is 0.7, it means it has 0.7 chance of being in class 1, do I do a regression or stick to classifiers and use the predict_proba function?
How is regression and predict_proba function different?
Any help is greatly appreciated!
Thank you!

A: Generally, for a qualitative problem that is to classify between categories or class, we prefer classification.

for example: to identify if it is night or day.

For Quantitative problems, we prefer regression to solve the problems.

for example: to identify if its 0th class or 1st class.

But in a special case, when we have only two classes. Then, we can use both classification and regression to solve two-class problems as in your case.
Please note that, this explanation is on the behalf of two-class point of view or multi-class problems. Though regression is to deal with real quantitative problems rather than classes.
Probability has nothing to deal specifically with methods. Each method deduce a probability and on the basis of that, they predict the outcome.

It is better if you explain the reference to predict_proba from your
  question.

Hope it helps!

A: Since you mention the predict_probafunction I'm assuming you are referring to the scikit-learn API.
To obtain class-membership probailities this is the right function. In the case of logistic regression, this function is somehow the natural output.
You should also check probability calibration


text:
Q: Turn led on in function with different args. Python I can't seem to wrap my head around how to do this. I tried searching but it just returns how to turn on a led with a raspberry pi. So here I am. I am trying to make a function so that I can check multiple values and if they match turn a led on. I guess my major issue is when it is true the led turns on, but if the next function shares the same led it will turn it off. If that makes sense.
#

def turnon(led,x)
    if x == updating_x:
        turn led # from led, on

    else:
        turn led # from led, off

while True:

    #led 1
    turnon(1,20)

    #led 1
    turnon(1,50)

    #led 2
    turnon(2,10)

So say updating_x=20 so the led #1 would turn on but then the next function that has the same LED would turn it off. I thought about changing it to this
if x == updating_x:
    turn led # from led, on
    time.sleep()
    turn led off

else:
    pass

But it is somewhat time critical and I will want the multiple leds to turn on together and not just one after the other. I don't want to get caught just sleeping if the value change true for another led.
FYI, the plan is 60ish leds with around 70 different check values
Any ideas on the right way to do this? and Thanks!
Edit:
Sorry I will try and explain it better. So with the example I gave, I want led 1 to turn on if the update_x  == 20 or 50. (if update_x = 20 now) In the loop, it runs the first function which is true so the led turns on. But the second function will be false so it turns the led off, although it is still true for the first function.  The problem is that I want to keep the led on until the first function returns false.
Ignore the second bit with the time.sleep in it, just an idea but won't work for what I want.
writing this I had an idea of having the x variables I want to work in a list and using that list in the function parameters, if that works.  In the end there will be around 60 leds with about 5 values to turn each one on, 60 lists sounds like a pain.


text:
Q: Java, multi-thread application,working main window when computing I would like to ask for advice how to design the application. Currently, I would like to rewrite a statistical application processing large data into a multi-thread version. My primary language is C++, sorry for my slightly beginner question :-).
The existing application is based on the following model. There is a MainWindow class continuously displaying previous results involving current zoom operation (GUI). Each statistical computation is based on the own class picking up the input data, performing the computation, showing results and its visualization (based on swing).
Unfortunately, the library is not written as multi-thread. It has an undesirable consequence: while a computation is running, it is impossible to work with MainWindow (browsing all results until new are obtained); it is "frozen"...
Yesterday, I tried to propose a single conceptual update:
public class MainWindow extends JFame {

private void fButtonActionPerformed(java.awt.event.ActionEvent e) {
   //Get data, single thread
   Matrix A = getData();  //Input data (block matrix)
   Matrix B;              //Output data (block matrix)

   //Computation in a separate thread
   FunctionMT f = new FunctionMT (A, B);
   Thread t = new Thread(f);
   t.start();    // Starting the thread

   //Display results in a form
   results.print(B);

   //Update graphic results
   scene.update(B);
   scene.repaint();
}

The sample function class FunctionMT  extends Thread library
public class FunctionMT extends Thread{
    private final Matrix A;
    private Matrix B;

    public FunctionMT (final Matrix A_, Matrix B_) {A = A_; B = B_;}
    public void run () { spDecomposition();}
    public void spDecomposition() {
        for (int i = 0; i < A.size; i++)
            for (int j = 0; j < A.size; j++)
                B(i,j) = f(A(i,));} //Some computationally hard step
}

The matrix A is the input matrix, B represents the output. The computation is performed in a single thread working with FunctionMT instance...
When a computation is run in a single thread, it is possible to work with the main window. Unfortunately, results are repainted before the computation is stopped.
I tried to add a join method()
 ...
 Thread t = new Thread(f);
 t.start();    // Starting the thread

 try{t.join();}  //Wait for its end
 catch(InterruptedException e) {e.printStackTrace();}

 results.print(B);

 scene.update(B);
 scene.repaint();
 ...

which waits until the results are processed.Unfortunately, it makes the main window frozen.
How to propose a multi-thread computation to be able to work with a main window during the computation as well as the form waits until the computation is finished?
Is it possible to add some function that processs system messages into for cycle ?
for (int i = 0; i < A.size; i++)
     for (int j = 0; j < A.size; j++)
          processSystemMessages();
          B(i,j) = f(A(i,));}

Another solution may join the computation algorithms and showing the results into the same thread, but it looks ugly :-) and breaks the design pattern.
Thank you very much for your help...

A: Try this:
UPDATE: looser coupling
public class MainWindow extends JFrame {

    private void fButtonActionPerformed(java.awt.event.ActionEvent e) {

        // ...

        FunctionMT f = new FunctionMT (A, B, new Runnable() {
            @Override
            public void run() {
                results.print(B);
                scene.update(B);
                scene.repaint();
            }
        });
        Thread t = new Thread(f);
        t.start();

        // Wait for computation:
        // won't do it here.
        // results.print(B);
        // scene.update(B);
        // scene.repaint();
    }
}

public class FunctionMT extends Runnable {

    // ...

    private Runnable callback;

    public FunctionMT (final Matrix A_, Matrix B_, Runnable callback) {

        // ...

        this.callback = callback;
    }

    private void spDecomposition() {

        // Do computation.

        SwingUtilities.invokeLater(callback);
    }
}


text:
Q: Проблемы с виджетом Twitter в sortable контейнере Сегодня столкнулся с еще одним глюком. На сайте в правом сайдбаре находятся share боксы фейсбука и твиттера, они помешены в ul li и обрабатываются плагином sortable jquery-ui для того, чтобы пользователи могли их сортировать между собой (не задумывайтесь зачем это - так захотели клиенты). Суть проблемы в том что когда хочешь передвинуть бокс с твиттером, происходит какое-то событие(курсор мыши прилипает к метке и даже если отпустить левую кнопку мыши бокс следует за курсором), а после того как мы переставили этот блок происходит перезагрузка страницы, правда мы видим только белый экран. Может кто знает что это может быть за глюки. (Все на локальной машине)

A: Странно,что никто не ответил, но проблему решил сам. Просто когда сортебле переставляет блоки и браузер перерисовывает их на новых местах, твиттеровский скрипт отрабатывал снова, что приводило к багу. Я не стал копаться в скриптах, а просто вынес вызов скрипта виджета на другую хтмл страницу и подгружал ее через ифрейм, конечно решение не очень "красивое", зато все работает.


text:
Q: knockout binding issue I use mapping plugin for creating the view model. Here's the watcher output from Chrome:
viewModel: Object
 Id: function observable()
 Language: function observable()
 QuoteListViewModel: Object
 QuoteSelectedViewModel: Object

The MVC Model is :
public class QuoteRequestViewModel
{
    public Guid Id { get; set; }
    public LanguageEnum Language { get; set; }

    public QuoteViewModel QuoteSelectedViewModel { get; set; }
    public QuoteListViewModel QuoteListViewModel { get; set; }
}

The QuoteViewModel is :
public class QuoteViewModel
{
    public string ProductName { get; set; }
    public decimal MonthPrice { get; set; }
    public decimal QuarterPrice { get; set; }
    public decimal BiannualPrice { get; set; }
    public decimal YearPrice { get; set; }

    public List<CoverQuoteViewModel> CoverQuotesViewModel { get; set; }
}

The QuoteListViewModel is not relevant here and actually works fine.
Two questions:
1) Why is QuoteSelectedViewModel  mapped as an Object instead of an Observable function ? I understand why it's the case for QuoteListViewModel  because it's an Array, but QuoteSelectedViewModel is not an Array.
2) I can't bind my DOM to QuoteSelectedViewModel. Here's what I do:
viewModel.customizeQuote = function () {
  viewModel.QuoteSelectedViewModel = this;
}

and customizeQuote is called there:

    Customize

When debugging, I can see that QuoteSelectedViewModel contains the correct Quote from the QuoteListViewModel Array. However doing:
viewModel.QuoteSelectedViewModel = this;

seems incorrect to me. It should be an observable and I should do
viewModel.QuoteSelectedViewModel( this );

Any idea what's wrong ?
[EDIT]
The fact that QuoteSelectedViewModel is not observable is obviously the root of the problem.
I've added the following code:
viewModel.SelectedQuote = ko.observable(viewModel.QuoteSelectedViewModel);

and in the customize method I do this instead:
viewModel.SelectedQuote(this);

So now, the list is bound. So how do I make the QuoteSelectedViewModel an observable object right from the beginning when I use the mapping plugin ?

A: The mapping plugin creates observables for the lowest level properties and arrays.  For nested objects it does not make the parent an observable.
var test = {
   sub: {
       name: "Bob"
   }
};

In this case, it will make name an observable, but sub will not be observable.
One option is to customize how objects are created using the mapping options, as described here.


text:
Q: How to split text file into multiple files and extract filename from line prefix? I have a simple log file with content like:
1504007980.039:{"key":"valueA"}
1504007990.359:{"key":"valueB", "key2": "valueC"}
...

That I'd like to output to multiple files that each have as content the JSON part that comes after the timestamp. So I would get as a result the files:
1504007980039.json
1504007990359.json
...

This is similar to How to split one text file into multiple *.txt files? but the name of the file should be extracted from each line (and remove an extra dot), and not generated via an index
Preferably I'd want a one-liner that can be executed in bash.

A: Since you aren't using GNU awk you need to close output files as you go to avoid the "too many open files" error. To avoid that and issues around specific values in your JSON and issues related to undefined behavior during output redirection, this is what you need:
awk '{
    fname = $0
    sub(/\./,"",fname)
    sub(/:.*/,".json",fname)
    sub(/[^:]+:/,"")
    print >> fname
    close(fname)
}' file

You can of course squeeze it onto 1 line if you see some benefit to that:
awk '{f=$0;sub(/\./,"",f);sub(/:.*/,".json",f);sub(/[^:]+:/,"");print>>f;close(f)}' file

A: awk solution:
awk '{ idx=index($0,":"); fn=substr($0,1,idx-1)".json"; sub(/\./,"",fn);
       print substr($0,idx+1) > fn; close(fn) }' input.log

*

*idx=index($0,":") - capturing index of the 1st :

*fn=substr($0,1,idx-1)".json" - preparing filename

Viewing results (for 2 sample lines from the question):
for f in *.json; do echo "$f"; cat "$f"; echo; done

The output (filename -> content):
1504007980039.json
{"key":"valueA"}

1504007990359.json
{"key":"valueB"}


text:
Q: Where are these javascript functions defined in this website? I was wondering whether is it possible to hide javascript files when visiting a website. In a first moment I thought it was not possible, you can obfuscate the code as much as possible but it will still be accessible to the user.
However I started reading some blog posts and sites that suggest some hacks to "try" to hide the js code. Some of the posts I read where theses:
http://www.webmasterworld.com/forum91/2713.htm
http://www.codingforums.com/archive/index.php/t-23293.html
I haven't understood them very well. Can someone explain them to me?
And here is an example: I have been browsing this page http://www.regexbuddy.com/ and I started looking at the source code with google chrome inspector to find out how were the functions that show the menus drop-down list implemented. I could see that every menu item has an onmouseover="showpopup(x);" event. Unfortunately I was not able to find this js function "showpopup", neither other javascript functions used throughout the code (showmenu for example). The server sends 2 javascript files menu.js and jgsoft.js but none of these files contained the functions definitions. These functions were neither defined in the html as inline script.
The curious thing is that if in the google console I type window.showpopup I am able to read the function. So where are these functions defined? Possible hacks to "try" to hide javascript files? Ways to bypass these hacks?

A: In the case of regexbuddy.com - the code is all in this file, as you guessed, but it's packed using packer. It's probably packed to try to deliver it faster, rather than to make it difficult to read, but it could be both reasons.
You can "unpack" it by pasting the contents of jgsoft.js into this tool.
So basically- yes you can hide all of the code, but since the browser has to execute it, it will always be possible to get at.

A: Javascript's eval() function takes a string as a parameter, parses the contents of that string as javascript source and executes it in the calling context. This is generally at the heart of such obfuscation code.
On your sample page, the file jgsoft.js contains javascript that, when executed, generates a string that contains the definitions for the functions it needs, then uses eval() to execute that and thus define the functions.
If you first go through the function and add line breaks / whitespace at relevant points, you can use a Javascript debugger that lets you step through execution line by line and view execution state, like Firebug, to observe the process.
In this case, the packing seems to have been done to make the file smaller, rather than just to obfuscate. In general, javascript obfuscation is pointless: if your browser can see it, so can you.

A: Here's a standard hack for you -
document.write(
  '<scr' + 'ipt type="text/javascript">function fo' + 'o(){alert("hello!");}');

Try searching the source for foo() :)
Ultimately, the script is always there - because Javascript is an interpreted (i.e. script) language, the source must be loaded naked at some point in order to be executed.  It might be obfuscated, but it must be there.
So, no, you can't 'hide' javascript source - you can just make it difficult to find.  Generally, a debug + step-through is the answer; if you have the patience.


text:
Q: ReSharper support for QUnit tests doesn't recognize Chutzpah Template import feature I have a bunch of QUnit tests. I am testing my code against html templates. For these tests I am using HTML template importing feature.
I have the following on the top of the JavaScript test file.
///<template path="mytemplate.html" mode="script" id="mytemplate" type="text/ng-template" />

If I run the tests using the VS 2015 Chutzpah plugin, the tests run fine but they fail if I use ReShaper(ReShaper ultimate 10.2). ReShaper won't recognize the template reference.
Has anyone tried to get ReShaper to run QUnit tests by using templates ? If this is not possible on ReShaper, has anyone tried to access html files during there QUnit tests which will work with ReShaper ?

A: After looking at ReSharper documentation looks like Reshaper doesn't really support Chutzpah. ReSharper will run Jasmine and QUnit.
ReShaper will however work with a custom html harness which could be generated by chutzpah.
This is something that unfortunately doesn't work for me because the html templates could change during development.
Maybe QUnit has a way to inject html templates in QUnit fixture.


text:
Q: Storing serialized data in a SQL Server XML / string column with DataTable and DataAdapter I wonder if someone can help me thru this scenario:
In SQL Server, I have a column of type XML or string . My application has a serializable data object which I want to store in that column.
The DataColumn in my DataTable has the type of this object. But when I try to update my database I get the exception

No mapping exists from object type […] to a known managed provider native type

This is actually clear, but is there a way to inject a converter / mapper doing this typed serialization and deserialization while Fill and Update using DataAdapter?
[Edit]

A: Yes, I do that. My column definition in the SQL Server table is:
[FileData] [varchar](max) NOT NULL

The Dataset in my app is defined like this, a string:

A: An Exception

No mapping exists from object type […] to a known managed provider native type

appears when you forget to serialize an object when working with an xml column.
Here is an example of the correct approach when working with xml type fields
    using (SqlConnection cnn = new SqlConnection(connectionString))
{
    string sql = "INSERT INTO Sale_T(SaleID, SaleInfo) values(@SaleId, @SaleInfo);";
    cnn.Open();
    using (SqlCommand cmd = new SqlCommand(sql, cnn))
    {
        Sale saleInfo = new Sale
        {
            Client = "Thomas",
            SaleDate = DateTime.Now,
            Items = new List<Product> {
                new Product { ProductName = "Apple", Price = 1.5 },
                new Product { ProductName = "Orange", Price = 0.8 } }
        };
        cmd.Parameters.AddWithValue("@SaleId", 2);
        // An attempt to directly assign an object leads to System.ArgumentException "No mapping exists from object type Sale to a known managed provider native type."
        // cmd.Parameters.AddWithValue("@SaleInfo", saleInfo);
        // you have to pre-serialize

        var Ser2String = (Sale si) =>  {
            XmlSerializer mySerializer = new XmlSerializer(typeof(Sale));
            using (StringWriter stringWriter = new StringWriter())
            {
                mySerializer.Serialize(stringWriter, si);
                return stringWriter.ToString();
            }
        };

        string serSale = Ser2String(saleInfo);
        cmd.Parameters.AddWithValue("@SaleInfo", serSale);
        cmd.ExecuteNonQuery();
    }
}

OK, here's the continuation of the story, only now using
void DataAdapterFillExample(){
using (SqlConnection con = new SqlConnection(connectionString))
{
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Sale_T", con))
    {
        cmd.CommandType = CommandType.Text;
        using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
        {
            using (DataTable dataTable = new DataTable())
            {
                dataAdapter.Fill(dataTable);
                foreach (DataRow row in dataTable.Rows)
                {
                    string saleID = row["SaleID"].ToString();
                    // here you can add desSerialization
                    string saleInfo = row["SaleInfo"].ToString();
                    Console.WriteLine($"{saleID} | {saleInfo}");
                }
            }
        }
    }
}

result:

1 | Peter0001-01-01T00:00:00Apple1.5Orange0.8
2 | Thomas2023-01-23T18:01:50.4545511+03:00Apple1.5Orange0.8


text:
Q: UIAlertController not getting deallocated I have created a UIAlertController and added a text field into it. The problem is that the after I dismiss the alertcontroller, it is not deallocating and shows in the memory graph.
        let alertController = UIAlertController(title: "Enter link", message: nil, preferredStyle: .alert)
        alertController.addTextField { (textField) in
            textField.placeholder = "www.xxx.com"
        }

        let cancel = UIAlertAction(title: "CANCEL", style: .cancel, handler: nil)
        let ok = UIAlertAction(title: "SUBMIT", style: .default) { [weak self] (_) in
            guard let self = self else { return }
            guard let textFields = alertController.textFields, let textField = textFields.first else { return }
            if let text = textField.text {

            }
        }
        alertController.addAction(cancel)
        alertController.addAction(ok)
        present(alertController, animated: true, completion: nil)

However, if I remove the alertController.addTextField then it gets deallocated and it does not exist in the memory graph.
I tried checking if there are any memory leaks introduced due to my code but found none.

A: You're retaining the alertController inside of "ok" alert action, which is in turn retained by UIAlertController.
That's a retain cycle, neither of objects will be able to release each other.
You should avoid that, perhaps by using a weak reference, i.e:
let ok = UIAlertAction(title: "SUBMIT", style: .default) { [weak alertController] (_) in
    // Upgrade weak to strong reference
    guard let alertController = alertController else { return }

    // Do your thing
}


text:
Q: Setting java classpath for lucene on a mac I downloaded the lucene jars and then added them to the CLASSPATH variable via my .bash_profile, the paths to the jars display correctly in the terminal.
export CLASSPATH=/Users/dk/lucene-3.4.0/lucene-core-3.4.0.jar
export CLASSPATH=$CLASSPATH:/Users/dk/lucene-3.4.0/contrib/demo/lucene-demo-3.4.0.jar

echo $CLASSPATH
/Users/dk/lucene-3.4.0/lucene-core-3.4.0.jar:/Users/dk/lucene-3.4.0/contrib/demo/lucene-demo-3.4.0.jar

However, java still complains to me when I try to run the demo:
java org.apache.lucene.demo.IndexFiles -docs .

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/lucene/demo/IndexFiles
Caused by: java.lang.ClassNotFoundException: org.apache.lucene.demo.IndexFiles
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
......

I was able to follow this exact procedure to get the lucene demo working on an ubuntu machine, now I just want it to be able to run on my mac. It seems there are similar questions floating around stackoverflow but none of them seem to answer this question.

A: Are you sure you have your paths right? It works fine for me.
.../lucene-3.4.0/tmp $ ls
lucene-core-3.4.0.jar   lucene-demo-3.4.0.jar
.../lucene-3.4.0/tmp $ export CLASSPATH=./lucene-core-3.4.0.jar:./lucene-demo-3.4.0.jar
.../lucene-3.4.0/tmp $ echo $CLASSPATH
./lucene-core-3.4.0.jar:./lucene-demo-3.4.0.jar
.../lucene-3.4.0/tmp $ java org.apache.lucene.demo.IndexFiles -docs .
Indexing to directory 'index'...
adding ./lucene-core-3.4.0.jar
adding ./lucene-demo-3.4.0.jar
1485 total milliseconds
.../lucene-3.4.0/tmp $

A: As of Lucene 6.0, these seem to work:
java -cp ./core/lucene-core-6.0.0.jar:./analysis/common/lucene-analyzers-common-6.0.0.jar:./demo/lucene-demo-6.0.0.jar  org.apache.lucene.demo.IndexFiles -docs <directory to index>

For the search demo:
java -cp ./core/lucene-core-6.0.0.jar:./analysis/common/lucene-analyzers-common-6.0.0.jar:./queryparser/lucene-queryparser-6.0.0.jar:./demo/lucene-demo-6.0.0.jar  org.apache.lucene.demo.SearchFiles


text:
Q: How to add template to child from ts code using ElementRef in angular2 Lets say i have a component app and a component child, in App Component template i have the ability to use
<child-template></child-template> and its working just fine.
I have another js data table add on that creating a table, i would like to find element in the table and use ElementRef.nativeElement in order to add the  dynamicly from the typescript code. is it possible by someway?
something like:
element = $(this.el.nativeElement.children[0]);
element.parent().find(".dt-toolbar").child( ---> <child-template> / new ChildComponent()<-----)


text:
Q: Bijection of complements Let $E$ and $F$ be subsets of some set $S$, which may be finite or infinite. Suppose we are given a bijection $g\colon E\to F$. Is there an explicit way to construct from $g$ a bijection $h\colon S\setminus F\to S\setminus E$?
By explicit, I mean that it is not enough to show that $g$ exists (this is clear, since the cardinalities of $S\setminus F$ and $S\setminus E$ are equal).


text:
Q: How come matlab run slower and slower when running a program that takes long time to execute? There is a program that my matlab runs, since there are two gigantic nested for-loop, we expect this program to run more than 10 hours. We ask matlab to print out the loop number every time when it is looping.
Initially (the first 1 hour), wee see the loop number increment very fast in our screen; as time goes by, it goes slower and slower..... now (more than 20 consecutive hours of executing the same ".m" file and it still haven't finished yet), it is almost 20 times slower than it had been initially.
The ram usage initially was about 30%, right now after 20 hours of executing time, it is as shown below:

My computer spec is below.
What can I do to let matlab maintain its initially speed?

A: Some general hints, if they don't help I suggest to add the code to the question.

*

*Don't print to console, this output slows down execution and the output is kept in memory. Write a logfile instead if you need it. For a simple status, use waitbar

*Verify you are preallocating all variables

*Check which function calls depend on the loop index, for example increasing size of variables.

*If any mex-functions are used, double check them for memory leaks. The standard procedure to do this: Call the function with random example data, don't store the output. If the memory usage increases there is a memory leak in the function.

*Use the profiler. Profile your code for the first n iterations (where n matches about 10 minutes), generate a HTML report. Then let it run for about 2 hours and generate a report for n iterations again. Now compare both reports and see where the time is lost.

A: I can only guess, but my bet is that you have some array variables that have not been preallocated, and thus their size increases at each iteration of the for loop. As a result of this, Matlab has to reallocate memory in each iteration. Reallocating slows things down, and more so the larger those variables are, because Matlab needs to find an ever larger chunk of contiguous memory. This would explain why the program seems to run slower as time passes.
If this is indeed the cause, the solution would be to preallocate those variables. If their size is not known beforehand, you can make a guess and preallocate to an approximate size, thus avoiding at least some of the reallocating. Or, if your program is not memory-limited, maybe you can use an upper-bound on variable size when preallocating; then, after the loop, trim the arrays by removing unused entries.

A: I'd like to point everybody to the following page in the MATLAB documentation: Strategies for Efficient Use of Memory. This page contains a collection of techniques and good practices that MATLAB users should be aware of.
The OP reminded me of it when saying that memory usage tends to increase over time. Indeed there's an issue with long running instances of MATLAB on win32 systems, where a memory leak exists and is exacerbated over time (this is described in the link too).
I'd like to add to Luis' answer the following piece of advice that a friend of mine once received during a correspondence with Yair Altman:

Allocating largest vars first helps by assigning the largest free contiguous blocks to the highest vars, but it is easily shown that in some cases this can actually be harmful, so it is not a general solution.
The only sure way to solve memory fragmentation is by restarting Matlab and even better to restart Windows.

More information on memory allocation performance can be found in the following undocumentedMatlab posts:

*

*Preallocation performance

*Allocation performance take 2


text:
Q: Proper practice of switching between user controls in an ASP.NET page Consider the following scenario:
I have a .aspx page without two .ascx(s). One of which contains search functionalities, while the other user control is responsible for user input.
Now I have a "Create" button located inside the first user control (search) that allows users to create new records from the second user control. Currently, this is what I have been doing.
//initial state
UserControlA (Search) - Visible="true"
UserControlB (Create) - Visible="false"

protected btnCreate_Click(object sender, EventArgs e)
{
    UserControlA.visible = false;
    UserControlB.visible = true;
}

In this case, my user controls are switched between the first and the second. However, this is posted whereby whenever user hits the refresh button, a "confirm form resubmission" alert box is shown.
What is the best practice in having to switch user controls on the same page url without having the form resubmission whenever a user hits the refresh button?


text:
Q: Cannot import enum from @prisma/client So i'm building a telegram bot using grammY, Prisma running on Deno. Whilst working on a functionality that requires users to fill in some fields for a form, i decided to use conversations like i always do but this i decided to use Prisma enums for the conversation.form.select. But when i tried importing the enum, i get this error:
error: Uncaught SyntaxError: The requested module '@prisma/client' does not provide an export named 'BusinessTypeEnum'
import { BusinessTypeEnum } from "@prisma/client";
         ^
    at <anonymous> (file:///home/waptik/code/bots/xxxxx/src/telegram/handlers/conversations/xxxx.conversation.ts:6:10)

Environment & setup

*

*OS: Ubuntu

*Database: PlanetScale

*Deno version:  1.30.3

*grammY: 1.13.1

Prisma Version
4.9.0

partial conversation.ts
import { GrammyContext, GrammyConversation } from "~grammy/context.ts";
import { Composer, createConversation } from "~grammy/deps.ts";
import { handleErrorMessage } from "~grammy/helpers/handleErrors.ts";
import { Prisma, BusinessTypeEnum } from "@prisma/client";

async function createXxxx(convo: GrammyConversation, ctx: GrammyContext) {
  try {
    await ctx.replyWithChatAction("typing");

    const bizTypes = Object.keys(BusinessTypeEnum).map((o) => o);
    console.log({ bizTypes });

  } catch (e) {
    const message = handleErrorMessage(e);
    await ctx.reply(message);
  }
  return;
}

partial schema.prisma
generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["deno"]
  output          = "./generated/client"
}

datasource db {
  provider     = "mysql"
  url          = env("DATABASE_URL")
  relationMode = "prisma"
}

enum BusinessTypeEnum {
  PRODUCT
  SERVICE
  BOTH
  OTHER
}

import_map.json
{
    "imports": {
        "@/": "./src/",
        "@utils/": "./src/utils/",
        "~grammy/": "./src/telegram/",
        "@prisma/client": "./prisma/generated/client/deno/edge.ts",
        "~prisma": "./prisma/mod.ts",
        "$std/": "https://deno.land/std@0.176.0/",
        "grammy": "https://deno.land/x/grammy@v1.13.1/mod.ts",
        "grammy/types": "https://deno.land/x/grammy@v1.13.1/types.deno.ts",
        "grammy-conversations/": "https://deno.land/x/grammy_conversations@v1.1.1/",
        "menu": "https://deno.land/x/grammy_menu@v1.1.2/mod.ts",
        "zod": "https://deno.land/x/zod@v3.20.5/mod.ts",
    }
}

So i'm expecting these values PRODUCT, SERVICE, BOTH, OTHER to be printed in console without any errors.
I also tried this suggestion as well as deleting prisma/generated, node_modules, package***.json before running deno run -A --unstable npm:prisma db push && deno run -A --unstable npm:prisma generate --data-proxy but nothing happened. I created a github issue but i got no replies, that's why i'm posting here


text:
Q: using apply to readd value back into orginal dataframe? I applogize in advance as this question is partly technical and partly understanding better pandas/python design.
Here's what I'm trying to do. Give this data:
a,b
1,2
1,3
2,4
2,5

I want to create a third column ['c'] with some data based on each column and grouping of A. The way I have done it is:
for item in df.a.unique():
   dataSetToProcess = df.loc[df['a'] == item][['a', 'b']]
   dataSetToProcess['c'] = dataSetToProcess.apply(MyFunction)

with this approach, I have a value for C but it's only on dataSetToProcess which is not part of the main DF. I would like to have the value of C available in the main DF.
my expected results(for simplicity of example, let's say each group of column A just averages the group itself and adds it to column C):
a,b,c
1,2, 2.5
1,3, 2.5
2,4, 4.5
2,5, 4.5

My two thoughts were to take each result and map column A,B to the original DF but was wondering if there was an easier/cleaner approach?

A: Let's suppose you have two dataframes, df1 and dataSetToProcess:
df1 = pd.DataFrame({"a": [1, 1, 2, 2], "b": [2, 3, 4, 5]})
dataSetToProcess = pd.DataFrame({"a": [1, 2], "c": [2.5, 4.5]})

print(df1)
print(dataSetToProcess)

   a  b
0  1  2
1  1  3
2  2  4
3  2  5
   a    c
0  1  2.5
1  2  4.5

Then:
df1 = df1.merge(dataSetToProcess, on="a")
print(df1)

Prints:
   a  b    c
0  1  2  2.5
1  1  3  2.5
2  2  4  4.5
3  2  5  4.5

From there, you can compute your variable based on a, b and c columns.