text:
Q: Fatal Exception: NSRangeException - index 2 beyond bounds [0 .. 1] In one of the library that i use in a swift project, a line causes app to crash. I try to understand and fix it but no luck. I know that it is caused by an array index error. Anyone can help?
Crash Report
Fatal Exception: NSRangeException
0  CoreFoundation                 0x180a42e38 __exceptionPreprocess
1  libobjc.A.dylib                0x1800a7f80 objc_exception_throw
2  CoreFoundation                 0x180922ebc -[__NSArrayM removeObjectAtIndex:]
3                          0x10000ac70 -[ChatSectionManager messageForIndexPath:] (ChatSectionManager.m:435)
4                          0x10001c194 -[Chat tableView:cellForRowAtIndexPath:] (Chat.m:596)
5  UIKit                          0x185ee2f40 -[UITableView _createPreparedCellForGlobalRow:withIndexPath:willDisplay:]
6  UIKit                          0x185ee30a8 -[UITableView _createPreparedCellForGlobalRow:willDisplay:]

ChatSectionManager.m
 - (QBChatMessage *)messageForIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.item == NSNotFound) {
        return nil;
    }

    QMChatSection *currentSection = self.chatSections[indexPath.section];
    //crashes here line 435
    return currentSection.messages[indexPath.item];
}

Chat.m
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.chatSectionManager messagesCountForSectionAtIndex:section];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.chatSectionManager.chatSectionsCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *) indexPath {

    QBChatMessage *messageItem = [self.chatSectionManager messageForIndexPath:indexPath];

... Method that contains removeObjectAtIndex
- (void)deleteMessages:(NSArray *)messages animated:(BOOL)animated {

    dispatch_async(_serialQueue, ^{

        NSMutableArray *messagesIDs = [NSMutableArray array];
        NSMutableArray *itemsIndexPaths = [NSMutableArray array];
        NSMutableIndexSet *sectionsIndexSet = [NSMutableIndexSet indexSet];

        self.editableSections = self.chatSections.mutableCopy;

        for (QBChatMessage *message in messages) {
            NSIndexPath *indexPath = [self indexPathForMessage:message];
            if (indexPath == nil) continue;

            QMChatSection *chatSection = self.chatSections[indexPath.section];
            [chatSection.messages removeObjectAtIndex:indexPath.item];

            if (chatSection.isEmpty) {
                [sectionsIndexSet addIndex:indexPath.section];
                [self.editableSections removeObjectAtIndex:indexPath.section];

                // no need to remove elements whose section will be removed
                NSArray *items = [itemsIndexPaths copy];
                for (NSIndexPath *index in items) {
                    if (index.section == indexPath.section) {
                        [itemsIndexPaths removeObject:index];
                    }
                }
            } else {

                [itemsIndexPaths addObject:indexPath];
            }
        }

        dispatch_sync(dispatch_get_main_queue(), ^{

            self.chatSections = self.editableSections.copy;
            self.editableSections = nil;

            if ([self.delegate respondsToSelector:@selector(chatSectionManager:didDeleteMessagesWithIDs:atIndexPaths:withSectionsIndexSet:animated:)]) {

                [self.delegate chatSectionManager:self didDeleteMessagesWithIDs:messagesIDs atIndexPaths:itemsIndexPaths withSectionsIndexSet:sectionsIndexSet animated:animated];
            }
        });
    });
}

NOTE: This crash happens randomly and i don't know why
FABRIC CRASH REPORT
http://crashes.to/s/679e90f0c90

A: It's definitely a problem with deleteMessages, look where your thread 16 is at the crash:

QMChatSectionManager.m line 228
  __48-[QMChatSectionManager deleteMessages:animated:]_block_invoke

Check which line 228 is exactly to know for sure what the problem is, but I'll go out on a limb here and guess it's
[chatSection.messages removeObjectAtIndex:indexPath.item];

so you're removing on thread 16 the data structure referenced on the main thread by messageForIndexPath. This, as you've noticed, is an open invitation to a race condition which is nigh on impossible to reproduce on demand.
The fix is to not modify the contents of chatSection in the background thread. Looks like you've already got the right idea where you assign the completed section list on the main thread,
self.chatSections = self.editableSections.copy;

just apply that logic to every item changed within the section list as well, and your random crashes will disappear.


text:
Q: Is it possible to decide which function runs on which processor in MPI or any other c++ library? Suppose I had 8 processes and four processors/cores.Can I allocate specific processes to specific cores before program execution?
e.g
Processor 1= process no 4,5
Processor 2= process no 1,3
Processor 3= process no 2,6
Processor 4= process no 7,8

A: You may want to have a look at the SetProcessorAffinityMask() function. It's not exactly what you want, but the closest you can get, IMHO.

A process affinity mask is a bit vector in which each bit represents a logical processor on which the threads of the process are allowed to run. The value of the process affinity mask must be a subset of the system affinity mask values obtained by the GetProcessAffinityMask function. A process is only allowed to run on the processors configured into a system. Therefore, the process affinity mask cannot specify a 1 bit for a processor when the system affinity mask specifies a 0 bit for that processor.

I'd recommend to also look at the comments on that page.

A: What operating system? See sched_setaffinity cpu affinity in linux for Linux.

redpajama_set_name: RedPajamaStackExchange


text:
Q: quartz crystal oscillator applied voltage I know that in quartz watches a quartz crystal is used to keep time by counting it's vibrations, caused by the voltage applied to it.
I don't understand if this voltage is DC or AC:
If DC is used, why does the quartz oscillate instead of changing position permanently?
If AC is used, doesn't he quartz oscillator have to oscillate at the same frequency as the AC? If so, then there's no need for the mechanical transducer.

A: It's AC, BUT:
It's not really that an AC voltage is applied to the quartz:
The quartz has the nice property of that if you invert the voltage across it, it takes some time for the quartz to "follow":

For a start, assume the left hand side of the quartz X has just become negative, the right hand side positive. That will lead to the quartz crystal expanding (or contracting) in a specific way, which will overshoot, and a little later invert that voltage. Since that will revert the voltage at the input of the first inverter, that will invert its output – and the cycle starts again.
The specific delay at which this happens due to the mechanical properties of the quartz leads to a resonance frequency that the quartz defines.
So, no, no AC voltage is applied, but with a bit of negative feedback, you can make a quartz oscillate at a stable freqeuncy.

A: A quartz crystal is used in an oscillator circuit.  The oscillator will be powered by DC, but generates an AC signal.  The frequency of the generated signal will be determined by the characteristics of the crystal.

A: Here is progressively more details on Quartz oscillator behavior

simulate this circuit – Schematic created using CircuitLab

A: There are simpler answers, but incomplete, so challenge yourself to understand and ask better questions. This is just a supplement to @analogsystemsrf fine answer.
There must be a DC bias for the inverter and it must be self-biased with this negative feedback to allow it to operate with max. the gain in the linear mode.

*

*Gain can be 10 to 100 typ. per stage in the inverter and frequency limited by output rise time BW=0.35/Tr.

*

*Every CMOS inverter has a gain-bandwidth factor ( often selected as unbuffered) but has excess gain to convert the sine-wave input biased at Vdd/2 into a full-swing square-wave output at, ( or near) a 50% duty cycle.

Since this question suggests a design using the inverting parallel resonant crystals, (Xtal) the CMOS inverter creates the gain-phase condition required to sustain oscillation by AC positive feedback.

doesn't the quartz oscillator have to oscillate at the same frequency as the AC?

It does not mean you get 5kV out of the crystal with 1V input because the gain is limited by the damping of the ESD input clamp diodes. Due to XTAL power limits of 10uW, a driver Rs of 1k is often mandatory for best MTBF.
Crystals > 20 MHz tend to operate as harmonic oscillators 3rd 5th or 7th harmonics called "overtones".
Anecdotal:  I used this fact to design an injection locked Xtal Oscillator that required only 10 clk cycles then no data transitions for 1024 NRZ data bits at 4Mbps to self-clock synchronous-data with no need for bi-phase or a separate clock signal to be transmitted. This was broadcast on TV in the early '80s using blanking interval lines to download games etc to home computers such as ][+, Commodore and TRS-80.  Sadly ahead of it's time for slow decision makers in Cable TV to buy our network design.


text:
Q: Not able to append to a file in PHP I am using the following code
$file = "./text.php";
$newData = "WQEQ";
file_put_contents($file, $new_data, FILE_APPEND | LOCK_EX);

When I check the file text.php after running the above the file has not been appended to, can someone explain what I am missing?

A: First, you use two different variables in your script. $newData and $new_data. You fail to define $new_data before using it.
Also, you may not have permission to write the file. You might want to check if the file exists and is writable first:
$file = "./text.php";
if (!file_exists($file)) {
  die("sorry!, but $file does not exist");
}
if (!is_writable($file)) {
  die("You do not have permission to write to $file");
}
$newData = "WQEQ";
file_put_contents($file, $newData, FILE_APPEND | LOCK_EX);

Also, as @dont-panic pointed out, you can more easily detect this sort of error -- where you try to use a variable you have not defined -- if your environment is configured to show errors of type E_WARNING and E_NOTICE. You shouldn't turn on that error reporting on a production machine, but on your development environment, consider using the error_reporting() function to set the error threshold or consider altering the error_reporting and display_errors settings in your PHP.ini file.


text:
Q: ionic 3 pull to refresh causing complete ion-content scroll in ios I had segment-buttons on top and ion-list down to it. I had ion-refresher at top of the list . When i continuously pull ion-refresher, Iam getting over-scroll effect in ios i.e., the segment buttons are getting pulled along with the list. I tried options no-bounce , has-bouncing="false", over-scroll="false" and what all I found in google, but nothing seems to work in ios.
Thanks in advance.


text:
Q: cv::HoughLines on iOS fails with 'OpenCV Error: Assertion failed' I'm in the process of writing an app for iOS (using ARC) that does Canny edge detection and a Hough transform on an image and returns the y position of a horizontal line from a specific portion of it. To achieve this, I'm using the OpenCV library.
The Canny edge detection was easy enough to do, but the cv::HoughLines method fails every time, with a nasty 'Assertion failed' error. Here is a code snippet of what I'm attempting:
cv::cvtColor(myImage, inputImage, cv::COLOR_RGB2GRAY);

cv::Canny(inputImage, outputImage, 200, 600);

cv::Vec2f lines; // short for 'Vec<float, 2>'
cv::HoughLines(outputImage, lines, 1, CV_PI/180, 100);

At first, I wasn't sure whether Vec2f was correct, so I've tried also defining lines as cv::Mat instead... But then, cv::HoughLines doesn't return any data at all - at least not when checking with cv::countNonZero(lines)
Being fairly new to iOS and Objective-C (and coming from a less C-based coding background) any corrections and tips would be greatly appreciated!

A: The docs are pretty much clear about this:
void HoughLines(Mat& image, vector<Vec2f>& lines, double rho, double theta, int threshold, double srn=0, double stn=0)

That said, you need to change the parameter type to std::vector<cv::Vec2f>:
std::vector<cv::Vec2f> lines;
cv::HoughLines(outputImage, lines, 1, CV_PI/180, 100);

If you have any more problems try to look for examples that use this function, like the FiducialDetector.


text:
Q: Navigate on Button Click to Path via React Router 5 I have a class-based App component in my React app. This component is defined like this:
import React from 'react';
import { Link, BrowserRouter as Router, Route, Switch, useHistory } from 'react-router-dom';

// Import pages
import Page1 from './pages/page-1';
import Page2 from './pages/page-2';

class App extends React.Component {
  navigateToPage1 = () => {
    const history = useHistory();
    history.push('/page-1');
  }

  navigateToPage2 = () => {
    const history = useHistory();
    history.push('/page-2');
  }

  render() {
    return(

        <Router>

            <button onClick={this.navigateToPage1}>Visit Page 1</button>
            <button onClick={this.navigateToPage2}>Visit Page 2</button>

            <Link to="/page-1">Page 1</Link>
            <Link to="/page-2">Page 2</Link>

            <Switch>
              <Route exact path="/">
                <Page1 />
              </Route>

              <Route path="/page-1">
                <Page1 />
              </Route>

              <Route path="/page-2">
                <Page2 />
              </Route>
            </Switch>

        </Router>

    );
  }
}

export default App;

When a user clicks one of the Link elements, the app behaves like I would expect. The Page1 or Page2 is shown without refreshing the browser. However, if I click one of the button elements, I receive an error that says: "Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.". My question is, how do I recreate the same behavior as the Link elements in a class-based component?
I am trying to figure out how to do this in JavaScript as I need to navigate to a path via a custom component. The sample code just isolates the issue to demonstrate it. I'm using the following versions:
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^5.3.0",

A:
My question is, how do I recreate the same behavior as the Link elements in a class-based component?

One solution is to define a custom Button component and then use that in the component prop of the Link component.
function Button(props) {
  const { navigate, href, children } = props;
  return (
    <button onClick={() => navigate(href)}>
      {children}
    </button>
  );
}

  <Link to="/page-1" component={Button}>Visit Page 1</Link>
  <Link to="/page-2" component={Button}>Visit Page 2</Link>

  <Link to="/page-1">Page 1</Link>
  <Link to="/page-2">Page 2</Link>


text:
Q: trying to get multimap to print out questions The multimap contains multimap<int,Questions*> map;.  Im trying to get the map printing out using the following method:
Questions* Questions::printQuestion(int level)
{
    multimap<int, Questions*>::iterator it;
    pair<multimap<int, Questions*>::iterator,multimap<int, Questions*>::iterator> ret;

    ret = map.equal_range(level);
    if(ret.first != ret.second)
    {
    size_t sz = distance(ret.first, ret.second);
    size_t idx = rand() % sz;
    advance(ret.first, idx);
    it =ret.first;
    return (*it).second;
    }
    else
    {
        return NULL;
    }
}

But the method does nothing.  Can anybody help me with this?

A: This function doesn't print anything. It returns a Questions* that is randomly chosen from all questions with the given level. So if there are three questions with level 5, and you call printQuestion(5), you will get a pointer to a random question of those three. If you want to print the question that is chosen in this function, you will have to do something like so:
Questions* question = (*it).second;
std::cout << question->getText() << std::endl;

Replace getText() with whatever you need to do to print the question.
If you want the client that calls the function to print the question, you'll do:
Questions* question = printQuestion(5);
std::cout << question->getText() << std::endl;

By the way, it's not very common to name classes with the plural form.  It'll be easier to read your code if you class is called Question instead of Questions.


text:
Q: angular-module-federation routing from micro frontend to shell I have angular microfrontnd application using angular-module-federation. It includes one main shell application and three microfronteds wrapped with web components. Microfrontends are using module-federation-tools's connectRouting function to connect shell routing with microfronteds routing. It is working well.
But... I have a case, where in microfronted application wrapped as web component is a link which provides to shell (like home button). Routing inside web component (microfronted) works pefectly fine.
Is there a possibility to trigger shell routing from microfronted wrapped with web component?


text:
Q: I Can't show my database tables through migration command on powershell terminal (Windows 10) I tried to run: php artisan migrate
Also to connect to MySQL using terminal on Windows.
I Got this error:
  SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it (SQL: select * from information_schema.tables where table_schema = firstproject and table_name = migrations and table_type = 'BASE TABLE')

  at C:\Users\ekind\Desktop\LaravelTest\FirstProject\vendor\laravel\framework\src\Illuminate\Database\Connection.php:692
    688▕         // If an exception occurs when attempting to run a query, we'll format the error
    689▕         // message to include the bindings with SQL, which will make this exception a
    690▕         // lot more helpful to the developer instead of just the database's errors.
    691▕         catch (Exception $e) {
  ➜ 692▕             throw new QueryException(
    693▕                 $query, $this->prepareBindings($bindings), $e
    694▕             );
    695▕         }
    696▕     }

  1   C:\Users\ekind\Desktop\LaravelTest\FirstProject\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDOException::("SQLSTATE[HY000] [2002] No connection could be made because the target machine actively refused it")

  2   C:\Users\ekind\Desktop\LaravelTest\FirstProject\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
      PDO::__construct()

