text:
Q: stop execution until jquery post is done I have problem with $.post here is my code:
$("#datepicker").click(function () {

    var id = $("#doctor_book").val();
    var url = $('#base_url').attr('data-url') + 'index.php/home/disable_days';

    $.post(url, { id: id }, function (r) {

        r = JSON.parse(r);

        var obj = {
            Mon: 1,
            Tue: 2,
            Wed: 3,
            Thu: 4,
            Fri: 5,
            Sat: 6
        };

        var specific = new Array();
        var final_array = new Array();

        for (var a = 0; a < r.length; a++) {
            for (var b = 0; b < Object.keys(obj).length; b++) {
                if (r[a] === Object.keys(obj)[b]) {
                    specific.push(Object.keys(obj)[b]);
                }
            }
        }

        for (var c = 0; c < specific.length; c++) {
            delete obj[specific[c]];
        }
        for (var key in obj) {
            final_array.push(obj[key]);
        }
        console.log(r);

        yverebi(final_array);
    });
});

function yverebi(final_array) {
    $("#datepicker").datepicker({
        beforeShowDay: function (date) {
            var day = date.getDay();
            return [$.inArray(day, final_array) == -1]
        }
    });

    $('#datepicker').datepicker("show");
}

r looks like this ["Mon", "Sat"], I saw examples of stopping ajax request and then executing some other functions but what I want is to stop running javascript code until post request is done.

A:
to stop running javascript code until post request is done

This is not how it works. Once you run some code, it runs. The POST is asynchronous, which means your remaining code will not (and will never) wait for it.
What you actually do is define a callback function (you have that already, it starts at function(r){ ...). This function and all the code inside is run after the POST finished.

A: You can use jquery post's different callback methods.
$.post( "example.php", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
});

which ever method you want.I think for your case you can use done() method.
you can change your code to
 $.post(url, { id: id })
   .done(function(r){
    // your code
 });

A: What you are talking about is called a promise. Whenever an async task is done then post it's completion the follow up tasks are executed using promises.
This same thing can be used in your own custom functions also sometimes.
Reference Article

A: You can use a "busy" variable :
var busy = false;

