text:
Q: react native app suspense first network request for a while My react native 0.69.0 android app suspense network request for a while, in dev and production and debug mode, in production about 30 seconds and dev about 2 minutes.
I tested a new react native project 0.69.5 and a new 0.60.5 react native project and the issue still exists.
Once the first request is fulfilled there is no problem with the next requests anymore.


text:
Q: Update querystring on checkbox click There are n input boxces, if user checked any check boxce, value in query string should be add in with name of check box and if user uncheck the check box, value should be omit.If there is same name of check boxes ,value should should add with comma separated.
Ex. ?name1=1,2,3&name2=9,8,10

A: $("template_filters").on("change", "input", function(event, element) {
    var path        =   window.location.search.substring(1);
    var attr_name   =   element.name;
    var attr_val    =   element.readAttribute('data-id');
    var currentqueryVar =   path.toQueryParams();
    var org_path    =   window.location.href;
    var cleanUrl    =   org_path.split('?');
    if(path.length > 0 && typeof currentqueryVar[attr_name] !== 'undefined')
    {
        var paramArray = path.split("&");
        var n = new Array();
        var i;
        for (i=0;i<paramArray.length;i++)
        {
           var  currentParameter = paramArray[i].split("=");
           if(currentParameter[0]==attr_name)//Parameter already exists in current url
           {
                var old_q_val   =   currentParameter[1].split(',');
                if(old_q_val.indexOf(attr_val)=== -1)
                    old_q_val.push(attr_val);
                else
                {
                    var unset_index = old_q_val.indexOf(attr_val);
                    if(unset_index != -1){
                         old_q_val.splice(unset_index, 1);
                    }
                }
                currentParameter[1] =old_q_val.join();
           }
           if(currentParameter[1]!='')
                n.push(currentParameter[0]+'='+currentParameter[1]);
        }
        var queryStrnig ='?'+ n.join("&");
    }
    else{
        queryStrnig ='?'+attr_name+'='+ attr_val;
        if(path!='')
            queryStrnig ='?'+path+'&'+attr_name+'='+ attr_val;
    }
    history.pushState(null, null, cleanUrl[0]+queryStrnig);
    return false;
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: NodeJs doesn't return Persian/Farsi words correctly The issue is once I console.log() a Persian/Farsi word. Node.js logs it in left to the right direction and it makes the word unreadable.
console.log("کیان");

The terminal logs: ن ای ک instead of کیان
Didn't find any solution in documentaries.
Also, the data which I store in MySQL, saves as a set of question marks.
Guys, I just figured out that the word is okay and in the proper way when it comes to reading it from MySQL and res.send() it to the browser. So my problem is kinda solved but the console.log() bug is still a thing.


text:
Q: ng-view not working on Microsoft Edge I am testing my application on Microsoft Edge and it throws this error:
    app.config(
        function ($routeProvider) {
      $routeProvider.
          when('/logout', {
              template: '<logout-page></logout-page>'
          })
          .when('/', {
              template: '<application-manage></application-manage>'
          })
});

In my index:

Loading....

With the first case: '<application-manage></application-manage>' it's working normal. But when I click logout. It throws error:
SyntaxError

Thanks everyone. The problem is solved, it's because of the way I am using basic authentication:
jQuery.ajax({
              type: "GET",
              url: logoutURL ,
              async: true,
              username: fakeUser,
              password: fakePassword,
              headers: {"Authorization": "Basic Authorization"}
          }).done(function () {
             console.log("Can not logout Basic Authentication in this browser");
         defer.resolve(true);
            }).fail(function () {
                console.log("You have successfully logged out!");
                defer.resolve(true);
           });

From: http://stackoverflow.com/questions/233507/how-to-log-out-user-from-web-site-using-basic-authentication

A: Suggestion here, can you please provide name to app as below in HTML:
ng-app="XYZManagementApp"

A: Try:

   app.config(
        function ($routeProvider) {
      $stateProvider
                .state('/logout', {
url:'/logout',
              template: '<ui-view>'
          })
          .state('/', {
url:'/',
              template: '<ui-view>'
          })
});

You can Also use external html file, in this case use **templateUrl:'your file.html'**


text:
Q: Should authentication token be encrypted? If I append an HMAC to the auth token then the token cannot be tampered with. I notice many articles also recommend encrypting the token (which contains user id, expiration date and hash). What is the point of encrypting? Isn't that a waste of CPU time? (You have to decrypt the token for each request.) If it is not encrypted, anyone can see the user id and expiration date. What is the harm there?

A: Using only HMAC is a viable option: http://c2.com/cgi/wiki/wiki?HmacUserAuthentication
But: Note from disadvantages

No privacy. If you need privacy, you need full encryption: use SSL.
  HmacUserAuthentication is for security of service provision, not
  privacy.

So encryption is a requirement if you use a plain connection. In case of SSL the additional encryption is needed only if you want to prevent the end user from reading the token.


text:
Q: How to store an image in two different folders in Laravel The code below stores the image in only one folder. I would like to store the image in two different folders (Folder-A and Folder-B)
Here is my controller:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Service;

class ServiceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
        $request->image->move(public_path('Folder-A/'), $input['image']);
        Service::create($input);

        return back()->with('success', 'CREATED SUCCESSFULLY.');
    }
}

A: You can't run move() twice for the same file because as it name says, it moves the file, so on the second run, the original file won't exist anymore.
You must copy the file:
$uploadPath = public_path('folder-one/');
$file = $request->file('image');
$photo_jpeg= time() . '.' .$file->getClientOriginalExtension();
$file->move($uploadPath,$photo_jpeg);
\File::copy($uploadPath.$photo_jpeg,public_path('folder-two/').$photo_jpeg);


text:
Q: Unable to install HPLIP Binary Plug-In My printer is HP LaserJet Pro MFP m126nw. After setting up my printer in Ubuntu 20.04 (using HPLIP 3.20.3), when I tried to scan, it was mentioned that driver plug-in installation is required. When I try to install the driver plug-in, it simply doesn't install.
Then I used the terminal and typed this command:
hp-plugin
The output was:
HP Linux Imaging and Printing System (ver. 3.20.3)
Plugin Download and Install Utility ver. 2.1

Copyright (c) 2001-18 HP Development Company, LP
This software comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to distribute it
under certain conditions. See COPYING file for more details.

HP Linux Imaging and Printing System (ver. 3.20.3)
Plugin Download and Install Utility ver. 2.1

Copyright (c) 2001-18 HP Development Company, LP
This software comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to distribute it
under certain conditions. See COPYING file for more details.