.env file:
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=firstprojectdb
DB_USERNAME=root
DB_PASSWORD=Ekin1234

I tried to change my DB_HOST to "localhost" but it didn't work.
When I want to show databases it shows those;
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| firstproject       |
| firstprojectdb     |
| information_schema |
| mysql              |
| performance_schema |
| sakila             |
| sys                |
| world              |
+--------------------+

But even if I create tables like these it didn't see
public function up()

{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id'); // İdentity(1,1) İd int
        $table->string('title');  // title (Create a new string column on the table.)
        $table->mediumText('body'); // body  (Create a new medium text column on the table.)
        $table->timestamps();
    });

As you see;
mysql> show tables;
Empty set (0.00 sec)

I even delete the extension of "extension=pdo_mysql" but it didn't work to me.
PLS HELP ME GUYS

A: Try to make sure that your server is running, if you are working on the localhost check your Xampp that the server and mysql both are running. see image here make sure these are not stopped like this First run: php artisan migrate and then if you get the error check your .env, that you have provided the correct details or not.
Note: localhost by default have no password, make sure that you have the same password and database name.
Furthermore, if the above doesn't work for you then try the below commands:
php artisan config:cache

and then:
php artisan migrate


text:
Q: How do I use Core Data and correctly show animation when switching between edit mode while using an extra row to insert a new record? I'm trying to use an extra row at the bottom of my UITableView which would be used to insert a record.  This works fine, but I'm having trouble getting it to animate properly.  Either the extra row is shown properly and I get no animation (by using [self.tableView reloadData] in the setEditing: method.  Or, I get animation and no extra row by not using reloadData.  I know that I'm probably not showing the extra row properly (returning one more row in my numberOfRowsInSection method, and using reloadData to force a refresh.).
I know there must be a right way to do this, but I haven't seen any examples.
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {

    [super setEditing:editing animated:animated];

    [self.tableView setEditing:editing animated:animated];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    if (self.editing == YES) {
        return [sectionInfo numberOfObjects] + 1;
    }
    return [sectionInfo numberOfObjects];

}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.row + 1 > [fetchedResultsController.fetchedObjects count]) {
        cell.textLabel.text = @"Add New Row...";
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    } else {

        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        MyManagedObject *aManagedObject = [fetchedResultsController.fetchedObjects objectAtIndex:indexPath.row];
        cell.textLabel.text = aManagedObject.planName;
    }
}

A: Use insertRowsAtIndexPaths:withRowAnimation: to inform the table view that you "inserted" a row at the necessary location when editing begins and deleteRowsAtIndexPaths:withRowAnimation: to inform the table view that you "removed" the row when editing is complete.

A: This is the kind of UI need that you should really use a tableFooterView for. That puts a custom view at the foot of the table but it does not affect the row count of the table itself. If you insert and actual row that is not reflected in the data, you have to micromanage all the functions related to row count because the rows in data no longer sync with the rows in the tableview.


text:
Q: CSS is messed up while running protractor on saucelabs I have a angular application for which I wrote e2e tests using protractor. I am running my tests on saucelabs. There is a small issue with my page for instance. If my browser is not maximized some of the css gets messed up ( i do plan on fixing this in the future), and this would definitely fail some of my test cases that I wrote.
However if my browser is maximized everything is perfect. Now the issue is when I run my test on saucelabs even though the browser looks maximized (according to saucelab screenshots) my css looks messed up as it does when my browser is not maximized locally.
I did some research and found that I can use
browser.driver.manage().window().maximize();

However in my case since browser is already maximized do i need to increase screen resolution or something? Please provide suggestions

A: I actually think you probably answered this question yourself by the suggestion of increasing the resolution. Because the resolution on your local machine is probably different than the saucelabs machine. I'm not sure what the default resolution but here are the different resolutions you can specify.
I would probably match the resolution that you know works on your machine along with the maximizing of the window.
EDIT: I added your config with the resolution option
exports.config = {
    framework: 'jasmine2',
    sauceUser: 'blahblhablah',
    sauceKey: 'xyzabcdxyzabac',
    capabilities :  {
            screenResolution: "1280x1024",
        },
    multiCapabilities: multiCapabilities,
    specs: ['e2e/main.spec.js'],
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 30000
    },


text:
Q: If module 'example' contains both function 'run' and submodule 'run', can I count on 'from example import run' to always import the former? If I have a Python module implemented as a directory (i.e. package) that has both a top level function run and a submodule run, can I count on from example import run to always import the function? Based on my tests that is the case at least with Python 2.6 and Jython 2.5 on Linux, but can I count on this generally? I tried to search information about the import priorities but couldn't find anything.
Background:
I have a pretty large package that people generally run as a tool from the command line but also sometimes use programmatically. I would like to have simple entry points for both usages and consider to implement them like this:
example/__init__.py:
def run(*args):
    print args  # real application code belongs here

example/run.py:
import sys
from example import run
run(*sys.argv[1:])

The first entry point allows users to access the module from Python like this:
from example import run
run(args)

The latter entry point allows users to execute the module from the command line using both of the approaches below:
python -m example.run args
python path/to/example/run.py args

This both works great and covers everything I need. Before taking this into real use, I would like to know is this a sound approach that I can expect to work with all Python implementations on all operating systems.

A: I think this should always work; the function definition will shadow the module.
However, this also strikes me as a dirty hack. The clean way to do this would be
# __init__.py
# re-export run.run as run
from .run import run

i.e., a minimal __init__.py, with all the running logic in run.py:
# run.py
def run(*args):
    print args  # real application code belongs here

if __name__ == "__main__":
    run(*sys.argv[1:])


text:
Q: Validating a simple .NET collection is failing when it should pass I'm trying to create a FluentValidation rule that tests that my IList<string> has to contain 1 or more items.
Therefore:

*

*It cannot be null

*It cannot be empty

*Count > 0

Using FluentValidation, I've setup a rule and then a unit test. The unit test fails.
I thought that .NotEmpty() will check to see those 3 checks (above)?
Can someone please explain which assumption I made (with respect to F.V.) I have wrong?
Show me da codez
public class AgentValidator : AbstractValidator<Agent>
{
    public AgentValidator()
    {
        RuleFor(agent => agent.Name).NotEmpty()
            .WithMessage("A name is required. eg. Jane Smith.");

        RuleFor(agent => agent.AgencyIds).NotEmpty()
            .WithMessage("At least one AgencyId is requires where this Agent works at.");
    }
}

and the test.
[Fact]
public void GivenNoAgencyIds_Validate_ShouldHaveAnError()
{
    // Arrange.
    var agencyIds = new string[]{}; // No Agency Id's.

    // Act & Assert.
    _agentValidator.ShouldNotHaveValidationErrorFor(agent => agent.AgencyIds, agencyIds);
}

And finally, the error message

