text:
Q: How to use zsh tab completion on Git without origin? I am using zsh with oh-my-zsh on Ubuntu 18.04.2. Currently, Git is installed at version 2.20.1.
Whenever I want to checkout a local branch from a remote (origin) I try to use the tab completion in the shell as follows:
git checkout fea<TAB>

The tab completion results in:
git checkout origin/feature

What I actually expect from the tab completion is:
git checkout feature

How can I configure the tab completion to correctly (?) complete the remote branch - or am I missing something? My dotfiles are public.

Reply to the comment from Tarun Lalwani: The output of git branch -a is:

develop
  * housekeeping
    remotes/origin/HEAD -> origin/develop
    remotes/origin/develop
    remotes/origin/master
    remotes/origin/release
    remotes/origin/feature

A: After thorough research, it turns out that completion of git checkout under ZSH is not fulfilled by oh-my-zsh, but from the _git function provided with the shell facilities.
As stated in the comments, I couldn't reproduce the issue you experienced. Everything seems to work as expected. Nevertheless…
Check out the following file:
/usr/share/zsh/<5.x>/functions/_git

My local zsh version is 5.2. Around row 450, you can see:
  case $state in
    (branch-or-tree-ish-or-file)
      # TODO: Something about *:: brings us here when we complete at "-".  I
      # guess that this makes sense in a way, as we might want to treat it as
      # an argument, but I can't find anything in the documentation about this
      # behavior.
      [[ $line[CURRENT] = -* ]] && return
      if (( CURRENT == 1 )) && [[ -z $opt_args[(I)--] ]]; then
        # TODO: Allow A...B
        local branch_arg='' \
              remote_branch_noprefix_arg='remote branches::__git_remote_branch_names_noprefix' \
              tree_ish_arg='tree-ishs::__git_tree_ishs' \
              file_arg='modified-files::__git_modified_files'

        if [[ -n ${opt_args[(I)-b|-B|--orphan|--detach]} ]]; then
          remote_branch_noprefix_arg=
          file_arg=
        elif [[ -n $opt_args[(I)--track] ]]; then
          branch_arg='remote-branches::__git_remote_branch_names'
          remote_branch_noprefix_arg=
          tree_ish_arg=
          file_arg=
        elif [[ -n ${opt_args[(I)--ours|--theirs|-m|--conflict|--patch]} ]]; then
          remote_branch_noprefix_arg=
        fi

        _alternative \
          $branch_arg \
          $remote_branch_noprefix_arg \
          $tree_ish_arg \
          $file_arg && ret=0

Removing one of the arrays passed to _alternative changes what's suggested to you when completing a branch name after git checkout. In particular, removing $remote_branch_noprefix_arg brings back remote branch names prefixed with origin or their respective remote repository name.
Therefore, upgrading your shell or downgrading to a former version may be a good idea.
Some details yet:

*

*I saw you've edited your original post and git push have good reasons to work slightly differently than git checkout ;

*The homolog local branch of a remote one may not forcibly exists: feature is different from origin/feature, even when the former one, when it exists, is generally configured to track the latter ;

*By default, if the local branch doesn't exist yet and when no explicit options are passed aside, checking out feature will create an eponym local branch configured to track the remote one, then switch to it, while checking out origin/feature will put you in detached mode, allowing to browse this remote branch but directly commit on top of it.

A: Note that since Git 2.23, you would use git switch instead of the confusing git checkout
And... before Git 2.27 (Q2 2020), the zsh command line completion would not work for git switch!
See commit 051cc54 (17 Apr 2020) by Terry Moschou (tmoschou).
(Merged by Junio C Hamano -- gitster -- in commit 7d96ac1, 28 Apr 2020)

complete: zsh: add missing sub cmd completion candidates
Signed-off-by: Terry Moschou

Add missing 'restore' and 'switch' sub commands to zsh completion candidate output. E.g.
$ git re<tab>
rebase    -- forward-port local commits to the updated upstream head
reset     -- reset current HEAD to the specified state
restore   -- restore working tree files

$ git s<tab>
show      -- show various types of objects
status    -- show the working tree status
switch    -- switch branches

And, with Git 2.28 (Q3 2020), the command line completion (in contrib/) learned to complete options that the "git switch" command takes.
See commit 9143992, commit acb658f, commit 00e7bd2, commit 6d76a5c, commit 68d97c7, commit 4e79adf, commit 6880779, commit 58a2ca3, commit 0408c6b, commit c81ca56, commit 7f59d60, commit b07d77a, commit c55b99c, commit e69fb0a, commit ab58e90, commit fab466f (28 May 2020) by Jacob Keller (jacob-keller).
(Merged by Junio C Hamano -- gitster -- in commit 3204218, 25 Jun 2020)
Example:

completion: improve handling of --detach in checkout
Signed-off-by: Jacob Keller
Just like git switch, we should not complete DWIM remote branch names if --detach has been specified. To avoid this, refactor _git_checkout in a similar way to _git_switch.
Note that we don't simply clear dwim_opt when we find -d or --detach, as we will be adding other modes and checks, making this flow easier to follow.
Update the previously failing tests to show that the breakage has been resolved.


text:
Q: Database Derived Value same as foreign key? Is database derived value the same as foreign key?
Based on connoly and begg books, fourth edition page 352 derived value is
An attribute that represents a value that is derivable from the value of a related attribute or set of attributes, not necessarily in the same entity type.
If we have 2 table such as, CUSTOMER and ORDER,
Customer
- Id_Cust
- Name
- Phone

ORDER
- Order_id<
- id_cust

Can we say "ORDER.id_cust is derived from Customer.id_cust" ?
Actually, I'm really confused about the concept above.

A: No, foreign keys and derived values are two different things.
product  quantity  price  subtotal
--
ACH123   5         $1.50  $7.50

In the simplified table above, "subtotal" is a derived value. It's derived from "quantity" and "price". (By multiplying them together.)
Database designers usually don't store derived values without using a CHECK() constraint or a trigger to make sure the derived value is always correct. In the table above, updating the quantity to 4 would make the derived value "subtotal" incorrect. A CHECK() constraint can prevent an update to "quantity" unless the update also has the correct value for "subtotal".  A trigger can automatically update "subtotal" when either "quantity" or "price" changes.
CHECK() constraints are usually a better choice.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does UnityEvent creates a dependency on the scripts called I know that we should avoid scripts to be dependent of each other. That's why I'm wondering if putting a script in a UnityEvent in the Inspector makes the script which owns this UnityEvent, dependent on the one called.
For instance, I have a script ScriptWithEvent.cs which has a UnityEvent. In the inspector I add an event to this UnityEvent which calls the method Open() inside an other script OtherScript.cs. Inside this script I have another method which changes a component active state linked to a GameObject containing ScriptWithEvent.cs or a public variable inside ScriptWithEvent.cs.
Does this make ScriptWithEvent.cs and OtherScript.cs dependent on each other ?
Does UnityEvent creates a dependency on the scripts we make it call ?

A: No it does not, UnityEvent takes a UnityAction which is a pointer to a method.
The script holding the UnityEvent does not know about the type of the method holder nor does it know about the content of the method. In the same way, a C# event would not know about the registered method, only that they need to match the delegate signature.
Your UnityEvent is a list of addresses where to find the methods to be run when invoke is called. But it is totally oblivious to what type it is stored in.
The only dependency for UnityEvent is that the method has to be stored in a MonoBehaviour and the method signature has some limitations.
UnityEvent has this advantage over normal C# event, in the latter the subscriber would need to find out how to register to the type or interface
UnityEvent via inspector removes that dependency as you can drag anything.


text:
Q: Error: Installing SciPy in Windows 10 64bit using pip (Python 3.5.2) I want to install SciPy package in my system through pip (command line). It is a Windows 10 64-bit system. I have installed Python 3.5.2. I have already installed other Machine Learning and statistical packages like numpy, sklearn, pandas, matplotlib, sympy, jupyter, ipython and nose. They have all installed successfully without any errors.
I am using this command to install scipy from pip:

C:\Projects\Kaggle>pip install scipy

But while installing scipy, I am getting this error:

C:\Projects\Kaggle>pip install scipy Collecting scipy   Using cached
  scipy-0.18.1.tar.gz Installing collected packages: scipy   Running
  setup.py install for scipy ... error
      Complete output from command c:\users\i319268\appdata\local\programs\python\python35\python.exe -u
  -c "import setuptools, tokenize;file='C:\Users\i319268\AppData\Local\Temp\pip-build-b1nkbg30\scipy\setup.py';f=getattr(tokenize,
  'open', open)(file);code=f.read().replace('\r\n',
  '\n');f.close();exec(compile(code, file, 'exec'))" install
  --record C:\Users\i319268\AppData\Local\Temp\pip-06bz__e6-record\install-record.txt
  --single-version-externally-managed --compile:
Note: if you need reliable uninstall behavior, then install
with pip instead of using `setup.py install`:

  - `pip install .`       (from a git repo or downloaded source
                           release)
  - `pip install scipy`   (last SciPy release on PyPI)

lapack_opt_info:
openblas_lapack_info:
  libraries openblas not found in ['c:\\users\\i319268\\appdata\\local\\programs\\python\\python35\\lib',

'C:\',
  'c:\users\i319268\appdata\local\programs\python\python35\libs']
        NOT AVAILABLE
lapack_mkl_info:
  libraries mkl_rt not found in ['c:\\users\\i319268\\appdata\\local\\programs\\python\\python35\\lib',

'C:\',
  'c:\users\i319268\appdata\local\programs\python\python35\libs']
        NOT AVAILABLE
atlas_3_10_threads_info:
Setting PTATLAS=ATLAS
c:\users\i319268\appdata\local\programs\python\python35\lib\site-packages\numpy\distutils\system_info.py:639:

UserWarning: Specified path
  C:\projects\numpy-wheels\windows-wheel-builder\atlas-builds\atlas-3.11.38-sse2-64\lib
  is invalid.
        warnings.warn('Specified path %s is invalid.' % d)

        NOT AVAILABLE
atlas_3_10_info:
<class 'numpy.distutils.system_info.atlas_3_10_info'>
  NOT AVAILABLE

atlas_threads_info:
Setting PTATLAS=ATLAS
<class 'numpy.distutils.system_info.atlas_threads_info'>
  NOT AVAILABLE

atlas_info:
<class 'numpy.distutils.system_info.atlas_info'>
  NOT AVAILABLE