$.post(url, {id: id}, function(r){
  if(busy) return false;
  var busy = true;
  /*rest of your code*/

 /* on your $.post callback : */
 var busy = false;


text:
Q: How to get Canon Pixma MG3660 to scan? I have searched through all the advice and followed all the steps.
But I can't get the printer to work without problems.
But the scanner has proved impossible to get to work.
After many hours of trying, I have decided that the best thing to do is use a skip bin and find an all-in-one that will actually be an all-in-one.
Could you please advise as to which brand and model.
Canon was just a complete waste of money and their support a joke.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setup.py - Add data files inside package in setuptools everyone! Jumping to my issue, I have this file structure, in Python 3.7:
mypackage/
 |- config/
 |---- config.json
 |- mypackage/
 |---- __init__.py
 |---- main.py
 |- docs/
 |---- __init__.py
 |---- doc_folder/
 |--------- text_file.txt
 |- setup.py
 |- MANIFEST.in

My setup.py is using setuptools and has, of relevance:
setup(
    name='mypackage',
    version='1.0',
    packages=find_packages(),
    include_package_data=True
)

And my MANIFEST.in has:
recursive-include config *
recursive-include docs *

When I either run pip install . or python setup.py sdist & pip install dist/mypackage-1.0, the same thing happens:

*

*When the distribution is built, the logs say both docs and config are copied into mypackage-1.0;

*When installed, I can't find config;

*When installed, docs is found in the site-packages folder (site-packages/docs).

*If i add an __init__.py to config, it also appears in the site-packages folder.
My objective would be to have docs and config inside of the mypackage directory, because I'm afraid if I pip install different projects with config folders, they're going to override each other. It'll also be more useful to do relative imports, I assume.

What do you guys think?

A: Moving both config and doc dirs under mypackage (the one that is actually a package, containing an __init__.py) should fix the issue. The changed directory structure from the question:
mypackage/
├── mypackage/
│   ├── __init__.py
|   ├── config/
|   |   └── config.json
|   ├── docs/
|   |   ├── __init__.py
|   |   └── doc_folder/
|   |       └── text_file.txt
|   └── main.py
├── setup.py
└── MANIFEST.in


text:
Q: proper mathematics way to explain in a comment that there is no duplicate items in a set i'm writing some code, and I want my code to be well documented.
there is a part in the code where I'm checking that when there is a try to insert new element E to a list L, the element E will be unique (so there is no other elements in L that equals to him).
I'm having difficult to write a user-friendly mathematics comment, something that will look like the example bellow
the function will change all elements (that in list L) fields E.color to "Black"  only if color to black element.size > 10.
so in that case I will write the comment -
[ X.color="Black" | X in L, X.size > 10]
but for the scenario above I couldnt find any satisfied mathmatics comment.

A: A mathematical set by definition has no duplicates inside it, so perhaps using the a set rather than a list would solve your problem.
However if that's too hard to change now then you could write something like:
[ L.insert(E) | E not in L ]
where E is the element and L is the list.

A: an exhaustive answer to your question requires two observations:

*

*Best coding practices require you to know collections very well and when to use them. So you want the right collection for the right Job. In this case as advised in other comments, you need to use a Set instead of a list. A Set uses a Map under the hood, having your elements as keys and values as DEFAULT. Every time that you add an element to your Set, the Hash value for it is calculated and compared using equals to the existing elements. So no dups are allowed.

*I really  appreciate the fact that you want to write good comments, however you don't need to for the following reasons:

*

*List and Sets behaviour is largely documented already, so nobody expects you to comment them;

*Books like Refactoring and Clean code, teach us that good code should never be commented as it should be self explaining. That means that your method/class/variable name should tell me what the method is doing.


text:
Q: Extracting rows values using jquery I have a gridview that has multiple rows. I am trying to iterate through each row get values and submit the values to database using ajax class.
The html from gridview for one row is
 <input id="GridView3_ctl03_chkEmployee" type="checkbox" name="$GridView3$ctl03$chkEmployee" />

                        6878

                        abcd Inc.

I have following jquery code that selects each row that has been checked.
$(document).ready(function () {
           $("#submit").click(function () {
               var record;
               alert("starting");
               $("#<%=GridView3.ClientID%> input[id*='chkEmployee']:checked").each(function () {
                   var value = $(this).find('.FName').val();
                   alert(value);
               });
           });
       });

I cant extract the values for both FName and idName. I get error undefined. Any ideas how to fix it?

A: As there are multiple classes you will need to try something like this
var arr = [];
  $('.yourClassName').each(function(){
      arr.push($(this).text());
   });

In this, array will have your values and you can exploit it as you like

A: Try this
$(document).ready(function () {
var arr = [];
 $('tr [type="checkbox"]:checked').parent().each(function () {
   var value = $(this).find('.FName').val();
   arr.push(value);
});
  callAjaxGetJoiningDate(arr);
});
function callAjaxGetJoiningDate(hashVal) {
var address = "Ypurpage.aspx";
$.ajax({
    type: 'POST',
    url: address,
    data: { empCode: hashVal },
    beforeSend: function () {
        // this is where we append a loading image
        $('#ajax-panel').html('

');
    },
    success: function (data) {
        // successful request; do something with the data
        $('#ajax-panel').empty();
        var actualData = data.trim().split('~');
        $("#YourResultControl").val(actualData[1]);

    },
    error: function () {
        // failed request; give feedback to user
        $('#ajax-panel').html('
Oops! Try that again in a few moments.
');
    }
});


text:
Q: Combine "toHaveBeenCalledWith" and "toBeCloseTo" I need a way to check if a spy was called with an approximate value, like it can be done with expect(value).toBeCloseTo(3,2).
Something like this:
expect(spy).toHaveBeenCalledWith("some string", valueToBeCloseTo(3, 2))

A: I think you can use the calls and mostRecent helpers.
const secondArgument = spy.calls.mostRecent().args[1]; // args[0] would be the string
expect(secondArgument).toBeLessThanOrEqual(3);
expect(secondArgument).toBeGreaterThanOrEqual(2);

Check out this link for most recent and this link for toBeLessThanOrEqual and toBeGreaterThanOrEqual.


text:
Q: Reactjs functional component common logic extraction I have a few functional components with a few common variables and functions. Please see below.
const Customer = () => {
   const [isReleased, setIsReleased] = useState(false)

   const release = () => {
        setIsReleased(true)
   }
}

const Order = () => {
   const [isReleased, setIsReleased] = useState(false)

   const release = () => {
        setIsReleased(true)
   }
}

As you can see from the above code fragment, the release() function has common logic. It accesses component's variables/functions.
Is there a way to move this release() function to a common file and import it from each component?
Please note that the release() method should be able to access scoped variables and functions of the caller.
Update
Below is the actual content of the release() function. I have put this. to denote that it refers to the variables/functions in the caller.
const release = () => {
  if (action === "new") {
    history.push(`/customers/new`)
  } else if (action === "save") {
    (async () => {
      try {
        if (this.dataMode === "new") {
          this.setMessage()
          this.setFormStatus("updating")
          let _res = await this.customer_api_create(this.formData)
          if ((_res.status === 200) && (_res.data.status === "success")) {
            this.setFormStatus()
            history.replace({ pathname: `/customers/${_res.data.data[0].id}` })
          }
        } else if (this.dataMode === "edit") {
          this.setFormStatus("updating")
          this.setMessage()
          let _res = await this.customer_api_update(this.formData)
          if ((_res.status === 200) && (_res.data.status === "success")) {
            this.setFormStatus()
            this.setMessage({ type: "info", text: "Saved" })
            this.setFormData(_res.data.data[0])
          }
        }
      } catch (e) {
        this.openMessageBox({
          prompt: e.response.data.message,
          type: this.constants.app.MessageBoxType.MB_Error,
          buttons: this.constants.app.MessageBoxButton.MB_Ok,
          show: true,
          setResult: () => console.log(this.constants.app.MessageBoxResult.MB_Ok)
        })
        this.setFormStatus("updating_error")
      }
    })();
  } else if (action === "del") {
    this.openMessageBox({
      prompt: `{ "": ["Are you sure you want to delete context customer?"] }`,
      type: this.constants.app.MessageBoxType.MB_Warning,
      buttons: this.constants.app.MessageBoxButton.MB_YesNo,
      show: true,
      setResult: (val) => {
        this.openMessageBox({ show: false })
        this.setShouldRecordDeleted(val)
      }
    })
  }
}

A: You can declare the function release in a different file and pass the setIsReleased method as an argument
import {release} from 'release';

const Customer = () => {
       const [isReleased, setIsReleased] = useState(false)
       release(setIsReleased)
    }

And in your release.js file
export const release = (setIsReleased) => {
   setIsReleased(true)
}

A: Maybe callback solve the problem, how about this?
anotherfile.js
    const release = (param, setter) => {
        if (true){
            setter(true)
        }
    }

yourfile.js
    import {release} from "anotherfile"
    const Customer = () => {
       const [isReleased, setIsReleased] = useState(false)
       release([parameter],setIsReleased)
    }


text:
Q: How to treat collection of data objects as a database table? I am trying to find a way to treat Java data object collection as a database table.
For example:
There is an array list of student data object scanned from Excel sheet. Now I want an easy way to list down :
•   Students born in the same months
or
•   Students from computer class
or
•   Students having the same street address
or
•   Students whose last name are XYZ
To achieve this, I don't want to loop through the list for every requirement.
I am looking for something like it that works in DB, just query for what you need and it returns you the requested information.


text:
Q: More nest Python nested dictionaries After reading What is the best way to implement nested dictionaries? why is it wrong to do:
c = collections.defaultdict(collections.defaultdict(int))

in python? I would think this would work to produce
{key:{key:1}}

or am I thinking about it wrong?

A: Eli Bendersky provides a great direct answer for this question. It might also be better to restructure your data to
>>> import collections
>>> c = collections.defaultdict(int)
>>> c[1, 2] = 'foo'
>>> c[5, 6] = 'bar'
>>> c
defaultdict(<type 'int'>, {(1, 2): 'foo', (5, 6): 'bar'})

depending on what you actually need.

A: The constructor of defaultdict expects a callable. defaultdict(int) is a default dictionary object, not a callable. Using a lambda it can work, however:
c = collections.defaultdict(lambda: collections.defaultdict(int))

This works since what I pass to the outer defaultdict is a callable that creates a new defaultdict when called.
Here's an example:
>>> import collections
>>> c = collections.defaultdict(lambda: collections.defaultdict(int))
>>> c[5][6] += 1
>>> c[5][6]
1
>>> c[0][0]
0
>>>


text:
Q: Why we get Error in NonGUIDriver java.lang.IllegalArgumentException in blazemeter while execution? I am getting below error while executing test in blazemeter.
jmeter.JMeter: Error in NonGUIDriver java.lang.IllegalArgumentException: Problem loading XML from:'/home/jmeter/abc.jmx', missing class com.thoughtworks.xstream.converters.ConversionException:

Have anyone face this issue....
Also  i am using random csv data set plug-in in my jmeter script which i have uploaded in blazemeter.

A: There are 3 possibilities:

*

*Either you forgot adding a plugin your test plan requires

*Or you forgot adding a dependency that a used plugin requires

*Or there is an incompatibility between the jmeter version used locally and on Blazemeter

A: Encountered this issue this morning. To solve it:
1) Add the jmeter plugin manager.
2) Close jmeter and reopen it.
3) It then suggested the plugins I was missing and allowed me to add them.
It worked fine after this. Hope this helps


text:
Q: installing and using pyserial in python 3.4 windows 8.1 I want to use pyserial but I do not know what I am doing wrong
I have installed python 3.4.2 from this link
www-python-org-downloads-release-python-342- the one that says "Windows x86-64 MSI installer" and I got this archive "python-3.4.2.amd64.msi" because my operating system is 64 bit
during the installation I have selected "add python.exe to path" (will be installed on local hard drive), and all the other ones
I went to the pyserial website http://pyserial.sourceforge.net/pyserial.html#installation
which say "Download the archive from http://pypi.python.org/pypi/pyserial. Unpack the archive, enter the pyserial-x.y directory and run:" and sent me to this link
http-pypi-python-org-pypi-pyserial
I have donwloaded from this link, these three archives
pyserial-2.7.tar.gz,    pyserial-2.7.win32.exe    pyserial-2.7.win32_py3k.exe
I have tried to run the .exe one but they say "No python installation found in the registry", which I dont know why
then I unpack the .gz file with Winrar enter into the folder and try to run "pyserial-x.y" but there is nothing like that in this folder
in this folder I can find
documentation (folder)
examples
serial
test
CHANGES.txt
LICENSE.txt
MANIFEST.in
PKG-INFO
README.txt
setup.py

I tried to run this "setup.py" but for a second a black window appears
detected Python 3, using 2to3
C;\Python34\lib\distutils\dist.py:260: UserWarning: Unknow distribution option: use_2to3
warning.warn(msg)
usage: setup.py [global_opts] [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help commands
or: setup.py cmd --help
error: no commands supplied

and then disappears
I went to the command prompt and wrote "python3 setup.py install" or python setup.py install
but it says
Microsoft Windows [Version 6.3.9600]    (c) 2013 Microsoft Corporation. All rights reserved.
    C:\Users\me>python3 setup.py install
'python3' is not recognized as an internal or external command operable program or batch file.
so I cant do that either
then in command prompt I chancge the directory with "cd C:\Users\me\Downloads\pyserial-2.7" which is the place where the folder .gz is then "python setup.py install" and "python3 setup.py install" but they do not work
there is the code and at the end it says
C:\Users\me\Downloads\pyserial-2.7>python setup.py install
Detected Python 3, using 2to3
C:\Python34\lib\distutils\dist.py:260: UserWarning: Unknown distribution option:
 'use_2to3'
  warnings.warn(msg)
running install
running build
running build_py
running build_scripts
running install_lib
running install_scripts
running install_egg_info
Removing C:\Python34\Lib\site-packages\pyserial-2.7-py3.4.egg-info
Writing C:\Python34\Lib\site-packages\pyserial-2.7-py3.4.egg-info
C:\Users\me\Downloads\pyserial-2.7>

then I try to write in the command prompt "python" then "import serial" but still it does not work
THEN i DO NOT KNOW WHAT TO DO
could somebody help me

A: well actually it is working, the last part of my question "last code" says that the installation was successful
sorry to bother
so in order to clarify this issue I will write the whole process, Please recommend this post to all the people who is having the same issue, IT WAS SO ANNOYING without  A CLEAR PROCESS

*

*first download Python 3.4.2, install it

*then download pyserial "pyserial-2.7.tar.gz"

*unzip with Winrar

*go to command prompt

*change the directory means write "cd C:\Users\me\Downloads\pyserial-2.7>" which is the inside of the unzipped folder, or wherever you unzipped the pyserial.gz

*then write "python setup.py install"

*in the installation process activate the last option, use in the local disk

done

A: As there are multiple issues with your installation, I recommend you start fresh by do the following:

*

*Uninstall the 64bit version of Python, reboot your computer.

*Download and install the 32bit MSI installer from python.org

A lot of libraries are already compatible with Python 3, but not everything is there yet and you don't want to run into issues during development; so I would recommend the latest 2.7.x version.

*Download and install the setuptools package.

*Download the file pyserial-2.7.win32.exe and then double click it to run.


text:
Q: Scrolling top function not is disturb by something I'm on chrome and I have the impression that my function works but there is something that returns me to my previous position
('html, body').animate({scrollTop:0},500);
(I really want to have it when I load the page, not when I click on a button) Thanks for help


text:
Q: How can I keep an image from overflowing its container? I'm working with Reactjs in a page... like a diary.
At the end of the page, there is an img that I'm trying to set inside the page but because of the size, it goes out of the page... I try to modify it with Css, but still not working. Can you help me please?
This is how the page looks:

This is how the html code looks:

            <input type="text" placeholder="Somer awesome title" className="notes__title-input" autoComplete="off"/>
            <textarea placeholder="What happened today?" className="notes__textarea"></textarea>

This is how I set the css:
    .notes__main-content{
    display: flex;
    flex-direction: column;
    height: 100%;
}

.notes__appbar{
    align-items: center;
    background-color: $primary;
    color: white;
    display: flex;
    justify-content: space-between;
    padding: 10px 20px 10px 20px;
}

.notes__content{
    display: flex;
    flex-direction: column;
    height: 100%;
    padding: 20px;
}

.notes__title-input, .notes__textarea{
    border: none;

    &:focus{
        outline: none;
    }
}

.notes__title-input{
    color: $dark-grey;
    font-size: 25px;
    font-weight: 700;
    margin-bottom: 10px;
}

.notes__textarea{
    border: none;
    color: $dark-grey;
    font-size: 20px;
    flex: 1 1 auto;
    resize: none;
}

.notes__image{
    box-shadow: 5px 5px $dark-grey;
    height:  150px;
}

To be clear, what I want to do is to set the img to 150px so it can fit my page. Thank you for your help

A: Images don't magically shrink to fit their containers. You need to tell them to do so:
.notes__image img {
  max-width: 100%; /* <-- here's your huckleberry */
}

You don't want to use the width property as that'll stretch images beyond their native size, and you don't want to set height as that will goof up aspect ratio.
Here I've converted className to class for demonstration purposes. If you view the fullscreen demo and shrink the window size you can see it in action.

.notes__main-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.notes__appbar {
  align-items: center;
  background-color: $primary;
  color: white;
  display: flex;
  justify-content: space-between;
  padding: 10px 20px 10px 20px;
}

.notes__content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
}

.notes__title-input,
.notes__textarea {
  border: none;

  &:focus {
    outline: none;
  }
}

.notes__title-input {
  color: $dark-grey;
  font-size: 25px;
  font-weight: 700;
  margin-bottom: 10px;
}

.notes__textarea {
  border: none;
  color: $dark-grey;
  font-size: 20px;
  flex: 1 1 auto;
  resize: none;
}

.notes__image {
  box-shadow: 5px 5px $dark-grey;
  height: 150px;
}
.notes__image img {
  max-width: 100%; /* <-- here's your huckleberry */
}

  <input type="text" placeholder="Somer awesome title" class="notes__title-input" autoComplete="off" />
  <textarea placeholder="What happened today?" class="notes__textarea"></textarea>

A: You can add another div inside notes__image div. Lets call it notes__image__inner with a div wrapper.

        <input type="text" placeholder="Somer awesome title" className="notes__title-input" autoComplete="off"/>
        <textarea placeholder="What happened today?" className="notes__textarea"></textarea>

Update the notes__image and img CSS with this:
.notes__image {
  box-shadow: 5px 5px $dark-grey;
  height: 150px;
  position: relative;
}
.notes__inner__image {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
.notes__inner__image img {
   width: 100%;
   position: static;
   height: 100%;
   object-fit: cover;
}

A: The className property is used in React. Is this a React application? If not, it needs to be revised to "class".
Also make sure your image does not overflow the bounds of the div. You can set strict width and height in the image by using the img tag's "width" and "height" properties. Or create a notes__image img declaration, like this:
.notes__image img {
  width: 100%;
  height: 100%;
}


text:
Q: Can I stop Drupal re-creating a form when it's submitted? I have a booking form that's built using options that are retrieved via a third party API and because of the need to have up to date information the results from the API can't be cached (at least not for very long).
The problem I'm having is I've noticed when the form is submitted Drupal is re-calling my _form function which is triggering the API calls again and I'd like to stop it doing that to try and reduce the number of API calls that are made.
Obviously if the validation fails it needs to re-draw the form and the API calls will need to be made again but I'm wondering if there's a way to stop it doing this when the form validates so I can stop it making lots of unnecessary calls to the API.
Thanks for any help.

A: You can not avoid the re-creation of the form, if the form is to be processed by Drupal. It is a central part of Drupals form processing workflow: Every form is at least build twice, once for initial output, and at least once again when the post from the client comes in. It can even be more than that, depending on what the form does afterwards, e.g. on redisplay when any validation errors occurs (Usually a cached version gets used by then, but that depends on the specific form).
What you should do is follow Simons suggestion - on the first call to your form builder function, make your API calls and store the results in $form_state['storage']['yourIdentifier'] ('yourIdentifier' being some string not used by standard form processing - usually starting with your modules name). On every call to your form builder function, you check if that results are already in $form_state['storage']. If they are, you just use those, skipping the API calls.
This will avoid the duplicate API calls, and gives you more control on how/when to do them (e.g. you can also clear those results during validation, if a special condition calls for a refetching from the external API).

A: Could you store/cache the return values from the API in the $form_state['storage'], so at least if _form gets called every time you can first check storage before making the API calls again.

A: First thing, If validation fails, Drupal has a copy of the form, so your form function won't actually be called.
Now to the solution.

*

*You can redirect to a new page in your form submit, go avoid the recalling og the form.

*Instead of calling your form directly in your menu definition make a callback that calls the form. You can then test if the form has been submitted or not and only call your form function when needed.

If you are this worried about the API calls you could also cache it for 5-10 mins which would make my two suggestions obsolete.

A: Drupal can't do this? "Can't" isn't in my vocabulary!
I had this same problem, but I couldn't let it beat me. Here's how I got over it:
In the processing form, after I insert the details into the database (or email or whatever), I set 2 drupal status messages like this
function process_form($form){
  $success = do_email($form);
  if ($success){
    drupal_set_message("Success");
    drupal_set_message("Your form worked!");
  }
}

And in the form generator I read and clear the messages, clear the form and output the status message as markup:
function form_generator($form_state,$parameters){
  $form = array();
   ...// This is where I make the regular form
  $messages = drupal_get_messages(); // this gets the messages and clears them
  if (isset($messages["status"])){
    if (isset($messages['status'][0]) && isset($messages['status'][1])){
      if ($messages['status'][0]=="Success"){
        $form = array(); // This clears the form I've just made
        $form['final_message']= array(
          '#type' => 'markup',
          '#markup' => $messages['status'][1],
        );
      }
    }
  }
}

This doesn't clear the form the first time it's shown because $messages isn't set and when you encounter validation errors they will still appear.
Drupal magic bars our way, but the will of PHP coder is stronger.


text:
Q: Python convert string to time I have continues time data list with min:sec.msec and it is like,
t=['10:44.7',...,'36:25.1',..,'59:59.9',..,'00:00.1',...,'18:01.2']

This includes min:sec.msec but I need to convert all the data format to Hour:min: sec. It means data should be,
t_converted=['12:10:45',...,'12:36:25',..,'13:00:00',..,'14:00:00',..,'14:18:01']

How can I do using python?

A: A simple time conversion can be done with
t_converted = [datetime.strptime(_t, '%M:%S.%f').strftime('%H:%M:%S') for _t in t]

The apparent requirement for everything to be offset by 12 hours makes it more complex
Firstly, the only way of knowing when to go from 12, 13 is for the next time to be less than the previous
e.g. 59:59.9, 00:00.1
If you had 30:30.0 then 45:00.0 and they were meant to be 12:30:30 and 13:45:00 there is literally no way of knowing
From that assumption, this code works:
from datetime import datetime, timedelta

t=['10:44.7','36:25.1','59:59.9','00:00.1','00:00.0','18:01.2']
t_converted = []
i = 0
prev_dt = None
for _t in t:
    dt = datetime.strptime(_t, '%M:%S.%f') + timedelta(hours=12+i)
    if prev_dt is not None and prev_dt > dt:
        i += 1
        dt += timedelta(hours=1)
    t_converted.append(dt.strftime("%H:%M:%S"))
    prev_dt = dt
print(t_converted)


text:
Q: VS code Exception error on python language Exception error
I have suddenly encountered this problem with VS code using python. I have tried reinstalling anaconda and also VS-code itself but nothing seems to be working.


text:
Q: Scala: apply Map to a list of tuples very simple question: I want to do something like this:
var arr1: Array[Double] = ...
var arr2: Array[Double] = ...

var arr3: Array[(Double,Double)] = arr1.zip(arr2)

arr3.foreach(x => {if (x._1 > treshold) {x._2 = x._2 * factor}})

I tried a lot differnt syntax versions, but I failed with all of them. How could I solve this? It can not be very difficult ...
Thanks!

A: Multiple approaches to solve this, consider for instance the use of collect which delivers an immutable collection arr4, as follows,
val arr4 = arr3.collect {
  case (x, y) if x > threshold => (x ,y * factor)
  case v => v
}

With a for comprehension like this,
for ((x, y) <- arr3)
  yield (x, if (x > threshold) y * factor else y)

A: I think you want to do something like
scala> val arr1 = Array(1.1, 1.2)
arr1: Array[Double] = Array(1.1, 1.2)

scala> val arr2 = Array(1.1, 1.2)
arr2: Array[Double] = Array(1.1, 1.2)

scala> val arr3 = arr1.zip(arr2)
arr3: Array[(Double, Double)] = Array((1.1,1.1), (1.2,1.2))

scala> arr3.filter(_._1> 1.1).map(_._2*2)
res0: Array[Double] = Array(2.4)

A: I think there are two problems:

*

*You're using foreach, which returns Unit, where you want to use map, which returns an Array[B].

*You're trying to update an immutable value, when you want to return a new, updated value. This is the difference between _._2 = _._2 * factor and _._2 * factor.
To filter the values not meeting the threshold:
arr1.zip(arr2).filter(_._1 > threshold).map(_._2 * factor)

To keep all values, but only multiply the ones meeting the threshold:
arr1.zip(arr2).map {
  case (x, y) if x > threshold => y * factor
  case (_, y)                  => y
}

A: You can do it with this,
arr3.map(x => if (x._1 > threshold) (x._1, x._2 * factor) else x)

A: How about this?
arr3.map { case(x1, x2) =>  // extract first and second value
  if (x1 > treshold) (x1, x2 * factor)   // if first value is greater than threshold, 'change' x2
  else (x1, x2)  // otherwise leave it as it is
}.toMap

Scala is generally functional, which means you do not change values, but create new values, for example you do not write x._2 = …, since tuple is immutable (you can't change it), but create a new tuple.

A: This will do what you need.
arr3.map(x => if(x._1 > treshold) (x._1, x._2 * factor) else x)

The key here is that you can return tuple from the map lambda expression by putting two variable into (..).
Edit: You want to change every element of an array without creating a new array. Then you need to do the next.
arr3.indices.foreach(x => if(arr3(x)._1 > treshold) (arr3(x)._1, arr3(x)._2 * factor) else x)


text:
Q: Real-time data standardization / normalization with Spark structured streaming Standardizing / normalizing data is an essential, if not a crucial, point when it comes to implementing machine learning algorithms. Doing so on a real time manner using Spark structured streaming has been a problem I've been trying to tackle for the past couple of weeks.
Using the StandardScaler estimator ((value(i)-mean)  /standard deviation) on historical data proved to be great, and in my use case it is the best, to get reasonable clustering results, but I'm not sure how to fit StandardScaler model with real-time data. Structured streaming does not allow it. Any advice would be highly appreciated!
In other words, how to fit models in Spark structured streaming?

A: I got an answer for this. It's not possible at the moment to do real time machine learning with Spark structured streaming, inluding normalization; however, for some algorithms making real time predictions is possible if an offline model was built/fitted.
Check:
JIRA - Add support for Structured Streaming to the ML Pipeline API
Google DOC - Machine Learning on Structured Streaming


text:
Q: Load function after whole page has been loaded I currently have a webpage made from html where the body is loaded externally using jquery load function. So inside the external code, there's a div with id="main", how do I load another external code into div with id="main" after the main body code and the whole page is loaded? Please help.
This is the code for the whole body of the page
$(document).ready(function(){
            $("#body").load("body.html");
        });

Inside the body, there's a div like this

So I have another external html where it should go into the "main" div with name main.html
i have tried putting this in the head and after the div but it doesn't work
$(document).ready(function(){
            $("#main").load("main.html");
        });

If you guys don't mind, visit this link and look at the source code and help out, sorry
http://proxcent.com/test.html

A: you can use onLoad method. See that:
On DOM ready (not completely resources loaded, only DOM tree)
$(document).ready();

On page totally loaded (images included)
$(window).on('load', function() { ..... });

A: You can check if the div with id as "main" exists on the page with $('#main').length > 0 and then load whatever external code that you have with $('#main').load()
$(window).on('load', function(){
        if($('#main').length > 0){
           $('#main').load('/yourExternalCode.html');
         }
    });

A: The jQuery load method takes a callback function as a second (or third if you want to send through data as second argument) argument, which is executed after post-processing and HTML insertion has been performed.
$("body").load("body.html",function(){
    // load more external content
    $(this).find("#main").load("main.html");
});


text:
Q: Lock The Dock On Multiple Screen Setup I like all the multiple screen features in Mavericks except one.
I HATE the hit cursor to the bottom of the screen to move the dock. I've searched hi an low for a way to stick the dock to one spot. I'd even buy a product.
There must be a way to say "Dock stick to Screen 2" or 1 or whatever. I have already read that you can go back to the old behavior of multiple screens, but then I loose the other features.


text:
Q: Recursively rendering component How do you render recursive lists using React? lets say you have a list data like
{
    "list": [
        "Parent",
        "subList": [
            {
                "First Child",
                "subList": [
                    {
                        "Grand Child 1-1"
                    },
                    {
                        "Grand Child 1-2"
                    }
                ]
            },
            {
                "Second Child",
                "subList": [
                    {
                        "Grand Child 2-1",
                        "sublist": []
                    }
                ]
            }
        ]
    ]
}

How would you write a recursive map function to render indented sublists? Below is my attempt but I would like to make it recursively.
renderCheckboxRows = (list) => {
    list.map((filter, index) => {

        let content = <FilterRow key={index} {...filter} />;
        let subListContent = [];

        if (filter.subList && filter.subList.length > 0) {
            filter.subList.map((filter, index) => {
                subListContent.push(<FilterRow key={index} {...filter} />);
            });
        }
        return (content + subListContent);
    });

}

A: I usually do it by introducing a dedicated component for that purpose.
Lets name it Node. Its usage will be as follows:
<Node caption={root.caption} children={root.children}/>

Then inside Node.render:
render()
{
    var children = [];

    children = this.props.children.map((c) =>
    {
        return <Node caption={c.caption} children={c.children}>
    });

    return (

{this.props.caption}

            {children}

    );
}

This is just a draft example and instead of divs you will have your own components, but it illustrates the idea.


text:
Q: Как вытащить из данной строки значение? Я делаю парсер дискорда, и я остановился на том что в цикле получаю такую строку:
[<Attachment id=794604792886198302 filename='25_3.jpg' url='https://cdn.discordapp.com/attachments/794541373440524328/794604792886198302/25_3.jpg'>]

Так вот: Как мне получить значение url, из этого списка? Может каждый раз проходиться по строке, и искать префикс url=', и возвращать на выходе значение после префикса, с концом '? Тогда как это сделать?
Код парсера:
@client.event
async def on_message(message):
    print(message.channel.id) # Debug
    message_history = await message.channel.history(limit=10000).flatten()
    for message_ in message_history:
        if message_.attachments != []:
            string = message_.attachments
            print(string)

A: Я сам решил проблему. Пишу ибо может кому-то понадобится. Поскольку эта "строка" была списком, надо было написать вместо
string = message_.attachments

Вот это:
string = message_.attachments[0].url


text:
Q: Is there any way to send message from SendEndpoint to exchange with argument alternate-exchange? I'm trying to use ISendEnpoint.Send method to send message to RabbitMq exchange that have argument alternate-exchange and I didn't find any way to set value for this argument.
If I don't specify this argument, I catch this exception:

"RabbitMQ.Client.Exceptions.OperationInterruptedException: The AMQP
  operation was interrupted: AMQP close-reason, initiated by Peer,
  code=406, text="PRECONDITION_FAILED - inequivalent arg
  'alternate-exchange' for exchange 'target_queue' in vhost '/':
  received none but current is the value 'norouted'".

How to specify this argument?

A: You can modify the publish topology of a message, such that the destination exchange specifies an alternate exchange and queue, so that published messages without a valid destination are delivered to the alternate.
https://github.com/MassTransit/MassTransit/blob/develop/tests/MassTransit.RabbitMqTransport.Tests/AlternateExchange_Specs.cs


text:
Q: Spring Batch : Difference between spring batch admin and command line when jobs are run in parallel When I run spring batch jobs in parallel using 'Split flow', I found that there are differences between spring batch admin and command line.
I have a job flow as the following:
Job1 -> Job2 -> Job3
     -> Job4

When I run these jobs from spring batch admin, 'Job1' can launch both 'Job2' and 'Job4', and then 'Job2' can launch 'Job3'.
Moreover, 'Job1' is completed after the 'step1' is finished. And then 'Job2' and 'Job4' continue their processes in parallel.
'Job1' does not wait for 'Job2' and 'Job4' to be finished.
app-context.xml and Job configuration for spring batch admin are as follows:
Job1.xml
<import resource="classpath*:META-INF/spring/batch/dependencies/parallel2.xml"/>
<import resource="classpath*:META-INF/spring/batch/dependencies/parallel3.xml"/>

<bean id="taskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor"/>

<bean id="simpleJobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
    <property name="jobRepository" ref="jobRepository" />
    <property name="taskExecutor" ref="taskExecutor" />
</bean>

<bean id="job1.stp01" class="com.jobs.Job1Step1" />

<batch:job id="Job1" restartable="true" >
    <batch:step id="step1" next="split">
        <batch:tasklet ref="job1.stp01" />
    </batch:step>

    <batch:split id="split" next="step3">
        <batch:flow>
            <batch:step id="flow1" >
                <batch:job ref="Job2" job-launcher="simpleJobLauncher"/>
            </batch:step>
        </batch:flow>

        <batch:flow>
            <batch:step id="flow2">
                <batch:job ref="Job3" job-launcher="simpleJobLauncher"/>
            </batch:step>
        </batch:flow>
    </batch:split>
</batch:job>

app-context.xml
<batch:job-repository id="jobRepository" />

<task:executor id="jobLauncherTaskExecutor" pool-size="10" rejection-policy="ABORT"/>

<bean id="jobRegistry" class="org.springframework.batch.core.configuration.support.MapJobRegistry" />

<bean class="org.springframework.batch.core.configuration.support.JobRegistryBeanPostProcessor">
    <property name="jobRegistry" ref="jobRegistry"/>
</bean>

But in command line, there are some differences from spring batch admin.
app-context.xml and job configuration for command line are as follows:
Job1.xml
<import resource="app-context.xml" />
<import resource="parallel2.xml"/>
<import resource="parallel3.xml"/>

<bean id="job1.stp01" class="com.jobs.Job1Step1" />

<batch:job id="Job1" restartable="true" >
    <batch:step id="step1" next="split">
        <batch:tasklet ref="job1.stp01" />
    </batch:step>

    <batch:split id="split" task-executor="jobLauncherTaskExecutor" next="step3">
        <batch:flow>
            <batch:step id="flow1" >
                <batch:job ref="Job2" job-launcher="simpleJobLauncher"/>
            </batch:step>
        </batch:flow>

        <batch:flow>
            <batch:step id="flow2">
                <batch:job ref="Job3" job-launcher="simpleJobLauncher"/>
            </batch:step>
        </batch:flow>
    </batch:split>
</batch:job>

app-context.xml
<bean id="springBatchDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    .......
</bean>

<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager" />

<bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
    <property name="databaseType" value="POSTGRES" />
    <property name="dataSource" ref="springBatchDataSource" />
    <property name="transactionManager" ref="transactionManager" />
</bean>

<bean id="simpleJobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
    <property name="jobRepository" ref="jobRepository" />
</bean>

<bean id="jobLauncherTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" />

When I run jobs form command line, 'Job1' can launch both 'Job2' and 'Job4', and then 'Job2' can launch 'Job3'.
The problem is
Although 'step1' is finished, the status of 'Job1' is still 'Unknown'. The status changes into 'Completed' only after 'Job2' and 'Job4' are finished.
'Job1' is waiting for 'Job2' and 'Job4' to be finished.
But in spring batch admin, 'Job1' does not wait for 'Job2' and 'Job4'. The status of 'Job1' changes into 'Completed' as soon as 'step1' is finished.
I would not like 'Job1' to wait for 'Job2' and 'Job4' in command line.
Is there a way to do so???
Ps. I'm sorry because of long question and thanks for help.

A: The correct behavior for this scenario is that in both cases, Job1 shouldn't be marked as COMPLETED until Job2 and Job4 are complete.  If that isn't happening in one of the scenarios, this is a bug and should be logged in Jira (https://jira.spring.io).  Are you sure that the other jobs are not complete in Spring Batch Admin when Job1 flags as COMPLETE?


text:
Q: How to make a pulse alternator in minecraft 1.12.2? I want to make a pulse alternator, so when a redstone pulse enters, output A on one side gives out a pulse, and when the second pulse enters, output B on the other side gives a pulse, and when the third pulse enters output A fires again (and so on). But I don't want the outputs to be sustained outputs (like a lever), just 2-4 redstone tick pulses. If anyone knows how to make something that does this, please tell me and screenshots would be appreciated.

A: A ring: 2 hoppers, 2 droppers, alternating, facing each into another in a circular fashion. Input signal activates the two droppers. Pairs: Comparator + repeater feed outputs A and B out of the hoppers. There's one item in this ring.

(the image shows the base level of the device. You will have connect the blocks marked 'I' drawing redstone between them above or below.)
This will activate the output A or B for duration it takes the hopper to eject the item into the dropper next to it. Next pulse on input I will inject the item into the other hopper. If instead of a ring you use a looping 'pipeline' of alternating hoppers and droppers, you can have as many outputs as you want.


text:
Q: Error (10536): VHDL Loop Statement error at InstructionMemory.vhd(31): loop must terminate within 10,000 iterations Can someone help me solve this problem?
Its my code below:
library ieee;
library std;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;
use std.textio.all;

--
entity InstructionMemory is
    port (
        clk, rst : in std_logic;
        address : in std_logic_vector(31 downto 0);
        instr_out : out std_logic_vector(31 downto 0)
    );
end entity;
architecture aim of InstructionMemory is

    type instr_mem is array(0 to 20) of std_logic_vector(31 downto 0);
    signal imem : instr_mem := (others => (others => '0'));

begin
    process (clk)
        file file_pointer : text;
        variable line_content : string (1 to 32);
        variable line_num : line;
        variable i : integer := 0;
        variable j : integer := 0;
        variable char : character := '0';
    begin

        file_open(file_pointer, "C:/Users/MM/Desktop/PF3/MIPS-Monocycle-32-bits-master/Testcases/instructions.txt", READ_MODE);
        while not endfile (file_pointer) loop -- this is line 31
            readline(file_pointer, line_num);
            READ(line_num, line_content);

            for j in 1 to 32 loop
                char := line_content(j);
                if (char = '0') then
                    imem(i)(32 - j) <= '0';
                else
                    imem(i)(32 - j) <= '1';
                end if;
            end loop;
            i := i + 1;
        end loop;
        file_close(file_pointer); -- Close the file
        wait;
    end process;

    process (clk, rst)
    begin
        if rst = '1' then
            instr_out <= "00000000000000000000000000000000";
        elsif clk'EVENT and clk = '0' then

                assert (( (to_integer(unsigned(address)) mod 4194304)/4) < instr_mem'LENGTH)
                report  "Simulation has ended"
                severity ERROR;
            instr_out <= imem((to_integer(unsigned(address)) mod 4194304)/4);
        end if;
    end process;
end architecture;

this is line that apear the erro
    while not endfile (file_pointer) loop -- this is line 31

this is the size of intructions, 22 lines.
00000000111100000000100010010011
00000001010000000000100100010011
00000000101000000000100110010011
00000000010100000000101000010011
00000000001000000000101010010011
00010000000000000000111010010111
11111110110011101000111010010011
00000000000010101010111000110011
00000010000011100001110001100011
00000000010010101010111000010011
00000010000011100000100001100011
00000000001011100001001100010011
00000001110100110000001100110011
00000000000000110010001010000011
00000000000000101000000001100111
00000001010010011000010000110011
00000001100000000000000001101111
00000001001001001000010000110011
00000001000000000000000001101111
01000001001001001000010000110011
00000000100000000000000001101111
01000001010010011000010000110011

A: It looks like you are trying to synthesize.  File access is not synthesizable.  "Compilation" in Quartus (and Vivado and similar tools) tries to convert the RTL, such as your VHDL, into hardware resources.
What you have might be applicable to simulation, but it is not appropriate for synthesis.


text:
Q: Is this a good practice for EF Database First? Me and my colleague had recently a discussion on good practices in EF.
So i show one of mine.
He said it is a little bit muddler.
My practice consist in modify the autogenerated class in a specific way.
This is my starting model:
namespace PCServer.Data
{
    using System;
    using System.Collections.Generic;

    public partial class Post: IEntity
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Message { get; set; }
        public DateTime Date { get; set; }

        public virtual Post ParentPost { get; set; }
        public virtual AspNetUser Author { get; set; }
    }
}

I like to extend it in this way:
public partial class Post
    {
        //This class "do" something, like adding a post or deleting a post
        public static class Do
        {
            public static void AddPost(ref ApplicationDbContext context, string postMessage)
            {
                //Create a post
                Post p = new Post();
                p.Title = "This is an example!";
                p.message = postMessage;
                p.Date = DateTime.UtcNow;

                //Adding to context
                BaseService.Add(post, out context);
            }

            public static void DeletePost(ref ApplicationDbContext context, int postId)
            {
                PostRepository postRepo = new PostRepository(context);

                postRepo.GetById(postId);

                //Removing from context
                BaseService.Remove(post, out context);
            }
        }

        //This class "Get" something, like all posts
        public static class Get
        {
            public static void GetPosts()
            {
                using(ApplicationDbContext context = new ApplicationDbContext())
                {
                    PostRepository postRepo = new PostRepository(context);
                    return postRepo.GetAllPosts();
                }
            }
        }

        //This class "Set" something, like title of the post or the post itself maybe
        public static class Set
        {
            public static void Title(ref ApplicationDbContext context, int postId, string title)
            {
                PostRepository postRepo = new PostRepository(context);
                Post post = postRepo.GetById(postId);
                post.Title = title;

                BaseService.Update(post, out context);
            }

            public static void ChangePost(ref ApplicationDbContext context, int postId, Post post)
            {
                PostRepository postRepo = new PostRepository(context);
                Post dbPost = postRepo.GetById(postId);
                dbPost = post;

                BaseService.Update(dbPost, out context);
            }
        }
    }

So, when i must to do something with an Entity, i can (for example only):
ApplicationDbContext c = new ApplicationDbContext();

Post.Do.AddPost(ref c,"Hi!");
IEnumerable<Post> posts = Post.Get.GetPosts();

Post.Set.Title(ref c,100,"Changing title!");

And after all:
await BaseService.CommitAsync<Post>(c);

SO.
What do you think? Would you use it? Why?
Thank you and sorry for long post.

A: One of the advantages of any design pattern is that of comprehensibility to others. Me: How are you designing your Web Services? You: We're using the repository pattern. Me: Ok, I understand that.
Whilst this is by no means a comprehensive answer, it goes a long way to understanding where to look for things and where things need changing when you're asked to make an update.
What you have is a design pattern that you like to use, but you should ask yourself whether it is easily comprehensible by others.
For example, you have a class named "Do". As a name, this gives no indication whatsoever as to what the class is for. Your comment indicates that it "does something", but is anyone else going to intuitively understand what goes in there? Adding and Deleting are obviously "doing" things, but why isn't Getting or Setting? This may make sense to you, but others may see things differently.
I'm assuming you are working in a team. If your team is going to adopt this as a pattern, then everyone needs to agree to use it, and to do that, everyone needs to understand intuitively how it works, and more importantly, how to extend it. If they don't, then you will start getting methods in your Do class that you don't think should be there, and you will be putting methods in other classes that other people can't find because they don't have the same mental model as you as to how this works. It does not take long for things to get messy if everyone is doing things differently.
With respect to extending Entities with partial classes, I would avoid this myself. Entities have a clearly defined responsibility, and by adding code to them, you are assigning extra responsibilities (c.f. the Single Responsibility Principle). Admittedly, your extra code is all separated into separate static sub classes, but if that is the case, why not simply make them classes in their own right and move them somewhere else in your application?
In terms of the classes themselves, static classes with static methods are going to make unit testing extremely difficult, and there's no reason why they should be static, so I would definitely change that. Of course now you have to instantiate them to use them, which presents more of an argument for moving them somewhere else.
On a more technical point, what is BaseService doing? You are creating a context, passing it by reference (why?) to AddPost (for example), and then using it as an out parameter in BaseService.Add. I'm not sure what's going on here, but it looks wrong.
As a pattern, I would say it needs work, but simply by attempting to have a pattern, you are heading in the right direction.
You haven't mentioned what your colleague thinks is 'good practice' but I suggest that you continue discussing this until you agree. Decide what you are trying to achieve, and what pattern best fits that. Maybe there is an established pattern that fits, but try not to overengineer it. My experience tells me that the more I try to abstract away from Entity Framework, the harder it can be to use some of it's more powerful features.


text:
Q: Проблема с PJAX в Yii2 Есть activeform форма, её я заключил между Pjax, и все вроде работает без перезагрузки страницы, но хлебные крошки при переходе по ссылкам не меняются. Методом тыка я так понял что причина в том что инициализация хлебных крошек происходит в шаблоне, и соответственно вот этот кусок кода
                    <?= Breadcrumbs::widget([
                    'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
                    'homeLink'=>isset($this->params['home']) ? $this->params['home'] : ['label'=>'Главная','url'=>'/admin']
                ]) ?>

не находится между Pjax и соответственно не обновляется...
попытался в js сделать reload блока breadcrumbs, но тогда перезагружается вся страница.. Есть какие то предложения обновлять хлебные крошки через Pjax?

A: Скорее всего вам придется делать это обычным ajax. Логика может такая: при обновлении формы следом запускаете ajax запрос на сервер. Сервер пусть обновит вам крошки. При успешном ответе ajax обновляете ваши крошки ответом с сервера. Для этого сделайте отдельный метод в контроллере, который будет принимать ajax запрос и отдельный view с крошками. Его контроллер будет рендерить и это и будет ответом сервера. Остается только вам положит его в нужный контейнер. Для этого можете обернуть крошки в див и назначить ему понятный id.

A: можно запустить скрипт перезагрузки другого Pjax при срабатывании первого
$this->registerJs(
    '$("document").ready(function(){
            $("#new_img").on("pjax:success", function() {
           твой код
});
 });'
);


text:
Q: Nullable integer values from reader how we read integer null values from Sql Data Reader
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
    mb.Id = (int)reader["Id"];
    mb.Mem_NA = (string)reader["Mem_NA"];
    mb.Mem_ResAdd4 = reader["Mem_ResAdd4"] == System.DBNull.Value ? null : (string)reader["Mem_ResAdd4"];
    //
   mb.Mem_ResPin = reader["Mem_ResPin"] as  int? ?? default(int);
  // shows the error "Object cannot be cast from DBNull to other types."
 }

mb.Mem_ResPin cant read from reader
 CREATE TABLE [dbo].[Mem_Basic] (
[Id]          INT           IDENTITY (1, 1) NOT NULL,
[Mem_NA]      VARCHAR (100) NOT NULL,
[Mem_ResAdd4] VARCHAR (100) NULL,
[Mem_ResPin]  INT           NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

A: I use a generic extension method for all DB casts:
public static T? DbCast<T>(this object dbValue)
        where T : struct
    {
        if (dbValue == null)
        {
            return null;
        }
        if (dbValue is System.DBNull)
        {
            return null;
        }
        T? value = dbValue as T?;
        if (value != null)
        {
            return value;
        }
        var conv = dbValue as IConvertible;
        if (conv != null)
        {
            value = (T)conv.ToType(typeof(T), CultureInfo.InvariantCulture);
        }
        return value;
    }

It tries to treat every situation we encountered so far. Adjust conditions as needed for you.
Usage:
int? value = reader["Mem_ResAdd4"].DbCast<int>()

A: Write a simple wrapper e.g. as an extension method and check for IsDBNull inside:
public static int SafeGetInt(this SqlDataReader reader, string colName)
{
    var colIndex = reader.GetOrdinal(colName);
    return !reader.IsDBNull(colIndex) ? reader.GetInt32(colIndex) : default(int);
}

usage:
var result = reader.SafeGetInt(colName);

A: You can use  SqlDataReader.GetSqlInt32 to handle Nullable<int>:
SqlInt32 resPin = reader.GetSqlInt32(reader.GetOrdinal("Mem_ResPin"));
mb.Mem_ResPin = resPin.IsNull ? (int?) null : resPin.Value;

A: Maybe try this extention:
public static class Helper
{
    public static T GetSafe<T>(this SqlDataReader reader, string name)
    {
        var value = reader[name];
        return value == DBNull.Value ? default(T) : (T) value;
    }
}

and use like this:
        if (reader.Read())
        {
            Mb mb = new Mb();
            mb.Id = reader.GetSafe<int>("Id");
            mb.Mem_NA = reader.GetSafe<string>("Mem_NA");
            mb.Mem_ResAdd4 = reader.GetSafe<string>("Mem_ResAdd4");

            mb.Mem_ResPin = reader.GetSafe<int>("ResPin");
        }

A: There are a few approaches here. Unfortunately, DBNull makes this vexing - the reader[name] API returns an object that could be your value, or that could be DBNull.Value - so you have to check for that (is) and handle it. The other approach is to use the reader.IsDBNull(ordinal) API, but as you will note : that needs an ordinal (column index) rather than a name. In either case, you can add things like utility methods to help:
static object Read(IDataReader reader, string name)
{
    var val = reader[name];
    return val is DBNull ? (object)null : val;
}

then (for example):
mb.Mem_ResPin = (int?)Read(reader, "Mem_ResPin")

However, again: tools like "dapper" might make this a lot easier for you; a single Query<T>(tsql, args).SingleOrDefault() would deal with all of this, including nulls, Nullable<T>, and a range of other scenarios.

A: public static class SqlDataReaderExtensions
{
    public static T Value<T>(this SqlDataReader reader, string name, T defaultValue = default)
    {
        var val = reader[name];

        if (val == DBNull.Value)
            return defaultValue;

        return (T)val;
    }
}

A: Just convert it, like you do in previous row
mb.Mem_ResAdd4 = reader["Mem_ResAdd4"] == System.DBNull.Value ? null : (string)reader["Mem_ResAdd4"];
//
    mb.Mem_ResPin = reader["Mem_ResPin"]== System.DBNull.Value ? default(int):(int)reader["Mem_ResPin"]

A: Compare is against DBNull.
var resPin = reader["Mem_ResPin"];
if(!Convert.IsDBNull(resPin))
  mb.Mem_ResPin = resPin as int?;
else
  mb.Mem_ResPin = new Nullable<int>();


text:
Q: How to redirect everything via Web.config or C# to https://www. version of the site? I have an ASP.NET website hosted on GoDaddy. I need to redirect (301) every request to https://www.example.com/whatever
So for example:

*

*http://example.com will be redirected to https://www.example.com

*http://www.example.com will be redirected to https://www.example.com

*http://example.com/section/page will be redirected to https://www.example.com/section/page
This is a piece of cake on Linux or cPanel hostings. But I don't know how to do this on GoDaddy (I asked support, but they don't seem to know nothing...). I guess it's easy to do with IIS, but GoDaddy doesn't give you IIS access.
So is there a way to do it via Web.config or C#? Preferably web.config

A: Check out this article of mine, which provides a number of different options for avoiding duplicate URLs in your ASP.NET site: Techniques for Preventing Duplicate URLs in Your Website. I've summarized the various techniques below, but see the article for a more in-depth treatment, as well as for a sample ASP.NET website demo.
Issuing Permanent Redirects from ASP.NET
You can check the incoming URL for every request in your Global.asax file's Application_BeginRequest event handler. If the URL is missing the leading www. you can append it and do a permanent redirect to the new URL.
protected void Application_BeginRequest(object sender, EventArgs e)
{
   if (Request.Url.Authority.StartsWith("www"))
      return;

   var url = string.Format("{0}://www.{1}{2}",
               Request.Url.Scheme,
               Request.Url.Authority,
               Request.Url.PathAndQuery);

   Response.RedirectPermanent(url, true);
}

Rewriting URLs Into Canonical Form Using IIS 7's URL Rewrite Module
If your website is hosted by IIS7 and Microsoft's URL Rewrite Module is installed, then you can add rewriting rules in your Web.config file. I don't have any sites hosted with GoDaddy, so I have no idea if they use IIS7 (I imagine they do) or if they have the URL Rewrite Module installed. Check with support.
Presuming these prerequisites are met, you would use the following configuration:
<configuration>
   ...

   <system.webServer>
      <rewrite>
         <rules>
            <rule name="Canonical Host Name" stopProcessing="true">
               <match url="(.*)" />

               <conditions>
                  <add input="{HTTP_HOST}" pattern="^yoursite\.com$" />
               </conditions>

               <action type="Redirect" url="http://www.yoursite.com/{R:1}" redirectType="Permanent" />
            </rule>
         </rules>
      </rewrite>
   </system.webServer>
</configuration>

Rewriting via a Third-Party Application
Many web hosting companies have a third-party URL rewriting application installed, such as ISAPI_Rewrite. I don't know if GoDaddy has this, you'd need to check with support. But this may be another option.
Telling Search Engine Spiders Your Canonical Form In Markup
Rather than worrying about redirecting users to the www. version, you could just let users arrive at your site however they want to, but add markup to your page to tell the search engines the canonical form of your URLs.
To specify the canonical URL simply add a <link> element in the <head> portion of the web page. The way this works as is follows - add the following markup to the <head> sections of those pages in your website that you want the search engines to consider all the same URL:
<link rel="canonical" href="canonical_url" />

If you do a View/Source on Stackoverflow.com you'll see this <link> tag in place. This is a great way to ensure that duplicate URLs in your site - e.g., www.yoursite.com/foo.aspx and yoursite.com/foo.aspx are treated as the same entry in the search engine's index.
Happy Programming!

A: Thanks Scott for the excellent answer!  This was very helpful.
Here is a mod to the Application_BeginRequest() code that 1) uses ordinal string comparisons for speed, 2) accommodates localhost and 3) highlights an asymmetric side-effect.
protected void Application_BeginRequest(object sender, EventArgs e)
{
    /**
     *  Note:
     *    Since Url.Authority always returns an all lowercase string, we can use
     *    StringComparison.Ordinal (instead of OrdinalIgnoreCase) for www and
     *    localhost checks.
     *
     *  Ordinal rationale:
     *    "Use comparisons with StringComparison.Ordinal or
     *    StringComparison.OrdinalIgnoreCase for better performance"
     *    see http://msdn.microsoft.com/en-us/library/dd465121.aspx#choosing_a_stringcomparison_member_for_your_method_call
     */
    if (Request.Url.Authority.StartsWith("www", StringComparison.Ordinal))
        return;

    /**
     * Avoid redirection on localhost.
     */
    if (Request.Url.Authority.StartsWith("localhost", StringComparison.Ordinal))
        return;

    /**
     * Because Uri.Authority is always lowercase, this code has the side-effect of
     * enforcing a lowercase authority (e.g., http://NoisyKeys.com/About is
     * converted to http://www.noisykeys.com/About).  This is asymmetric with
     * previous conditionals.  To attain symmetry, we probably want to use
     * Request.Url.OriginalString instead of Request.Url.Authority.
     */
    var url = string.Format("{0}://www.{1}{2}",
        Request.Url.Scheme,
        Request.Url.Authority,
        Request.Url.PathAndQuery);

    Response.RedirectPermanent(url, true);
}