FluentValidation.TestHelper.ValidationTestExceptionExpected no
  validation errors for property AgencyIds    at
  FluentValidation.TestHelper.ValidatorTester`2.ValidateNoError(T instanceToValidate)
  in
  c:\Projects\FluentValidation\src\FluentValidation\TestHelper\ValidatorTester.cs:
  line 40

A: I think you're using the wrong testing method:
_agentValidator.ShouldNotHaveValidationErrorFor(...)

ShouldNotHaveValidationErrorFor ensures that an error does not exist. But you WANT an error to exist!  The function you want would be ShouldHaveValidationErrorFor.


text:
Q: How do you remove file named: "str\\escape.rs" It's weird that I could not "rm -rf str\\escape.rs"
And even if I just simply put "rm -rf *.rs" nothing changes
The file is just there..
This file is from source of cm10.2 as well as cm12. But this is just weird.. any thoughts would be appreciated!
Update:
So if I do:
rm 'str\\escape.rs'

It throws error that
rm: cannot remove `str\\\\escape.rs': No such file or directory

Update2:
The permission is
-rwxrwx--- 0 myu myu 53 May 21 00:17 str\\escape.rs

And I tried few things like type "rm " and then press tab (since it's the only file left..), it gives
rm str\\\\escape.rs

and something like removing the directory that contains this file "rm -rf P_str_escape". It either says
rm: cannot remove `str\\\\escape.rs': No such file or directory

or
rm: cannot remove `P_str_escape': Directory not empty

A: You need to escape more slashes:
rm -rf str\\\\escape.rs

Edit: I just tried this, and it works fine:
$ ls
str\\escape.rs
$ rm str\\\\escape.rs
$ ls
$

A: There are at least two options:

*

*take file name in single quotes, to avoid bash substitutions:
rm 'str\\escape.rs'

Evidence:
$ touch 'str\\escape.rs'
$ ls  'str\\escape.rs'
str\\escape.rs
$ rm 'str\\escape.rs'
$ ls  'str\\escape.rs'
str\\escape.rs: No such file or directory

*Just escape slashes:
rm str\\\\escape.rs

More information about how escaping works:
http://www.tldp.org/LDP/abs/html/escapingsection.html


text:
Q: how to use variable in firestore query I use firebase firestore db. This project have two main collection "securecollection" and "publiccollection". The securecollection is where all important data is stored and only accessible to authenticated users. But in order for some information to be visible to guest users, I am copying them into the publiccollection. Then, I want to save the id of this newly created public document in the secure document.
When I write a variable
db.collection('securecollection').doc(secureDocid).update({ inside the query sentence, I get this error:

Uncaught (in promise) TypeError: o.indexOf is not a function

If I write the id as text db.collection('securecollection').doc('7llDqIWlmE5VM69Zzle2').update({, the code works.
Here is my code:
function toggleOlustur(secureDocid) {
  const db = firebase.firestore();
  db.collection("securecollection").get()
    .then(querySnapshot => {
      querySnapshot.forEach(doc => {
        if (doc.id == secureDocid) {
          db.collection("publiccollection").add({
              oad: doc.data().oad,
              osad: doc.data().osad,
              opuan: doc.data().opuan,
              odtarih: doc.data().odtarih,
              odurum: "1",
            })
            .then((docRef) => {
              db.collection('securecollection').doc(secureDocid).update({
                preference: docRef.id
              })
            });
        }
      });
    });
}

A: The doc() method expects a string argument, and from the error message it sounds like your secureDocid is not a string value. If you console.log(JSON.stringify(secureDocid)) you can see what it outputs, which might help to figure out the problem.


text:
Q: How to access a PSDrive from System.IO.File calls? I'm writing a c# cmdlet which copies files from one location to another (similar to rsync).   It even supports ToSession and FromSession.
I'd like it to work with PSDrives that use the Filesystem provider but it currently throws an error from System.IO.File.GetAttributes("psdrive:\path")
I'd really like to use calls from System.IO on the PSDrive.
How does something like copy-item do this?
I've performed a search for accessing PSDrives from c# and have returned no results.
This is the equivalent of my code
new-psdrive -name mydrive -psprovider filesystem  -root \\aserver\ashare -Credential domain\user
$attributes=[system.io.file]::GetAttributes("mydrive:\path\")

returns
Exception calling "GetAttributes" with "1" argument(s): "The given path's format is not supported."

A: .NET knows nothing about PowerShell drives (and typically also has a different working directory), so conversion to a filesystem-native path is necessary:
In PowerShell code:
Use Convert-Path to convert a PowerShell-drive-based path to a native filesystem path that .NET types understand:
$attributes=[System.IO.File]::GetAttributes((Convert-Path "mydrive:\path\"))

By default (positional argument use) and with -Path, Convert-Path performs wildcard resolution; to suppress the latter, use the -LiteralPath parameter.
Caveat: Convert-Path only works with existing paths. Lifting that restriction is the subject of the feature request in GitHub issue #2993.

In C# code:
In PSCmdlet-derived cmdlets:

*

*Use GetUnresolvedProviderPathFromPSPath() to translate a PS-drive-based path into a native-drive-based path[1] unresolved, which means that, aside from translating the drive part:

*

*the existence of the path is not verified (but the drive name must exist)

*and no wildcard resolution is performed.

*Use GetResolvedProviderPathFromPSPath() to resolve a PS-drive-based path to a native-drive-based one, which means that, aside from translating the drive part:

*

*wildcard resolution is performed, yielding potentially multiple paths or even none.

*literal path components must exist.

*Use the CurrentProviderLocation() method with provider ID "FileSystem" to get the current filesystem location's path as a System.Management.Automation.PathInfo instance; that instance's .Path property and .ToString() method return the PS form of the path; use the .ProviderPath property to get the native representation.
Here's a simple ad-hoc compiled cmdlet that exercises both methods:
# Compiles a Get-NativePath cmdlet and adds it to the session.
Add-Type @'
    using System;
    using System.Management.Automation;
    [Cmdlet("Get", "NativePath")]
    public class GetNativePathCommand : PSCmdlet {

        [Parameter(Mandatory=true,Position=0)]
        public string PSPath { get; set; }

        protected override void ProcessRecord() {
            WriteObject("Current directory:");
            WriteObject("  PS form:      " + CurrentProviderLocation("FileSystem"));
            WriteObject("  Native form:  " + CurrentProviderLocation("FileSystem").ProviderPath);
            //
            WriteObject("Path argument in native form:");
            WriteObject("  Unresolved:");
            WriteObject("    " + GetUnresolvedProviderPathFromPSPath(PSPath));
            //
            WriteObject("  Resolved:");
            ProviderInfo pi;
            foreach (var p in GetResolvedProviderPathFromPSPath(PSPath, out pi))
            {
              WriteObject("    " + p);
            }
        }
    }
'@ -PassThru | % Assembly | Import-Module

You can test it as follows:
# Create a foo: drive whose root is the current directory.
$null = New-PSDrive foo filesystem .

# Change to foo:
Push-Location foo:\

# Pass a wildcard path based on the new drive to the cmdlet
# and have it translated to a native path, both unresolved and resolved;
# also print the current directory, both in PS form and in native form.
Get-NativePath foo:\*.txt

If your current directory is C:\Temp and it happens to contain text files a.txt and b.txt, you'll see the following output:
Current directory:
  PS form:      foo:\
  Native form:  C:\Temp\
Path argument in native form:
  Unresolved:
    C:\Temp\*.txt
  Resolved:
    C:\Temp\a.txt
    C:\Temp\b.txt

[1] If a PS drive (created with New-PSDrive) referenced in the input path is defined in terms of a UNC path, the resulting native path will be a UNC path too.


text:
Q: Why do we like gauge potentials so much? Today I read articles and texts about Dirac monopoles and I have been wondering about the insistence on gauge potentials. Why do they seem (or why are they) so important to create a theory about magnetic monopoles?
And more generally, why do we like gauge potentials so much?

A: 1) Postponing for a moment the issue of magnetic monopoles, one conventional answer is, that the gauge potential $A_{\mu}$ (as opposed to, e.g., the electric and magnetic $\vec{E}$ and $\vec{B}$ fields) constitute the true fundamental variables and (the photon field) of QED.
At the classically level, by saying that $A_{\mu}$ are fundamental variables, we mean that the Maxwell action $S[A]$ depends on $A_{\mu}$, and that the corresponding Euler-Lagrange equations are the remaining Maxwell equations, namely Gauss' and (modified) Ampere's laws. (The obsolete Maxwell equations are Bianchi identities, which are rendered vacuous by the existence of the gauge potential $A_{\mu}$.)
Quantum mechanically, it seems appropriate to mention the Aharonov Bohm effect, which seem to indicate that the $A_{\mu}$ gauge field has physical consequences not already encoded in the gauge-invariant $\vec{E}$ and $\vec{B}$ fields. (However, check out this and this Phys.SE posts.)
2) Up until now we haven't discussed magnetic monopoles and Dirac strings.
At a Dirac magnetic monopole, the $A_{\mu}$ gauge potential is not well-defined. This is the main topic of, e.g., this, and this questions.
Dirac magnetic monopoles are usually dismissed, but there are other types of magnetic monopoles, namely the (generalized) 't Hooft-Polyakov magnetic monopole. See also this Phys.SE post.
Although (generalized) 't Hooft-Polyakov magnetic monopoles have so far not been experimentally detected, there are various theoretical reasons to believe they do exist, see e.g. this, this, and this questions.

A: It is the gauge potentials, not the fields, that determine the quantum motion of particles. In either the Schrodinger equation or the path integral, the gauge field appears, not the E and B, and for nonabelian theories, this is impossible to fix because you don't have a integral Stokes law relation.
The interaction with charged particles is that a particle moving along a path gets a phase equal to the integral of A along the path. If you want to replace the A with B, you need to use the fact that the integral of A along a closed loop is the magnetic flux enclosed by the loop, and this is a nonlocal condition. So you can't write local equations of motion for a quantum particle using E and B.
The integral relation for B states that if you make a circle, and you want the phase that the charged particle will get if it moves on this circle, you draw some surface whose boundary is the circle, and the magnetic flux through this surface is the phase.
The dirac condition is simply the statement that if you have a monopole and draw a circle around the monopole, the flux through the northern hemisphere is equal to the flux through the southern hemisphere, up to a multiple of 2pi, which is an undetectable phase change. This tells you that the magnetic charge times the electric charge must be an integer multiple of $2\pi$.


text:
Q: How to create a custom event in jquery I want to create a custom event that will be triggered whenever a numeric value is entered in an input type="text". Alphabets should be ignored. change and blur events didn't work well for me.
Any suggestions? Thanks.

A: You can easily create custom events :
// handle event
$('#mydiv').on('customevent', function(e) { });

// trigger event
$('#mydiv').trigger('customevent');

A: You're looking for a keydown, keypress or keyup event to catch input, and reject non-numeric input.
Out of these three options, for integer input, the keypress event very suitable.
$('input#selector').keypress(function(event) {
    if (e.which < 48 || e.which > 57) { // or:
  //if (!/\d/.test(String.fromCharCode(e.which))) {
        event.preventDefault();
    }
});

However, you should also use blur / change, to deal with input from copy-pasting/dragging.

A: $( '#input-id' ).keyup(function(e)
    {
        if (e.keyCode >= 48 && e.keyCode <= 57 )
        {
            doThis();
        }
    });

A: You might still be able to use change or blur events, but insert some additional logic to detect if your input is something that you'd want to trigger an event with, so
$(".field").on("change blur keydown keyup", function(){
    if($(this).val().match(/^\d+$/){
      //your code
    } else {
      //do nothing
    }

});

A: I think this will help you..
Alphanumeric Demo

A: good artical is here..http://javascript.mfields.org/2011/creating-custom-events-with-jquery/
but i cant think it needs .you can use keydown, keypress or keyup as suggested by Rob.


text:
Q: Not able to deploy Python program from Azure IOT Edge to Rasberry Pi I installed the IOT Edge runtime using below link:
https://learn.microsoft.com/en-us/azure/iot-edge/how-to-install-iot-edge-linux-arm
I am following the below tutorial to deploy a docker image to IOT Edge (Rasberry Pi):
https://learn.microsoft.com/en-us/azure/iot-edge/quickstart-linux
and able to deploy the tempSensor image to my Rasberry Pi
I decided to deploy my own program "blink.py".
I created the program and its working fine in the local Rasberry Pi using below command:
$docker container run --device /dev/gpiomem -d blink

I followed the below steps to deploy my own program from Azure IOT Edge portal:
1.) Create a docker image using Dockerfile:
FROM arm32v7/python:2.7.15-stretch
COPY blink.py
CMD ["python","./blink.py"]

then ran the command:
$docker build -t "blink" ./

2.) Now i pushed the image to Azure container Registry. Followed below steps:
a.) Login to Azure container registry
$docker login blink.azurecr.io

b.) Push to Azure container registry
$docker tag blink link.azurecr.io/blink
$docker push blink.azurecr.io/blink

3.) Deploy image in Azure container registry to IOT Edge device using below link:
https://learn.microsoft.com/en-us/azure/iot-edge/quickstart-linux#deploy-a-module

I see a container image created in the Raspberry Pi as "blink.azurecr.io/blink"

I see that IOTEdge runtime tried to deploy this image as container but it failed.
When i try to see the logs using command
>docker logs blink

It shows an error:

Traceback (most recent call last):
  File "./blink.py", line 6, in <module>
    GPIO.setup(4,GPIO.OUT)
RuntimeError: No access to /dev/mem. Try running as root!

Seems like some access issue but not sure how to solve it?
Do i need to put anything in the createOptions while deploying the edge module from azure portal ?
-Sandy

A: From the error log, it seems that the module has no permission to access device/gpio. sudo should be able to used inside the container. You can try to add the following command in Dockerfile.
RUN apt-get update && apt-get -y install sudo

RUN useradd -m docker && echo "docker:docker" | chpasswd && adduser docker sudo

This topic in stackoverflow as a reference.

A: ok so it worked!
I provided below in the createOptions:
{
    "HostConfig": {
        "Devices": [
            {
                "PathOnHost": "/dev/gpiomem",
                "PathInContainer": "/dev/gpiomem",
                "CgroupPermissions": "rwm"
            }
        ]
    }
}

After re-deploying.. it worked, Hurray !!!!


text:
Q: Validating Form Fields on button click in office fabric Ui control I have one TextField and PrimaryButton in my form.
On button click i want to validate textfield.If there is no value then fire requiredfield validation on button click and display message same as display on onGetErrorMessage event.
I know validation is fire onBlur event but i want to fire validation on button click.
How can i do it?

A: First you have to use refs to your TextField
<TextField ref={(input) => { this.textInput = input; }} label='test' />

Now you can set onGetErrorMessage on click using refs
onClick(e){
    if(this.refs.input.value == undefined ||  this.refs.input.value == null || this.refs.input.value == '')
        this.refs.input.onGetErrorMessage = "you error message"
}

Update 1:  Check out this code snippet
class FormExample extends React.Component {
  constructor() {
    super();
    this.state={
      inputError:''
    }
    this.ValidateText = this.ValidateText.bind(this)
  }
  ValidateText(e){
    this.setState({
      inputError:this.input.value?'':'testing'
    })
  }
  render() {
    return (

          <TextField
            ref={(input) => { this.input = input; }}
            label="Name"
            errorMessage={this.state.inputError}
        />
          <input type='button' value='Submit'
          onClick={this.ValidateText} />

    );
  }
}


text:
Q: Login to admin by frontend form? I'm developing a website by wordpress, customer want I build a custom login page and login by email, not username.
And admin page with custom url '/manage/'
Below my code for login:
$email = $_POST['email'];
$pass = $_POST['password'];
$user = get_user_by('email', $email);
if (wp_check_password($pass, $user->data->user_pass, $user->ID)) {
   wp_set_current_user($user->data->ID, $user->data->user_login);
   wp_set_auth_cookie($user->data->ID);
   do_action( 'wp_login', $user->data->user_login );
   $_SESSION['success'] = 'Hello ' . $user->data->display_name . '!';
   wp_safe_redirect(wp_get_referer());
   exit();
}

My problem is:
When I submit, website return success and current user on Frontend changed. But when I try go to admin dashboard, it redirect me to wp-login.php and require me login again.
I don't what is wrong or how to fix that.
So, please, help me!

A: What you have should work - although you should not use $_SESSION (as Tom already noted).  Also ID, user_pass, and user_login are all top level in the user object.
Here's what I would try:
$email = sanitize_email( $_POST['email'] );
$pass  = $_POST['password'];
$user  = get_user_by( 'email', $email );

if ( wp_check_password( $pass, $user->user_pass, $user->ID ) ) {
   wp_set_current_user( $user->ID );
   wp_set_auth_cookie( $user->ID );
   do_action( 'wp_login', $user->user_login );
   wp_safe_redirect( wp_get_referer() );
   exit();
}


text:
Q: 214721900 error during run time What is wrong in this code:
 Dim con As ADODB.Connection
 Dim rec As ADODB.Recordset
 Set con = New ADODB.Connection
 Set rec = New ADODB.Recordset
 Dim count As Integer
 con.Open "Provider=MSDAORA.1;Password=****;User ID=system;Persist Security   Info=False"
 con.CursorLocation = adUseClient
 rec.Open "select count(*) as c from login_hisab where username = " & Text1.Text & " and password = " & Text2.Text & "", con, adOpenDynamic, adLockOptimistic
 count = rec.Fields("c")
 If count = 0 Then
   MsgBox "Invalid USERNAME or PASSWORD"
 End If

A: You probably have to put your sql values inside single quotes:
where username = '" & Text1.Text & "' and password = '" & Text2.Text & "'"

A: Try using a parameterized query like this (air code). Means you don't have to worry about passwords containing ' or ", you don't have to worry about SQL Injection, etc.
dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.CommandType = adCmdText
cmd.CommandTimeout = 30
cmd.CommandText = "select count(*) as c from login_hisab where username = ? and password = ?"
cmd.Parameters.Append cmd.CreateParameter("userid", adVarChar, _
  adParamInput, Len(Text1.Text), Text1.Text)
cmd.Parameters.Append cmd.CreateParameter("pwd", adVarChar, _
  adParamInput, Len(Text2.Text), Text2.Text)
cmd.ActiveConnection = con
Set rec = cmd.Execute()

count = rec.Fields("c")
 If count = 0 Then
   MsgBox "Invalid USERNAME or PASSWORD"
 End If


text:
Q: Version controlled South migrations in virtualenv I have a Django site placed in folder site/.  It's under version control.  I use South for schema and data migrations for my applications.  Site-specific applications are under folder site/ so they are all version-controlled along with their migrations.
I manage a virtualenv to keep third party components dry and safe. I install packages via PyPI. The installed packages' list are frozen in requirements.txt so the they can be easily installed in another environment. The virtualenv is not under VCS. I think it is a good way if virtualenv can be easly deleted and reconstructed at any time. If I need to test my site, for instance, using another version of Python interpreter, simply activate another virtulalenv.
I'd like to use South for third party packages, though. Here comes the problem. Migration scripts stored in the application's folder so they are outside of my site's repository. But I want migration scripts to be under version control so I can run them on different stages as well.
I don't want to version control the whole virtualenv but the migration scripts for third party applications. How can I resolve this conflict? Is there any misconcept in my scenario?

A: The SOUTH_MIGRATION_MODULES setting allows you to put migration modules for specified apps wherever you want them (i.e. inside your project tree).

A: I think it depends a litte bit on your version control system. I recommend to use a sparse tree, one that only manages the migration folders of the various packages. Here I see two alternatives:

*

*Make a truly sparse tree for all packages, one that you check out before creating the virtualenv. Then populate the virtualenv, putting stuff into the existing folders.

*Collect all migrations into a separate repository, with a folder per project/external dependency. Check this out into the virtualenv, and create symlinks, linking from each project to its migration folder.
In either case, I believe you can arrange for the migrations to exist as a separate project, so you can install it with the same process as you install everything else (easy_install/pip/whatever).


text:
Q: compress with tar, tar : Exiting with failure status due to previous errors I'm trying to compress files, but I use other user
Say there are two user here, user 1 "test1" and user 2 "test2"
I logged in as user 2 "test2"
Then, I wanted to compress files in the user directory "test1"
"/Home/test1/Downloads/repos/"

I've run the command
$ Tar -zcvf $HOME/backup_file.tar.gz /home/test1/Downloads/repos/

When there is an error compress process
tar : Exiting with failure status due to previous errors

I've tried the way of the link below, but still error
tar Exiting with failure status due to previous errors
Assistance and solutions is greatly appreciated

A: The original folder compressed was created by the root authority, and your implementation of the tar maybe no sudo


text:
Q: How to split dataframe depending on the values of multiple columns I am using Python. I want to split my dataframe depending on the values of two columns. Every time the value pair changes, I want to split my dataframe at this position.
Example:
df = pd.DataFrame({'Distance':[1,1,1,1,3,3,3], 'labels':[1,2,2,2,4,4,5]})

df=

    Distance  labels
0       1       1
1       1       2
2       1       2
3       1       2
4       3       4
5       3       4
6       3       5

I want to get:
list_of_dfs[0]=

    Distance    labels
0       1       1

list_of_dfs[1]=

    Distance    labels
1       1       2
2       1       2
3       1       2

list_of_dfs[2]=

    Distance    labels
4       3       4
5       3       4

list_of_dfs[3]=

    Distance    labels
6       3       5

This is how it works:
l = [1,4,6,7]
l_mod = [0] + l + [max(l)+1]
list_of_dfs = [df.iloc[l_mod[n]:l_mod[n+1]] for n in range(len(l_mod)-1)]

My question:
How can I automatically get the array l=[1,4,6,7] ?
This is all I need to finish this task!

A: Use pd.duplicates to find the unique rows.
# use duplicated to determine rows that are original and create list
ind = df[~df.duplicated()].index.tolist()

# account for the last row, append value one greater than maximum index.
ind.append(df.shape[0])

# create dictionary for dataframe.
dfs = {}

# use iloc to create new dataframes, then add to dictionary.
for i in range(len(ind)-1):
    df_temp = df.iloc[ind[i]:ind[i+1], :]
    dfs[i] = df_temp

Retrieve your dataframes from the dictionary:
df0 = dfs[0]
       Distance  labels
0         1       1

df1 = dfs[1]
print(df1)

  Distance  labels
1         1       2
2         1       2
3         1       2


text:
Q: Highcharts 3.0 clip-path confusion If I look at the DOM element of Highcharts I do see a clippath:
<clipPath id="highcharts-2">
  <rect fill="none" x="0" y="0" width="796" height="367"></rect>
</clipPath>

and the series group referencing to it:
<g class="highcharts-series"..... clip-path="url(#highcharts-2)">

as the clip rectangle is overlapping the renderd series, shouldn't the clipPath have an effect on it? I think in previous versions it was possible to manipulate the clipPath with jQuery and show only parts of the series.
How can I
a) make this clipPath effective
b) even add my own clipPaths and animate them on the fly