c:\users\i319268\appdata\local\programs\python\python35\lib\site-packages\numpy\distutils\system_info.py:1532:

UserWarning:
          Atlas (http://math-atlas.sourceforge.net/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [atlas]) or by setting
          the ATLAS environment variable.
        warnings.warn(AtlasNotFoundError.doc)
      lapack_info:
        libraries lapack not found in ['c:\users\i319268\appdata\local\programs\python\python35\lib',
  'C:\',
  'c:\users\i319268\appdata\local\programs\python\python35\libs']
        NOT AVAILABLE
c:\users\i319268\appdata\local\programs\python\python35\lib\site-packages\numpy\distutils\system_info.py:1543:

UserWarning:
          Lapack (http://www.netlib.org/lapack/) libraries not found.
          Directories to search for the libraries can be specified in the
          numpy/distutils/site.cfg file (section [lapack]) or by setting
          the LAPACK environment variable.
        warnings.warn(LapackNotFoundError.doc)
      lapack_src_info:
        NOT AVAILABLE
c:\users\i319268\appdata\local\programs\python\python35\lib\site-packages\numpy\distutils\system_info.py:1546:

UserWarning:
          Lapack sources not found.
          Directories to search for the sources can be specified in the
          numpy/distutils/site.cfg file (section [lapack_src]) or by setting
          the LAPACK_SRC environment variable.
        warnings.warn(LapackSrcNotFoundError.doc)
        NOT AVAILABLE
Running from scipy source directory.
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\i319268\AppData\Local\Temp\pip-build-b1nkbg30\scipy\setup.py",

line 415, in
          setup_package()
        File "C:\Users\i319268\AppData\Local\Temp\pip-build-b1nkbg30\scipy\setup.py",
  line 411, in setup_package
          setup(**metadata)
        File "c:\users\i319268\appdata\local\programs\python\python35\lib\site-packages\numpy\distutils\core.py",
  line 135, in setup
          config = configuration()
        File "C:\Users\i319268\AppData\Local\Temp\pip-build-b1nkbg30\scipy\setup.py",
  line 335, in configuration
          config.add_subpackage('scipy')
        File "c:\users\i319268\appdata\local\programs\python\python35\lib\site-packages\numpy\distutils\misc_util.py",
  line 1000, in add_subpackage
          caller_level = 2)
        File "c:\users\i319268\appdata\local\programs\python\python35\lib\site-packages\numpy\distutils\misc_util.py",
  line 969, in get_subpackage
          caller_level = caller_level + 1)
        File "c:\users\i319268\appdata\local\programs\python\python35\lib\site-packages\numpy\distutils\misc_util.py",
  line 906, in _get_configuration_from_setup_py
          config = setup_module.configuration(*args)
        File "scipy\setup.py", line 15, in configuration
          config.add_subpackage('linalg')
        File "c:\users\i319268\appdata\local\programs\python\python35\lib\site-packages\numpy\distutils\misc_util.py",
  line 1000, in add_subpackage
          caller_level = 2)
        File "c:\users\i319268\appdata\local\programs\python\python35\lib\site-packages\numpy\distutils\misc_util.py",
  line 969, in get_subpackage
          caller_level = caller_level + 1)
        File "c:\users\i319268\appdata\local\programs\python\python35\lib\site-packages\numpy\distutils\misc_util.py",
  line 906, in _get_configuration_from_setup_py
          config = setup_module.configuration(*args)
        File "scipy\linalg\setup.py", line 20, in configuration
          raise NotFoundError('no lapack/blas resources found')
      numpy.distutils.system_info.NotFoundError: no lapack/blas resources found
---------------------------------------- Command "c:\users\i319268\appdata\local\programs\python\python35\python.exe -u

-c "import setuptools, tokenize;file='C:\Users\i319268\AppData\Local\Temp\pip-build-b1nkbg30\scipy\setup.py';f=getattr(tokenize,
  'open', open)(file);code=f.read().replace('\r\n',
  '\n');f.close();exec(compile(code, file, 'exec'))" install
  --record C:\Users\i319268\AppData\Local\Temp\pip-06bz__e6-record\install-record.txt
  --single-version-externally-managed --compile" failed with error code 1 in C:\Users\i319268\AppData\Local\Temp\pip-build-b1nkbg30\scipy\

I have also tried the unofficial SciPy wheel packages from Christoph Gohlke. When I try to install from his wheel packages, it gives an error like this:

C:\Projects\Kaggle>pip install scipy-0.18.1-cp36-cp36m-win32.whl
scipy-0.18.1-cp36-cp36m-win32.whl is not a supported wheel on this
platform.

I have already looked at StackOverflow for answers but I am completely stuck and unable to figure out anything. Any help will be appreciated. Thanks in advance.

A: This has been solved. Thanks to @BrenBarn's help above in the comments I got everything up and running now.
The best way to get everything working in to use the wheel packages from Christoph Gohlke.
However, the main thing to note here is that you should use all the packages you want from his unofficial packages only as a number of packages might be dependent on other wheel packages. The other thing that one needs to keep in mind is to choose the proper version of the wheel packages (32bit or 64bit and the correct version of python as well [mainly mentioned in the wheel package name as cp]).
For example,
SciPy wheel package for 64bit system and Python 3.6: scipy‑0.18.1‑cp36‑cp36m‑win_amd64.whl

SciPy wheel package for 32bit system and Python 2.7: scipy‑0.18.1‑cp27‑cp27m‑win32.whl

Hope this will be helpful to others as well. Thanks for the help again @BrenBarn.


text:
Q: using material box for card images I am trying to use material box for card images. My target is to click on card image and view it fullscreen.

      ${movie.title + " - " + movie.imdbRating}more_vert

${movie.genre.join(', ')}

      ${movie.title}close

${movie.director}

${movie.genre.join(', ')}

${movie.actors.join(', ')}

${movie.plot}

The problem is that it could not make the image container bigger. So the image will be zoomed but because the container is small it couldn't show all of the image.

A: It was an issue an fixed in their last commit:
https://github.com/Dogfalo/materialize/issues/2091


text:
Q: Passing Data TextView Using Protocol I have two view controller ...
The ViewController 1 has a label which should show the text entered through a TextView.
the ViewController 2 has a TextView that passes the text to the label of the ViewController 1
To do this I used the protocols in this way
Header File VC2.h
@protocol TransferTextViewDelegate <NSObject>
-(void)PassedData:(NSString *)text;

@end

@interface VC2 : UIViewController <UITextViewDelegate>

@property (nonatomic, weak)id <TransferTextViewDelegate> delegate;

@property (strong, nonatomic) IBOutlet UITextView *FFTextView;
@property (strong, nonatomic) NSString *title;

- (IBAction)sendTextViewcontent:(id)sender;

@end

In the Implementation File VC2.m
#import "VC2.h"
#import "VC1.h"

@interface VC2 ()

@end

@implementation VC2
@synthesize FFTextView;
@synthesize delegate;
@synthesize title;

- (void)viewDidLoad {
    [super viewDidLoad];
    [FFTextView becomeFirstResponder];
    FFTextView.delegate = self;
}

- (IBAction)sendTextViewcontent:(id)sender {

    if (delegate) {
        title = FFTextView.text;
        [delegate PassedData:title];
    }

    [self dismissViewControllerAnimated:YES completion:nil];

}

@end

In the ViewController 1, like I said, this is a UILabel which should show the text entered in the TextView of the ViewController 2
Implementation File VC1.m
-(void)viewWillAppear:(BOOL)animated {
    TitoloAnnuncio.text = TitoloAnnuncioInserito;
}

-(void)PassedData:(NSString *)text {
    TitoloAnnuncioInserito = text;
}

In The Header File VC1.h implemented this property:
@property (strong, nonatomic) IBOutlet UILabel *TitoloAnnuncio;
@property (strong, nonatomic) NSString *TitoloAnnuncioInserito;

My problem is that I can not understand why my label does not show the text .. It remains empty ... I can not pass data from ViewController 2 in 1 ViewController
Can you help?

A: Leaving aside the issue of naming variables with an initial lower case letter...
You are setting a string value in the delegate method, however, iOS is not OS X, there are not bindings, so just changing the value of the property does not automatically change the value displayed in the textfield.
You have a couple of options, one is to update the display in the delegate method.
- (void)PassedData:(NSString *)text {
    TitoloAnnuncioInserito = text;
    TitoloAnnuncio.text = TitoloAnnuncioInserito;
}

Another way is to set the display in the label whenever the property value changes - which is a bit more robust.
- setTitoloAnnuncioInserito:(NSString *)string {
    _TitoloAnnuncioInserito = string;
    self.TitoloAnnuncio.text = string;
}

And with this you can change the delegate method to:
- (void)PassedData:(NSString *)text {
    self.TitoloAnnuncioInserito = text;
}


text:
Q: Validate Textbox Javascript Here is the following code, I am learning Javascript on my own and wanted to know how I could validate my code to make the textboxes say something like "please enter a value" or "please enter a valid Username or password.
I've attempted, but this is as far as online searching that I have done for it.

      <title>Login Form</title>
      <link rel="stylesheet" href="css/style.css"/>

Login

          <form method="post" action="index.xhtml">

<input type="text" name="login" value="" id="Username or Email" />

<input type="password" name="password" value="" id="Password"/>

                <input type="checkbox" name="remember_me" id="remember_me"/>
                Remember me on this computer

<input type="submit" name="commit" value="Login" onchange="nullcheck()"/><button type="reset" value="Clear">Clear</button>

          </form>

    </htm

A: You can validate items one at a time, but a more general solution is to write a validate() function.  Make your form element look like this:
<form method="post" action="index.xhtml" onsubmit="return validate();">

If the validate() function returns false, the form will not be submitted.  It is up to the validate() function to issue prompts, etc.
Sample function:
function validate() {
var error = false,
    errmsg="";
    if(document.getElementById("username").value==="") {
       error = true;
       errmsg = "User name may not be blank.\n";
    }
    if(document.getElementById("password").value==="") {
       error = true;
       errmsg = "Password may not be blank.\n";
    }
    if (error) {
       alert(errmsg);
       return false;
    } else {
       return true;
    }
} // validate


text:
Q: PHP to html template without template manager Here I am again... I've been watching some tutorials and I'm now in good way on php programing...
What I want to know is: with a template manager like for example smarty, you can make 1 php page with the code and redirect it to the view html file... something like this on the php...
$a = new Trabalhos();
$id = new Users();
$sm->assign("id", $a->select());