text:
Q: Is it correct that a sphere of water the size of Venus's orbit would instantly be a black hole? Let's say I have a genie and wish for a sphere of water at earth density the size of Venus' orbit - would it be instantly indistinguishable from a supermassive black hole due to the schwarzchild radius exceeding the volume at normal density?
Would it also outweigh Sagittarius A* at 150 million Suns?
I've taken the Schwarzchild radius formula, the density formula, and solved for r with the density of 1000 kg/m^3
Apologies, I don't know how to do formula in stack overflow.


text:
Q: Python minidom and UTF-8 encoded XML with hash references I am experiencing some difficulty in my home project where I need to parse a SOAP request. The SOAP is generated with gSOAP and involves string parameters with special characters like the danish letters "æøå".
gSOAP builds SOAP requests with UTF-8 encoding by default, but instead of sending the special chatacters in raw format (ie. bytes C3A6 for the special character "æ") it sends what I think is called character hash references (ie. æ).
I don't completely understand why gSOAP does it this way as I can see that it has marked the incomming payload as being UTF-8 encoded anyway (Content-Type: text/xml; charset=utf-8), but this is besides the question (I think).
Anyway I guess gSOAP probably is obeying transport rules, or what?
When I parse the request from gSOAP in python with xml.dom.minidom.parseString() I get element values as unicode objects which is fine, but the character hash references are not decoded as UTF-8 character codes. It unescapes the character hash references, but does not decode the string afterwards. In the end I have a unicode string object with UTF-8 encoding:
So if the string "æble" is contained in the XML, it comes like this in the request:
"æble"