A: You can either manipulate this using jQuery, or you can use the Highcharts renderer like Highcharts does internally. This will also work with old IE browsers.

chart.clipRect.attr({ width: 300 });

See http://jsfiddle.net/highcharts/7c8am/. You can create your own clips using Element.clip.


text:
Q: How to send data and image together through ajax json in asp.net mvc Previously, I just had a requirement to create a form that contains only data to be sent to the action and not the image, now, I've confronted with a requirement to POST the data along with an image to the action. I've no idea how to append the image to the data so that I can get it work to proceed further in action.
This is how I'm posting the data and the image together but I receive null in action :
HTML
<input type="file" id="profilePic" name="file" value="Browse">
<input type="text" id="EmployeeCode" name="EmployeeCode" value="EmployeeCode">
<input type="text" id="SystemCode" name="SystemCode" value="SystemCode">
<input type="button" value="Create" onclick="SaveEmpData()" />

I know how to get the input type text data and send it through ajax request and in a json format and save it to database, but when it comes to get the data and image through the ajax request in a json format, I've got no clue about how to do this.
JS
var empdata = { "SystemCode": "", "EmployeeCode": "" };

empdata.EmployeeCode = $("#EmployeeCode").val();
empdata.SystemCode = $("#SystemCode").val();

var data = new FormData();
var files = $("#profilePic").get(0).files;
data.append("Image", files[0]);