Checking for network connection...
Downloading plug-in from:
Traceback (most recent call last):
  File "/usr/share/hplip/ui5/plugindialog.py", line 248, in NextButton_clicked
    status, download_plugin_file, error_str = self.pluginObj.download(self.plugin_path,self.plugin_download_callback)
  File "/usr/share/hplip/installer/pluginhandler.py", line 254, in download
    core = core_install.CoreInstall()
  File "/usr/share/hplip/installer/core_install.py", line 239, in __init__
    self.passwordObj = password.Password(ui_mode)
  File "/usr/share/hplip/base/password.py", line 88, in __init__
    self.__readAuthType()  # self.__authType
  File "/usr/share/hplip/base/password.py", line 110, in __readAuthType
    distro_name = get_distro_name().lower()
  File "/usr/share/hplip/base/password.py", line 78, in get_distro_name
    return distro.linux_distribution(full_distribution_name=False)[0]
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 125, in linux_distribution
    return _distro.linux_distribution(full_distribution_name)
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 681, in linux_distribution
    self.version(),
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 741, in version
    self.lsb_release_attr('release'),
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 903, in lsb_release_attr
    return self._lsb_release_info.get(attribute, '')
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 556, in __get__
    ret = obj.__dict__[self._fname] = self._f(obj)
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 1014, in _lsb_release_info
    stdout = subprocess.check_output(cmd, stderr=devnull)
  File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.8/subprocess.py", line 512, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '('lsb_release', '-a')' returned non-zero exit status 1.
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 153, in apport_excepthook
    with os.fdopen(os.open(pr_filename,
PermissionError: [Errno 13] Permission denied: '/var/crash/_usr_share_hplip_plugin.py.1000.crash'

Original exception was:
Traceback (most recent call last):
  File "/usr/share/hplip/ui5/plugindialog.py", line 248, in NextButton_clicked
    status, download_plugin_file, error_str = self.pluginObj.download(self.plugin_path,self.plugin_download_callback)
  File "/usr/share/hplip/installer/pluginhandler.py", line 254, in download
    core = core_install.CoreInstall()
  File "/usr/share/hplip/installer/core_install.py", line 239, in __init__
    self.passwordObj = password.Password(ui_mode)
  File "/usr/share/hplip/base/password.py", line 88, in __init__
    self.__readAuthType()  # self.__authType
  File "/usr/share/hplip/base/password.py", line 110, in __readAuthType
    distro_name = get_distro_name().lower()
  File "/usr/share/hplip/base/password.py", line 78, in get_distro_name
    return distro.linux_distribution(full_distribution_name=False)[0]
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 125, in linux_distribution
    return _distro.linux_distribution(full_distribution_name)
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 681, in linux_distribution
    self.version(),
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 741, in version
    self.lsb_release_attr('release'),
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 903, in lsb_release_attr
    return self._lsb_release_info.get(attribute, '')
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 556, in __get__
    ret = obj.__dict__[self._fname] = self._f(obj)
  File "/home/rls/.local/lib/python3.8/site-packages/distro.py", line 1014, in _lsb_release_info
    stdout = subprocess.check_output(cmd, stderr=devnull)
  File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.8/subprocess.py", line 512, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '('lsb_release', '-a')' returned non-zero exit status 1.

Output of lsb_release -a is:
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04 LTS
Release:    20.04
Codename:   focal

I messed up the pre-installed Python in my device.
An excerpt from one of my questions (in which I explained about the Python issue):

I guess Python 3.8.2 was pre-installed with my Ubuntu installation. I
wanted to upgrade to Python 3.8.3. So I followed the instructions
mentioned in this website Install Python 3.8.3 in Ubuntu 20.04 LTS -
TechPiezo.
At the end of the article, two suggestions were given. First is to
replace (or overwrite) already installed version 3.8.2 of Python;
second is to install Python v3.8.3 alongside the Python v3.8.2. I
followed the first option.

With Kulfy's help (link to Kulfy's answer), I hopefully reverted back to the pre-installed Python 3.8.2.
Now, the output of hp-plugin is:
HP Linux Imaging and Printing System (ver. 3.20.3)
Plugin Download and Install Utility ver. 2.1

Copyright (c) 2001-18 HP Development Company, LP
This software comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to distribute it
under certain conditions. See COPYING file for more details.

HP Linux Imaging and Printing System (ver. 3.20.3)
Plugin Download and Install Utility ver. 2.1

Copyright (c) 2001-18 HP Development Company, LP
This software comes with ABSOLUTELY NO WARRANTY.
This is free software, and you are welcome to distribute it
under certain conditions. See COPYING file for more details.

Checking for network connection...
Downloading plug-in from:
Traceback (most recent call last):
  File "/usr/share/hplip/ui5/plugindialog.py", line 248, in NextButton_clicked
    status, download_plugin_file, error_str = self.pluginObj.download(self.plugin_path,self.plugin_download_callback)
  File "/usr/share/hplip/installer/pluginhandler.py", line 254, in download
    core = core_install.CoreInstall()
  File "/usr/share/hplip/installer/core_install.py", line 239, in __init__
    self.passwordObj = password.Password(ui_mode)
  File "/usr/share/hplip/base/password.py", line 88, in __init__
    self.__readAuthType()  # self.__authType
  File "/usr/share/hplip/base/password.py", line 110, in __readAuthType
    distro_name = get_distro_name().lower()
  File "/usr/share/hplip/base/password.py", line 78, in get_distro_name
    return distro.linux_distribution(full_distribution_name=False)[0]
  File "/usr/lib/python3/dist-packages/distro.py", line 122, in linux_distribution
    return _distro.linux_distribution(full_distribution_name)
  File "/usr/lib/python3/dist-packages/distro.py", line 677, in linux_distribution
    self.version(),
  File "/usr/lib/python3/dist-packages/distro.py", line 737, in version
    self.lsb_release_attr('release'),
  File "/usr/lib/python3/dist-packages/distro.py", line 899, in lsb_release_attr
    return self._lsb_release_info.get(attribute, '')
  File "/usr/lib/python3/dist-packages/distro.py", line 552, in __get__
    ret = obj.__dict__[self._fname] = self._f(obj)
  File "/usr/lib/python3/dist-packages/distro.py", line 1012, in _lsb_release_info
    stdout = subprocess.check_output(cmd, stderr=devnull)
  File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.8/subprocess.py", line 512, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '('lsb_release', '-a')' returned non-zero exit status 1.
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 153, in apport_excepthook
    with os.fdopen(os.open(pr_filename,
PermissionError: [Errno 13] Permission denied: '/var/crash/_usr_share_hplip_plugin.py.1000.crash'

Original exception was:
Traceback (most recent call last):
  File "/usr/share/hplip/ui5/plugindialog.py", line 248, in NextButton_clicked
    status, download_plugin_file, error_str = self.pluginObj.download(self.plugin_path,self.plugin_download_callback)
  File "/usr/share/hplip/installer/pluginhandler.py", line 254, in download
    core = core_install.CoreInstall()
  File "/usr/share/hplip/installer/core_install.py", line 239, in __init__
    self.passwordObj = password.Password(ui_mode)
  File "/usr/share/hplip/base/password.py", line 88, in __init__
    self.__readAuthType()  # self.__authType
  File "/usr/share/hplip/base/password.py", line 110, in __readAuthType
    distro_name = get_distro_name().lower()
  File "/usr/share/hplip/base/password.py", line 78, in get_distro_name
    return distro.linux_distribution(full_distribution_name=False)[0]
  File "/usr/lib/python3/dist-packages/distro.py", line 122, in linux_distribution
    return _distro.linux_distribution(full_distribution_name)
  File "/usr/lib/python3/dist-packages/distro.py", line 677, in linux_distribution
    self.version(),
  File "/usr/lib/python3/dist-packages/distro.py", line 737, in version
    self.lsb_release_attr('release'),
  File "/usr/lib/python3/dist-packages/distro.py", line 899, in lsb_release_attr
    return self._lsb_release_info.get(attribute, '')
  File "/usr/lib/python3/dist-packages/distro.py", line 552, in __get__
    ret = obj.__dict__[self._fname] = self._f(obj)
  File "/usr/lib/python3/dist-packages/distro.py", line 1012, in _lsb_release_info
    stdout = subprocess.check_output(cmd, stderr=devnull)
  File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.8/subprocess.py", line 512, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '('lsb_release', '-a')' returned non-zero exit status 1.

What should I do to install the plug-in?

A: At first reinstall possible missed lsb-release with
sudo apt-get install --reinstall lsb-release

Also you have a mess of local and global python modules.
Remove problematic with
pip3 uninstall distro

and retry.


text:
Q: After recent shared hosting updates to Php, MySQL and Apache my site is not pulling data from MySQL (1064 syntax error) Newbie here. My hosting company recently upgraded their server(s) and that's where my website problems began:
FYI:

*

*MySQL upgraded from 5.1.70 to version 5.5.32

*Apache upgraded from 2.2.25 to version 2.4.6

*PHP upgraded from 5.3.27 to version 5.4.22

*I have a shared hosting account

For the last 2 days I've been searching Google, online manuals and developer/tech forums for possible answers to my "issues" and I'm having no luck finding good answers that help me fix my code to make my website display properly. Very frustrating. Obviously I need to learn more.
BKGD: I hired a developer to build a CMS for my website a couple of years ago and have since been trying to learn so I have a VERY basic understanding of Php, MySQL and HTML... but obviously not enough to fix these issues. Can you/anyone please help me get closer to fixing this nightmare.

*

*I know my original website code worked fine a week ago - prior to the hosting updates.

*The Index page and other "main Sections" currently display just fine for some reason. But if you click on any of the links to "articles", "news" and other "pages", those pages are not connecting properly >> not pulling table data from the associated MySQL database. Those pages showed a couple of different error messages.... initially displayed ONLY a "1064 syntax error" message OR "no page found" error (no "header", "footer", "page title", or any other info). I've since tweaked the code (I.e., I "hid" some of it with "//") and have it displaying the header and footer but nothing from MySQL database.

*The original "php.ini" file needed extra code >> "register_globals=on" << to work properly after the second-to-last Php & MySQL update. That is now "deprecated" and "removed".

*This newbie thinks that the following code is ONE EXAMPLE that isn't working properly (that I believe needs to be edited/updated to allow it to connect to MySQL). I think if I figure this one out I can apply similar tweaks to the other "news" and "article" pages:

//-- START: SAMPLE CODE ----

include "init.php";

$res = mysql_query("SELECT * FROM {$prefix}pages WHERE pag_name='$page_name'") or report();

if (mysql_num_rows($res)==1)
    cdie("no page found");
else
    $row=fetch($res);

$title = "$row[pag_title]";
$desc = "$row[pag_description]";

//------- END: SAMPLE CODE --

I realize I might be way off on this being the issue (E.g., the problem might be in the functions.php file) but that's where I'm at right now. Clueless. Ugh.
Any thoughts or suggestions? Need more info (just ask and I'll reply as soon as I get the email).

A: If your code relies on register_globals, you are going to run into undefined variable problems.
For example, if the $page_name variable comes from a query string like index.php?page_name=test, you could access it before like $page_name but now you must access it like $_GET['page_name'].
You need to check all your code to see if your variables are defined (a good IDE can help with that).
As a sidenote, you also need to double-check to see if you don't have any sql injection problems, injecting variables directly in a query is normally not a good sign. You should really switch to PDO or mysqli and prepared statements but at the very least use mysql_real_escape_string on your variables before you use them in your queries.


text:
Q: Entity Framework on .Net Core Server with multiple databases I have a hoster that only offers databases with 2 GB. However, my application will soon need significantly more. The provider wants to provide me with several databases.
Do I have to write a separate DBContext for each database or can I somehow configure Entity Framework to manage it? Is it better later handling, to subscibe otherwhere a bigger database?


text:
Q: How to manage setting file in WebStorm using VCS? I have several computers... like you. home desktop, mac, office desktop, etc.
Each of computer installed WebStorm IDEA, I want to share my idea setting file every computers.
I found Exporting setting file menu on WebStorm, which makes settings.jar file.
Okay, If I import this settings.jar file from another computer, it will be a way of it.
But my settings file updated very often. so above way little bit inconvenient, I want to simply manage it with VCS, How can I do that??
Thanks in advance..

A: Please consider using the Settings Repository plug-in. It does exactly what you need.

A: You just check in most of the project files.
Here is a good description: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
For us it worked fine as long as all developers use the same IDEA version. When versions differ it might lead to "settings ping pong" where each version stores the project settings a little differently and so they keep changing.


text:
Q: Bootstrap 4 - How To Properly Center a Div (Form)? I'm just getting started into using Bootstrap, and am having a bit of trouble getting a form to display in the center of the page. So far, what I have done is use CSS-styling to make sure that both html and body tags are at 100% height. Then I have two divs: the outer div uses the entire height of the page, and uses "justify-content-center." The inner div uses "align-items-center." With this, I have managed to get the form to display in the center. However, I'm left with this whitespace that stretches on the top and bottom of the form.
This is somewhat of a vague question, but is there a way for me to to either remove that whitespace (as in like shrink the container or something), or perhaps go about centering a div a different way?
I am using jade/pug for my view template engine. Here is the source code:

block content
  div(class="row h-100 justify-content-center")
    div(class="d-flex align-items-center shadow-lg p-3 mb-5 bg-white rounded")
      div
        h3(class="text-center") Submit Your Attendance
        form
          div(class="form-group")
            label(for="firstname") First Name
            input(class="form-control", type="text", id="firstname", placeholder="John", name="firstname")
          div(class="form-group")
            label(for="lastname") Last Name
            input(class="form-control", type="text", id="lastname", placeholder="Doe", name="lastname")
          div(class="form-group")
            label(for="email") Email Address
            input(class="form-control", type="text", id="email", placeholder="johndoe@email.com", name="email")
          div(class="text-center")
            button(class="btn btn-primary", type="submit") Submit

Here is the layout.jade that it inherits from:
doctype html
html(style="height:100%")
  head
    title= title
    link(rel='stylesheet', href='/node_modules/bootstrap/dist/css/bootstrap.min.css')
    script(src="/../node_modules/jquery/jquery.min.js")
    script(src="/../node_modules/popper.js/dist/umd/popper.min.js")
    script(src="/../node_modules/bootstrap/dist/js/bootstrap.min.js")
  body(style="height:100%;background-image:url(../public/images/index-background.jpg);")
    block content

And here is what the page looks like:
screenshot of the page
Any suggestions would be appreciated, thank you very much!

A: Just add align-items-center class along with row class.
block content
  div(class="row h-100 justify-content-center align-items-center") /*add align-items-center here*/
    div(class="d-flex flex-column align-items-center shadow-lg p-3 mb-5 bg-white rounded")
      div
        h3(class="text-center") Submit Your Attendance
        form
          div(class="form-group")
            label(for="firstname") First Name
            input(class="form-control", type="text", id="firstname", placeholder="John", name="firstname")
          div(class="form-group")
            label(for="lastname") Last Name
            input(class="form-control", type="text", id="lastname", placeholder="Doe", name="lastname")
          div(class="form-group")
            label(for="email") Email Address
            input(class="form-control", type="text", id="email", placeholder="johndoe@email.com", name="email")
          div(class="text-center")
            button(class="btn btn-primary", type="submit") Submit

just I converted pug html into normal its working fine.
DEMO:

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset=" utf-8 ">
  <meta name="viewport " content="width=device-width, initial-scale=1 ">
  <link rel="stylesheet " href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css ">

Submit Your Attendance form

      <form>

          First Name
          <input class="form-control " type="text " id="firstname " , placeholder="John " name="firstname ">

          Last Name
          <input class="form-control " type="text " id="firstname " , placeholder="John " name="firstname ">

          Email
          <input class="form-control " type="text " id="email " placeholder="johndoe@email.com " name="email ">

          <button type="submit " value="Submit ">submit</button>

      </form>


text:
Q: How I validate this kind of a number I'm looking for a function or some logic that will validate a 10 digit long phone number. I'd like to make sure that the number is exactly 10 digits, no letters, no hyphens etc.. And also need to check first digit of the number start with 0.
Eg: 0714556260

UPDATE
$test = 0714556260;

if (preg_match("|^[0-9]{10}$|", $test)) {
      echo 'valid';
} else {
    echo 'not valid';
}

A: if (preg_match('/^0\d{9}$/', 0714556260) ) {
    // OK
}

A: $str = "0714556260";
if (preg_match("|^[0-9]{10}$|", $str))
    echo "ok";

A: You can use this regex to validate your phone number in preg_match function:
/^0\d{9}$/

A: Please read the documentation
$test = 0714556260;

if (intval($test) && preg_match($test,"/^0[0-9]{9}$/")) {
      //do stuff
}


text:
Q: Specifying columns in scikit-learn pipeline after ColumnTransformer I want to construct a scikit-learn pipeline in which some columns have values imputed, and then scaling is subsequently applied to some. If I put both operations in the same columntransformer this does not work as they proceed in parallel (and so missing values cause the scaler to fail). If I make two columntransformers and run them in series, however, I run into the issue that I cannot specify column names (as output of the first transformer is a np array). What is the correct way to go about this?
numeric_columns = list(X.select_dtypes('float64').columns)
cat_columns = list(X.select_dtypes('object').columns)+list(X.select_dtypes('int64').columns)

# Imputation
imp_mean = SimpleImputer(strategy='mean')
imp_freq = SimpleImputer(strategy='most_frequent')
imputer = ColumnTransformer(
    [('Imput_mean', imp_mean, numeric_columns),
     ('Imput_freq', imp_freq, cat_columns),
    ], remainder='passthrough'
)

# Scaling
feature_transformer = ColumnTransformer(
    [('num',StandardScaler(),numeric_columns),
    ], remainder='passthrough'
)

#Hyperparameters
parameters = {'model__n_components':[1,2,3,4,5]}

#Pipeline
pipeline = Pipeline([('imputer', imputer),
                     ('feature_transformer', feature_transformer),
                     ('model', PLSRegression())])

#Cross validation strategy
cv = KFold(n_splits=10, shuffle=True)

#Cross valdiate and evaluate
clf = GridSearchCV(pipeline, parameters, scoring="r2", cv=10)
cross_val_score(clf, X, y, cv=cv, scoring="r2"))

A: You might nest a Pipeline which takes care of the preprocessing of the numerical columns (performed serially) within the ColumnTransformer instance.
Here's an example:
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

X = pd.DataFrame({'city': ['London', 'London', '', 'Sallisaw'],
          'title': ['His Last Bow', 'How Watson Learned the Trick', 'A Moveable Feast', 'The Grapes of Wrath'],
          'expert_rating': [5, 3, np.nan, 5],
          'user_rating': [4, np.nan, 4, 3]})

numeric_columns = list(X.select_dtypes('float64').columns)
cat_columns = list(X.select_dtypes('object').columns) + list(X.select_dtypes('int64').columns)

imp_mean = SimpleImputer(strategy='mean')
imp_freq = SimpleImputer(missing_values='', strategy='most_frequent')

ct = ColumnTransformer([
        ('Imput_freq', imp_freq, cat_columns),
        ('pipe_num', Pipeline([('Imput_mean', imp_mean), ('num', StandardScaler())]), numeric_columns)
    ], remainder='passthrough'
)

pd.DataFrame(ct.fit_transform(X))

Here's a similar post: How to execute both parallel and serial transformations with sklearn pipeline?.


text:
Q: How to store sharedPreferences on Google Drive correctly? Log in and receive permission from Google already has.
Already I know how to create, delete, empty files, but I can not write data to a file.
Tell me how to send sharedPreferences file to Google Drive, and how to get it back.
Can you just describe the steps I could find - I would be very grateful!
Something like that:

*

*Open the file (File f = getActivity () getDatabasePath (
"prefname");.)

*Get mime (f.getMime)

*Get in bytes (f.toByte)

*Writing to Drive (DriveFile DF = Drive.DriveApi.getAppFolder (apiClient)
                             .createFile (apiKlient, metadata, bytes)
PS: I'm so tired of all the search ...


text:
Q: Extract text from file over separate/separated lines in Python Hoping someone can help as I'm very new to Python and struggling a bit.
I need to take a text file's contents and extract elements of it into another file, capturing some lines but ignoring others.  As an example, this is a portion of the original file:
input1
   name "Bob"
   Always_active
next_input
input2
   name "Alice"
   Sometimes_active
next_input
input3
   name "Ted"
   Always_active
next_input
input4
   name "Albert"
   Never_active
next_input
input5
   name "Sue"
   Always_active
next_input
input6
   name "David"
   Never_active
next_input
input7
   name "Building1"
   Always_active
next_input
input8
   name "Building2"
   Always_active
next_input
input9
   name "Building3"
   Always_active
next_input
input10
   name "Building4"
   Always_active
next_input

And this is what I'd like to be able to capture:
input1
   name "Bob"
input2
   name "Alice"
input3
   name "Ted"
input4
   name "Albert"
input5
   name "Sue"
input6
   name "David"
input7
   name "Building1"
input8
   name "Building2"
input9
   name "Building3"
input10
   name "Building4"

So essentially I need to ignore some of the lines and capture the remainder.  How can I achieve this?

A: You can start with reading the file:
with open(r'C:\your_file_path\your_file_name.txt', 'r') as f:
    text = f.read().splitlines()

then you will have variable "text" which is a list and every element in this list is one of the lines from your text. Next you should check every line for your "condition"
new_text = []
for i in text:
    if i[:5] == 'input':
        new_text.append(i)
    elif i[:6] == 'name \"':
        new_text.append(i)

variable "new_text" is a list with elements-lines of text that you wanted.

A: You should read the file line by line and filter the line you want to write them in a new file.
# First read file
with open(filename, 'r') as f:
    file = f.readlines()

# Create new file
f2 = open(filename, 'a')

for line in file:
    if line not in ('Always_active', 'Never_active'): # Filter lines you don't want
        f2.write(line) # Write line
        f2.write('\n') # Break line

# Close file
f2.close()

Should work

A: You could use pandas to read and edit the file.
Assuming you have the text saved in temp_txt_file.txt in the same folder as your python script.
import pandas as pd
import csv

data = pd.read_csv("./temp_txt_file.txt", header=None)
data_filtered = data.loc[data.loc[:, 0].apply(lambda x: x.find("name") == 0 or x.find("input") == 0)]
data_filtered.to_csv(path_or_buf='./filtered_data.txt', index=False, header=False, quoting=csv.QUOTE_NONE)

You first load the data into a pandas.DataFrame. In the second line you locate all rows where your string begins with either name or input (this is done by .find(), which returns 0 if the string begins with the query)
Note: With .apply(lambda x: function) you apply a function to every row of the pandas.DataFrame with x containing the row as a string.
The code:
data.loc[:, 0].apply(lambda x: x.find("name") == 0 or x.find("input") == 0)

yields a series of "True / False" which you can consider as a mask for filtering out unwanted rows. You then apply (locate) this in the pandas.DataFrame and save it to a new file *filtered_data.txt" without any header and index of the pandas.DataFrame.
Note: qutoing=csv.QUOTE_NONE is needed to avoid unnecessary escape characters for "
Advise: if you can format the text file differently and using .csv file this would help a lot as it seems your data is somewhat a table. Then you could dig into pandas which is perfect for organizing data.


text:
Q: Is there any way to share Y axis among only part of subplots in matplotlib? I have N subplots, and I want to share Y axis for all but one of them. Is it possible?

A: Yes, you can specify which suplots shares which axis with which axes (this is not a typo I mean this sentence). There's a sharex and a sharey argument for add_subplot:
For example:
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1,2,3,4,5])
y1 = np.arange(5)
y2 = y1 * 2
y3 = y1 * 5

fig = plt.figure()
ax1 = fig.add_subplot(131)                # independant y axis (for now)
ax1.plot(x, y1)
ax2 = fig.add_subplot(132, sharey=ax1)    # share y axis with first plot
ax2.plot(x, y2)
ax3 = fig.add_subplot(133)                # independant y axis
ax3.plot(x, y3)
plt.show()

this will create a plot like this (1st and 2nd share the y axis, but the 3rd does not):

You can find another example of this in the matplotlib examples "Shared axis Demo".

A: if you are using this format.
fig, axs = plt.subplots(4,1,sharex=True,figsize=(8,8))

You can try
axs[2].sharey(axs[1])

axs[3].sharey(axs[1])

After each subplot.


text:
Q: iOS bluetooth printer implementation I'm a newbie in iOS. I want to know if there's any possibility to do printing at a portable bluetooth printer from iPhone app?
iOS Bluetooth printer?
The thread above said it's not possible but it's two years old. Is there any chance we could do it now?


text:
Q: Submitting a form with file input using remotipart wraps a textarea to response Using Ruby on Rails 4 and Ruby 2.
Here's my simple controller action. When validation fails I render the 'new' action and inject the contents of the view into the .ajax-target div.
$("body").on("ajax:success", '.remote-form', (e, data, status, xhr) ->
    $(this).parent().parent().after(xhr.responseText);
    $.colorbox.resize();
  ).on "ajax:error", '.remote-form', (e, xhr, status, error) ->
    $(this).parent().parent().after("Error");

def create
  @floor = Floor.new(floor_params)
  if @floor.save
    render action: 'edit', layout: false
  else
    render action: 'new', layout: false
  end
end

#popupBox.ajax-target
  %h1 New Floor
  = render 'shared/form_errors', resource: @floor
  #formHolder
    = simple_form_for @floor, html: { multipart: true, class: 'remote-form' }, remote: true do |f|
      = f.input :name, required: true
      = f.input :prefix, required: true
      = f.input :plan, class: 'file_hidden', label: 'Floorplan'

      .clearfix
      = f.button :submit, 'Create Floor'

This works structure works fine for every type of form except ones that have a file input type that have a selected file. If I submit the form with all fields blank, I see the form reloading fine. If I select an image and leave other fields blank (to trigger the validations) I get:
"Error" text because of the ajax:error response. And also see this in the Network tab:
<textarea data-type="text/html" data-status="200" data-statusText="OK">

New Floor

        Prefix
        has already been taken

    <form accept-charset="UTF-8" action="/floors" class="simple_form remote-form" data-remote="true" enctype="multipart/form-data" id="new_floor" method="post" novalidate="novalidate">
<input name="utf8" type="hidden" value="&#x2713;" />

* Name<input class="string required" id="floor_name" name="floor[name]" type="text" value="FLR001" />

* Prefix<input class="string required" id="floor_prefix" name="floor[prefix]" type="text" value="FLR001" />

* Floorplan<input class="file required" id="floor_plan" name="floor[plan]" type="file" />

        <input class="btn" name="commit" type="submit" value="Create Floor" />
    </form>

</textarea>

A: I know this is too late to answer considering the date of the post.But I hope it is useful if someone ends up looking for an answer.
The render_with_remotipart def renders that way and there is a reason for that.Without worrying about that you can just handle it in the javascript see e.g. here
Just do eg. is in coffeescript but you get the idea right.
var element = "#parent_element_with_form"

$(form).on 'ajax:remotipartComplete', (e, data) ->
  $(element).html($(data.responseText).html())

or
$(form).on 'ajax:success' && $(form).on 'ajax:error'

depending on your application circumstances.


text:
Q: No midi ports available I am trying to configure my midi settings so that I can have midi IO in my laptop.
I am starting timidity with the following:
jackd -R -P 70 -d alsa -p 256 -n 3 -r 44100

then by doing
aplaymidi -l

I get:
Port    Client name                      Port name
14:0    Midi Through                     Midi Through Port-0
128:0    TiMidity                         TiMidity port 0
128:1    TiMidity                         TiMidity port 1
128:2    TiMidity                         TiMidity port 2
128:3    TiMidity                         TiMidity port 3

It seems that there are 4 ports available on the timidity server. However when I try to find output port, nothing is found by my C++ app (it uses the Rtmidi library).
int main(){

RtMidiOut *midiout = 0;
midiout = new RtMidiOut();
std::vector<unsigned char> message;
midiout->openVirtualPort();

unsigned int nPorts = midiout->getPortCount();

if (nPorts == 0) {
    std::cout << "No ports available!\n";
    return;
}
std::cout << "\nThere are " << nPorts << " MIDI output ports available.\n";
}


text:
Q: Why doesn't this cascading nullify trigger work on SQL Server 2000 I've got the tables A and B. Table B has a foreign key constraint refering to table B. But since SQL Server 2000 only supports cascading delete, and not nullify, I decided to fix this with a trigger.
The problem: the trigger below doesn't work:
CREATE TRIGGER dbo.TR_A_B_CascadingNullify ON dbo.A
FOR DELETE
AS
    UPDATE dbo.B
    SET idA = NULL
    WHERE idA IN (SELECT id FROM DELETED)
;

When deleting a row in A that isn't refered to, everything works. But when a refered to row is deleted, it fails on the foreign key constraint with the message DELETE statement conflicted with COLUMN REFERENCE constraint 'FK_B_A'. The conflict occurred in database 'x', table 'B', column 'idA'.
And finally, when setting the option Enforce Foreign Key Constraint to No, the trigger does work, and the column in table B is set to NULL.
What am I doing wrong?

A: The easiest solution is probably to use an INSTEAD OF trigger, not an AFTER trigger. Then the  DELETE operation itself will never actually happen; instead, whatever logic you put into the trigger will run.
And as a standard comment, SQL 2000 is no longer supported by Microsoft so you should upgrade to a newer version as soon as you can.

A: Your trigger fires after the DELETE, ie after all reference checks have been done. From the documentation of CREATE TRIGGER;
AFTER is the default when FOR is the only keyword specified.
Your only option afaik is to use an INSTEAD OF trigger.


text:
Q: How to create a custom system field in magento 1? Magento 1.9
I want to create a new tab in System > Configuration.
In this tab, I need a group tab and in this group tab i want a textarea which is connected to a field of my database. If i edit my textarea, it will modify my database field too.
Look at this: https://prnt.sc/orwph1
I don't know how to connect my textarea with my db.. Create a new tab with a new group it's easy but connect it to the db..
Thanks!

A: let's assume you want a section that has 2 fields: multiselect, text area. In the multiselect you have all your customer and in the text are you get the modify to apply for a certain db field (related to the customer).
your system.xml should me something like this:
<config>
<tabs>
    <admin_customTab_2 translate="label" module="sections">
        - TAB NAME -
        <sort_order>2</sort_order>
    </admin_customTab_2>
</tabs>

<sections>
    <customsection2 translate="label" module="sections">
        label name
        <tab>admin_customTab_2</tab>
        <frontend_type>text</frontend_type>
        <sort_order>1</sort_order>
        <show_in_default>1</show_in_default>
        <show_in_website>1</show_in_website>
        <show_in_store>1</show_in_store>
        <groups>
            <block translate="label">
                label name
                <frontend_type>text</frontend_type>
                <sort_order>1</sort_order>
                <show_in_default>1</show_in_default>
                <show_in_website>1</show_in_website>
                <show_in_store>1</show_in_store>
                <fields>
                    <block_customers>
                        Select user
                        <comment>user list</comment>
                        <frontend_type>multiselect</frontend_type>
                        <backend_model>sections/users</backend_model>
                        <source_model>sections/users</source_model>
                        <sort_order>1</sort_order>
                        <show_in_default>1</show_in_default>
                        <show_in_website>1</show_in_website>
                        <show_in_store>1</show_in_store>
                    </block_customers>
                    <block_textarea>
                        changes to apply
                        <frontend_type>text</frontend_type>
                        <sort_order>1</sort_order>
                        <show_in_default>1</show_in_default>
                        <show_in_website>1</show_in_website>
                        <show_in_store>1</show_in_store>
                    </block_textarea>
                </fields>
            </block>
        </groups>
    </customsection2>
</sections>

this is not enough for the configs, you need to tell Magento about the access control list (ACL) or admin-users will not see it. It is done in the config.xml
like this:
    <adminhtml>
    <acl>
        <resources>
            <admin>
                <children>
                    <system>
                        <children>
                            <config>
                                <children>
                                    <customsection2>
                                        <title>Customer Changes?</title>
                                    </customsection2>
                                </children>
                            </config>
                        </children>
                    </system>
                </children>
            </admin>
        </resources>
    </acl>
</adminhtml>

all is setted, but doing nothing but showing us the tabs and forms.
If you was brave enough you noticed a tag in the system.xml code up here,
<backend_model>sections/users</backend_model>
<source_model>sections/users</source_model>

this tell magento that you are using a model relating to this form, where you can do operations.
So, in your Model's path create the (in this example) User.php
and here we go:
you want to extend your custom class  with this one.
    class Admin_Sections_Model_Users extends Mage_Core_Model_Config_Data
yes but we still didn't insert any data in the form.
You can do this by just adding a special function toOptionArray()  :
    public function toOptionArray()
{
    $collections = Mage::getModel("customer/customer")->getCollection();

    foreach ($collections as $colletion){
        $user = Mage::getModel("customer/customer")->load($colletion->getId());
        $array[] = array('value'=>$user->getEntityId(),'label'=>Mage::helper("sections")->__($user->getName()));
    }
    return $array ;
}

this will set ALL the customer's name into the multi-select form.
"yeah, nice.. I asked about the text-area"
before telling you how to get Data from Store Configs, you should know that there are 2 main methods for elaborating the form data:
    public function _afterSave()
{}
    public function _beforeSave()
{}

in there you can put all your code, no need to explain what is the difference between them.
in this function you can easy get the Data from Store Config by doing:
$text_area_string = Mage::getStoreConfig('customsection2/block/block_textarea');

"yeah nice... but my main problem is to save things in DB"
you can use whenever you prefer the Mage::getModel('') method , this can connect you to the database. Lets make an example; modify the 'is_active' field on 'customer_entity' table.
    $customer = Mage::getModel("customer/customer")->load($customer_id);
    $customer->setData("is_active",0);
    $customer->save();

this field doesn't do really anything, it is just a very fast example.
This should let you do what you are aiming for.
If something sounds strange, please let me know!


text:
Q: Custom animate chart with jquery and html 5 Need to create this chart in html5 with animation and chart update on select change.
Chart Image Example

A: I think you can achieve this by using an HTML5 chart library like Chart.js
with some CSS modifications... Just an idea.
Pie-Chart Doc


text:
Q: What criteria are required for fields to be equated? I'm building a query builder module in C# and Java, where users can join tables based on a specified join expression, for example [Table1].[ID] = [Table2].[ID].
Users can modify the join expression, and can choose to equate any field from Table1 with any field in Table2.
I thought of checking to see whether the column data types and lengths are the same, however a varchar(10) column can be joined with an nchar(10) column for example. As long as the lengths are the same, these different data types can be selected.
Thus, what conditions should I specify in my checks to see that the user's selected join expression is valid? I cannot rely on PK/FK constraints alone.
The criteria could be applied to C# or Java - does not matter, as once I have a general answer I can convert my solution to fit both.

A: Books Online will give you the datatypes and which can be implicityl converted, which must be explicitly converted and which cannot convert. Search for CAST and CONVERT (Transact-SQL)  and scroll down.
You should be able to build some sort of rules engine now that you knw the rules.

A: I think your best bet is to simply have hardcoded sets, and then check whether both fields are in the same set, and only then compare the length.
var TypeSets = new Dictionary<string, List<string>> {
                   { "string", new[] { "varchar", "nchar", "text" } },
                   { "integer", new[] { "int", "smallint" } },
               };

Then:
if (TypeSets.Any(x => x.Value.Contains(fieldType1) && x.Value.Contains(fieldType2)))
{
   // Check length of each field
}
else
{
    return false;
}


text:
Q: If else condition in document to control format of equation How can I create a variable in the beginning of the latex document that will dictate how certain equation will be shown? Concretely, in the beginning I want to define a variable x which will take value either double column or single column. Based on the value x takes, in the document certain equation will be one or the other. How can I do this? I put what I want in the comment here:
\documentclass{article}
\usepackage[utf8]{inputenc}

%set variable x = "double column"

\begin{document}

%if x == "double column" compile:
    \begin{equation}
        x = 2
    \end{equation}
%else compile:
    \begin{equation}
        y = 40
    \end{equation}

\end{document}

A: The basic approach of conditioning can be done in a number of ways. Here are a couple of ways:

*

*Define and compare macros/commands using \ifx<cmdA><cmdB>:
\documentclass{article}

\newcommand{\myvar}{double column}
\newcommand{\doublecolumn}{double column}

\begin{document}

\ifx\myvar\doublecolumn
  \begin{equation}
    x = 2
  \end{equation}
\else
  \begin{equation}
    y = 40
  \end{equation}
\fi

\end{document}

*Compare your variable like one would normally, using a text comparison via \pdfstrcmp{<stringA>}{<stringB>}. This returns the number 0 if <stringA> equals <stringB> (-1/1 if <stringA> lexicographically precedes/succeeds <stringB>).
\documentclass{article}

\newcommand{\myvar}{double column}

\begin{document}

\ifnum\pdfstrcmp{\myvar}{double column}=0
  \begin{equation}
    x = 2
  \end{equation}
\else
  \begin{equation}
    y = 40
  \end{equation}
\fi

\end{document}

\pdfstrcmp expands its arguments, which is often helpful if they contain macros themselves. It's also available via pdftexcmds if your engine doesn't provide it.

*Define a new \if-conditional:
\documentclass{article}

\newif\ifdoublecolumn% Default is \doublecolumnfalse

\doublecolumntrue

\begin{document}

\ifdoublecolumn
  \begin{equation}
    x = 2
  \end{equation}
\else
  \begin{equation}
    y = 40
  \end{equation}
\fi

\end{document}

This option is more intuitive.

A: Just make the \if@twocolumn conditional available at the user's level.
\documentclass[twocolumn]{article}

\usepackage{lipsum} % for mock text

\makeatletter
\let\iftwo\if@twocolumn
\makeatother

\begin{document}

\lipsum[1][1-4]
\iftwo
  \begin{equation}
  c=2
  \end{equation}
\else
  \begin{equation}
  c=1
  \end{equation}
\fi
\lipsum[2]

\end{document}

One column

Two column

A more flexible approach that can save typing. Also the braces around the arguments to \OneOrTwo will avoid problems if the code is used inside align or similar environments.
\documentclass[twocolumn]{article}
\usepackage{amsmath}

\usepackage{lipsum} % for mock text

\makeatletter
\let\iftwo\if@twocolumn
\DeclareRobustCommand{\OneOrTwo}[2]{%
  \if@twocolumn#2\else#1\fi
}
\makeatother

\begin{document}

\lipsum[1][1-4]
\iftwo
  \begin{equation}
  c=2
  \end{equation}
\else
  \begin{equation}
  c=1
  \end{equation}
\fi
\lipsum[1][1-4]
\begin{equation*}
  c=2
  \OneOrTwo{+long+long+long+long+long+long}
           {\begin{aligned}[t]&+long+long+long \\ &+long+long+long\end{aligned}}
\end{equation*}
\lipsum[2]

\end{document}

One column

Two column


text:
Q: Quartz Drawing weirdly what I'm trying to do is create a custom progress bar, with quartz drawing, what I do is the following,
- (void)drawRect:(CGRect)rect {
    // Drawing code.
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect currentBounds = self.bounds;
    CGContextSetLineWidth(context, 20.0f);
    CGContextSetStrokeColorWithColor(context, [ProgressBarView redColor]);

    CGContextBeginPath(context);
    CGContextMoveToPoint(context, CGRectGetMinX(currentBounds), CGRectGetMidY(currentBounds));
    CGContextAddLineToPoint(context, CGRectGetMaxX(currentBounds) * time, CGRectGetMidY(currentBounds));
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathStroke);
}

In the CGContextAddLineToPoint I multiply the maxX times time, which is calculated with this function every second.
- (void)pushTime {
    if (time >= 1.0) {
        time = 0.0;
    } else {
        time = time += 0.1;
    }
    [self setNeedsDisplay];
}

It works great the first time, but then the progress bar never gets back to the starting point, I already tried to change the start value to other than 0, so that quartz can create the path without a problem, but that didnt do it.
Anyway, thank you for your help.

A: It seems your view does not clear previously drawn content for some reason - you can fix that by explicitly forcing view to clear before redrawing itself:
- (void)drawRect:(CGRect)rect {
    // Drawing code.

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextClearRect(context, rect);
    ...

Although I expected that clearing should be done automatically (and tweaking the value of clearsContextBeforeDrawing property does not make any effect...)


text:
Q: When abruptly exiting a C program mid-loop, why do additional loop iterations occur? Consider the basic client and server programs below (just bare bones / to illustrate my question). The client initiates a connection with the server, prompts the user to enter a message, which is then sent to the server and printed to screen.
If I abruptly quit the client program in the middle of the loop (e.g. by closing the terminal window), sometimes the client will continue to iterate through the loop for a period of time (i.e. the last message sent to the server / currently residing in the write buffer at the time the client is closed, is repeatedly sent to the server, typically until the loop is exhausted). Other times however, the read() call on the server correctly returns 0, and the connection is closed without issue (the behavior seems to be fairly random).
I don't quite understand what's going on here. First off, why do additional loop iterations occur after the program closes? Is there just a lag time between when the terminal window is closed, and when the actual process itself ends? Even if additional loop iterations do occur, shouldn't the call to fgets() block until a message is entered by the user?
I'm using Fedora 25 Workstation with XFCE desktop.
I tried searching for info on this, but didn't have much luck (I'm not sure how to search for this in a succinct way). Any help is much appreciated.
Thanks
CLIENT:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    int sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(3000);
    inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);
    connect(sockfd, (struct sockaddr *)&server, sizeof(server));

    int i;
    for (i = 0; i < 20; i++) {
        char buf[512];
        printf("Send a message: ");
        fgets(buf, 512, stdin);
        write(sockfd, buf, sizeof(buf));
    }

    close(sockfd);
}