After parsing the XML the unicode string in the DOM Text Node's data member looks like this:
u'\xc3\xa6ble'

I would expect it to look like this:
u'\xe6ble'

What am I doing wrong? Should I unescape the SOAP XML before parsing it, or is it somewhere else I should be looking for the solution, maybe gSOAP?
Thanks in advance.
Best regards Jakob Simon-Gaarde

A: æble is actually æble.
To get the expected Unicode string u'\xe6ble' after parsing, the string in the request should be æble.

A: Some more detail about my problem. The project I am creating uses wsgi. The SOAP request is extracted using environ['wsgi.input'].read(). It always seems to return a raw string. I created a function that unescapes the character hashes:
def unescape_hash_char(req):
  pat = re.compile('&#(\d+);',re.M)
  parts = pat.split(req)
  a=0
  ret = ''
  for p in parts:
    if a%2:
      n = chr(int(p))
    else:
      n = p
    ret += n
    a+=1
  return ret

After doing this I parse the XML and I get the expected reslut.
Still I would like to know what you think, and if it is a good solution. Also I wrote the function because I couldn't find a function to do the job in the standard python modules, does such a function exist?
Best regards
Jakob Simon-Gaarde

A: Here's how to unescape such stuff: http://effbot.org/zone/re-sub.htm#unescape-html
However the primary problem is what you and/or this "gSOAP" (URL, please) are doing ...
Your example character is LATIN SMALL LIGATURE AE (U+00E6). As you say, encoded in UTF-8, this is \xc3\xa6. 0xc3 == 195 and 0xa6 == 166. 0xe6 == 230. Escaping your character should produce 'æ', not 'æ'.
However it appears that it is encoding to UTF-8 first and then doing the escaping.
What you need to do is to show us in fine detail the code that you are using together with diagnostic prints (using the repr() function so that we can see the type and unambiguously-represented contents) of each str and unicode object involved in the process. Also provide the docs for the gSOAP API(s) that you are using.
On the receiving end, please show us the repr() of the raw XML that you receive.
Edit in response to this comment on another answer: """The problem is that minidom.parseString() does not seem to unescape the character hash representation before it decodes to unicode."""
It (and any other XML parser) {does not, cannot in generality, and must not} unescape numerical character references or predefined character entities BEFORE decoding.
(1) unescaping "<" to "<" would blow up
(2) what would you unescape "&#256" to? "\xc4\x80"?
(3) how could it unescape at all if the encoding was UTF-16xx?