Ajax
$.ajax({
    url: '/EmployeeMasterA/Create',
    headers: headers,
    data: JSON.stringify({ employeeMasterA: empdata, profilePic: data }),
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    traditional: true,
    success: function (result) {

        if (result.Success == "1") {
            window.location.href = "/EmployeeMasterA/Index";
        }
        else {
            alert(result.ex);
        }
    }
});

and Create Action :
[HttpPost]
public ActionResult Create([Bind(Include = "SystemCode,EmployeeCode")] EmployeeMasterA employeeMasterA, HttpPostedFileBase profilePic)
{
    var pic = System.Web.HttpContext.Current.Request.Files["Image"];
}

In the above code, the pic variable is null. My question is:
What is the proper way to get the data + image from the form, and send it through the ajax request to the action? Any help is deeply appreciated :)
Update
After referring to liran's answer, I tried binding by editing my code this way :
JS
var empbind = { "profilePic" : "", "employeeMasterA" : "" };
// Created empdata and data (image) object as mentioned above
empbind.employeeMasterA = empdata;
empbind.profilePic = data;
var empbindjson = JSON.stringify(empbind);

and changed the Ajax data parameter as below :
$.ajax({
   .
   .
   data: empbindjson,
   .
   .
});

And Changed my controller action :
[HttpPost]
public ActionResult Create([Bind(Include = "employeeMasterA,profilePic")]       EmployeeBind bind)
{
    var pic = System.Web.HttpContext.Current.Request.Files["Image"];
}

Both employeeMasterA,profilePic are received null in debug mode of the above code, this is my new class for binding :
public class EmployeeBind
{
    public EmployeeMasterA employeeMasterA { get; set; }
    public HttpPostedFileBase profilePic { get; set; }
}

Ok, Now, I've changed my code to bind it with the profilePic, Is there any thing I doing wrong? because both bind parameter of the create action contains null for both employeeMasterA and profilePic.

A: Try change something like that need to work:
  $('#save').click(function () {

    var form = $("#yourForm");
    var data = new FormData();
    var files = $("#profilePic").get(0).files;
    data.append("Image", files[0]);
    $.each(form.serializeArray(), function (key, input) {
        data.append(input.name, input.value);
    });

  $.ajax({
      url: '/EmployeeMasterA/Create',
      data: data,
      type: 'POST',
      processData: false,
      contentType: false,
      success: function (result) {

          if (result.Success == "1") {
              window.location.href = "/EmployeeMasterA/Index";
          }
          else {
              alert(result.ex);
          }
      }
  });
});

In Html:
 <form id="yourForm">
    <input type="file" id="profilePic" name="file" value="Browse">
    <input type="text" id="EmployeeCode" name="EmployeeCode" value="EmployeeCode">
    <input type="text" id="SystemCode" name="SystemCode" value="SystemCode">
    <input type="button" value="Create" onclick="SaveEmpData()" id="save">
</form>

Edit: if that still not working so bind the EmployeeMasterA and HttpPostedFileBase  to same class something like :
    [HttpPost]
    public ActionResult Create([Bind(Include = "SystemCode,EmployeeCode")] VMNewClass bind)
    {
        var pic = System.Web.HttpContext.Current.Request.Files["Image"];
    }

public class VMNewClass{

 public EmployeeMasterA employeeMasterA {get;set;}
 public  HttpPostedFileBase profilePic {get;set;}

}

if you don't want to do:
 $.each(form.serializeArray(), function (key, input) {
        data.append(input.name, input.value);
    });

you can write:
var data = new FormData();
    var files = $("#profilePic").get(0).files;
    data.append("profilePic", files[0]);
    data.append("EmployeeCode", $("#EmployeeCode").val());
    data.append("SystemCode", $("#SystemCode").val());

Edit if article I've attached in comment
 <script>
        var empdata = { "SystemCode": "", "EmployeeCode": "" };

        empdata.EmployeeCode = $("#EmployeeCode").val();
        empdata.SystemCode = $("#SystemCode").val();

        var data = new FormData();
        var files = $("#profilePic").get(0).files;
        data.append("Image", files[0]);
        data.append("EmployeeCode", $("#EmployeeCode").val());
        data.append("SystemCode", $("#SystemCode").val());

        $.ajax({
            url: '/EmployeeMasterA/Create',
            data: data,
            type: 'POST',
            contentType: false, // Not to set any content header
            processData: false, // Not to process data
            success: function (result) {

                if (result.Success == "1") {
                }
                else {
                    alert(result.ex);
                }
            }
        });

</script>

Controller :
[HttpPost]
public ActionResult Create([Bind(Include = "SystemCode,EmployeeCode")] EmployeeMasterA employeeMasterA)
{
    HttpPostedFileBase profilePic = Request.Files[0]; // your file
}


text:
Q: How can I sort a 2-D array in MATLAB with respect to one column? I would like to sort a matrix according to a particular column. There is a sort function, but it sorts all columns independently.
For example, if my matrix data is:
 1     3
 5     7
-1     4

Then the desired output (sorting by the first column) would be:
-1     4
 1     3
 5     7

But the output of sort(data) is:
-1     3
 1     4
 5     7

How can I sort this matrix by the first column?

A: I think the sortrows function is what you're looking for.
>> sortrows(data,1)

ans =

    -1     4
     1     3
     5     7

A: An alternative to sortrows(), which can be applied to broader scenarios.

*

*save the sorting indices of the row/column you want to order by:
[~,idx]=sort(data(:,1));

*reorder all the rows/columns according to the previous sorted indices
data=data(idx,:)


text:
Q: Json crash only on watch kit I have this function to load Json, works fine on the iPhone  and watchkit simulator, but crashes when I'm installing it on the watch. Why?
func get(){

   let url = NSURL(string: "http://www.ddd.com/xxx.php")
   let data = NSData(contentsOf: url! as URL)
   values = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers)  as! NSMutableArray
}

debug :

dnssd_clientstub ConnectToServer: connect()-> No of tries: 1
  failed path:/var/run/mDNSResponder Socket:7 Err:-1 Errno:1 Operation not permitted
  nw_resolver_create_dns_service_on_queue DNSServiceCreateConnection failed: ServiceNotRunning(-65563)