if (isset($_GET['del'])) {
    $a->setId($_GET['del']);
    $a->delete();
}

if (isset($_POST['id'])
        and isset ($_POST['trolha'])
        and isset($_POST['padeiro'])
        and isset($_POST['arquitecto'])
        and isset($_POST['engenheiro'])
        and isset($_POST['medico'])
        and ! isset($_GET['edit'])) {
    $a->setId($_POST['id']);
    $a->setTrolha($_POST['trolha']);
    $a->setPadeiro($_POST['padeiro']);
    $a->setArquitecto($_POST['arquitecto']);
    $a->setEngenheiro($_POST['engenheiro']);
    $a->setMedico($_POST['medico']);
    $a->insert();
}

$lista = $a->select();
$sm->assign("lista", $lista);
$sm->display("trabalhos.html");

Then I make the view page in trabalhos.html and I put this:
<form method="post">
            | id <select name ="id">
                {foreach from=$id item=d}
                <option value ="{$d.id}">{$d.id}</option>
                {/foreach}
            </select>
            | Trolha <input name ="trolha" type="text" />
            | Padeiro <input name ="padeiro" type="text" />
            | Arquitecto <input name ="arquitecto" type="text" />
            | Engenheiro <input name ="engenheiro" type="text" />
            | Medico <input name ="medico" type="text" />
            <input type="submit" value="Guardar"/>
        </form>

                ID
                Trolha
                Padeiro
                Arquitecto
                Engenheiro
                Medico
                Acoes

            {foreach from = $lista item = row}

                {$row.id}
                {$row.trolha}
                {$row.padeiro}
                {$row.arquitecto}
                {$row.engenheiro}
                {$row.medico}
                Edit | Delete

            {/foreach}

OK till there I get it and I make it work with the help of the tutorial and giving my variables
Now what I really want to know is how can I do the same without the help of external template managers, everyone will say that is easier with this and that, but I'm looking to learn php, not to run pre-made scripts, if you know what I mean
Right now I don't trust on external code... to trust it I need to understand it
So if they made it work with smarty I have to make it work by myself right?
Is there need of other languages out of php to do it? like java or something similar?
Or can I do it just with php and html coding?
If is possible to do it just with php and html coding can anyone tell me for example how will I make that column with the foreach php function work? And how do I transmit to the html the variables info?
Really sorry for that huge post, but I didn't see anything like what I'm asking in here and on google i just see people and forums talking about template managers, and that's not what I'm looking for ;)
Thank you very much for the answers last post got a positive one ;)

A: Trying to write your own template engine is a hard task. But you can do it in plain PHP, not need for other language.
Basically, your template engine will need 2 things in order to work:

*

*Templates. Your trabalhos.html file is a template. It's a HTML file that contains special placeholders (like {$d.id}) that have a particular meaning for your template engine.

*Variables. If you want to do something useful with your templates, you must provides variables to work with (this is what you do with an instruction like this $a->setId($_POST['id']);).

Now what you need to do is write some code that is able to parse your template files (recognize the placeholders you defined) and work with them. This is quite easy to do if you only need to replace placeholders with the value of a variable but will get tricky as soon as you start to implement features a little more complex like loops.
In addition to that, you also need to write some code that enables you to bind values to your variables as well as objects to store these.
This is a huge job but if your aim is to learn PHP, it's a really good way. Good luck!

A: You can use file write function.
$file = fopen("trabalhos.html","w");
fwrite($file,$lista);
fclose($file);


text:
Q: Parsing html in with BeautifulSoup fails to find a table I am trying to parse the data in this website:
http://www.baseball-reference.com/boxes/CHN/CHN201606020.shtml
I want to extract some of the data in the tables. But for some reason, I am struggling to find them. For example, what I want to do is this
from bs4 import BeautifulSoup
import requests

url = 'http://www.baseball-reference.com/boxes/CHN/CHN201606020.shtml'
soup = BeautifulSoup(requests.get(url).text)
soup.find('table', id='ChicagoCubsbatting')

The final line returns nothing despite a table with that id existing in the html. Furthermore, len(soup.findAll('table')) returns 1 even though there are many tables in the page. I've tried using the 'lxml', 'html.parser' and 'html5lib'. All behave the same way.
What is going on? Why does this not work and what can I do to extract the table?

A: use soup.find('div', class_='placeholder').next_sibling.next_sibling to get the comment text, then build a new soup using those text.
In [35]: new_soup = BeautifulSoup(text, 'lxml')

In [36]: new_soup.table
Out[36]:

SFG
6

Final

ATL
0

</table


text:
Q: MSMQ Server error I am configuring, turning windows features, on Windows 7 for MSMQ, but after I checked all the child nodes under the MSMQ, I am having an error, all features are not installed successfully.
I tried installing Microsoft Fix, for updates, but that did not fix it.
How can I resolve this problem ?


text:
Q: Authentication with Gitblit as Plug-in in Gerrit I have a Gerrit installation on ubuntu which uses HTTP Authentication with an apache2.
As a viewer we would like to use Gitblit as a plug-in in Gerrit.
I found already the plugin here here and I followed the install instruction there.
Since all other plugins in Gerrit works properly, like blabla.com/gerrit/plugins/gitiles/ or some other, I always get a log-in request when I try to browse to blabla.com/gerrit/plugins/gitblit/ (Also the documentation folder).
I think I have anything wrong or missing in the apache2 configuration, but I don't found the right so far.
After installation of the apache2 for Gerrit (by this guide) I haven't touched the apache2.conf, I just added a gerrit.conf in the mods-enable subfolder of apache2 with this content:
ProxyPass           /gerrit  http://localhost:8081/gerrit nocanon
ProxyPassReverse    /gerrit  http://localhost:8081/gerrit nocanon
ProxyRequests       Off

<Proxy http://localhost:8081/gerrit>
  Order deny,allow
  Allow from all
</Proxy>

<Location /gerrit>
  AuthType Digest
  AuthName "gerrit"
  AuthUserFile /etc/apache2/.htdigest
  Require valid-user
</Location>