A: Note that
In [5]: 'æ'.encode('utf-8')
Out[5]: '\xc3\xa6'

So we have is the unicode object u'\xc3\xa6' and we really want the string object'\xc3\xa6'. This transformation can be performed with the raw-unicode-escape codec:
In [1]: text=u'\xc3\xa6'
In [2]: text.encode('raw-unicode-escape')
Out[2]: '\xc3\xa6ble'

In [3]: text.encode('raw-unicode-escape').decode('utf-8')
Out[3]: u'\xe6'

In [4]: print(text.encode('raw-unicode-escape').decode('utf-8'))
æ

A: Unless someone can tell me that gSOAP is not producing valid encoded SOAP XML: (see http://pastebin.com/raw.php?i=9NS7vCMB or the codeblock below) I see no other solution than to unescape character hash references before parsing the XML.
Of course as John Machin has pointed out, I cannot unescape XML control characters like "<" and ">".
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns1="urn:ShopService"><SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><ns1:createCompany><company-code>DK-123</company-code><name>Ã¦ble</name></ns1:createCompany></SOAP-ENV:Body></SOAP-ENV:Envelope>

/ Jakob


text:
Q: Finding linking path between two points in array php I would like to find possible options from an array that connects two points.
Eg.
$startPoint = 1;
$endPoint = 5;
$points = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 5] [4, 3], [1, 4], [1, 3], [1, 5], [1, 6]];
function should return
$possibleOptions = [[1, 5], [[1, 4], [4, 5]], [[1, 6], [6, 5]], [[1, 2], [2, 3], [3, 4], [4, 5]]]
Would be nice to add a possible option limit eg. if maximum of 3 combinations are allowed, then the function would return
$possibleOptions = [[1, 5], [[1, 4], [4, 5], [[1, 6], [6, 5]]
as [[[1, 2], [2, 3], [3, 4], [4, 5]]] is a total of 4 combinations.
I have tried looping through the array and finding a direct match first. If no direct match is found i loop through points again and create a new array with all the points that have start point as first value. I then check if the new array has an element where the last value is the endpoint. However, i feel like it is repetitive code and could be optimized as I have to repeat the code for the the max amount of combinations. Just not sure how...
Here is an example of my code:
$results = [];

        $startPoint = 1;
        $endPoint = 3;

        $points = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [4, 3], [1, 4], [1, 3]];

        foreach ($points as $point) {
            if ($point[0] == $startPoint && $point[1] == $endPoint) {
                $results[] = $point;
            }
        }

        $newStartPoints = [];

        foreach ($points as $point) {
            if ($point[0] == $startPoint) {
                $newStartPoints[] = $point;
            }
        }

        foreach ($points as $point) {

            foreach ($newStartPoints as $startPoint) {
                if ($point[0] == $startPoint[1] && $point[1] == $endPoint) {
                    $results[] = [$startPoint, $point];
                }
            }
        }

        print_r($results);

A: Here is a solution:
$startPoint = 1;
$endPoint = 5;
$max_combinations = 3;
$points = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [4, 3], [1, 4], [1, 3], [1, 5]];