function signature specialization <preserving fragile attribute, Arg[1] = [Closure Propagated : reabstraction thunk helper from @callee_owned (@unowned Swift.UnsafeBufferPointer) -> () to @callee_owned (@unowned Swift.UnsafeBufferPointer) -> (@out ()), Argument Types : [@callee_owned (@unowned Swift.UnsafeBufferPointer) -> ()]> of generic specialization  of Swift.StaticString.withUTF8Buffer <A> ((Swift.UnsafeBufferPointer) -> A)

A: You forcing unwrapping twice in your code, when you could do it the clean way. Check this https://stackoverflow.com/a/39455186/1585121
This is probably the cause of the runtime crash.
An optionnal value can contain the a value of the optional type or nothing.
You say to the compiler "this will always have a value", when in reality you can't know in your case. Maybe the string you give to NSUrl is invalid for example? And it return nil?
You don't give much informations about you problem so we can't tell you exactly but my guess is that url or data, the optionnals you force unwrap, end up with nil at runtime.


text:
Q: My Nested For loops Run "faster" than inline For loop For a class I'm in we are asked to write out a brute force method for finding 2 elements in lists S1, S2, that add to a specified value x. So far I have it written out as such:
@timing
def brute_force_nested(x, s1 : list, s2 : list) -> bool:
    for a in s2:
        for b in s1:
            if a + b == x:
                return True
    return False

@timing
def brute_force_inline(x, s1 : list, s2 : list) -> bool:
    return bool([ (a,b) for a in s2 for b in s1 if a + b == x ])

But when I run them in the terminal, I get a very large difference in times:
>>> brute_force_nested(5123, S1, S2):

func:brute_force_nested took: 0.007085800170898438 sec and gave: True

>>>func:brute_force_inline(5123, S1, S2)

func:brute_force took: 3.0208868980407715 sec and gave: True

Why is this happening? I was under the impression that the inline syntax was essentialy just syntactical sugar for written out nested loops, but something is obviously different, and I don't know what.

A: The loops are indeed equal, but not the condition to break it. In the first nested loop, the code stops when the first equality is reached. In the second one, all tests are computed until all combinations are exhausted.
The equivalent of the first loop with the comprehension syntax would be to use a generator and any, that will stop when the first truthy value is reached
return any((a+b==x for a in s2 for b in s1))

A: This is because you are only iterating over the lists in the first fuinction and returning on the first value. The second you are creating a list then evaluating the Truthy value of that list. For them to be comparable you need to use any and a generator comprehension.
def brute_force_inline(x, s1 : list, s2 : list) -> bool:
    return any(a + b == x for a in s2 for b in s1)

P.S Technically both of your approaches are nested loops one is just done using a comprehension.
This can also be done more efficiently using itertools.product:
from itertools import product

def brute_force_inline(x, s1 : list, s2 : list) -> bool:
    return any(sum(ab) == x for ab in product(s2, s1))


text:
Q: How to distribute a Web API 2 web app to my clients? I would like to distribute a Web API 2 app to my clients, but I want to only give them the output .dll-s and explain to them how to host them in a container as IIS. What is the general way to host the provided .dll-s?

A: The general way is to host Web API application on IIS. Here is a brief tutorial: http://www.c-sharpcorner.com/UploadFile/2b481f/how-to-host-Asp-Net-web-api-on-iis-server.
An alternative way is to host the Web API application outside IIS in an external app like console/desktop app/windows service and send them the app. Here is a tutorial how to do that: https://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api.


text:
Q: Hard drive further partioning i am using Ubuntu 16.04.before i was using windows 8.1.i installed Ubuntu and now only one partition appearing, with 804 GB free and 119 gb used total 923gb.kindly how i partition my hard-drive

A: If you have a GUI installation then one of the easiest way to format drives is using Gparted.
sudo apt-get install gparted

It's possible that you've installed Ubuntu alongside Windows 8.1, in which case the other 804GB may still be in use by Windows.
If this is the case, but you want to use the entire drive, then you have two options:

*

*You can re-install Ubuntu entirely and erase the entire drive during the setup. This will allow you to have one big partition, which is easiest to manage.

*You can format the extra space with GParted and mount it as an additional storage location by going to File Explorer -> Other Locations and accessing the partition there.


text:
Q: Storing Zip file in Postgres I've been storing the contents of zip files in a LONGBLOB in a MySQL database, but I'm moving to Postgres.  From what I've read, the equivalent to LONGBLOB in Postgres is bytea.  Unfortunately, I can't get the zip contents to write to the database.  First, I got this error:
Warning: pg_query(): Query failed: ERROR:  invalid byte sequence for encoding "UTF8"
 0x5c

Then I created a new database with SQL_ASCII encoding (the previous had UTF8), and got this error:
PHP Warning:  pg_query(): Query failed: ERROR:  syntax error at or near "v╘▓ú5"
LINE 2: ...√╢V[úB√▬┌»å⌐²└ù╙±b±≡ß▼┐π}°ï»┌G╜₧╧εo»~°0o╞W/_╝ƒL¢\'v╘▓ú5;Ω░#╩...

Is there any way to create a database/table/column in Postgres without encoding?  If not, how should I store this information?  I tried using pg_escape_bytea but that produces errors when I try to unzip the contents.  Not sure that this really matters, but here's the PHP I'm using to write to the database:
$content = file_get_contents($zipLocation);
$content = addslashes($content);

$sql="INSERT INTO ZIP_TBL ( BUILD, CONTENT)
    VALUES ('$build', '$content')";

if (!pg_query($con,$sql)) {
    die('Error: ' . pg_last_error($con));
}

A: One of the bytea input formats is hexadecimal. So use bin2hex
$content = file_get_contents($zipLocation);
$content = '\\x' . bin2hex($content);

$sql="
    insert into zip_tbl ( build, content)
    values ('$build', E'$content')
";

http://www.postgresql.org/docs/current/static/datatype-binary.html#AEN5318
http://php.net/manual/en/function.bin2hex.php
BTW, if you are not aware, you are susceptible to SQL injection.

A: Now is a good opportunity to switch to PDO, which does this sort of thing cleanly and sanely.
Here's an earlier answer I wrote on this topic, which discusses the numerous ways in which the old-style PostgreSQL driver is truly awful for binary data.
The short version is that your code should be more like:
$sth = $pdo->prepare('INSERT INTO mytable(somecol, byteacol) VALUES (:somecol, :byteacol)');
$sth->bindParam(':somecol', 'bork bork bork');
$sth->bindParam(':byteacol', $thebytes, PDO::PARAM_LOB);
$sth->execute();

A: Try to use base64encode() function:
$content = file_get_contents($zipLocation);
$content = base64encode($content);

$sql="INSERT INTO ZIP_TBL ( BUILD, CONTENT)
    VALUES ('$build', '$content')";

if (!pg_query($con,$sql)) {
    die('Error: ' . pg_last_error($con));
}

And when you will need this data back, use base64decode() function. Also, type of your column needs to be text to store this data.

string base64_encode ( string $data )
string base64_decode ( string $data [, bool $strict = false ] )

http://php.net//manual/en/function.base64-decode.php
http://php.net//manual/en/function.base64-encode.php


text:
Q: MongoDB failure using AWS Cloud9 While using mongo on the cloud9 IDE, I followed the instructions on github. everything works fine when I run ./mongod for the first time after following the instructions. But when I try repeating the same command after closing the mongo bash, I end up with the following error, and all of my databases being lost.
2020-05-15T14:13:46.120+0000 I CONTROL  [initandlisten] MongoDB starting : pid=4361 port=27017 dbpath=data 64-bit host=ip-172-31-9-233
2020-05-15T14:13:46.120+0000 I CONTROL  [initandlisten] db version v3.6.18
2020-05-15T14:13:46.120+0000 I CONTROL  [initandlisten] git version: 2005f25eed7ed88fa698d9b800fe536bb0410ba4
2020-05-15T14:13:46.120+0000 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.0-fips 29 Mar 2010
2020-05-15T14:13:46.121+0000 I CONTROL  [initandlisten] allocator: tcmalloc
2020-05-15T14:13:46.121+0000 I CONTROL  [initandlisten] modules: none
2020-05-15T14:13:46.121+0000 I CONTROL  [initandlisten] build environment:
2020-05-15T14:13:46.121+0000 I CONTROL  [initandlisten]     distmod: amazon
2020-05-15T14:13:46.121+0000 I CONTROL  [initandlisten]     distarch: x86_64
2020-05-15T14:13:46.121+0000 I CONTROL  [initandlisten]     target_arch: x86_64
2020-05-15T14:13:46.121+0000 I CONTROL  [initandlisten] options: { storage: { dbPath: "data", journal: { enabled: false } } }
2020-05-15T14:13:46.121+0000 E STORAGE  [initandlisten] Failed to set up listener: SocketException: Address already in use
2020-05-15T14:13:46.121+0000 F -        [initandlisten] Invariant failure globalStorageEngine src/mongo/db/service_context_d.cpp 272
2020-05-15T14:13:46.121+0000 F -        [initandlisten]

***aborting after invariant() failure

2020-05-15T14:13:46.143+0000 F -        [initandlisten] Got signal: 6 (Aborted).

 0x5624cebe3891 0x5624cebe2aa9 0x5624cebe2f8d 0x7f7f389db600 0x7f7f386343a7 0x7f7f38635a98 0x5624cd2da320 0x5624cd582bd8 0x5624cea8c531 0x5624cea88617 0x5624cd351c2c 0x5624cebdec55 0x5624cd2db4f9 0x5624cd27418c 0x5624cd3595ca 0x5624cd2dc449 0x7f7f38620575 0x5624cd340e71
----- BEGIN BACKTRACE -----
{"backtrace":[{"b":"5624CC93D000","o":"22A6891","s":"_ZN5mongo15printStackTraceERSo"},{"b":"5624CC93D000","o":"22A5AA9"},{"b":"5624CC93D000","o":"22A5F8D"},{"b":"7F7F389CC000","o":"F600"},{"b":"7F7F385FE000","o":"363A7","s":"gsignal"},{"b":"7F7F385FE000","o":"37A98","s":"abort"},{"b":"5624CC93D000","o":"99D320","s":"_ZN5mongo22invariantFailedWithMsgEPKcS1_S1_j"},{"b":"5624CC93D000","o":"C45BD8","s":"_ZN5mongo20ServiceContextMongoD9_newOpCtxEPNS_6ClientEj"},{"b":"5624CC93D000","o":"214F531","s":"_ZN5mongo14ServiceContext20makeOperationContextEPNS_6ClientE"},{"b":"5624CC93D000","o":"214B617","s":"_ZN5mongo6Client20makeOperationContextEv"},{"b":"5624CC93D000","o":"A14C2C"},{"b":"5624CC93D000","o":"22A1C55"},{"b":"5624CC93D000","o":"99E4F9","s":"_ZN5mongo8shutdownENS_8ExitCodeERKNS_16ShutdownTaskArgsE"},{"b":"5624CC93D000","o":"93718C","s":"_ZZN5mongo13duration_castINS_8DurationISt5ratioILl1ELl1000EEEES2_ILl1ELl1EEEET_RKNS1_IT0_EEENKUlvE_clEv"},{"b":"5624CC93D000","o":"A1C5CA","s":"_ZN5mongo11mongoDbMainEiPPcS1_"},{"b":"5624CC93D000","o":"99F449","s":"main"},{"b":"7F7F385FE000","o":"22575","s":"__libc_start_main"},{"b":"5624CC93D000","o":"A03E71"}],"processInfo":{ "mongodbVersion" : "3.6.18", "gitVersion" : "2005f25eed7ed88fa698d9b800fe536bb0410ba4", "compiledModules" : [], "uname" : { "sysname" : "Linux", "release" : "4.14.177-107.254.amzn1.x86_64", "version" : "#1 SMP Thu May 7 18:30:14 UTC 2020", "machine" : "x86_64" }, "somap" : [ { "b" : "5624CC93D000", "elfType" : 3, "buildId" : "BFF2746BD1982D6569D4870654128D11148441FF" }, { "b" : "7FFD53718000", "elfType" : 3, "buildId" : "FCDA16E475615B36B646D5639C780F22F648405D" }, { "b" : "7F7F39BDC000", "path" : "/lib64/libresolv.so.2", "elfType" : 3, "buildId" : "9CBEE9AA7ED85AD5BE053B483993D677420A765E" }, { "b" : "7F7F3977D000", "path" : "/lib64/libcrypto.so.10", "elfType" : 3, "buildId" : "CEC0EE1141809208648C0C3B1ACB43C3CD8D485E" }, { "b" : "7F7F3950C000", "path" : "/lib64/libssl.so.10", "elfType" : 3, "buildId" : "398164A11688E492630B353F96B4C0486C141264" }, { "b" : "7F7F39308000", "path" : "/lib64/libdl.so.2", "elfType" : 3, "buildId" : "4663D1734EAE35F43F257D29615C1AFF5E060AE0" }, { "b" : "7F7F39100000", "path" : "/lib64/librt.so.1", "elfType" : 3, "buildId" : "C07056C6DA664000A4DAAF8960AB182A8602E910" }, { "b" : "7F7F38DFE000", "path" : "/lib64/libm.so.6", "elfType" : 3, "buildId" : "08C69C7E15BA7B4E199D2FDC1DC29B1CC1996BC1" }, { "b" : "7F7F38BE8000", "path" : "/lib64/libgcc_s.so.1", "elfType" : 3, "buildId" : "A03C9A80E995ED5F43077AB754A258FA0E34C3CD" }, { "b" : "7F7F389CC000", "path" : "/lib64/libpthread.so.0", "elfType" : 3, "buildId" : "383B229C0E6E99B4E3BA6FC8B8C096C103226984" }, { "b" : "7F7F385FE000", "path" : "/lib64/libc.so.6", "elfType" : 3, "buildId" : "8BDBE5043577FC2EA218FAFD7EDF175D219698FB" }, { "b" : "7F7F39DF5000", "path" : "/lib64/ld-linux-x86-64.so.2", "elfType" : 3, "buildId" : "405C4E6374AAAB00F3A7F7986679078870DC2460" }, { "b" : "7F7F383E8000", "path" : "/lib64/libz.so.1", "elfType" : 3, "buildId" : "89C6AF118B6B4FB6A73AE1813E2C8BDD722956D1" }, { "b" : "7F7F3819B000", "path" : "/usr/lib64/libgssapi_krb5.so.2", "elfType" : 3, "buildId" : "D99D708ED949CDD8C415E101385BCD4B7E55C703" }, { "b" : "7F7F37EB2000", "path" : "/usr/lib64/libkrb5.so.3", "elfType" : 3, "buildId" : "FC76FD92303FA56FC5D600EA7AB8A6D526C3A7C1" }, { "b" : "7F7F37CAF000", "path" : "/usr/lib64/libcom_err.so.2", "elfType" : 3, "buildId" : "AB007F5DF96C66E515542598F5BE1429ED63D86F" }, { "b" : "7F7F37A94000", "path" : "/usr/lib64/libk5crypto.so.3", "elfType" : 3, "buildId" : "17F45835B4BB8649628DC476A8940F7F8D978B4B" }, { "b" : "7F7F37885000", "path" : "/usr/lib64/libkrb5support.so.0", "elfType" : 3, "buildId" : "CB655C972CCCD844E292069A5D7DAEBA0ADF4922" }, { "b" : "7F7F37682000", "path" : "/lib64/libkeyutils.so.1", "elfType" : 3, "buildId" : "37A58210FA50C91E09387765408A92909468D25B" }, { "b" : "7F7F37461000", "path" : "/usr/lib64/libselinux.so.1", "elfType" : 3, "buildId" : "F5054DC94443326819FBF3065CFDF5E4726F57EE" } ] }}
 mongod(_ZN5mongo15printStackTraceERSo+0x41) [0x5624cebe3891]
 mongod(+0x22A5AA9) [0x5624cebe2aa9]
 mongod(+0x22A5F8D) [0x5624cebe2f8d]
 libpthread.so.0(+0xF600) [0x7f7f389db600]
 libc.so.6(gsignal+0x37) [0x7f7f386343a7]
 libc.so.6(abort+0x148) [0x7f7f38635a98]
 mongod(_ZN5mongo22invariantFailedWithMsgEPKcS1_S1_j+0x0) [0x5624cd2da320]
 mongod(_ZN5mongo20ServiceContextMongoD9_newOpCtxEPNS_6ClientEj+0x158) [0x5624cd582bd8]
 mongod(_ZN5mongo14ServiceContext20makeOperationContextEPNS_6ClientE+0x41) [0x5624cea8c531]
 mongod(_ZN5mongo6Client20makeOperationContextEv+0x27) [0x5624cea88617]
 mongod(+0xA14C2C) [0x5624cd351c2c]
 mongod(+0x22A1C55) [0x5624cebdec55]
 mongod(_ZN5mongo8shutdownENS_8ExitCodeERKNS_16ShutdownTaskArgsE+0x364) [0x5624cd2db4f9]
 mongod(_ZZN5mongo13duration_castINS_8DurationISt5ratioILl1ELl1000EEEES2_ILl1ELl1EEEET_RKNS1_IT0_EEENKUlvE_clEv+0x0) [0x5624cd27418c]
 mongod(_ZN5mongo11mongoDbMainEiPPcS1_+0x87A) [0x5624cd3595ca]
 mongod(main+0x9) [0x5624cd2dc449]
 libc.so.6(__libc_start_main+0xF5) [0x7f7f38620575]
 mongod(+0xA03E71) [0x5624cd340e71]
-----  END BACKTRACE  -----
./mongod: line 1:  4361 Aborted                 mongod --dbpath=data --nojournal

I'm following "the complete web development bootcamp" course by Colt Steele on Udemy.
The stack I'm using is NodeJS, express, and mongo.
Please help.

A: if you still getting error then run this command line by line
first, remove MongoDB
[1] sudo yum erase -y mongodb-org*

[2] create fill using command
touch mongodb-org-3.6.repo

[3] copy the code beloved and past into that created file
[mongodb-org-3.6]
name=MongoDB Repository

baseurl=https://repo.mongodb.org/yum/amazon/2013.03/mongodb-org/3.6/x86_64/

gpgcheck=1

enabled=1

gpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc

[4] sudo mv mongodb-org-3.6.repo /etc/yum.repos.d
[5]sudo yum install -y mongodb-org
[6]sudo service mongod start
if you are getting an error about
Error — /var/run/mongodb/mongod.pid exists
[7] run this command
sudo rm /var/run/mongodb/mongod.pid

[8] than again run
sudo service mongod start
[9]now run mongod

A: there is a problem when you start the mongo but not stop the server before closing the tab so there is a process to set up this
step 1: remove the preinstall MongoDB in AWS cloud9 and other IDE is use code
sudo yum erase -y mongodb-org*
step 2:
then install mongodb from :
https://github.com/nax3t/aws-cloud9-instructions
note: when you close the tab make sure you stop the mongo
use command
sudo service mongod stop


text:
Q: Pyplot modifies zoom when calling plt.draw() I wrote a function that lets the user pick points from an image and returns the coordinates.
fig, ax = plt.subplots()
ax.imshow(pixel_array, cmap=plt.cm.hot)
plt.ion()
plt.show()
coords = get_points(fig, ax, 4)

where the function get_points is defined as
def get_points(fig, ax, n):
    # Request the user to select n points in the figure fig on the axis ax
    # If n is zero or negative, allow the selection of as many points as the user would like (minimum abs(n))
    # If n is positive, allow only n points to be selected
    if n > 0:
        print('Select', n, 'points.')
    elif n < 0:
        print('Select at least', abs(n), 'points.')
    else:
        print('Select any number of points.')
    print("Press 'Esc' to cancel the last point, or 'Enter' when complete.")
    coords = []
    handles = []
    finished = False
    def onClick(event):
        nonlocal coords
        if fig.canvas.manager.toolbar.mode != '': return # Don't take clicks involved in toolbar functions (pan, zoom, ...)
        if event.inaxes!=ax: return # Don't take clicks outside the axes
        if len(coords) < n or n <= 0:
            coords.append((event.xdata, event.ydata))
            handles.append(plt.scatter(event.xdata, event.ydata, s=100, c='red', marker='+'))
            plt.draw()
        else:
            print('You have reached the maximum number of points for this operation.')
    def onKey(event):
        nonlocal finished
        if event.key == 'escape':
            if len(coords) > 0:
                del coords[-1]
                handles[-1].remove()
                del handles[-1]
                plt.draw()
        elif event.key == 'enter':
            if len(coords) >= abs(n):
                finished = True
            else:
                print('You have selected', len(coords), 'out of a required', n, 'points.')
        else:
            print('You pressed "', event.key, '" which is unsupported', sep='')
    cid = fig.canvas.mpl_connect('button_press_event', onClick)
    cid2 = fig.canvas.mpl_connect('key_press_event',onKey)
    while not finished:
        plt.waitforbuttonpress(-1)
    plt.disconnect(cid)
    plt.disconnect(cid2)
    return np.array(coords)

But the problem is that if I zoom or pan, then each time I select a point it resets the zoom/pan to the default.  Is there any way to have it not do this?  Is there a better way to do this overall?
Thanks in advance.


text:
Q: 4.2.1 is overriding Base SDK to 4.3 I'm getting this message in parenthesis next to the device when installing the app through Xcode. xxxx's iPhone(4.2.1 is overriding Base SDK to 4.3)
The deployment target for the app is 4.0. Any ideas why I am getting this?
Thanks for your time.

A: From what I can understand:

*

*You're using 4.3 as base SDK specified in target settings

*You have 4.2.1 installed on your device

*You have 4.0 as your deployment target

the "override base SDK to 4.3" is a reminder you're building against 4.3 headers and libraries and not 4.2.1 (because the 4.2.1 indication is referring to the operating system installed into the device, and thus can be misleading). If you have more SDKs installed in your xcode (such as 5.0 beta or older 3.x SDKs) other schema choices should appear.
In my case I have 3.1.2 and 3.1.3 installed and two more entries appears, but both are missing the "overriding base sdk to" indication, so I don't know whether I'm building for 3.1.2 or 3.1.3 unless i check the build logs. I guess this is due to missing support for older <3.2 SDKs in xcode 4.
To know which SDK version and which deployment target are you building you can check the build log: look at any compiler command line for the -isysroot option, which specifies the SDK location (aka base SDK), and the -miphoneos-version-min=x.x.x which specifies deployment target.


text:
Q: Bubble sort not printing last element My code asks a user to enter an amount of temperatures and prints out the average, then sorts the temperatures in ascending order and descending order. For ascending order I've used selection sort and for descending order I've used bubble sort. My problem is that when I use bubble sort, the last sorted element does not print and I'm not sure why it's doing this. What am I doing wrong?
   public static void main(String[] args) {

    Scanner keyboard=new Scanner(System.in);
    System.out.println("How many temperatures?");
    int size=keyboard.nextInt();
    int temp[]=new int[size];
    System.out.println("Please enter "+temp.length+" temperatures");
    double sum=0;
    for(int i=0;i<temp.length;i++){
        temp[i]=keyboard.nextInt();
        sum=sum+temp[i];
    }
    double average=sum/temp.length;
    System.out.println("The average temperature is: "+average);

  System.out.println(" ");
  System.out.println("Selection sort algorithm for ascending order");
  int min;
  for (int i = 0; i < temp.length; i++) {

    min = i;
    for (int j = i + 1; j < temp.length; j++) {
        if (temp[j] < temp[min]) {
            min = j;
        }
    }
    if (min != i) {
        int temporary_var = temp[i];
        temp[i] = temp[min];
        temp[min] = temporary_var;
    }
    System.out.print(temp[i]+ " ");

}
 System.out.println("");
 System.out.println("Bubble sort algorithm for descending order");
 for(int i=0; i<temp.length-1; i++)
 {
  if(temp[i]>temp[i+1])
  {
   int temporary_var = temp[i ];                //swap elements
   temp[i] = temp[ i+1 ];
   temp[i+1] =  temporary_var;
  }
 System.out.print(temp[i]+" ");
}
}

}