When I access Gerrit using our address/gerrit I get asked for the permission which we added using htdigest in the first place.
Any Idea what's wrong? Why Gitblit is ask for a log-in and doesn't accept any?
(I'm new in Apache authentication at all)

A: http://gitblit.com/setup_authentication.html
Gitblit only support authtype below:
LDAP authentication
Windows authentication
PAM authentication
Htpasswd authentication
HTTP header authentication
Redmine auhentication
Salesforce.com authentication
Servlet container authentication

But your auth type is Digest, you can try switching auth type to htpasswd by the below steps:

*

*add a new auth file
sudo htpasswd -c /etc/apache2/.htpasswd log_name_xxx

*modify your gerrit.conf in /etc/apache2/...

  AuthType Basic
  AuthName "gerrit"
  AuthUserFile /etc/apache2/.htpasswd
  Require valid-user

*restart apache2
sudo service apache2 restart
Please let me know if there is any other problem.
Hope it useful. Ahhhhh


text:
Q: Error "No such module" when installed framework with pod in swift 3 I had manually added Alamofire, realm and swiftjson framework in my swift project. At that time my project was working properly.
Now I created a Podfile in my project directory and added the following pods
pod 'Alamofire'
pod 'RealmSwift'
pod 'SwiftyJSON'

It is successfully installed.
I opened .xcworkspace and tried to import the framework. But is showing error message "No such module Realmswift", "No such module Alamofire", "No such module SwiftyJson".
Framework search paths are as follows:
$(inherited)
$(PROJECT_DIR)/app_name/Frameworks
$(PROJECT_DIR)

Even "Build Active Architecture Only" is set to NO.
How can I resolve this problem?

A: Set Build Active Architectures Only to No in Pods subproject also. It works for me!

A: Did you run pod install in your project directory?


text:
Q: ReferenceError: window is not defined when using mergeImages in express.js I'm using mergeImages on my express.js server but I'm getting error of "ReferenceError: window is not defined". I don't know what it's saying. Even I haven't used window word in my code.
Please check my code of server.js. at the end of the code I have mergeimage function.
const express = require('express');
const app = express();
const fs = require('fs');
const mergeImages = require('merge-images');
const bodyParser = require('body-parser');
const multer = require('multer');
const { response } = require('express');
const cors = require('cors');

app.use(cors());

app.use(express.static(__dirname + '/public'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get('/', (req,res) => {
    res.send('this is express!');
})

app.listen(8000, (err) =>{
    if(err) console.log(err);
    console.log('Server Started please listen to port: 8000');
})

app.get('/get-image', function(req,res,next){
    const pixel_base_value = 1.31;
    const top_margin = 5;
    const left_margin = 3;
    var photo_frame = [];
    for(var j = 1; j <= req.query.row; j++){
      var total_width_check = 0;
      var total_height_check = 0;
      for(var k= 1; k <= req.query.col; k++){
          var height_cal =  req.query.photo_height*pixel_base_value;

          var width_cal = req.query.photo_width*pixel_base_value;

          if(j !== 1){
              var top1 = top_margin + height_cal + 3;
          }else{
              top1 = top_margin;
          }
          if(k !== 1){
              var left1 =  (width_cal * (k-1) + (left_margin * k));
          }else{
              left1 = left_margin;
          }
          total_width_check = total_width_check + req.query.photo_width*pixel_base_value + left_margin;

          total_height_check = total_height_check + req.query.photo_height*pixel_base_value + top_margin;

          if(total_width_check >= req.query.board_width*pixel_base_value-3 && total_height_check >= req.query.board_height*pixel_base_value-3){

          }else{
              photo_frame.push({src:'http://localhost:8000/image/'+ req.query.img_name +'', x: left1, y: top1, width: width_cal, height: height_cal});
          }
      }
      total_width_check = 0;
  }
  //check photo_frame is a valid Array
  mergeImages(photo_frame).then((b64) =>{ //add options here for canvas
    console.log(b64)
  },(error) =>{
    console.log(error);
  } );
  return res.end('done');
})

Please help!
Thanks!

A: I think for node usage, you should add node-canvas and pass it via option object. Currently, you are not using the canvas.
const mergeImages = require('merge-images');
const { Canvas, Image } = require('canvas'); // import this

mergeImages(['./body.png', './eyes.png', './mouth.png'], {. //pass Valid images in array
  Canvas: Canvas, // here you need to add canvas
  Image: Image
})
  .then(b64 => ...);

For sample project in Node.js, you can check here


text:
Q: I cant make the textfile appear to my JTextArea This is my first time to post a question. So please be friendly.
I'm having trouble with my java program which is the textfile can't appear in my JTextArea, I'm using Eclipse Luna.
Here is my program :
public class Frame_Cashier extends JFrame {
    String[] category = {"Breakfast","Drinks","Add-ons","Desserts","Happy Meal","Value Meal"};
    JComboBox comboBox = new JComboBox(category);
    private JPanel contentPane;
    JTextArea txtrItemId;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Frame_Cashier frame = new Frame_Cashier();
                    frame.setVisible(true);
                    frame.setLocationRelativeTo(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public Frame_Cashier(){

        Container c = getContentPane();

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 759, 469);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JMenuBar menuBar = new JMenuBar();
        menuBar.setBackground(new Color(178, 34, 34));
        menuBar.setBounds(0, 0, 752, 21);
        contentPane.add(menuBar);

        JMenu mnFile = new JMenu("File");
        mnFile.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
            }
        });
        mnFile.setForeground(new Color(255, 255, 255));
        mnFile.setBackground(new Color(255, 69, 0));
        mnFile.setFont(new Font("MV Boli", Font.BOLD, 15));
        JMenuItem transaction = new JMenuItem("Transaction");
        transaction.setForeground(new Color(255, 255, 255));
        transaction.setBackground(new Color(178, 34, 34));
        transaction.setFont(new Font("MV Boli", Font.BOLD, 12));
        JMenuItem logout = new JMenuItem("Logout");
        logout.setForeground(new Color(255, 255, 255));
        logout.setBackground(new Color(178, 34, 34));
        logout.setFont(new Font("MV Boli", Font.BOLD, 12));
        menuBar.add(mnFile);
        mnFile.add(transaction);
        mnFile.add(logout);

        JLabel img_background = new JLabel("");
        img_background.setBackground(new Color(255, 51, 0));

        Image img = new ImageIcon(this.getClass().getResource("cashier_img.jpg")).getImage();

        JTextArea textArea = new JTextArea();
        textArea.setEditable(false);
        textArea.setBorder(new LineBorder(new Color(0, 0, 0), 3, true));
        textArea.setBackground(new Color(255, 255, 204));
        textArea.setBounds(380, 32, 353, 280);
        contentPane.add(textArea);

        JTextArea txtrItemId = new JTextArea();
        txtrItemId.setBackground(new Color(255, 255, 204));
        txtrItemId.setToolTipText("Item ID / Item Name");
        txtrItemId.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
        txtrItemId.setBounds(20, 114, 119, 150);
        txtrItemId.setEditable(false);
        contentPane.add(txtrItemId);

        comboBox.setSelectedIndex(1);
        comboBox.setSelectedIndex(5);
        comboBox.setBackground(new Color(255, 255, 204));
        comboBox.setBounds(20, 61, 338, 21);
        contentPane.add(comboBox);

        JTextArea textArea_2 = new JTextArea();
        textArea_2.setEditable(false);
        textArea_2.setBackground(new Color(255, 255, 204));
        textArea_2.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
        textArea_2.setBounds(175, 114, 72, 150);
        contentPane.add(textArea_2);

        JTextArea textArea_3 = new JTextArea();
        textArea_3.setEditable(false);
        textArea_3.setBackground(new Color(255, 255, 204));
        textArea_3.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
        textArea_3.setBounds(273, 114, 72, 150);
        contentPane.add(textArea_3);

        JTextArea textArea_1 = new JTextArea();
        textArea_1.setBackground(new Color(255, 255, 204));
        textArea_1.setBorder(new LineBorder(new Color(0, 0, 0), 2));
        textArea_1.setBounds(63, 290, 119, 22);
        contentPane.add(textArea_1);

        JTextArea txtrNoImage = new JTextArea();
        txtrNoImage.setBackground(new Color(255, 255, 204));
        txtrNoImage.setBorder(new LineBorder(new Color(0, 0, 0), 3, true));
        txtrNoImage.setText("No Image");
        txtrNoImage.setBounds(202, 274, 144, 126);
        contentPane.add(txtrNoImage);

        JLabel lblPrice = new JLabel("Price");
        lblPrice.setForeground(new Color(255, 204, 51));
        lblPrice.setFont(new Font("MV Boli", Font.BOLD, 12));
        lblPrice.setBounds(281, 89, 64, 14);
        contentPane.add(lblPrice);

        JLabel lblNewLabel_3 = new JLabel("Stock");
        lblNewLabel_3.setForeground(new Color(255, 204, 51));
        lblNewLabel_3.setFont(new Font("MV Boli", Font.BOLD, 12));
        lblNewLabel_3.setBounds(186, 89, 48, 14);
        contentPane.add(lblNewLabel_3);

        JLabel lblNewLabel_2 = new JLabel("Item ID / Item Name");
        lblNewLabel_2.setForeground(new Color(255, 204, 51));
        lblNewLabel_2.setFont(new Font("MV Boli", Font.BOLD, 12));
        lblNewLabel_2.setBounds(10, 89, 157, 14);
        contentPane.add(lblNewLabel_2);

        JLabel lblNewLabel_1 = new JLabel("Item I.D");
        lblNewLabel_1.setForeground(new Color(255, 204, 0));
        lblNewLabel_1.setFont(new Font("MV Boli", Font.BOLD, 12));
        lblNewLabel_1.setBounds(0, 290, 64, 22);
        contentPane.add(lblNewLabel_1);

        JLabel lblNewLabel = new JLabel("Select Category");
        lblNewLabel.setFont(new Font("MV Boli", Font.BOLD, 13));
        lblNewLabel.setForeground(new Color(255, 204, 0));
        lblNewLabel.setBounds(10, 32, 134, 31);
        contentPane.add(lblNewLabel);

        JButton btnNewButton_1 = new JButton("Void");
        btnNewButton_1.setBackground(SystemColor.controlDkShadow);
        btnNewButton_1.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
        btnNewButton_1.setForeground(new Color(255, 215, 0));
        btnNewButton_1.setFont(new Font("MV Boli", Font.BOLD, 13));
        btnNewButton_1.setBounds(634, 340, 99, 31);
        contentPane.add(btnNewButton_1);

        JButton btnNewButton = new JButton("Pay");
        btnNewButton.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
        btnNewButton.setFont(new Font("MV Boli", Font.BOLD, 15));
        btnNewButton.setForeground(new Color(255, 215, 0));
        btnNewButton.setBackground(SystemColor.controlDkShadow);
        btnNewButton.setBounds(380, 340, 99, 31);
        contentPane.add(btnNewButton);

        JButton btnNewButton_2 = new JButton("Edit");
        btnNewButton_2.setBorder(new LineBorder(new Color(0, 0, 0), 2, true));
        btnNewButton_2.setBackground(SystemColor.controlDkShadow);
        btnNewButton_2.setFont(new Font("MV Boli", Font.BOLD, 13));
        btnNewButton_2.setForeground(new Color(255, 215, 0));
        btnNewButton_2.setBounds(513, 340, 89, 31);
        contentPane.add(btnNewButton_2);

        img_background.setIcon(new ImageIcon(img));
        img_background.setAlignmentX(Component.CENTER_ALIGNMENT);
        img_background.setBounds(0, 21, 752, 410);
        contentPane.add(img_background);

        combohandler1 ch1 = new combohandler1();
        comboBox.addActionListener(ch1);
    }

    private class combohandler1 implements ActionListener {
    public void actionPerformed(ActionEvent e){
            String item1,item2,item3,item4,item5,item6;
            if(comboBox.getSelectedItem().equals("Breakfast")){
                try{
                        FileReader file = new FileReader("breakfast.txt");

                        BufferedReader br = new BufferedReader(file);

                        item1 = br.readLine();
                        item2 = br.readLine();
                        item3 = br.readLine();
                        item4 = br.readLine();
                        item5 = br.readLine();

                        System.out.println("test.txt");
                        txtrItemId.setText("\n"+item1+"\n"+item2+"\n"+item3+"\n"+item4+"\n"+item5+"\n");

                        br.close();
                    }catch(Exception x){
                    JOptionPane.showMessageDialog(null,"Unable to find");
                }
            }
        }
    }
}

A: You have declared the text area twice, once locally in the constructor and once globally
you will be getting a nullPointerException at txtrItemId.setText();
change : JTextArea txtrItemId = new JTextArea();
to: txtrItemId = new JTextArea();
When you try to access txtrItemId in your event handler, you are accessing the one that is declared globally where as you have initialized the variable declared in the constructor, the scope of this variable(declared in the constructor) will be limited only to that method/constructor.


text:
Q: How to convert utf-8 characters to "normal" characters in string in python3.10? I have raw data that looks like this:

25023,Zwerg+M%C3%BCtze,0,1,986,3780
25871,red+earth,0,1,38,8349
25931,K4m%21k4z3,90,1,1539,2530

It is saved as a .txt file: https://de205.die-staemme.de/map/player.txt
The "characters" starting with % are unicode, as far as I can tell.
I found the following table about it: https://www.i18nqa.com/debug/utf8-debug.html
Here is my code so far:
urllib.urlretrieve(url,pfad + "player.txt")

f = open(pfad + "player.txt","r",encoding="utf-8")
raw = raw.split("\n")
f.close()

Python does not convert the %-characters. They are read as if they were seperate characters.
Is there a way to convert these characters without calling .replace like 200 times?
Thank you very much in advance for help and/or useful hints!

A: The %s are URL-encoding; use urllib.parse.unquote to decode the string.
>>> raw = """25023,Zwerg+M%C3%BCtze,0,1,986,3780
... 25871,red+earth,0,1,38,8349
... 25931,K4m%21k4z3,90,1,1539,2530"""
>>> import urllib.parse
>>> print(urllib.parse.unquote(raw))
25023,Zwerg+Mütze,0,1,986,3780
25871,red+earth,0,1,38,8349
25931,K4m!k4z3,90,1,1539,2530


text:
Q: converting the tag names in JSON to follow CamelCase notation I am having a JSON like following :
{
    "Person": {
       "IDCountry": "0",
       "Home": {
          "ID": "ABC-XYZ",
           "Laptop": {
             "FileName": "/usr/temp/RPM_020515_.tar.gz",
             "Key": "123456789"
           },

          "Location": {
              "Number": "62",
              "MaxSize": "0"
           },
        }
    }
 }