$result = [];

for ($i = $startPoint; $i <= $endPoint; $i++) {
    $sub_result = [];

    if (in_array([$startPoint, $i], $points)) {
        $sub_result[] = [$startPoint, $i];

        for ($j = $i; $j <= $endPoint; $j++) {
            if (in_array([$j, $j + 1], $points) && $j + 1 <= $endPoint) {
                $sub_result[] = [$j, $j + 1];
            }
        }
    }

    if (count($sub_result) != 0 && (count($sub_result) <= $max_combinations || $max_combinations === -1)) {
        $result[] = $sub_result;
    }
}

sort($result);

print_r($result);

The first four variable declarations can be modified according to your needs.
Note that setting $max_combinations equal to -1 it will mean that it will match all paths rather than having a limit.
Live demo


text:
Q: Load Bitmap Image into WINApi C++ and Display I am building a GUI using WINApi C++ Unicode. My ultimate goal is not to load the .bmp image from a file because i will be passing around the GUI as a .exe file.
Is it possible to load the .bmp image into the GUI's resource and load the image from there every time I want to display on my GUI?

A: Sure. There's a resource type specially for bitmaps. Just use "Add resource" in the Visual Studio resource view. Example code on how to use it should be available in the MSDN.

A: Put this in the resource (.rc) file
IDI_NORMAL    BITMAP    "Normal.bmp"