SERVER:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>

int main(void) {
    int listenfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(3000);
    inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);
    bind(listenfd, (struct sockaddr *)&server, sizeof(server));

    listen(listenfd, 10);
    printf("Listening...\n");

    struct sockaddr_in client;
    socklen_t client_size = sizeof(client);
    int clientfd = accept(listenfd, (struct sockaddr *)&client, &client_size);

    for (;;) {
        char buf[512];
        int i = read(clientfd, buf, sizeof(buf));

        if (i == 0) {
            close(clientfd);
            printf("Connection Closed\n");
            break;
        } else {
            printf("%s", buf);
        }
    }

    close(listenfd);
}

A: When your terminal (and thus the remote/master side of the pty device connected to your process's stdin/out/err) is closed, fgets will see end-of-file status on stdin, and will return immediately with either an incomplete line (not ending in \n) or no input at all (null return value); in practice it's going to be the latter. If you checked the result, you would see this and be able to act accordingly.

A: in the server, this line:
printf("%s", buf);

should be replaced with:
*buf[i] = '\n';
printf( "%s", buf );

so there is a valid string to print (read() will not terminate the string)
Note: if a I/O error occurs or a signal occurs, etc then read() will return a value less than 0 and should result in exiting the for(;;;) loop, not continuing in the loop, printing the 'old' contents of buf[]
in this line in the client:
write(sockfd, buf, sizeof(buf));

if the write fails, it will return a value less than 0  if/when such an event occurs, the loop should exit, not continue looping,
It is very important to check all error conditions.   such error checking (and the resulting handling of the error) can easily double the size of the code, but it must be done; otherwise such 'odd' events as you are seeing will happen, with no simple explanation of what happened.
When a system function returns an error indication, use the function perror()  to have some text you provide displayed on stderr, along with the message from the system as to why it thinks the error occurred.

A:
If I abruptly quit the client program in the middle of the loop (e.g. by closing the terminal window),

Closing the terminal window does not quit the client program -- it continues running, just with no input (so any reads from the now-closed terminal will return EOF).  However, you never check the return value of fgets in the client so you you never notice, you just keep looping, sending the same buffer.
In addition, the code:
fgets(buf, 512, stdin);
write(sockfd, buf, sizeof(buf));

reads a line of up to 511 chars from the input, but then sends the entire 512 byte buffer, regardless of how long the actual message is.  What you want is something more like:
if (fgets(buf, 512, stdin))
    write(sockfd, buf, strlen(buf));
else
    break;  // there was an error or EOF on reading from stdin

Of course, this still has issues with lines longer than 511 bytes and then there's the issue that TCP does not preserve message boundaries, so on the server you might get more than one or only part of a message in a single read call.


text:
Q: Wipe usb flash drive ubuntu I have made a bootable USB drive with Ubuntu installer and now I can't delete Ubuntu from it. I tried to use GParted and erased the partition table, made a new ms-dos partition table and formatted the drive as FAT32. Now the name of the drive is still Ubuntu 13.04 amd64 and a couple of files and folders from ubuntu installer are still there(eg: wubi.exe, boot and others). I can't delete them because it is read-only. I also tried the following:
open terminal

sudo fdisk /dev/sdb
  command: n
  partition type: p
  partition number: 1
Now, the minimum value of the first sector is 2048 instead of 62 (the drive has 62 sectors /track)
  Tried with 2048 as first and all remained the same as before.
  I need urgent help, any command or thing that might help. Preferably not stuff like Gutmann wipe :)