This JSON is getting generated from some separate method from an XML file in perl using following code:
    #!/usr/bin/perl
    use strict;
    use warnings;
    use JSON;
    use XML::Simple;
    use XML::LibXML;
    # Create the object of XML Simple
    my $xmlSimple = new XML::Simple(KeepRoot   => 1);

    # Load the xml file in object
    my $dataXML = eval { $xmlSimple->XMLin($xmlFileName)};

    # use encode json function to convert xml object in json.
    my $jsonString = eval { encode_json($dataXML) };

    print $jsonString;

Everything is working fine here. But i want to get the output JSON tag names as all lower case. That is i want my output like this.
 {
    "person": {
       "idCountry": "0",
       "home": {
          "id": "ABC-XYZ",
           "laptop": {
             "fileName": "/usr/temp/RPM_020515_.tar.gz",
             "key": "123456789"
           },

          "location": {
              "number": "62",
              "maxSize": "0"
           },
        }
    }
 }

My current output JSON tags has same name as the name of elements in the xml file from which it is being generated.
How can i make change in my current perl script to have the tags in json all following  camel case notations.
Thanks.
JSON for case when we want to handle condition that specific element gets lower case and specific element gets camel case.
 {
    "person": {
       "idcountry": "0",
       "home": {
          "id": "ABC-XYZ",
           "laptop": {
             "fileName": "/usr/temp/RPM_020515_.tar.gz",
             "key": "123456789"
           },

          "location": {
              "number": "62",
              "maxSize": "0"
           },
        }
    }
 }

If you will see maxSize and fileName are following camelCase convention but all other tags got lower case.
That is we have two list :
{ FileName, MaxSize } these gets converted following came case whereas
{ Person, IDCountry, Home, ID, Laptop, Key, Location, Number } all gets converted into lower case.

A: use List::Util 1.29 qw( pairmap );

my %override = map { fc($_) => $_ } qw( maxSize fileName );

sub fix {
   my ($arg) = @_;

   defined($arg)
      or return;

   my $reftype = ref($arg)
      or return;

   if ($reftype eq 'ARRAY') {
      fix($_) for @$arg;
   }
   elsif ($reftype eq 'HASH') {
      %$arg = pairmap { $override{fc($a)} // lc($a), $b } %$arg;

      fix($_) for values(%$arg);
   }
}

my $data = { Person => { ... } };
fix($data);

For backwards compatibility, you can replace
use List::Util 1.29 qw( pairmap );

my %override = map { fc($_) => $_ } qw( maxSize fileName );

%$arg = pairmap { $override{fc($a)} // lc($a), $b } %$arg;

with
my %override = map { lc($_) => $_ } qw( maxSize fileName );

my @old_keys = keys(%$arg);
my @new_keys = map { $override{lc($_)} || lc($_) } @old_keys;
@$arg{@new_keys} = delete( @$arg{@old_keys} );


text:
Q: Making an instance to other class typed variable in typescript? Lets say we have a class of Animal,
class Animal {
    name: string;

    constructor(name: string) {
        this.name = name;
    }

    eat() {
        console.log(this.name + " is a Animal and is eating");
    }
}

and a class of Robot,
class Robot {
    name: string;

    constructor(name: string) {
        this.name = name;
    }
}

then how is this possible to have an instance of Animal having type of Robot class..
let r0: Robot = new Animal("Donkey"); //how is this possible?

and also note the in the animal class there is an extra method so how is it possible?


text:
Q: Cannot read contents from file app\design\adminhtml\Magento\backend\etc\module.xml in Magento 2 I have created a adminhtml theme but it's throwing error. Could you please clarify me where I went wrong?
my code is:
root/app/design/adminhtml/Magento/backend/composer.json
{
    "name": "magento/theme-adminhtml-backend",
    "description": "N/A",
    "require": {
        "php": "~5.5.0|~5.6.0|~7.0.0",
        "magento/framework": "100.0.*"
    },
    "type": "magento2-theme",
    "version": "100.0.2",
    "license": [
        "OSL-3.0",
        "AFL-3.0"
    ],
    "autoload": {
                 "files": [
             "registration.php"
         ]
     }

}

root/app/design/adminhtml/Magento/backend/registration.php
<?php
    /**
     * Copyright © 2015 Magento. All rights reserved.
     * See COPYING.txt for license details.
     */

\Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'adminhtml/Magento/backend',
        __DIR__
    );

root/app/design/adminhtml/Magento/backend/theme.xml
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
    <title>Magento 2 backend</title>
</theme>

Could you please clarify me where I went wrong?

A: Your registration.php file has declared the wrong type; You need to change it to;
\Magento\Framework\Component\ComponentRegistrar::THEME

Because you have declared it as ::MODULE it is looking for the module.xml definition.

A: In your theme:
registration.php
<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::THEME,
    'adminhtml/CompanyName/backend',
    __DIR__
);