Then this in main colde (.cpp) file
HBITMAP hBMP = (HBITMAP)LoadBitmapW(hInst, MAKEINTRESOURCEW(IDI_NORMAL)); //test bitmap

HDC hMemDC = CreateCompatibleDC(hdc);
::SelectObject(hMemDC, hBMP);
BitBlt(hdc, 0, 0, 1000, 1000, hMemDC, 0, 0, SRCCOPY);
::DeleteDC(hMemDC);

Works perfectly


text:
Q: add new SSH user account for AZURE ubuntu VM I have an azure ubuntu vm up and running (Ubuntu 18.04.1 LTS) to learn and experiment.  Thus far my NGINX / NODE.js / Socket.io experiments all worked great, but in my effort to see if there was a way to EXPORT an Azure VM and import it locally, I created a headache for myself.
I came across this resource Download a Linux VHD from Azure, and without reading close enough (in hindsight) I ran the following commands via an SSH session from my mac book pro:
ssh azureuser@<publicIpAddress>
sudo waagent -deprovision+user -force
exit

So now, needless to say, I am unable to login to the VM using ssh.  I AM still able to access the account via the Azure portal though, and Im fairly certain theres a way to re-create my user account that I can use to access the machine via SSH.
Anyone familiar with how / where in the Azure portal I would accomplish this?
Now when I try to connect via SSH as the previous user, I get "Host key verification failed".  Will I need to just scrap this VM altogether?
When I try to access the Serial Console for the VM, I just get this repeating over and over:  "WARNING cloud-init does not appear to be running"

A: Because the command you ran generalized OS, no user information.
You can try copying disk/vhd, make image of copy disk/vhd and try new deployment using image.
Hope this helps.


text:
Q: Let $A \in \mathbb{R}^{5 \times 5}$, then $A$ has...
a) an eigenvalue which is purely imaginary.
b) at least one real eigenvalue.
c) at least two eigenvalues which are not real.
d) at least 2 distinct real eigenvalues.

Is this explanation correct?
Why is (c) not possible?
Is there any generalization for a square matrix of odd order?

A: I think your explanation it's correct. For the (c) part
you can use one of these examples you have already used in (a) or (d). The key is that it's said that at least two eigenvalues are not real, which it's not an obligation.
Knowing that complex eigen values count two in the number of the dimension you can make a generalization ( I mean, for example in this exercise, if you got 2 complex eigen values, you have these numbers and their conjugates, so you have 4 eigen values, and the one left must be real)


text:
Q: java : Handling Null check through a Combination I am able to handle null check on a String with this below piece of code
 if (acct != null && !acct.isEmpty()|| !acct.equals(""))

what i mean from the above code is , if

*

*Accountid is not equal to null And

*Accountid length is greater than 0
(These two is a combination of checks )

Or

*

*Accountid  is not equal to ""

Does my code satisfy these combination i mentioned above , or do i need to add any brackets ?? to satisfy the combination ( first 1 and 2 ) i mentioned above ??
Thanks

A: Yes it does, and is always evaluated before or, i.e.  your code is the same as
if ((acct != null && !acct.isEmpty()) || !acct.equals(""))

However, logically it does not make sense to me.  Do you really need the last part? Isn't "acct.isEmpty()" the same as "acct.equals(""))" in this specific instance?

A: isEmpty() and .equals("") are exactly the same condition. And your test will throw a NullPointerException if acct is null.
I don't understand exactly which test you want to make, but this one is wrong. Think about it once again, and implement a unit test to test all the cases:

*

*null string,

*empty string,

*not empty string.

A: As per your question framed by you, it should have brackets as below
if ((acct != null && !acct.isEmpty()) || !("".equals(acct) ))

After the || operator, the code is changed which will avoid facing NullPointerException when acct is NULL.
This SO answer explains more about using "".equals().
https://stackoverflow.com/a/3321548/713414


text:
Q: Check file size while writing file and create new file I am trying to write java code to write ".dat" File. While writing, check size as well. Every 200 KB create new ".dat" file and continue to write file. Is there any way that I can do that?
When file is bigger than 200KB, create a new one like this:
1st file name: 1_filename
2nd file name: 2_filename
3rd file name: 3_filename
...
or if only one file is created (meaning it is smaller than 200KB) then:
file name: filename
I wrote the code, but it's only writing 2 files, so that's not the right way to do it.
Here is my code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class xmlfile1filebytes {

  public static void main(String[] args) throws IOException {

    File folder = new File ("07072013");
    File[] listOfFiles = folder.listFiles();

    System.out.println("There are " + listOfFiles.length + " files");
    String filesin;

    String timeStamp = new SimpleDateFormat("MM-dd-yyyy[HH.mm.ss]")
     .format(Calendar.getInstance().getTime());
     System.out.println(timeStamp);

    BufferedWriter xmlfile = null;
    BufferedWriter datfile = null;

    String outxmlfile = ("07072013\\" + timeStamp + ".xml");
    xmlfile = new BufferedWriter(new FileWriter(outxmlfile));

    String outdatfile = ("07072013\\" + timeStamp + ".dat");
    datfile = new BufferedWriter(new FileWriter(outdatfile));

    int offset = 0;
    int size = 0;

    for (int i = 0; i < listOfFiles.length; i++) {

        File f = listOfFiles[i];

       // System.out.println(i + " " + f.getAbsolutePath());
        if (f.isFile()) {

            filesin = listOfFiles[i].getName();

            if (filesin.endsWith("pdf")) {

                Path aPath = Paths.get(f.getAbsolutePath());

                System.out.println(filesin);

                byte[] actualBytes = Files.readAllBytes(aPath);
                size = actualBytes.length;

                xmlfile.append((i + 1) + ")" + " File = " + filesin + ", Offset = " + offset + ", Size = " + size + "\n");

                offset = offset + size;
                xmlfile.newLine();

                String s = new String(actualBytes);

                datfile.append(s);
                datfile.newLine();

                File datfileinfolder = new File ("07072013\\" + timeStamp + ".dat");

                long datfilesize = datfileinfolder.length();
                long datfilesizeinkb = datfilesize /1024;

                System.out.println(datfilesizeinkb);

                if (datfilesizeinkb >= 200) {
                     datfile.close();

                      BufferedWriter datfile1 = null;
                      String outdatfile1 = ("07072013\\" + "1_"+ timeStamp + ".dat");
                      datfile1 = new BufferedWriter(new FileWriter(outdatfile1));

                      String s1 = new String(actualBytes);
                      datfile1.append(s1);
                      datfile1.close();
                }

             }
        }
    }

     xmlfile.close();
  }
}

And I get an error when the file is bigger than 400 KB.
ERROR:
There are 10 files
07-09-2013[16.03.00]
1192970_eBill_20130709.pdf
96
1321470_eBill_20130709.pdf
208
1724897_eBill_20130709.pdf
Exception in thread "main" java.io.IOException: Stream closed
    at java.io.BufferedWriter.ensureOpen(Unknown Source)
    at java.io.BufferedWriter.write(Unknown Source)
    at java.io.Writer.write(Unknown Source)
    at java.io.Writer.append(Unknown Source)
    at xmlfile1filebytes.main(xmlfile1filebytes.java:65)

A: I suggest you create a separate class whose only job it is to create files (in sequence), write data to the file, keep an eye on the size, and close / open files as needed. This will make your code more organized - you will be able to see your mistakes more clearly. The class would have the following methods:
setMax(maxVal)                 - set the maximum file size (default 400k)
setRoot(rootPath)              - folder where files will be created
setName(rootName)              - "format string" used to generate file names
                                 (e.g. "myFile%03d.dat")
writeData(dataSize, dataBlock) - write data. If no file open, open it.
                                 If file too big, split it.
closeFile()                    - flush buffers, close the last file.
                                 Could be part of the destructor
currentFile()                  - returns name of current file (for debug)
currentSize()                  - returns current file size (for debug)

If you can figure out how to write this class you will solve your initial problem and have something you can re-use at the same time.
If you want to stay with (mostly) the code structure you already have, then your fix is to remove your current line 85.
         83:         String s1 = new String(actualBytes);
         84:         datfile1.append(s1);
         85:         datfile1.close();  <<<<<<<<<<< remove this line
         86:      }

Once you have closed the file, your next attempt to write to it will fail - and that's the error you are seeing.

A: Since Java 8 (or maybe Java 7), there is a better way to check file size (and take action accordingly)
if(Files.size(Paths.get(csvFile.toURI())) > 3000000 ){
// Create a new file at same path and use from next time - if current file is greater than X MB
}


text:
Q: Send invites from guild 1 to guild 2 I am developing a way to generate a single use invite from a guild, we'll call it Guild One.
If were to do !invite <@user> in Guild 2, it would (again) send them the invite that the bot generated from guild 1 and send it to the <@user> via dms from guild 2. Any help would be highly appreciated :)
If you were to use the !invite <@user> command in Guild 1 it would send them an invite that the bot has created in Guild 2. It would then send the invite link to the mentioned user.
Any help would be appreciated.