A: You are printing in the sorting loop which is for(int i=0; i<temp.length-1; i++) having length-1. That is why it does not print the last element. Change it to for(int i=0; i<temp.length; i++) since you already have a < than operator.

A: I don't believe Your bubble sort algorithm is correct. Just one loop and swapping? it's just one pass of bubble sort and that won't sort the array for you.
First correct your algorithm and then output the numbers outside loop
Here's the correct code for bubble sort
    for(int k=0; k<temp.length; k++)
     {
      for(int i=0;i<temp.length-1;i++)
      {
        if(temp[i]>temp[i+1])
        {
          int temporary_var = temp[i ];                //swap elements
          temp[i] = temp[ i+1 ];
          temp[i+1] =  temporary_var;
        }

    }

//print array here

A: Your bubble sort's print statement is part of a for loop that only reaches an index of length minus 2. On zero indexed arrays the last index is length - 1.


text:
Q: redirect to another controller method directly avoiding the view I am trying C# MVC and I have stumbled on the following issue. I am playing with a small project which is sort of task management tool. At this moment I have 2 (user, task) models and corresponding controllers and set of views.
The user controler has an method 'Create' which obviously create a new user basing on the data received from the form. When the user is created a task should be automatically created for him. Here is my user controller create/register method:
public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "userId,dateCreated,dateRemoved,level,firstName,lastName,login,emailAddress,password")] User user)
    {
        user.dateCreated = DateTime.Now;
        if (ModelState.IsValid)
        {
            db.User.Add(user);
            db.SaveChanges();

            return RedirectToAction("Create", "Tasks", new { Id = user.userId });

           //return RedirectToAction("Index");
        }

        return View(user);
    }

Here is the Create Task method of the task controller
public ActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "taskId,dateCreated,dateAssigned,userId,assigneeId,taskCategory,taskType,taskPriority,taskStatus,taskName,dateDue,dateClosed,Comments")] Task task, int? Id)
    {
        task.dateCreated = DateTime.Now;

        if (Id != null)
        {
            task.userId = (int)Id;
            task.dateAssigned = DateTime.Now;
            task.dateCreated = DateTime.Now;
            task.dateDue = DateTime.Now.AddDays(7);
            task.taskCategory = taskCategory.assigned;
            task.taskType = taskType.System_Induction;
            task.assigneeId = 2;
            task.taskPriority = taskPriority.Low;
            task.taskName = "Iduction to TaskManagementTool";
            task.Comments = "Please go through the following training materials:";
            task.taskStatus = taskStatus.Assigneed;

            if (ModelState.IsValid)
            {

                db.Tasks.Add(task);

                db.SaveChanges();

                ViewBag.TaskAssignedNotification = "Hello " + Session["login"].ToString() + " you have new task assigned" ;

                switch (Session["level"].ToString())
                {
                    case "Basic":
                        return RedirectToAction("LoggedAsBasic", "Home");
                        break;

                    default:
                        return RedirectToAction("LoggedAsBasic", "Home");
                }

                //return RedirectToAction("Index", "Home");
            }
        }
        else
        {
            task.userId = Int32.Parse(Session["userId"].ToString());
            task.taskStatus = taskStatus.Created;

            if (Session["level"].ToString() == "Assigner" && task.taskCategory == taskCategory.assigned)
            {
                task.dateAssigned = DateTime.Now;

            }

            if (Session["level"].ToString() == "Basic")
                task.taskCategory = taskCategory.own;

            if (ModelState.IsValid)
            {

                db.Tasks.Add(task);

                db.SaveChanges();

                return RedirectToAction("TasksIndex");
            }
        }
        return View(task);
    }