theme.xml
Note how the parent theme has been defined
<!--
/**
 * Copyright © 2017 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
    <title>CompanyName BackendTheme</title>
    <parent>Magento/backend</parent>
</theme>


text:
Q: Why does this code not work? (Python and PyGame) import math, sys, os, pygame, random, time

pygame.init()
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption('Tester.')
pygame.mouse.set_visible(0)

def smileMove():
    smiley = pygame.image.load('smiley.png')
    random.seed()
    xMove = random.randrange(1,501)
    yMove = random.randrange(1,501)

    screen.blit(smiley,(xMove,yMove))

c = 0

while c <5:
    smileMove()
    time.sleep(3)
    c = c + 1

pygame.quit()

I'm very new to programming and I'm just trying out a few basic things with PyGame.
The screen remains black and no smiley faces appear. I am trying to make the faces appear on the black background, and change to another random place every 3 seconds, 5 times and then quit.

A: You are missing a call to pygame.display.flip() to actually update the window contents- put it just before your time.sleep call.
My advice at this early stage of experimenting with Python and the pygame API would be to try stuff at the interactive console..

A: first of all, it needs to be in a while loop (at least if you are going to do much more) also, you are missing the background. this should work:
import math, sys, os, pygame, random, time

pygame.init()
screen = pygame.display.set_mode((500,500))
pygame.display.set_caption('Tester.')
pygame.mouse.set_visible(0)
white = ( 255, 255, 255)

def smileMove():
    screen.fill(white)
    smiley = pygame.image.load('smiley.png')
    random.seed()
    xMove = random.randrange(1,501)
    yMove = random.randrange(1,501)

    screen.blit(smiley,(xMove,yMove))

c = 0
done = False
while done==False:
    for event in pygame.event.get(): # User did something
        if event.type == pygame.QUIT: # If user clicked close
            done=True # Flag that we are done so we exit this loop

    screen.fill(white)
    while c <5:
        smileMove()
        pygame.display.flip()
        c = c + 1
        time.sleep(3)
pygame.quit()


text:
Q: Capitalize both parts of a hyphenated word with Rails I'm trying to capitalize both parts of a hyphenated word with Rails:
"hello-world".capitalize
# => Hello-world

"hello-world".titleize
# => Hello World

Is there a quick way of doing this? If not then I will write a custom solution, I can figure that out, but I'm hoping there is some really quick and dirty method that can do this for me

A: You can try titleize, but also add gsub
"hello-world".titleize.gsub(' ', '-')

It returns:
irb(main):006:0> "hello-world".titleize.gsub(' ', '-')
"Hello-World"

A: There isn't an inflector that will do what you want, but you can do this, which is quick and dirty:
'hello-world'.split('-').map(&:capitalize).join('-')

A: Try this i hope this will helping you
"hello-world".split('-').map(&:capitalize)*'-'


text:
Q: How to get rid of whitespace in Smarty {block}s? I've run into a problem where defining the value of a {block} introduces a lot of unnecessary whitespace.
I've a main template, let's call it main.html, which looks like this (simplified):
<html>
<title>{block name=title}{$default_title}{/block}</title>
...
</html>

Then I inherit from it in let's say topics.html, and I define the title block in it:
{extends file="main.html"}

{block title}
{if $topic}
  {if $topic == "all"}
    {eval $Config['titles']['topics']['all']}
  {else}
    {eval $Config['titles']['topics']['particular']}
  {/if}
{else}
  {eval $Config['titles']['topics']['list']}
{/if}
{/block}

Now when I compile the topics.html template, there is so much whitespace inside of <title>...</title> tag.
For example, it looks like this:
<title>
    Showing all wiki topics  </title>

How could I trim/strip the whitespace from the result of evaluating a block so it looked like the following:?
<title>Showing all wiki topics</title>

I tried adding {strip}...{/strip} around the {block title}...{/block} like this:
{strip}
{block title}
...
{/block}
{/strip}

But that didn't change anything.
I also tried this:
{block title|strip}
...
{/block}

But that was a syntax error. I also tried this:
{block title|trim}
...
{/block}

But it also was a syntax error.
I also tried:
{block title}
{strip}
...
{/strip}
{/block}

But that didn't help either as I already introduced a new-line after {block title}so it stays there in the compiled template.
Any help appreciated!

A: As of Smarty 3.1 you cannot wrap {block}s in other constructs. (This might change with Smarty 3.2)
Have you tried putting the {strip} tags inside the {block}s? Otherwise have a look at my answer here


text:
Q: Symfony2 DomCrawler and FB2 book format parser All!
How do I parse correctly described XML file with Symfony2 DomCrawler component?
I need to split all the sections and collect an internal tags (epigraph, p, poem etc.) with the current section together which belongs to this section only.
I've standard FB2 book XML format described below:
<?xml version="1.0" encoding="utf-8"?>
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
<description></description>

    <title>
Level 1, section 1
</title>

        <title>
Level 2, section 2
</title>

            <title>
Level 3, section 3
</title>

Level 3, section 3, paragraph 1

            <poem>
                <stanza>
                    <v>bla-bla-bla 1</v>
                    <v>bla-bla-bla 2</v>
                    <v>bla-bla-bla 3</v>
                </stanza>
            </poem>

Level3, section 3, paragraph 2

            <subtitle>x x x</subtitle>

            <title>
Level 3, section 4
</title>

Level 3, section 4, paragraph 1

Level 3, section 4, paragraph 2

            <subtitle>x x x</subtitle>

            <title>
Level 3, section 5
</title>

Level 3, section 5, paragraph 1

Level 3, section 5, paragraph 2

Level 3, section 5, paragraph 3

            <empty-line/>
            <subtitle>This file was created</subtitle>
            <subtitle>with BookDesigner program</subtitle>
            <subtitle>bookdesigner@the-ebook.org</subtitle>
            <subtitle>22.04.2004</subtitle>

</FictionBook>

The code below do not work, so could somebody help me to solve this?
Btw, title parsed correctly... but section's tags not...
private function loadBookSections(Crawler $crawler)
{
    $sections = $crawler->filter('section')->each(function(Crawler $node) {
        $c = $node->filter('section')->reduce(function(Crawler $node, $i) {
            return ($i == 0);
        });

        return array(
            'title' => $node->filter('title')->text(),
            'inner' => $c->html(),
        );
    });

    echo "*******************************************\n";

    foreach($sections as $section ) {
        echo ">>> ".$section['title']."\n";
        echo "!!! ".$section['inner']."\n";
    }
}

And Thanks for help!

A: After four days... I've found the solution via XPath...
private function loadBookSections(Crawler $crawler)
{

    $sections = $crawler->filter('section')->each(function(Crawler $node) {
        return array(
            'title' => $node->filter('title')->text(),
            'inner' => $node->filterXPath("//*[not(section)]")->html(),
        );
    });

    foreach($sections as $section) {
        echo "TITLE: ".$section['title']."\n";
        echo "INNER: ".$section['inner']."\n";
    }
}

A: If you reduce your XML file quite a bit you get something like this:

You want to catch the children section elements, not the parent one.
Currently you are iterating only over the list of parent section elements, which means you only get the HTML of the parent section element.
To iterate over the children, you need to select section section instead of section.

Side information to further improve your code: instead of the ugly reduce call, just use ->first() to get the first element of the node list.

In total, your code will be:
$sections = $crawler->filter('section section')->each(function(Crawler $node) {
    $c = $node->filter('section')->first();

    return array(
        'title' => $node->filter('title')->text(),
        'inner' => $c->html(),
    );
});


text:
Q: Apagar dados por checkbox Bem pessoal estou aqui com um problema eu tenho no meu sistema categorias em que insiro os produtos nas diversas categorias que podem escolher por meio de checkbox só que agora estou a enfrentar um problema e que quero apagar um registo por exemplo:
Tenho uma checkbox selecionada e esta guardada no banco queria que ao desmarcar essa caixa ele apaga-se no banco de dados eu tentei aqui construir o código só que agora não me esta a inserir nem apagar da base de dados.
Codigo Php
<?php
                     if($_REQUEST['op']=="editar" && $_REQUEST['valida']=="ok"){
                        if($_REQUEST['op']=="editar"){
                            //$result_existe=mysql_query("select * from colecoes where activo=1");
                            //$row_existe=mysql_query($result_existe);
                            //$result_existe=mysql_query("select * from categorias_estabelecimentos where estabelecimento_id = '".$_REQUEST['id']."' and categoria_slug = '".$row_existe->slug."'");
                            //if(mysql_num_rows($result_existe)>0){
                                if (!isset($_POST['categoria'])){
                                    foreach($_POST['categoria'] as $entry_categorias_delete){
                                    $categorias_delete= $entry_categorias_delete;
                                        $sql="DELETE FROM categorias_estabelecimentos WHERE estabelecimento_id = '".$_REQUEST['id']."' and categoria_slug='".$categorias_delete."'";
                                        mysql_query($sql) or die (mysql_error() );
                                    }
                                }
                            }else{
                                $checkBox = $_POST['categoria'];
                                $estabelecimento_id = $_REQUEST['id'];
                                foreach($checkBox as $entry_categorias){
                                $categorias= $entry_categorias;
                                    $query="INSERT INTO categorias_estabelecimentos (estabelecimento_id, categoria_slug) VALUES ('".$estabelecimento_id."', '".$categorias."')";
                                    mysql_query($query) or die (mysql_error() );
                                }
                            }
                        }
                    //}
                    ?>

A: Levando em consideração as opções que o utilizador propôs fiz as modificações onde foram necessárias:
if (!isset($_POST['categoria'])){
    $categorias = '' . implode('\',\'', $_POST['categoria']);
    $id = $_REQUEST['id'];
    $sql= "DELETE FROM categorias_estabelecimentos WHERE estabelecimento_id = $id AND categoria_slug NOT IN ($categorias)";
    mysql_query($sql) or die (mysql_error() );
}

Assim ele vai deletar tudo que não está "selecionado" na tela; Não testei, qualquer erro por favor avise.


text:
Q: Jenkins Service Call failed > Server Error? I am trying to run Jenkins on localhost:8080, in an Ubuntu VM. When I try to run a gradle script which creates a few jobs on jenkins, i get the following stack trace:
:ci:<job name>
Creating new item <item name> on http://localhost:8080/
:ci:<job name>FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Jenkins Service Call failed
> Server Error

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
com.terrafolio.gradle.plugins.jenkins.service.JenkinsServiceException: Jenkins Service Call failed
    at com.terrafolio.gradle.plugins.jenkins.service.JenkinsRESTServiceImpl.createConfiguration(JenkinsRESTServiceImpl.groovy:112)
    at com.terrafolio.gradle.plugins.jenkins.service.JenkinsService$createConfiguration$0.call(Unknown Source)
    at com.terrafolio.gradle.plugins.jenkins.tasks.UpdateJenkinsItemsTask$_doExecute_closure1$_closure2.doCall(UpdateJenkinsItemsTask.groovy:20)
    at com.terrafolio.gradle.plugins.jenkins.tasks.AbstractJenkinsTask$_eachServer_closure4.doCall(AbstractJenkinsTask.groovy:71)
    at com.terrafolio.gradle.plugins.jenkins.tasks.AbstractJenkinsTask.eachServer(AbstractJenkinsTask.groovy:69)
    at com.terrafolio.gradle.plugins.jenkins.tasks.UpdateJenkinsItemsTask$_doExecute_closure1.doCall(UpdateJenkinsItemsTask.groovy:16)
    at com.terrafolio.gradle.plugins.jenkins.tasks.UpdateJenkinsItemsTask.doExecute(UpdateJenkinsItemsTask.groovy:15)
    at com.terrafolio.gradle.plugins.jenkins.tasks.AbstractJenkinsTask.executeTask(AbstractJenkinsTask.groovy:26)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:227)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:220)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:209)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:585)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:568)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
    at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:154)
    at org.gradle.internal.Factories$1.create(Factories.java:22)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:52)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:151)
    at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
    at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:99)
    at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:93)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:62)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:93)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:82)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:94)
    at org.gradle.tooling.internal.provider.ExecuteBuildActionRunner.run(ExecuteBuildActionRunner.java:28)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:43)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
    at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:75)
    at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:45)
    at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:51)
    at org.gradle.launcher.exec.DaemonUsageSuggestingBuildActionExecuter.execute(DaemonUsageSuggestingBuildActionExecuter.java:28)
    at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:43)
    at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:170)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35)
    at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
    at org.gradle.launcher.Main.doAction(Main.java:33)
    at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35)
    at org.gradle.launcher.GradleMain.main(GradleMain.java:23)
    at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:30)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:61)
Caused by: groovyx.net.http.HttpResponseException: Server Error
    at groovyx.net.http.RESTClient.defaultFailureHandler(RESTClient.java:263)
    at groovyx.net.http.HTTPBuilder$1.handleResponse(HTTPBuilder.java:503)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:218)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:160)
    at groovyx.net.http.HTTPBuilder.doRequest(HTTPBuilder.java:515)
    at groovyx.net.http.RESTClient.post(RESTClient.java:141)
    at groovyx.net.http.RESTClient$post$0.call(Unknown Source)
    at com.terrafolio.gradle.plugins.jenkins.service.JenkinsRESTServiceImpl.restServicePOST(JenkinsRESTServiceImpl.groovy:50)
    at com.terrafolio.gradle.plugins.jenkins.service.JenkinsRESTServiceImpl$restServicePOST$0.callCurrent(Unknown Source)
    at com.terrafolio.gradle.plugins.jenkins.service.JenkinsRESTServiceImpl.createConfiguration(JenkinsRESTServiceImpl.groovy:110)
    ... 75 more

BUILD FAILED

Total time: 25.892 secs

*

*Ways I've tried to debug this issue:

*

*Making sure there is nothing wrong with the gradle script (it runs fine on our corporate jenkins server)

*Disabling "Prevent Cross Site Request Forgery exploits"

*Changing the of /var/lib permissions to 777

*Running the docker image of jenkins

*Trying different versions (latest, 1.651.3, 2.7.2)

*Manually sending post requests to the jenkins server via postman

*

*Causes java.io.IOException: Failed to persist config.xml error

*Restarting jenkins

*https://wiki.jenkins-ci.org/display/JENKINS/Disable+security?showComments=true&showCommentArea=true#addcomment
Note: I am using the terrafolio plugin for gradle
Any suggestions welcome!

A: Try checking the jenkins log at /var/log/jenkins/jenkins.log while running the gradle script:
tail -f /var/log/jenkins/jenkins.log


text:
Q: EDI X.12 PHP Mapping - resources needed Is there any php libraries or API's that help when dealing with X12 documents in php? Googling around doesn't help much, so looking for people with experience in this field.

A: If you know which Segments and what the meaning in all segments. Then its just about php
$file = file_get_contents('/edi.x12');
$segments = explode(~\n,$file);
foreach($segments as $segment){

$elements = explode('*',$segment);

foreach($elements as $element){

     switch($elements[0]){
          case 'ISA':
              break;
     /// And so on
}
}
}

Then you will have an Array consisting all Segments in the file. If your just iterate over the array it is possible  to get all Elements for given Segment.
But for creating a x12 Edi file it is a little bit more tricky.
I dont see the point in first convert to Xml.

A: Doing a quick google search, I found a couple of tools that will convert X12 documents to XML. PHP has made a lot of progress in the area of XML parsing.
Is converting to XML first an option?

A: not PHP, but python: http://bots.sourceforge.net
translates from and to x12.


text:
Q: I can't import data from gtm's data layer into my own database I created a data layer in GTM ( Google Tag Manager ) and wrote a script to import the information reflected in this part into my own data store but something seems wrong.

I have a trigger called addToCard, and with this event, my script fires as it pulls the data but my data block looks empty as seen in the image

Please help, I can explain more details you want. at least give me advice..
<script>

    var SvstData={};

    var a = window['dataLayer']
    var x =[]
    var b
    a.forEach(item=>{
        if(item.event=="addToCart"){
            b=item
        }
    })
    if(a){
        b.ecommerce.add.products.forEach((item) = function() {

            x.push({
                pId: item.id,
                pQty: item.quantity,
                pPrice: item.price,
                pName: item.name,
                url: '0',
                pimg: '0',
                image_url: '0',
                category_name: item.category,
                category_id: '0',
                brand: item.brand,
                brand_id: '0',
                product_code: '0',
                title: item.name,
                currency: '0',
                price_sell: item.price,
                price_order_general: item.price
            })
        })
        SvstData.product = x
        SvstData.count = x.length
        SvstData.email= a[2].userinfo.email;
        SvstData.oAmt= a[4].ecommerce.checkout.products[0].price;
        SvstData.oID= a[4].ecommerce.checkout.products[0].id;
    }

    SvstData.status= "cart";

</script>

I want to pass information from GTM data layer to my own data block


text:
Q: Android Eclipse - Measuring time accurately I'm creating an app where I need for something to happen if a button isn't pressed within 'x' seconds but if it is pressed then the timer resets and the cycle starts again, but that time frame will most likely be around 0.3 - 0.5 seconds so I can't use a Chronometer right? How should I go about this

A: A chonometer cant solve your issue. Use a CountDownTimer instead.
http://developer.android.com/reference/android/os/CountDownTimer.html


text:
Q: how to check if item in a list is exist in other list with python? I have a text file containing these lines for example
[:];@;;]wqwww actualnumber 1234 ;;:@##
aaaa ''3# allnumber 9876
///qqq |||)))
]][]: best 56

I want to get the value 1234,9876,56. Like this(desired output)
1234
9876
56

I tried with the following script but it did not print out anything
with open("test.txt", "r") as f:
    lines = f.readlines()
    stripped_lines = [line.strip() for line in lines]

    word = ["actual number", "potential", "time"]
    if any(item in stripped_lines for item in word):
        aa = stripped_lines.split("actualnumber ")[1].split(" ")[0]
        bb = stripped_lines.split("allnumber ")[1].split(" ")[1]
        cc = stripped_lines.split("best ")[1]

        print aa
        print bb
        print cc

Did I miss something?

A: you can do it with re module
import re
with open('f.txt') as f:
    data = f.read()
    act = re.findall(r'actualnumber\s+(\d+)',data)
    best = re.findall(r'best\s(\d+)',data)
    allnumber = re.findall(r'allnumber\s(\d+)',data)
    print "actualnumber  : ", act[0] if act else None
    print "allnumber  : ", allnumber[0] if allnumber else None
    print "best  : ", best[0] if best else None

output
actualnumber  :  1234
allnumber  :  9876
best  :  56

A: You can extract numbers like this:
k = '[:];@;;]wqwww actualnumber 1234 ;;:@##'
for item in k.split():
    if item.isnumeric():
        print(item)

You would use your striped lines instead. For each line in stripped line, split it, and check if any item in the split line is numeric. isnumeric() works only on unicode objects.
with open("test.txt", "r") as f:
    lines = f.readlines()
    stripped_lines = [line.strip() for line in lines]

words = ['actualnumber', 'allnumber', 'best']
found = {}
for line in stripped_lines:
    current_line = line.split()
    for position, item in enumerate(current_line):
        if item in words:
            found[item] = current_line[position + 1]

Now that you have them in a dictionary, you can access them as: found['actualnumber']. And do further processing, such as storing them in a database.

A: The simple way is by using isdigit()
f = open('test.txt')
data = f.read()
[int(s) for s in data.split() if s.lstrip("-").isdigit()]

Output :
[1234, 9876, 56]

A:     word = ["actualnumber", "potential", "time"]
    with open("./abx.txt") as file:
         temp_list = [line.strip() for line in file.readlines()]
         list_val = [item for item in temp_list if any(x in item for x in word)]
         final_list = []
         match_value = ["actualnumber", "allnumber", "best"]
         if list_val:
           for val in temp_list:
             val_list = val.split(" ")
             for key, value in enumerate(val_list):
                 if value in match_value:
                    final_list.append(val_list[key+1])

        print(final_list):

And at the end you can iterate list and find out your expected values.


text:
Q: Inserting new line in sequence manner I have a question about inserting a new line in a big text.file by bash scripting;
My file;
E.coli.1    gi|1035701777|ref|WP_064543348.1|   85.62   160 23  0   12  171 1   160 4,00E-103   300
E.coli.2    gi|1035701777|ref|WP_064543348.1|   85.62   160 23  0   1   160 1   160 3,00E-103   300
E.coli.5    gi|1036669825|ref|WP_064721309.1|   96.69   393 13  0   2   394 1   393 0.0 748
E.coli.6    gi|1036669825|ref|WP_064721309.1|   96.69   393 13  0   2   394 1   393 0.0 748
E.coli.7    gi|1037427804|ref|WP_064741043.1|   67.95   78  25  0   1   78  1   78  9,00E-33    114

My expected output:
E.coli.1    gi|1035701777|ref|WP_064543348.1|   85.62   160 23  0   12  171 1   160 4,00E-103   300
E.coli.2    gi|1035701777|ref|WP_064543348.1|   85.62   160 23  0   1   160 1   160 3,00E-103   300
E.coli.3
E.coli.4
E.coli.5    gi|1036669825|ref|WP_064721309.1|   96.69   393 13  0   2   394 1   393 0.0 748
E.coli.6    gi|1036669825|ref|WP_064721309.1|   96.69   393 13  0   2   394 1   393 0.0 748
E.coli.7    gi|1037427804|ref|WP_064741043.1|   67.95   78  25  0   1   78  1   78  9,00E-33    114

A: If I understood your problem with not-so-clear description, you can solve it using awk:
awk -F '[.[:blank:]]+' 'p{for (;p<$3; p++) print f p} NF>3{p=$3+1; f=$1 "." $2 "."}1' file

E.coli.1    gi|1035701777|ref|WP_064543348.1|   85.62   160 23  0   12  171 1   160 4,00E-103   300
E.coli.2    gi|1035701777|ref|WP_064543348.1|   85.62   160 23  0   1   160 1   160 3,00E-103   300
E.coli.3
E.coli.4
E.coli.5    gi|1036669825|ref|WP_064721309.1|   96.69   393 13  0   2   394 1   393 0.0 748
E.coli.6    gi|1036669825|ref|WP_064721309.1|   96.69   393 13  0   2   394 1   393 0.0 748
E.coli.7    gi|1037427804|ref|WP_064741043.1|   67.95   78  25  0   1   78  1   78  9,00E-33    114


text:
Q: SOQL multiple LIKE matches I am trying to figure out the best way to do multiple LIKE matches in a complicated soql statement.
I want to change the hubFilter value from just "BCS%" to "BCS%,Benefit Advisor,Mgr of Ben,BSR".
I tried this and got nothing back so I assume it's not reading those as separate values. Any ideas?
Here is a basic example of what my query looks like:
list<BCS__c>hubs = new list<BCS__c>();
private string hubfilter;
if(showAll == TRUE){
    hubFilter = '%';
}else{
    hubFilter = 'BCS%';
}
hubs = [
    SELECT /*fields and subqueries*/ FROM BCS__c
    WHERE /*other clauses*/ AND Title__c LIKE :hubFilter
];