A: problem is if @user is not in guild1 (apparently not), u cannot access that user in guild2 since you dont have the user's attributes/id. You may need to enter user's id as text instead of @user like !invite {USERID}.
Also if @user is not in the bots cache (user has shown no activity in guild2 after bot was started) u need to fetch that @user into guild.members
https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=fetch
but the user in guild2 can ask for invite link to join guild1

A: A way to accomplish this would be to create a <Collection> that stores the invite link mapped by the ID of the <User> that generated it, and then access this same <Collection> through the ID of the user that issues the command !invite in "Guild 2" to get the invite link URL.


text:
Q: Get a generic's member names as strings without knowing the type parameters I'm using reflection to get some member names as strings. I'm using a method I found on Google Code (but I don't have a strong grasp of the reflection/LINQ magic it uses):
public static class MembersOf<T> {
    public static string GetName<R>(Expression<Func<T,R>> expr) {
        var node = expr.Body as MemberExpression;
        if (object.ReferenceEquals(null, node))
            throw new InvalidOperationException("Expression must be of member access");
        return node.Member.Name;
    }
}

This works great in static constructors. I just use it like this:
using ClassMembers = MembersOf<MyClass>;

class MyClass
{
    public int MyProperty { get; set; }

    static MyClass
    {
        string lMyPropertyName = ClassMembers.GetName(x => x.MyProperty);
    }
}

With this approach you avoid misspelling member names in string literals and can use automatic refactoring tools. It's nice to have when implementing INotifyPropertyChanged!
But now I have a generic class that I want to use in the same manner, and I've learned that you can't use unbound types as generic type parameters:
using ClassMembers = MembersOf<MyGeneric<>>;

class MyGeneric<T> { }

What would be a good way to work around this problem?

A: The best way would be to forget the using directive and just use the class directly:
string propName = MembersOf<MyGeneric<T>>.GetName(x => x.SomeProp);

A: D'oh! The using ClassMembers alias was hiding the obvious. I just need to use MembersOf<MyGeneric<T>> directly in my class!
class MyGeneric<T>
{
    public int MyProperty { get; set; }

    static MyClass<T>
    {
        string lMyPropertyName = MembersOf<MyGeneric<T>>.GetName(x => x.MyProperty);
    }
}


text:
Q: how to share service between two modules in angular2 in my application, I have two different module (@NgModule) running independently and now I want they should communicate to each other and share data.the two modules are lazy loaded.how to reflect the service changes in module1 to module2

A: Create SharedModule and Inject SharedService in providers array as shown below
import { CommonModule } from '@angular/common';

import { SharedService } from './shared.service';

@NgModule({
    imports: [
        FormsModule,
        CommonModule
    ],
    exports: [

    ]
})
export class SharedModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: SharedModule,
            providers: [SharedService]
        };
    }
}

And Create SharedService  as shown below with bookTitleOrAuthorSearchEvent EventEmitter
import { Injectable, Inject, EventEmitter } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class SharedService {

    public bookTitleOrAuthorSearchEvent = new EventEmitter<string>();

   }

and Inject SharedModule to app.module as for forRoot as shown below
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';

import { SharedModule } from './modules/shared/shared.module';

@NgModule({
  declarations: [
    AppComponent,
    //..
  ],
  imports: [
    //..
    SharedModule.forRoot()
  ],
  providers: [
  //...
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

and Inject sharedService in any of your module's component and an instance of sharedService is available in all components of any modules and you can use EventEmitter or BehaviorSubject to emit the data and capture it where is required as shown below
import { Component, OnInit, DoCheck, ViewEncapsulation } from '@angular/core';
import { SharedService } from './../shared/shared.service';

@Component({
  selector: 'app-anytime-lib',
  templateUrl: './anytime-lib.component.html',
  styleUrls: ['./anytime-lib.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class AnytimeLibComponent implements OnInit, DoCheck {

  constructor(private sharedService: SharedService) {

  }

  ngOnInit() {
    this.clearSession();
  }
  clearSession() {
    // this.sharedService.removeSessionItem('userInfo');
  }

  ngDoCheck() {
    this.sharedService.bookTitleOrAuthorSearchEvent.subscribe((data) => {
      console.log('Emitted data', data);
    });
  }

}


text:
Q: LokiJS inconsistent with updates & reads while working with 50k+ reads and writes Currently we are working with nodeJS & LokiJS. as our application is dealing with real-time data; to communicate with external NoSQL/Relational DB will cause the latency problems.
So we decided to use in-memory database i.e, LokiJS.
LokiJs is good at when we are working with a collection which has 500-100 documents in it. but when it comes to the updates & parallel reads; it is worse.
meaning one of our vendor is published Kafka endpoint to consume the feed, and serve it to some external service again; From Kafka topic we are getting 100-200 events per second. So whenever, we received an Kafka event, we are updating the existing collection. As the delta updates are too frequent, LokiJS collection updates are not done properly by that read giving inconsistency results.
Here is my collection creation snippet.
    let db= new loki('c:\products.json', {
        autoload: true,
        autosave: true,
        autosaveInterval: 4000
    });
     this.collection= db.addCollection('REALTIMEFEED', {
                        indices: ["id", "type"],
                        adaptiveBinaryIndices: true,
                        autoupdate: true,
                        clone: true
                    });

function update(db, collection, element, id) {
    try {
        var data = collection.findOne(id);
        data.snapshot = Date.now();
        data.delta = element;
        collection.update(data);
        db.saveDatabase();
    } catch (error) {
        console.error('dbOperations:update:failed,', error)
    }
}

Could you please suggest me that, am I missing anything here.

A: I think your problem lies in the fact that you are saving the database at each update. You already specified an autoSave and an autoSaveInterval, so LokiJS is going to periodically save your data. If you also force saving from each update you are clogging the process, since JS is single-threaded so it has to handle most of the operation (it can keep running when the save operations is passed off to the OS for the file save bit).


text:
Q: How do I navigate to a parent StackNavigator from a nested toptabnavigator? I am trying to use this.props.navigation.navigate("DetailScreen") in my createMaterialTopTabNavigator screens to redirect to the DetailScreen in the StackNavigator but I am getting an error "Cannot read property 'navigate' of undefined', how can I structure my code to prevent it? Navigating from DetailScreen to Leaderboard works, but not the other way.
const LeaderBoardWrapperView = createStackNavigator({
Leaderboard: {
screen: Leaderboard = createMaterialTopTabNavigator({
  Alltime: () =>
    <AllTimeLeaderBoard path="allTime" />,
  Semester: () =>
    <AllTimeLeaderBoard path="semester" />,
  Weekly: () =>
    <AllTimeLeaderBoard path="weekly" />,
   })
  },
   DetailScreen: {
     screen: DetailScreen,
   }
})

Picture of my code with better formatting

A: navigation is not passed as a property to your top tab screen.
so you must pass this. for example:
Alltime: ({navigation}) =>
    <AllTimeLeaderBoard navigation={navigation} path="allTime" />


text:
Q: Is this context free or regular Strings over the alphabet {a, b, c, d} where no c is immediately followed by an a and no d is immediately followed by b.
This would be a context free and not regular right?

A: To answer a question like this, you are generally going to want to assume the most restrictive kind of language, then attempt to disprove it. If you can't disprove it, you need to find a way to express it using an appropriate grammar or automaton. If you can disprove it, move to the next level of the hierarchy and repeat.
In this case, you have at least two options to try to prove that the language isn't regular: the pumping lemma for regular languages, and the Myhill-Nerode theorem. If the language cannot be proven irregular from these, you'll need to right a regular grammar, regular expression, or finite automaton for exactly that language. Often, failed attempts at using the pumping lemma or Myhill-Nerode theorem give some insight as to how the you might find such representations of regular languages (for instance, the pumping lemma can show you that there must be a potential for a cycle in a finite automaton, and the Myhill-Nerode theorem can show you how many states a finite automaton must have, and what transitions must go between them).

This would be a context free and not regular right?

Why would you say that? Post the argument leading to this conclusion, and I will evaluate the argument.


text:
Q: How do I load files from GitHub rather than locally? [React App from GitHub Pages] I have finally incorrectly published my React App onto GitHub Pages. I believe that the issue is that my React App is trying to pull files from my local computer instead of my GitHub (which I don't want anyways). How would I change this?
My website has the error:
Not allowed to load local resource: file:///C:/Users/numak/Desktop/MyWebsite/dist/bundle.js
This first issue (of probably many) is in my index.html file which sources my bundle.js file like this:
<!DOCTYPE html>

            <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
            <title>React Starter</title>

                You need to enable JavaScript to run this app.

I'm not sure if this is actually an issue with the way I sourced it. It could also have to do with how I setup my website in my package.json or webpack.config.js files.
Here is a link to my GitHub branch that hosts the files for the GitHub Pages website:
https://github.com/NumaKarolinski/PersonalWebsite/tree/websiteVersion1
Here is a link to my GitHub Pages branch:
https://github.com/NumaKarolinski/PersonalWebsite/tree/gh-pages
Here is a link to my GitHub Pages website:
https://numakarolinski.github.io/PersonalWebsite/
Thanks for any help!

A: The comment by MaddEye helped me discover my final solution.
The comment was slightly wrong because https://raw.githubusercontent.com/NumaKarolinski/PersonalWebsite/websiteVersion1/dist/bundle.js has a MIME type of text/plain, but a MIME type of text/javascript is required.
I found that you can replace raw.githubusercontent by cdn.rawgit with a final solution of: https://cdn.rawgit.com/NumaKarolinski/PersonalWebsite/websiteVersion1/dist/bundle.js
I found this solution here: Link and execute external JavaScript file hosted on GitHub


text:
Q: *http.http2gzipReader vs io.ReadCloser Golang In the defination of the source code of response.go it is defined that the Body of type io.ReadCloser but while printing the type of Body by the following code it prints *http.http2gzipReader. Are they both same?
package main

import (
    "fmt"
    "net/http"
)

func main() {
    //any url
    url := "https://www.goal.com/en-in"
    res, _ := http.Get(url)
    body := res.Body
    fmt.Printf("tpye is %T", body)
}

A: No, they are not same.
io.ReadCloser interface is the type of request body but the *http.http2gzipReader is the concrete type assigned to the interface. That's what we call, *http.http2gzipReader implements io.ReadCloser interface.


text:
Q: Issue with MailChimp delete API? For DELETE APIs, if we hit the API with invalid data, the API responds with proper error message. If we use the same HTTP connection object to hit another API, the request fails.
This issue is not seen for Create or Update APIs. Also if the Delete request is sent with valid data, then using the same HTTP connection object for next request works fine.
Please note that this behavior has implications for connection pooling in client applications, and we were just wondering if its known issue and if there is any available workaround.