While creating the new user the new user Id should be passed to Create method of the task controller and predefined task (in if (Id != null))should be created for the new user without opening the Create view with the HTML form. Unfortunatley I am not able to call the Create method of the task controller from the user controller. At best I end up with the task create for to be filled. Can you folks help me out on this?

A: All I needed in this case was new task object created withing the users/create action method togather with the user object so I do not need to point at any other controller/actionresult to create the task.
[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "userId,dateCreated,dateRemoved,level,firstName,lastName,login,emailAddress,password")] User user, Task task)
    {
        user.dateCreated = DateTime.Now;
        if (ModelState.IsValid)
        {
            db.User.Add(user);
            db.SaveChanges();

            task.userId = 2;
            task.dateAssigned = DateTime.Now;
            task.dateCreated = DateTime.Now;
            task.dateDue = DateTime.Now.AddDays(7);
            task.taskCategory = taskCategory.assigned;
            task.taskType = taskType.System_Induction;
            task.assigneeId = user.userId;
            task.taskPriority = taskPriority.Low;
            task.taskName = "Iduction to TaskManagementTool";
            task.Comments = "Please go through the following training materials:";
            task.taskStatus = taskStatus.Assigneed;

            if (ModelState.IsValid) {

                db.Tasks.Add(task);
                db.SaveChanges();

            }

           return RedirectToAction("Index");
        }

        return View(user);
    }


text:
Q: creditcard processing from iphone app I have an iphone app, i need to implement payment gate way on it.customers need to purchase item using their credit card number.I have checked paypal service , but it supports paypal to paypal transactions,
anybody knows paypal have any library for creditcard transaction from iphone?
help is highly appreciated.
Thanks,
VKS

A: Is it for some kind of in app purchase? As im sure that's against apples guidelines and your app will be rejected.


text:
Q: EF Core App - How do I script for installation? I've got a an EF Core Application (using WPF, C#) that I can build and run just fine as a developer.  I have no problems editing my data model, creating migrations and updating the database from Package Manager Console.  But now I'm trying to write an installer (evaluating various install tools) and I'm wondering what to do at installation time.
All the EF Core documentation I can find seems to address database creation purely from a developer's perspective.  But I can't exactly have a user run package-manager console on my source code.  Yet once my app is installed, the database needs to exist.  I don't know how best to use the outputs that EF Core gives me to create the database at install time.  What is the best practice?
For example, in my project I see that "Migrations" folder, that EF Core created for me when I ran the add-migration command from PM Console.  It has a class derived from "Migration" with the "Up" method that creates tables in C#.
public partial class init : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "AnalysisTypes",
            columns: table => new
            {
                Key = table.Column<string>(nullable: false),
                Name = table.Column<string>(nullable: true),
                Show = table.Column<bool>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_AnalysisTypes", x => x.Key);
            });

        ...etc ... etc... etc...

It seems as if it would be ideal to create my database.  Like maybe I should somehow extract this Migration-derived class into a separate console app to be run at install time to create the database. Is this something that is typically done?
Alternately, if I run the script-migration -idempotent command from PM Console, I get a SQL script that creates the tables I need.
IF OBJECT_ID(N'[__EFMigrationsHistory]') IS NULL
BEGIN
    CREATE TABLE [__EFMigrationsHistory] (
        [MigrationId] nvarchar(150) NOT NULL,
        [ProductVersion] nvarchar(32) NOT NULL,
        CONSTRAINT [PK___EFMigrationsHistory] PRIMARY KEY ([MigrationId])
    );
END;

GO

CREATE TABLE [AnalysisTypes] (
    [Key] nvarchar(450) NOT NULL,
    [Name] nvarchar(max) NULL,
    [Show] bit NOT NULL,
    CONSTRAINT [PK_AnalysisTypes] PRIMARY KEY ([Key])
);

GO

... etc ... etc... etc...

But that script only creates tables.  It has no provision to connect to the database or see if it exists and create it if it does not.  I need a smarter script to

*

*Connect to the right sql server

*Check to see if the database exists

*Create it if it does not.

*Ensure its schema is up to date.

So am I supposed to take this script-migration-generated script and wrap it in some larger one that does all of that work for me?  Is there some command that will do all that?
I assume this is a solved problem in the EF Core world.  I'm just looking for what is a best practice.  Can anyone give me any guidance here?

A: If you already have the database created, you can set the Database initializer to migrate to the newest version by setting calling SetInitializer.
Database.SetInitializer<ObjectContext>(new MigrateDatabaseToLatestVersion<ObjectContext, Configuration>());

From: https://msdn.microsoft.com/en-us/magazine/dn818489.aspx

If you were to compile the project and give it to another developer
  who hasn't migrated her own development database, the initializer
  would trigger the app to look for a migration. The migration will be
  found because it's in the project. The initializer will check the
  database's migration history table and update the database schema, if
  necessary.
Considering this in production, not development, the migration class
  will be compiled into your assembly and deployed as part of the
  application. When the application is run, it will respond to a
  MigrateDatabaseToLatestVersion setting (in the appropriate place in
  your application) and update the database schema accordingly.

You can read more about Migrations here.
EDIT
For EF Core:
From: http://flores.eken.nl/ef-core-equivalent-of-migratedatabasetolatestversion/

And now the important part. Of course you want your program to run the
  migration (and subsequent ones) automatically upon application
  startup. In the EF 6.x days this could be done by using the
  MigrateDatabaseToLatestVersion database initializer.
This changed in EF core. Now you will have to use:

context.Database.Migrate();


text:
Q: How to hide HTML Page Source in php by detecting the URL I do not care about people viewing my source code, however, I want Bots to avoid coming on to my site and getting through my security. I was hoping to disable page source viewing. To do this, I am using this code:
$url= $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$needle = "view-source:";
if (strpos($url,$needle)) { echo "You can not see me";}
else {
//The rest of my index page
}

The objective here is that if someone tries to view my page source or if a bot tries to, that rather than being able to see it, the code will detect that the page URL is view-source:www.yoururl.com and will display a "Nice try" message in the source instead of the page source. The code above in theory should have worked, but didn't. Any other idea's to try and make this work?

A: This cannot be done, the HTML source code is passed to whoever requests it. You should probably redesign your captcha, as it is not secure from how you described it. Use session variables to store the data and to check against the submitted value on the form processor script.

A: you could use mod_rewrite and a permanent 301 redirect in your .htaccess to hide the ?captcha=xxxx part of your url, if it is your sole concern.


text:
Q: Having problem with Select using month/hour The database is from a Hospital and the problem is when the month changes, like this: The patient gets to the UTI on the date 30/03/2020 6AM and left on 02/04/2020 11AM so theoretically they spend (18+24+24+11) 89 hours in total butIput this on Business Intelligence(BI) the BI thinks that they spent 77hours on the UTI only on March and didn't show anything for April
So i have to divide like 30/03/2020 6AM end on 31/03/2020 23:59PM = 42h, and 01/04/2020 start on 00AM and end on 02/04/2020 11PM = 47h
So they achieve 77 hours but it is divided between March and April.
My goal is to divide this in SQL Server with select or something, i was reading about DATEPART/DATENAME but unsuccessfully.

SELECT
        S.STR_NOME
     , LOC.LOC_NOME
     , LTO.LTO_TIPO
     , LTO.LTO_PAC_REG
     , PAC.PAC_NOME
     , MTL.MTL_DESCR
     --, BLC.BLC_LOC_COD
     --, BLC.BLC_DTHR_INI
     --, BLC.BLC_STATUS
     ,LTO.LTO_DTHR_INI
     ,LTO.LTO_DTHR_FIM

  FROM LTO
  JOIN PAC ON PAC.PAC_REG = LTO.LTO_PAC_REG
  JOIN LOC ON LOC.LOC_COD = LTO.LTO_LOC_COD
  LEFT JOIN MTL ON MTL.MTL_COD = LTO.LTO_MTL_COD
  LEFT JOIN STR S ON S.STR_COD =LOC.LOC_STR
  --FULL OUTER JOIN BLC ON BLC.BLC_LOC_COD = LOC.LOC_COD AND BLC.BLC_DTHR_FIM = LTO.LTO_DTHR_INI

 WHERE LTO.LTO_DTHR_INI >= '2020-01-01 00:00:00'
 AND LOC.LOC_NOME ='ENFERMARIA 112-A    '
 AND LTO.LTO_PAC_REG = '144755'

 ORDER BY LTO.LTO_DTHR_INI

A: What you need to do is add a row for each month into your data. One method is using an rCTe, however, I prefer to use a Tally as they are significantly faster for larger data sets; though here there's likely to be little to no performance difference.
I assume 36 rows, 3 years, is enough here. I then use a small inline tally to create a row for each month for the start and end dates, and then a get the difference, in hours, for each month using DATEDIFF:
CREATE TABLE dbo.YourTable (ID int IDENTITY(1,1),
                            ArrivalTime datetime2(0),
                            DepartureTime datetime2(0));
GO
INSERT INTO dbo.YourTable
VALUES('2020-03-30T06:00:00','2020-04-02T11:00:00'),
      ('2020-01-17T17:00:00','2020-10-30T09:00:00');

GO

SELECT *
FROM dbo.YourTable;
GO

WITH Tally AS (
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) -1 AS I
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL)) N1(N)
         CROSS JOIN (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N2(N)), --36 rows, 3 years.
Months AS(
    SELECT YT.ID,
           YT.ArrivalTime,
           YT.DepartureTime,
           T.I,
           D.MonthStart AS MonthStartD,
           D.NextMonthStart AS NextMonthStartD,
           CASE WHEN D.MonthStart < YT.ArrivalTime THEN YT.ArrivalTime ELSE D.MonthStart END AS MonthStart,
           CASE WHEN YT.DepartureTime > D.NextMonthStart THEN D.NextMonthStart ELSE YT.DepartureTime END AS MonthEnd
    FROM dbo.YourTable YT
         JOIN Tally T ON DATEDIFF(MONTH, YT.ArrivalTime,YT.DepartureTime) >= T.I
         CROSS APPLY (VALUES(DATEADD(MONTH,T.I,DATEFROMPARTS(YEAR(YT.ArrivalTime),MONTH(YT.ArrivalTime),1)),
                             DATEADD(MONTH,T.I+1,DATEFROMPARTS(YEAR(YT.ArrivalTime),MONTH(YT.ArrivalTime),1))))D(MonthStart,NextMonthStart))
SELECT ID,
       DATEPART(YEAR, MonthStart) AS Year,
       DATENAME(MONTH, MonthStart) AS Month,
       DATEDIFF(HOUR,MonthStart,MonthEnd) AS Hours
FROM Months
ORDER BY ID,
         DATEPART(YEAR, MonthStart),
         DATEPART(MONTH, MonthStart);

GO
DROP TABLE dbo.YourTable;

db<>fiddle