A: You can use a collection with LIKE:
Set<String> fuzzyMatches = new Set<String> { 'A%', 'B%', 'etc%' };
List<MyObject__c> records = [SELECT Id FROM MyObject__c WHERE Field__c LIKE :fuzzyMatches];

You can also define the collection inline:
SELECT Id FROM MyObject__c WHERE Field__c LIKE ('A%', 'B%', 'etc%')

Your specific hubfilter would be:
new Set<String> { 'BCS%', 'Benefit Advisor', 'Mgr of Ben', 'BSR' };

Note that you only use a fuzzy match on the first string. It is unclear if any of the other values should also be a fuzzy match.

A: For anyone else who finds this post in future, I ended up with this code.
set<string> hubfilter = new set<string>();

        if(showAll == TRUE){
            hubfilter = new Set<String> { '%' };
        }else{
            hubFilter = new Set<String> { 'BCS%', 'Benefit Advisor', 'Mgr of Ben', 'BSR' };
        }


text:
Q: New line not working Description:
I have the follwoing code:
        if(isset($riskTriggerFlag) && $riskTriggerFlag==1) // if risk_mitigator process reads and offer weight is  maintained based on offer mentioned.
        {
            echo "Risk Weight: ".$risk_weight ."\n";
            $randNo = rand(1,100);

            echo "Random Weight: ". $randNo ."\n";
            if($randNo < intval(100 - $risk_weight))
            {
                $flagThrowPostback = 1;
            }
        }

As you can see,I am putting \n in the text,but still the message in getting printed in this matter:
Risk Weight: 20 Random Weight: 20

What am I doing wrong?
Note:
I can't use br tag or nl2br() since the total page is just a php page, and I don't want to add any html tags.
output on broswer is coming like this:

Multiple row Risk Weight: 20 Random Weight: 20

A: I think better way is to check whether php file is executed from CLI or browser. In case it is from browser then use  else newline.
$newline = "
";
if (PHP_SAPI === 'cli')
{
   // ...
   $newline = "\n";
}
if(isset($riskTriggerFlag) && $riskTriggerFlag==1) // if risk_mitigator process reads and offer weight is  maintained based on offer mentioned.
    {
        echo "Risk Weight: ".$risk_weight . $newline;
        $randNo = rand(1,100);

        echo "Random Weight: ". $randNo . $newline;
        if($randNo < intval(100 - $risk_weight))
        {
            $flagThrowPostback = 1;
        }
    }


text:
Q: Android - TabHost inside ScrollView I'm writing an app that implements nested tabs. Because two sets of tabs occupy quite a bit of space and generally because the nature of the content I would like to place the whole inner TabHost into a scrollable structure. I can make tabcontent of the outer activity FrameLayout, LinearLayout, even ViewFlipper; when I try to make it ScrollView, the program crashes.
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <ScrollView
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
    </LinearLayout>

</TabHost>

So apparently TabHost likes to live inside non-scrollable frames. Is there any way to go around this without creating a whole lot of a mess?

A: Sorry I figured it out on my own. The solution is to wrap the second TabHost inside a ScrollView within its own XML file. That works just fine.
Outer:
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>
    </LinearLayout>