A: Note: make sure that you have no needed data on the USB, because this is not reversible.
Just press Ctrl+Alt+T on your keyboard to open Terminal. When it opens, run the command(s) below:
sudo umount -l /dev/sdbx
sudo dd if=/dev/zero of=/dev/sdbx

Replace x with your device ID.
Make sure that you format the drive after that.

A: open disks, unmount your usb stick, format it, done
worked for me

A: I had this exact problem after using a flash drive as an ESXi boot drive. I finally solved it by using the GParted live CD. Nothing else worked for me.


text:
Q: 'libxml/xmlwriter.h' not found after updating to Xcode 7.0.1 and El Capitan I just updated my MacBook to El Capitan and I have now Xcode 7.0.1. When compiling my NS-3 script, I get the following error (I didn't have before the update):
 In file included from ../src/config-store/model/config-store.cc:11:
    ../src/config-store/model/xml-config.h:5:10: fatal error: 'libxml/xmlwriter.h' file not found
    #include <libxml/xmlwriter.h>
             ^
    1 error generated.
    Waf: Leaving directory `/Users/marcogiordani/final-ns3-mmwave-dir/build'
    Build failed
     -> task in 'ns3-config-store' failed (exit status 1):
        {task 4469735696: cxx config-store.cc -> config-store.cc.1.o}
    ['/usr/bin/g++', '-Wall', '-Werror', '-Wno-potentially-evaluated-expression', '-Wno-unused-local-typedefs', '-fPIC', '-I.', '-I..', '-I/usr/include/libxml2', '-DNS3_ASSERT_ENABLE', '-DNS3_LOG_ENABLE', '-DHAVE_SYS_IOCTL_H=1', '-DHAVE_IF_NETS_H=1', '-DHAVE_NET_ETHERNET_H=1', '-DHAVE_SQLITE3=1', '../src/config-store/model/config-store.cc', '-c', '-o', 'src/config-store/model/config-store.cc.1.o']

Any suggestion to this issue?

A: update on this with macOS Mojave: I still had the problem after installing both CLI tools with xcode-select --install and libxml2 / libxslt with brew.
The only thing that fixed the problem was installing missing legacy headers as pointed out here: https://silvae86.github.io/sysadmin/mac/osx/mojave/beta/libxml2/2018/07/05/fixing-missing-headers-for-homebrew-in-mac-osx-mojave.html
Simply run
sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /
and there you go!

A: To whom it may concern, I have just solved the problem by typing on the Terminal:
xcode-select —-install

For some reason, when updating to Xcode 7.0.1, the CommandLineTool hadn't been updated too, so I did it manually. Now everything works fine.


text:
Q: перевод миллисекунд в минуты Здравствуйте! При переводе миллисекунд в минуты, число превышает 60, должно быть меньше 60. Что я делаю не так, подскажите? Спасибо.
private String funMinutes(int arg) {
 String str = null;
 if(TimeUnit.MILLISECONDS.toMinutes(arg) < 10) {
  str = "0" + String.valueOf(TimeUnit.MILLISECONDS.toMinutes(arg));
 }
 else {
  str = String.valueOf(TimeUnit.MILLISECONDS.toMinutes(arg));
 }
 return str;
}

A: Вот так по симпатичнее будет:
private String funMinutes(long arg) {
 return String.format("%02d", TimeUnit.MILLISECONDS.toMinutes(arg));
}

A: Вот такой код прекрасно работает:
public class mainClass
{
    public static void main(String[] args)
    {
        for(long i = 60000; i < 600000; i+=60000)
        System.out.println(funMinutes(i));
    }

    private static String funMinutes(long arg)
    {
        String str = null;
        if (TimeUnit.MILLISECONDS.toMinutes(arg) < 10)
        {
            str = "0" + String.valueOf(TimeUnit.MILLISECONDS.toMinutes(arg));
        }
        else
        {
            str = String.valueOf(TimeUnit.MILLISECONDS.toMinutes(arg));
        }
        return str;
    }
}

Выдает прекрасно:
01
02
03
04
05
06
07
08
09

Я советую поменять параметр у Вас на long (как сделал я). Прорвете подключение пакетов. Отдебажте код. Чудес не бывает.


text:
Q: How to generate PPT in laravel in windows Os? i am generating Powerpoint from my database.It works fine on ubuntu but doesnot display on windows.Only blank ppt is shown .In windows blank ppt is generated.my code is
// Create slide
    $currentSlide = $objPHPPowerPoint->getActiveSlide();

// Create a shape (drawing)
    $shape = $currentSlide->createDrawingShape();
    $shape->setName('PHPPresentation logo')
        ->setDescription('PHPPresentation logo')
        ->setPath(base_path().'/public/images/pp_bg.jpg')
        ->setHeight(36)
        ->setOffsetX(10)
        ->setOffsetY(10);
    $shape->getShadow()->setVisible(true)
        ->setDirection(45)
        ->setDistance(10);

// Create a shape (text)
    $shape = $currentSlide->createRichTextShape()
        ->setHeight(300)
        ->setWidth(600)
        ->setOffsetX(170)
        ->setOffsetY(180);
    $shape->getActiveParagraph()->getAlignment()->setHorizontal( Alignment::HORIZONTAL_CENTER );
    $textRun = $shape->createTextRun('Thank you for using PHPPresentation!');
    $textRun->getFont()->setBold(true)
        ->setSize(60)
        ->setColor( new Color( 'FFE06B20' ) );

    // generate PPT file.
    $oWriterPPTX = IOFactory::createWriter($objPHPPowerPoint, 'PowerPoint2007');
    $oWriterPPTX->save("Proposal $id.ppt");
    $file_url = "Proposal $id.ppt";
    header('Content-Description: File Transfer');
    header('Content-Type: application/vnd.openxmlformats-officedocument.presentationml.presentation');
    header('Content-Disposition: attachment; filename='.basename($file_url));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' .filesize($file_url));

    readfile($file_url);

A: I'm not sure but this is may be issue with you are using font's are not exist/installed into your WinOS system. Try with support font(Your both ubuntu + WinOs). You can read more here about PHPPresentation
 package feature.
Helpful link: Slides show up blank (white) when opening presentation in Powerpoint for Mac 2011
Hope this will help you!


text:
Q: Corona sdk app to put text in a video Is it possible to create an app in corona to put some text in a video and save that new video with the text included?

A: This cannot be done in Corona SDK. It might be possible with Corona Enterprise.


text:
Q: Memory issue in high resolution image loading I have a image gallery application. When a user click a thumbnail of a gallery image it will show the actual high resolution image (nearly 2000x1500). For the faster viewing I have added pre-loading of images.The main problem noticed in this application is
The memory utilization increases substantially in ie8 when viewing the actual high resolution images. I have tested the jQuery lightbox plugin in ie8. Still the issue is light box too.. How can resolve this issue? It it a general issue of ie8 ? If there is any solution available please share with me !

A: If your image format is BMP or PNG then convert into a jpg beacause BMP and PNG image size is much bigger then JPG. i suggest use JPG Image


text:
Q: Oscillation operator of a function Call a function from $[0, 1]$ to itself a box function.
Given any box function $f$, define its oscillation function $Of$ as $$Of(x) = \lim _{d \to 0} \sup _{y, z \in B_d (x)} |f(y) - f(z)| \, .$$ Then $Of(x)$ is itself a box function.

Is it true that for every box function $f$, $OOOf = OOf$?

A: Yes, it is true.
For a function $h(x)$ we denote by $LS(h)$, $LI(h)$ the functions defined as $$LS(h)(x)=\max(h(x),\limsup_{y\to x} h(y)),\\ LI(h)(x)=\min(h(x),\liminf_{y\to x} h(y)).$$
Then $$Og=LS(g)-LI(g).$$
Denote $g(x)=Of(x)$. Note that $g=LS(g)$, i.e. $$g(x)\geqslant \limsup_{y\to x} g(y).$$ Indeed, for any $d>0$ and any $a$ such that $|a-x|<d$, we have $\sup_{y,z\in B_d(x)} |f(y)-f(z)|\geqslant g(a)$, taking limsup in $a\to x$ we get $\limsup_{a\to x} g(a)\leqslant \sup_{y,z\in B_d(x)} |f(y)-f(z)|$, now take limit in $d\to 0$.
So we have $OOf=Og=g-LI(g)$, $OOOf=O(Og)=Og-LI(Og)$. Thus your relation $OOf=OOOf$ rewrites as $LI(Og)=0$. In other words, we should prove that for any $\varepsilon>0$, any $x\in [0,1]$  and and $d>0$ there exists $y\in (x-d,x+d)$ such that $Og(y)<\varepsilon$.  Denote $s=\inf_{(x-d,x+d)} g$ and choose $y\in (x-d,x+d)$ such that $g(y)<s+\varepsilon$. But $LI(g)(y)\geqslant s$ and we conclude that $Og(y)=g(y)-LI(g)(y)<\varepsilon$ as desired.


text:
Q: In Spring MVC, what is the correct configuration for using Jaxb annotations for request body? Currently I have a RESTful service, and I am trying to deserialize a POST request body, that is XML, that is not working. I've tried all solutions out there, but none seem to work. JSON works perfectly with Spring MVC, but getting XML to work is such a pain..
I'm using Spring 5.1.5 version, and using Jaxb for the marshalling and unmarshalling.
The following is what I currently have:
This is my spring mvc configuration:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <context:component-scan base-package="my.project.controllers" />

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter">
                <property name="objectMapper" ref="xmlMapper"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
          p:indentOutput="true"
          p:simpleDateFormat="yyyy-MM-dd"
          p:modulesToInstall="com.fasterxml.jackson.module.paramnames.ParameterNamesModule"/>

    <bean id="xmlMapper" parent="objectMapper" p:createXmlMapper="true"/>
</beans>

These are my pom.xml dependencies:
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.guice</groupId>
            <artifactId>spring-guice</artifactId>
            <version>${spring.guice.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>

        <!-- Logging -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>${sl4j-log4j.version}</version>
        </dependency>

        <!-- Other dependencies -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>${javax.annotation.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>${guice.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.1</version>
        </dependency>

This is my RestController:
@RestController
@RequestMapping("issuance")
public class ProtocolController {

    @Autowired
    private IssuerManager issuerManager;

    @PostMapping(value = "init", produces = "application/xml", consumes = "application/xml")
    public IssuanceMessageAndBoolean initializeIssuance(@RequestBody final IssuancePolicyAndAttributes ipaa) throws CryptoEngineException {
        IssuanceMessageAndBoolean imab = issuerManager.initializeIssuanceProtocol(ipaa);
        return imab;
    }

This is the object that I am trying to deserialize (IssuancePolicyAndAttributes):

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(
    name = "IssuancePolicyAndAttributes",
    namespace = "http://abc4trust.eu/wp2/abcschemav1.0",
    propOrder = {"issuancePolicy", "attribute"}
)
@XmlRootElement(
    name = "IssuancePolicyAndAttributes"
)
public class IssuancePolicyAndAttributes implements Serializable {
    private static final long serialVersionUID = 6699648078303838561L;
    @XmlElement(
        name = "IssuancePolicy",
        namespace = "http://abc4trust.eu/wp2/abcschemav1.0",
        required = true
    )
    protected IssuancePolicy issuancePolicy;
    @XmlElement(
        name = "Attribute",
        namespace = "http://abc4trust.eu/wp2/abcschemav1.0"
    )
    protected List<Attribute> attribute;

    public IssuancePolicyAndAttributes() {
    }

    public IssuancePolicy getIssuancePolicy() {
        return this.issuancePolicy;
    }

    public void setIssuancePolicy(IssuancePolicy value) {
        this.issuancePolicy = value;
    }

    public List<Attribute> getAttribute() {
        if (this.attribute == null) {
            this.attribute = new ArrayList();
        }

        return this.attribute;
    }
}

And this is my XML that I am sending as the request body:
<abc:IssuancePolicyAndAttributes
        xmlns:abc="http://abc4trust.eu/wp2/abcschemav1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://abc4trust.eu/wp2/abcschemav1.0 ../../../../../../../../abc4trust-xml/src/main/resources/xsd/schema.xsd">

    <abc:IssuancePolicy Version="1.0">
        <abc:PresentationPolicy PolicyUID="http://ticketcompany.com/tickets/issuance/policy">
            <abc:Pseudonym Exclusive="true" Scope="http://ticketcompany.com/tickets/vip" Established="false"
                           Alias="#nym"/>
            <abc:Message>
                <abc:Nonce>KNsRu9cGzkaeabogeRVV</abc:Nonce>
                <abc:ApplicationData>
                    <abc:TestApplicationData>
                        <abc:Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                                  xmlns:xs="http://www.w3.org/2001/XMLSchema"
                                  xsi:type="xs:string">Some data
                        </abc:Data>
                    </abc:TestApplicationData>
                </abc:ApplicationData>
            </abc:Message>
        </abc:PresentationPolicy>

        <abc:CredentialTemplate SameKeyBindingAs="#nym">
            <abc:CredentialSpecUID>http://MyFavoriteSoccerTeam/tickets/vip</abc:CredentialSpecUID>
            <abc:IssuerParametersUID>http://ticketcompany/MyFavoriteSoccerTeam/issuance:idemix</abc:IssuerParametersUID>
            <abc:UnknownAttributes/>
        </abc:CredentialTemplate>
    </abc:IssuancePolicy>

    <abc:Attribute>
        <abc:AttributeUID>-5027215341191833963</abc:AttributeUID>
        <abc:AttributeDescription DataType="xs:string" Encoding="urn:abc4trust:1.0:encoding:string:sha-256"
                                  Type="FirstName">
            <abc:FriendlyAttributeName lang="en">first name</abc:FriendlyAttributeName>
            <abc:FriendlyAttributeName lang="da">fornavn</abc:FriendlyAttributeName>
        </abc:AttributeDescription>
        <abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
                            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">John
        </abc:AttributeValue>
    </abc:Attribute>
    <abc:Attribute>
        <abc:AttributeUID>-2715953330829768453</abc:AttributeUID>
        <abc:AttributeDescription DataType="xs:string" Encoding="urn:abc4trust:1.0:encoding:string:sha-256"
                                  Type="LastName">
            <abc:FriendlyAttributeName lang="en">last name</abc:FriendlyAttributeName>
            <abc:FriendlyAttributeName lang="da">efternavn</abc:FriendlyAttributeName>
        </abc:AttributeDescription>
        <abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
                            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">Dow
        </abc:AttributeValue>
    </abc:Attribute>
    <abc:Attribute>
        <abc:AttributeUID>-2231744817504418816</abc:AttributeUID>
        <abc:AttributeDescription DataType="xs:date" Encoding="urn:abc4trust:1.0:encoding:date:unix:signed"
                                  Type="Birthday">
            <abc:FriendlyAttributeName lang="en">birthday</abc:FriendlyAttributeName>
            <abc:FriendlyAttributeName lang="da">fødselsdag</abc:FriendlyAttributeName>
        </abc:AttributeDescription>
        <abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
                            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">1985-05-05Z
        </abc:AttributeValue>
    </abc:Attribute>
    <abc:Attribute>
        <abc:AttributeUID>-2231744817504418826</abc:AttributeUID>
        <abc:AttributeDescription DataType="xs:date" Encoding="urn:abc4trust:1.0:encoding:date:unix:signed"
                                  Type="Matchday">
            <abc:FriendlyAttributeName lang="en">Match day</abc:FriendlyAttributeName>
            <abc:FriendlyAttributeName lang="da">Kamp dag</abc:FriendlyAttributeName>
        </abc:AttributeDescription>
        <abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
                            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">2013-08-07Z
        </abc:AttributeValue>
    </abc:Attribute>
    <abc:Attribute>
        <abc:AttributeUID>-1231744817504418817</abc:AttributeUID>
        <abc:AttributeDescription Type="MemberNumber" DataType="xs:integer"
                                  Encoding="urn:abc4trust:1.0:encoding:integer:unsigned">
            <abc:FriendlyAttributeName lang="en">VIP member id</abc:FriendlyAttributeName>
            <abc:FriendlyAttributeName lang="da">VIP medlems nummer</abc:FriendlyAttributeName>
        </abc:AttributeDescription>
        <abc:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema"
                            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:integer">23784638726
        </abc:AttributeValue>
    </abc:Attribute>
</abc:IssuancePolicyAndAttributes>

When I debug and check the value of the variable ipaa of the RestController, the variable itself is instantiated but all of its members are null, which indicates the unmarshalling is not occurring correctly.
What am I doing wrong?

A: change the name of xml element
@XmlElement(name = "abc:IssuancePolicy", namespace = "http://abc4trust.eu/wp2/abcschemav1.0", required = true)
protected IssuancePolicy issuancePolicy;

@XmlElement(name = "abc:Attribute", namespace = "http://abc4trust.eu/wp2/abcschemav1.0")
protected List<Attribute> attribute;


text:
Q: Why do we need a chain of resistors to increase the voltage? I did a workshop on SMT today and we made this board attached. However, what I don't understand completely is the logic: why do we need 3 resistors to increase the voltage (on the boost part)? What do they do exactly?

A: It's an SMT practice board. ALL of the resistors are 10k, probably because whoever's running the course didn't want to have to stock different values. Therefore, to get a value of 30k, they put three in series.
Sometimes, multiple SMT resistors are put in series for high-voltage circuits because their individual voltage ratings are insufficient. But that isn't an issue in a circuit that outputs 5.5V at most.
BTW, before you reflow the board, you should flip over the resistors that are showing the white side up. It makes no difference functionally, but it makes it easier to inspect the board afterward.

A: I guess you are on about R4,5,6 on the boost converter ?? if so I would think this is a fed back circuit to make sure the output voltage is always correct.
it hard to say for sure as the as the chip is missing. if you can get the part numbers for the chip you can then google it and find the circuit diagram/manual which will tell you what they are for.
good luck!


text:
Q: How to clear RAID "Error Occurred(0)" member disk message? I had a bad SATA cable which caused an "Error Occurred(0)" message to appear on one of the member disks. I replaced the cable and everything works fine now, but the message remains and the RAID logon prompt stays on longer than normal unless I press escape. How do I get rid of this message? I don't see anything in RAID BIOS that would be helpful.

A: Cleared this error using Intel Rapid Storage Technology software.


text:
Q: Display progress bar while compressing video file I have to compress video files. So I used this link http://whaticode.com/tag/audio/ and xuggler for the compression. Now I want to show the progress bar while compressing the video file in javafx.
import java.io.File;
import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.IMediaWriter;
import com.xuggle.mediatool.MediaToolAdapter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.mediatool.event.AudioSamplesEvent;
import com.xuggle.mediatool.event.IAddStreamEvent;
import com.xuggle.mediatool.event.IAudioSamplesEvent;
import com.xuggle.mediatool.event.IVideoPictureEvent;
import com.xuggle.mediatool.event.VideoPictureEvent;
import com.xuggle.xuggler.IAudioResampler;
import com.xuggle.xuggler.IAudioSamples;
import com.xuggle.xuggler.IRational;
import com.xuggle.xuggler.IStreamCoder;
import com.xuggle.xuggler.IVideoPicture;
import com.xuggle.xuggler.IVideoResampler;
import com.xuggle.xuggler.ICodec;

public class ConvertVideo extends MediaToolAdapter implements Runnable{

    private int VIDEO_WIDTH = 640;
     private int VIDEO_HEIGHT = 360;

     private IMediaWriter writer;
     private IMediaReader reader;
     private File outputFile;

     public ConvertVideo(File inputFile, File outputFile) {
     this.outputFile = outputFile;
     reader = ToolFactory.makeReader(inputFile.getAbsolutePath());
     reader.addListener(this);
    }

     private IVideoResampler videoResampler = null;
     private IAudioResampler audioResampler = null;

     @Override
     public void onAddStream(IAddStreamEvent event) {
     int streamIndex = event.getStreamIndex();
     IStreamCoder streamCoder = event.getSource().getContainer().getStream(streamIndex).getStreamCoder();
     if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
     writer.addAudioStream(streamIndex, streamIndex, 2, 44100);
     } else if (streamCoder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
     streamCoder.setWidth(VIDEO_WIDTH);
     streamCoder.setHeight(VIDEO_HEIGHT);
     streamCoder.setBitRate(100);
     streamCoder.setBitRateTolerance(100);
     writer.addVideoStream(streamIndex, streamIndex, ICodec.ID.CODEC_ID_H264,IRational.make((double)15),VIDEO_WIDTH, VIDEO_HEIGHT);
     }
     super.onAddStream(event);
     }

     @Override
     public void onVideoPicture(IVideoPictureEvent event) {
     IVideoPicture pic = event.getPicture();
     if (videoResampler == null) {
     videoResampler = IVideoResampler.make(VIDEO_WIDTH, VIDEO_HEIGHT, pic.getPixelType(), pic.getWidth(), pic.getHeight(), pic.getPixelType());
     }
     IVideoPicture out = IVideoPicture.make(pic.getPixelType(), VIDEO_WIDTH, VIDEO_HEIGHT);
     videoResampler.resample(out, pic);

     IVideoPictureEvent asc = new VideoPictureEvent(event.getSource(), out, event.getStreamIndex());
     super.onVideoPicture(asc);
     out.delete();
     }

     @Override
     public void onAudioSamples(IAudioSamplesEvent event) {
     IAudioSamples samples = event.getAudioSamples();
     if (audioResampler == null) {
     audioResampler = IAudioResampler.make(2, samples.getChannels(), 44100, samples.getSampleRate());
     }
     if (event.getAudioSamples().getNumSamples() > 0) {
     IAudioSamples out = IAudioSamples.make(samples.getNumSamples(), samples.getChannels());
     audioResampler.resample(out, samples, samples.getNumSamples());

     AudioSamplesEvent asc = new AudioSamplesEvent(event.getSource(), out, event.getStreamIndex());
     super.onAudioSamples(asc);
     out.delete();
     }
     }

     public void run() {
     writer = ToolFactory.makeWriter(outputFile.getAbsolutePath(), reader);
     this.addListener(writer);
     while (reader.readPacket() == null) {
         System.out.println("Converting file..");
     }
     }

     public static void main(String[] args) {

            try {
                System.out.println("Converting process started");
                File file = new File("C:\\Development\\1.mp4");
                file.createNewFile();

                ConvertVideo obj = new ConvertVideo(new File("C:\\Development\\camera 1_record_1417702745727.wmv"),file);

                obj.run();
                System.out.println("Converting process end");
            } catch (Exception e) {

                e.printStackTrace();
            }

        }
}

Thanks for any help!

A: I would suggest that you read this doc from oracle. It describes the basics of Concurrency in JavaFX.

A: *

*Use a Task or a Service instead of a Runnable.

*Use Task.updateProgress() to inform on the current progress / work done.

*Bind the progressProperty of your running Task to a ProgressBar or ProgressIndicator.


text:
Q: Search files from a list for a string I have a directory of text files, and each of those files contains a line "Feature Number: " followed by some number. I also have another text file with a list of the file names in the order I want to search them. I tried the following bash command:
while read LINE; do
  grep -i 'feature number' $LINE > outputFile.txt
done < ../listOfFiles.txt

but never receive any output.
grep -f ../listOfFiles.txt p*.txt doesn't return anything either, but
read LINE < ../listOfFiles.txt; echo $LINE does, and
grep -i 'feature number' oneOfTheFiles.txt does.
Which part of the command isn't working, and how do I fix it?

A: To provide an answer that summarizes all the helpful hints in the comments on the question:
@fedorqui points out that by using > inside the loop, you overwrite the output file in every iteration of the loop, so that in effect only the last iteration's output is captured in the output file.
An immediate fix is to use >> instead, which appends to an existing output file (or creates it, if it doesn't exist).
while read -r LINE; do
  grep -i 'feature number' "$LINE" >> outputFile.txt
done < ../listOfFiles.txt

Note that I've also made the snippet more robust:

*

*read -r ensures that input lines are read without interpretation of \ chars. - leading and trailing whitespace is trimmed from each line, however.

*"$LINE" is now double-quoted to protect it from expansions by the shell; this is necessary, for instance, if the variable value contains spaces.

However, >> appends to any preexisting outputFile.txt, so if you ran the snippet multiple times, for instance, the file would keep growing.

To prevent that, you can either explicitly truncate (: >outputFile.txt) or remove (rm -f outputFile.txt) the output file beforehand, or, preferably, take advantage of the simplification recommended by @konsoelbox:
while read -r LINE; do
  grep -i 'feature number' "$LINE"
done < ../listOfFiles.txt > outputFile.txt

By placing the output redirection - with > - at the end of the while loop, output from all iterations is captured as a whole, while replacing any preexisting file.

Finally, @tripleee suggests a more radical simplification that uses xargs instead of a while loop:
xargs grep -h -i 'feature number' < ../listOfFiles.txt > outputFile.txt

This will (typically) result in a single invocation of grep with all input lines passed as filename arguments.
Aside from being shorter to write, this approach is much more efficient.
Note the use of grep -h, which suppress prefixing of matches with the name of the originating file.
Caveat: This works fine as long as the filenames in ../listOfFiles.txt have no embedded spaces, as each such filename would be split into multiple arguments.
To handle filenames with embedded spaces correctly:

*

*If you have GNU xargs, use -d'\n' to ensure that each line is considered its own argument when passed to grep:
xargs -d'\n' grep -h -i 'feature number' < ../listOfFiles.txt > outputFile.txt

*If you only have a POSIX-compliant xargs: use -I, which, however, means that grep is invoked once for each input line.
xargs -I % grep -i 'feature number' % < ../listOfFiles.txt > outputFile.txt

*Finally, if you have an xargs version that supports -0 for processing NUL-separated input (e.g., GNU xargs, FreeBSD (OSX) xargs), you can use the following trick:
xargs -0 grep -h -i 'feature number' \
   < <(tr '\n' '\0' < ../listOfFiles.txt) > outputFile.txt

Note that the -0-based approach is generally the most robust one, as it even supports arguments with embedded \n chars., but NUL-separated input isn't always readily available, as the need for the tr trick demonstrates.

A: The grep command should be like this:
grep -inr "search string"