</TabHost>

Inner:
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
            <ViewFlipper
                android:id="@android:id/tabcontent"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"/>
        </LinearLayout>

    </TabHost>

</ScrollView>


text:
Q: Django - Problem with Implementing Models and Views in My PhoneReview Application I am a beginner in Django. I am building a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It will also display phone brands, along with the associated phone models. I have already created models for:

*

*Brand – details on brand, such as, name, origin, manufacturing since, etc

*Model – details on model, such as, model name, launch date, platform, etc

*Review – review article on the mobile phone and date published, etc

*Many-to-many relationship between Review and Model.
Now, I have to create views for the following:
a. An index page that display all Brands available for mobile phone in the
database
b. A phone model page that display model when a brand is selected.
c. A detail page when a model is selected that contain reviews and newslink
I have managed to create view for "a. An index page that display all Brands available for mobile phone in the database." However, I am stuck with "b. A phone model page that display model when a brand is selected."
I have managed to display the phone model page. However, the name of the phone model is not being displayed. So, I feel that there is a problem with either the views or templates. But I don't get any error while running the server. So, I am a bit confused.
Here are the codes of models.py of the PhoneReview app.
from django.db import models
from django.template.defaultfilters import slugify

# Create your models here.
class Brand(models.Model):
    brand_name = models.CharField(max_length=100)
    origin = models.CharField(max_length=100)
    manufacturing_since = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        return self.brand_name

class PhoneModel(models.Model):
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    model_name = models.CharField(max_length=100)
    launch_date = models.CharField(max_length=100)
    platform = models.CharField(max_length=100)

    def __str__(self):
        return self.model_name

class Review(models.Model):
    phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
    review_article = models.TextField()
    date_published = models.DateField(auto_now=True)
    slug = models.SlugField(max_length=150, null=True, blank=True)

    def __str__(self):
        return self.review_article

Here are the codes of urls.py of the PhoneReview app:
from . import views
from django.urls import path

urlpatterns = [
    path('index', views.BrandListView.as_view(), name='brandlist'),
    path('phonemodel/<int:pk>/', views.ModelView.as_view(), name='modellist'),
]

Here are the codes of views.py of the PhoneReview app:
from django.views import generic
from .models import Brand, PhoneModel

class BrandListView(generic.ListView):
    template_name = 'PhoneReview/brandlist.html'
    context_object_name = 'all_brands'

    def get_queryset(self):
        return Brand.objects.all()

class ModelView(generic.DetailView):
    model = PhoneModel
    template_name = 'PhoneReview/phonemodel.html'

Here are the codes of base.html file. As the name suggests, this is the base page. It will be extended for being used by the other pages, like brandlist.html for showing phone brand list and phonemodel.html for showing phone models. It is located inside templates > GameReview folder:
<!DOCTYPE html>

  <title>{% block title %}  {% endblock %}</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      </button>
      Phone Radar

#

Add Phone

Add Review

 Login

   {% block content %}  {% endblock %}

Here are the codes of brandlist.html file, which displays the list of the phone brands. It located inside templates > GameReview folder. I have managed to display the phone brands at http://127.0.0.1:8000/index.
{% extends 'PhoneReview/base.html' %}

{% load static %}

{% block title%}
Brand List
{% endblock %}

{% block content %}

This is Brand List Page

        {% for brand in all_brands %}

{{ brand.brand_name }}

        {% endfor %}

{% endblock %}

Here are the codes of phonemodel.html file, which is supposed to display the phone brands. However, I can't display the output of {{ phonemodel.model_name }} at http://127.0.0.1:8000/phonemodel/1/. It just shows the H1 heading. The file is located inside templates > GameReview folder.
{% extends 'PhoneReview/base.html' %}

{% load static %}

{% block title%}
Phone Model Page
{% endblock %}

{% block content %}

This is Phone Model Page

        {% for phonemodel in all_phonemodel %}

{{ phonemodel.model_name }}

        {% endfor %}

{% endblock %}

I am stuck here. The phonemodel.html is supposed to display the phone brands. However, I can't display the output of {{ phonemodel.model_name }} at http://127.0.0.1:8000/phonemodel/1/. It just shows the H1 heading. There are no errors showing. I tried several hours to fix it. But being a Django beginner, I am facing a hard time fixing it.

A: Your phonemodel template is totally wrong. Not only do you not have anything called all_phonemodel in the template context, even if you did it wouldn't be iterable because this is a detail view, not a list view.
Remove the loop and just access object:

{{ object.model_name }}

A: Add this to your "class ModelView":
context_object_name = 'all_phonemodel'

def get_queryset(self):
        return PhoneModel.objects.all()


text:
Q: Is canonical SOP/POS form for a boolean expression unique? I was trying to find equivalence between two boolean expressions and thought if I convert both of them to canonical sum of product or product of sum form they should match. But I am not sure if these forms are unique for a boolean expression, are they?

A: Yes, "canonical" sum of products and canonical product of sums are unique for a boolean expression, and hence can be used for checking the equivalence of two boolean expressions.
Reference:Switching Theory for Logic Synthesis By Tsutomu Sasao


text:
Q: Any references / MSDN tutorials to show support for either "if (!condition)" or "if (condition == false)"? For those who misread the question: let's pretend we're on Wikipedia.
I'm not looking for "the right way", I'm looking for verifiable references to support either side.
(Please read to the end)
The Context
In a comment on a different thread, a person said his friends would beg to differ with my opinion on whether
if (!condition)

or
if (condition == false)

is preferred in C#.
As much as I was sure I know how to do the Right Thing™, I was unable to find any evidence my opinion is official in neither C# coding nor design guidelines.
The Question
Is there anything substantial to show in support of either side, apart from the common sense?
(a paragraph in a widely admired book or any document hosted at microsoft.com that uses or prescribes either style over another will answer the question)

A: if (!condition) and if (condition) are preferred over if (condition == false) and if (condition == true) because the former is just as readable and less verbose.
Bottom section of page 13 of C# Coding Standards for .NET created by Lance Hunt says:

Avoid evaluating Boolean conditions against true or false.

// Bad!
if (isValid == true)
{ ... }
// Good!
if (isValid)
{ ... }

However it is not by any means official and it doesn't come from Microsoft.

A: Sometimes I use if (condition == false) if the condition being false is an extreme edge case - it brings attention to that fact for me.


text:
Q: Best approach to mirror All databases of a sql server I see here that we have a lot of questions about best approach to mirror a single database. I got a new job and people there is  under a task to mirror all databases, to a secondary one, in a different city for security (if we lost a server, we have everything on the mirror).
1) to mirror ALL databases, should I repeat the mirroring step for every database?
2)is this the best approach to high availability?
I'm thinking about something with raid, so we have a mirror disk that if a disk fails, there is this secondary ( i just forgot what raid is this, im on the cellphone and will search later).
I think there will be a lot of requests to mirror the data ( it's not going to be synchronous) if we really  chose to mirror ALL databases ( there are more than 200).
What would you  guys do in this situation? I would even prefer log shipping.
I just found this question  but i really need to sleep now. Will study it tomorrow. It says about log shipping too.

A: I do not see what version of SQL Server you are using and from the tag assuming it is SQL Server.
From Books Online:
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use Always On Availability Groups instead.

*

*If you are at 2012 or above I highly recommend you to consider Always ON Availability group. Besides High Availability you can also gain performance benefit by offloading certain maintenance operations and read traffic.  It will depend on your setup, application design and requirement. You can read more in details here.
FYI :This technology is built upon mirroring which you mentioned in the question.

*Log Shipping is definitely another option but your read only copy cannot be available for read traffic all the time and not in sync as close to real time as Always ON Availability Group.  See details about Log Shipping here.
Few more options that you can consider based on your requirements:

*Failover Clustering

*Failover Clustering in conjuntion with storage level replication.

*AlwaysOn Failover Clustering Instances

*Replication

A: Since the comments are running long, I'm dumping this to a formal answer.
First, in regards to mirroring, there are some hard limitations on the number of databases that can be mirrored between instances.  This number can float anywhere up to 50+, though I have often seen it start to affect performance in the single-digit range as instance activity will heavily influence these limits. More info on the details behind why these limits exist can be found here.
Because you're using SQL 2008, you are a little more limited in what's available.  Basically you're left with Log Shipping or Replication.
Log Shipping is lightweight and is what I would recommend if you can accept some level of data loss in the event of a failure.  You can log ship hundreds of databases between instances as performance limitations are related more to file-level and bandwidth constraints.
Replication, much like Mirroring, also suffers from volume limitations as a publication requires some resources to maintain.  What's arguably worse about Replication is that it may require DML changes be made to the data model of a database if tables don't have PKeys.  These changes are necessary to ensure records are replicated properly and your subscriber(s) are kept in sync.  There are other considerations as well, found here, so Replication is not something I would say is simple to implement and should only be used after ample testing.
If you don't think Mirroring, Log Shipping, or Replication will work, your other options are basically hardware related such as SAN-to-SAN replication, or simply upgrade to SQL 2012 or later and take advantage of Availability Groups as stated by SqlWorldWide.


text:
Q: How to use Microsoft.AspNetCore.DataProtection in the console application? On the page Non-DI aware scenarios for Data Protection in ASP.NET Core I find the code that is intended to be a console application.
It is unexpected for me because console application references to ASP.NET Core library:
using Microsoft.AspNetCore.DataProtection;

When I tried to run it, I expectedly got an error message about missing assembly.
I asked Microsoft about this https://github.com/dotnet/AspNetCore.Docs/issues/17098. But I just got the come-off answer, I just got the reference to the page which is upper in the content: https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/introduction?view=aspnetcore-3.1#package-layout
When I run the code in the ASP.NET app, the following statement dataProtectionProvider.CreateProtector("Program.No-DI") returned Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.
Which library contains KeyRingBasedDataProtector?
I included the package https://www.nuget.org/packages/Microsoft.AspNetCore.DataProtection.Abstractions/, but it expectedly does not contain implementation.
In general, are ASP.NET libraries are suitable to use in console applications?
After all, how to run the code from the page Non-DI aware scenarios for Data Protection in ASP.NET Core?
Thank you

A: I included 3 packages to the console project:

*

*Microsoft.AspNetCore.DataProtection

*Microsoft.AspNetCore.DataProtection.Abstractions

*Microsoft.AspNetCore.DataProtection.Extensions

This makes the console project working.