text:
Q: How do I connect an existing solution in Visual Studio 2015 to an existing Project in Visual Studio Team Services Project I have an existing solution on my desktop.  My IT administrator created a project on Visual Studio Team Services for me to connect my solution to.  However, I have no found any way that will actually work.  So far I have tried to:
First attempt. Result is all of my files have have the locked icon next to them as if they have been check in but there is no way to upload the code.
 1. Connect my Team Explorer in Visual Studio 2015 to my online account.
 2. Right click on my solution and click Add Solution to source control.
Second attempt. Result, same as first attempt.
 1. Go to visualstudio.com and select my project, then select the code tab. Click on clone in Visual Studio.
 2. In Visual Studio, open my solution and click Add Solution to source control.
I cannot find a location to enter my clone URL into my solution in Visual Studio. I checked in both Solution Explorer and Team Explorer and there appears to be no option.  This is very frustrating because Microsoft gives very little instruction online.

A: If you are using TFVC, you need to configure the workspace first after connecting to your team project from Team Explorer and move your solution/project to the workspace folder. And then you can right click on the solution to add it to source control and check in. Refer to this link for details: Add an existing app.
If you are using Git, you can clone the VSTS remote repository to your local machine from Team Explorer and copy your solution into the local Git repository folder, and then commit the changes and push to VSTS. Refer to this link for details: Develop and share your code in Git using Visual Studio. You can also convert the folder of your solution to a local Git repository and then push it to VSTS remote repository via following commands:
git init
git add .
git commit -m 'commitcomment'
git remote add origin <vsts remote repository url>
git push origin master

A: Create a new Git repository for your solution in the VSTS project.
On the top left of the Code page is a dropdown with the option to create one.

A: You can also launch VS 2015 from your team project overview page in your Visual Studio Team Services account:

You can get more details at Connect to Team Services.


text:
Q: PyAudio throws ´unable to open slave` error Hi every time i execute pyauido.PyAudio() i get the following error.
I try to display the audio recorded by my mic using these instructions: https://swharden.com/wp/2016-07-19-realtime-audio-visualization-in-python/
and use my USB-Mic and the headphone-jack of my raspberry pi 3+
Expression 'alsa_snd_pcm_hw_params_set_period_size_near( pcm, hwParams, &alsaPer                                  iodFrames, &dir )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 924
Expression 'alsa_snd_pcm_hw_params_set_period_size_near( pcm, hwParams, &alsaPer                                   iodFrames, &dir )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 924
ALSA lib pcm_dmix.c:1108:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.hdmi
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.hdmi
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.modem
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.modem
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.phoneline
ALSA lib pcm.c:2565:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.phoneline
ALSA lib pcm_dmix.c:1108:(snd_pcm_dmix_open) unable to open slave
Expression 'alsa_snd_pcm_hw_params_set_period_size_near( pcm, hwParams, &alsaPer                                   iodFrames, &dir )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 924

Update: As mentioned in the comments i got rid of the "Unknown PCM" by editing the alsa.conf file, but i realised that the traceback was not added to the snippet i posted here so here is the "new, complete"-Message:
Expression 'alsa_snd_pcm_hw_params_set_period_size_near( pcm, hwParams, &alsaPeriodFrames, &dir )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 924
ALSA lib pcm_dsnoop.c:638:(snd_pcm_dsnoop_open) unable to open slave
ALSA lib pcm_dmix.c:1108:(snd_pcm_dmix_open) unable to open slave
ALSA lib pcm_dmix.c:1108:(snd_pcm_dmix_open) unable to open slave
Expression 'alsa_snd_pcm_hw_params_set_period_size_near( pcm, hwParams, &alsaPeriodFrames, &dir )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 924
Traceback (most recent call last):
  File "sound.py", line 9, in <module>
    frames_per_buffer=CHUNK)
  File "/usr/lib/python2.7/dist-packages/pyaudio.py", line 750, in open
    stream = Stream(self, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/pyaudio.py", line 441, in __init__
    self._stream = pa.open(**arguments)
IOError: [Errno -9996] Invalid input device (no default output device)

Additional information:
**** List of CAPTURE Hardware Devices ****
card 2: Device [USB PnP Audio Device], device 0: USB Audio [USB Audio]
  Subdevices: 1/1
  Subdevice #0: subdevice #0

[12:06:02] openhabian@openhab:~$ aplay -l
**** List of PLAYBACK Hardware Devices ****
card 0: b1 [bcm2835 HDMI 1], device 0: bcm2835 HDMI 1 [bcm2835 HDMI 1]
  Subdevices: 4/4
  Subdevice #0: subdevice #0
  Subdevice #1: subdevice #1
  Subdevice #2: subdevice #2
  Subdevice #3: subdevice #3
card 1: Headphones [bcm2835 Headphones], device 0: bcm2835 Headphones [bcm2835 Headphones]
  Subdevices: 4/4
  Subdevice #0: subdevice #0
  Subdevice #1: subdevice #1
  Subdevice #2: subdevice #2
  Subdevice #3: subdevice #3

.asoundrc - configuration:

pcm.!default {
  type asym
  capture.pcm "hw:2,0"
  playback.pcm "hw:1,0"
}

A: If anyone else comes along this problem here at least a solution for removing the "Unknown..."-Messages:
PyAudio working, but spits out error messages each time

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extract bounding box points from IAM paragraph xml file
import xml.etree.ElementTree as ET
from xml.sax.saxutils import unescape
import glob
import sys,os

classes = ['line']
xml_dir = "annots/"
output_dir = "labels/"
image_dir = "images/"

index=0
files = glob.glob(os.path.join(xml_dir, '*.xml'))
for file in files:
    base_name = os.path.basename(file)
    filename = os.path.splitext(base_name)[0]
    if not os.path.exists(os.path.join(image_dir, f"{filename}.jpg")):
        print(f"{filename} image does not exist!")
        continue
    print(f'form {file}')
    width, height = int(root.attrib['width'])//2, int(root.attrib['height'])//2
    root = ET.parse(file).getroot()
    xmin, ymin = [sys.maxsize] * 2
    xmax, ymax = [0] * 2
    ftxt = ''
    result = []

    for line in root.findall('.//line'):
        txt,id = line.attrib['text'],line.attrib['id']
        txt = unescape(txt, {"'": "'", """: '"'})
        ftxt = ftxt + txt + '\n'

        for cmp in line.findall('.//cmp'):
            dm = list(map(int,[ cmp.attrib['x'],cmp.attrib['y'],cmp.attrib['width'],cmp.attrib['height']]))
            print(f'xmin = {xmin} , dm = {dm[0]}')
            xmin = min(xmin,dm[0])
            print(f'just got xmin of:  {xmin}')
            ymin = min(ymin,dm[1])
            xmax = max(xmax,dm[0]+dm[2])
            ymax = max(ymax,dm[1]+dm[3])

        # devide by 2 because image has been downsampled by a factor of 2
        pil_bbox = [xmin//2, ymin//2, xmax//2, ymax//2]
        yolo_bbox = xml_to_yolo_bbox(pil_bbox, width, height)
        bbox_string = " ".join([str(x) for x in yolo_bbox])
        result.append(f"{index} {bbox_string}")

        if result:
            with open(os.path.join(output_dir, f"{filename}.txt"), "w", encoding="utf-8") as f:
                f.write("\n".join(result))

I am trying to find the bbox points for each line from this Iam dataset file. I get the lower bounds correct but the upper bound seem to be not updating, specifically the y1 and y2 values with the code above.
can anyone give it a shot for me? image attached and xml below: note: the cordinates at the end should be devided by 2 because the image has been downsampled by a factor of 2

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE form SYSTEM 'http://www.iam.unibe.ch/~fki/iamdb/form-metadata.dtd'>

<form created="2002-01-15" height="3542" id="b04-208" last-modified="2002-07-17" skew="30" status="final" version="3.0_beta" width="2479" writer-id="114">
  <machine-printed-part>
    <machine-print-line text="At the beginning of this wonderful century many people believed that there were no" />
    <machine-print-line text="more worlds to conquer." />
  </machine-printed-part>
  <handwritten-part>
    <line ass="-691" asx="0" asy="518" character-width="999" dss="-691" dsx="0" dsy="706" fd0="12676" fd1="2502" fd2="-1099" filter-width="3" id="b04-208-00" lbs="-763" lbx="0" lby="611" segmentation="ok" slant="87000" stroke-width="4877" threshold="182" text="At the beginning of this wonderful century many" ubs="-549" ubx="0" uby="580">
      <word id="b04-208-00-00" sentence-start="yes" tag="IN" text="At">
        <cmp x="358" y="561" width="34" height="75" />
        <cmp x="392" y="565" width="33" height="71" />
      </word>
      <word id="b04-208-00-01" tag="ATI" text="the">
        <cmp x="465" y="557" width="96" height="74" />
      </word>
      <word id="b04-208-00-02" tag="NN" text="beginning">
        <cmp x="614" y="527" width="36" height="103" />
        <cmp x="647" y="576" width="78" height="134" />
        <cmp x="731" y="580" width="8" height="11" />
        <cmp x="738" y="586" width="47" height="42" />
        <cmp x="790" y="590" width="71" height="39" />
        <cmp x="858" y="571" width="9" height="8" />
        <cmp x="869" y="592" width="80" height="127" />
      </word>
      <word id="b04-208-00-03" tag="INO" text="of">
        <cmp x="999" y="598" width="35" height="39" />
        <cmp x="1031" y="555" width="40" height="158" />
      </word>
      <word id="b04-208-00-04" tag="DT" text="this">
        <cmp x="1115" y="565" width="85" height="76" />
        <cmp x="1208" y="590" width="24" height="53" />
        <cmp x="1210" y="582" width="10" height="8" />
      </word>
      <word id="b04-208-00-05" tag="JJ" text="wonderful">
        <cmp x="1296" y="572" width="43" height="67" />
        <cmp x="1339" y="557" width="132" height="75" />
        <cmp x="1476" y="556" width="56" height="149" />
        <cmp x="1538" y="591" width="44" height="41" />
        <cmp x="1589" y="563" width="28" height="64" />
      </word>
      <word id="b04-208-00-06" tag="NN" text="century">
        <cmp x="1679" y="573" width="77" height="57" />
        <cmp x="1763" y="558" width="24" height="78" />
        <cmp x="1793" y="585" width="101" height="113" />
      </word>
      <word id="b04-208-00-07" tag="AP" text="many">
        <cmp x="1950" y="577" width="65" height="61" />
        <cmp x="2023" y="593" width="20" height="30" />
        <cmp x="2040" y="586" width="62" height="47" />
        <cmp x="2106" y="589" width="27" height="117" />
      </word>
      <lower-contour>
        <point x="356" y="714" />
        <point x="928" y="719" />
        <point x="2087" y="719" />
      </lower-contour>
    </line>
    <line ass="-383" asx="0" asy="713" character-width="999" dss="-383" dsx="0" dsy="851" fd0="12678" fd1="2659" fd2="-1157" filter-width="3" id="b04-208-01" lbs="-414" lbx="0" lby="800" segmentation="ok" slant="90000" stroke-width="4888" threshold="182" text="people believed that there were no more worlds to" ubs="-321" ubx="0" uby="764">
      <word id="b04-208-01-00" tag="NNS" text="people">
        <cmp x="356" y="737" width="61" height="118" />
        <cmp x="418" y="779" width="26" height="29" />
        <cmp x="453" y="733" width="45" height="114" />
        <cmp x="500" y="741" width="41" height="60" />
      </word>
      <word id="b04-208-01-01" tag="VBD" text="believed">
        <cmp x="605" y="718" width="60" height="90" />
        <cmp x="670" y="729" width="51" height="73" />
        <cmp x="720" y="758" width="5" height="4" />
        <cmp x="729" y="760" width="65" height="46" />
        <cmp x="798" y="734" width="62" height="77" />
      </word>
      <word id="b04-208-01-02" tag="CS" text="that">
        <cmp x="921" y="730" width="34" height="82" />
        <cmp x="959" y="729" width="29" height="80" />
        <cmp x="993" y="775" width="24" height="34" />
        <cmp x="1018" y="741" width="54" height="67" />
      </word>
      <word id="b04-208-01-03" tag="EX" text="there">
        <cmp x="1119" y="720" width="146" height="91" />
      </word>
      <word id="b04-208-01-04" tag="BED" text="were">
        <cmp x="1300" y="758" width="44" height="57" />
        <cmp x="1349" y="766" width="82" height="42" />
      </word>
      <word id="b04-208-01-05" tag="ATI" text="no">
        <cmp x="1489" y="752" width="33" height="73" />
        <cmp x="1517" y="772" width="31" height="39" />
        <cmp x="1552" y="777" width="25" height="35" />
      </word>
      <word id="b04-208-01-06" tag="AP" text="more">
        <cmp x="1624" y="748" width="69" height="72" />
        <cmp x="1696" y="785" width="20" height="29" />
        <cmp x="1720" y="769" width="47" height="44" />
      </word>
      <word id="b04-208-01-07" tag="NNS" text="worlds">
        <cmp x="1819" y="763" width="88" height="56" />
        <cmp x="1909" y="747" width="31" height="64" />
        <cmp x="1934" y="782" width="20" height="15" />
        <cmp x="1953" y="733" width="30" height="83" />
      </word>
      <word id="b04-208-01-08" tag="TO" text="to">
        <cmp x="2031" y="740" width="38" height="78" />
        <cmp x="2064" y="777" width="22" height="30" />
      </word>
      <upper-contour>
        <point x="356" y="714" />
        <point x="928" y="719" />
        <point x="2087" y="719" />
      </upper-contour>
      <lower-contour>
        <point x="357" y="855" />
        <point x="629" y="855" />
      </lower-contour>
    </line>
    <line ass="-2630" asx="0" asy="910" character-width="999" dss="-2630" dsx="0" dsy="1023" fd0="13343" fd1="2856" fd2="-650" filter-width="3" id="b04-208-02" lbs="-372" lbx="0" lby="980" segmentation="ok" slant="87000" stroke-width="4844" threshold="182" text="conquer." ubs="-7148" ubx="0" uby="887">
      <word id="b04-208-02-00" tag="VB" text="conquer">
        <cmp x="359" y="929" width="42" height="58" />
        <cmp x="378" y="929" width="4" height="7" />
        <cmp x="401" y="929" width="48" height="53" />
        <cmp x="460" y="953" width="29" height="92" />
        <cmp x="498" y="942" width="85" height="44" />
      </word>
      <word id="b04-208-02-01" tag="." text=".">
        <cmp x="618" y="980" width="10" height="12" />
      </word>
      <upper-contour>
        <point x="357" y="855" />
        <point x="629" y="855" />
      </upper-contour>
    </line>
  </handwritten-part>
</form>


text:
Q: Show outline of empty label in Visual Studio I am working on a XAML page in VS2012.
The page has a couple of empty labels (which programatically get filled in later). Because the labels are empty, they do not appear on the page unless moused over.
Is there any way to have VS show me the outline of these labels only in the design pane (so in release it would be invisible).

A: First and foremost, the comments are correct - you should fill the controls in with dummy values and then clear them on startup (either automatically with databinding, or otherwise).
Now, to actually answer the question, you can check if Visual Studio is in "Design Mode", and then programmatically set the border of a control... or better, set the text to something easily noticeable in the UI:
// Check for design mode.
if ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue))
{
    myTextBlock.Text = "*** DESIGN ***";
}

This code should be run in the constructor of your WPF window/control class (or something invoked from the constructor) so that the designer executes it.
The code to check for design time was taken from this post.


text:
Q: Как выбрать систему хранения данных innodb? На одном хостинге, при создании таблиц в базе данных, по умолчанию создаются таблицы myisam. И дело в том, что это нигде нельзя выбрать, чтобы по умолчанию создавались innodb.
Подскажите, как создавать таблицы innodb? т.е. допустим я устанавливаю wordpress и мне нужно, чтобы создавались таблицы innodb, а по умолчанию создаются myisam.
Можно ли как-то после установки wordpress, переопределить таблицы из myisam в innodb ?

Сейчас есть возможность проверить только на локальном сервере, на котором только innodb.
Взял код из приведённой ниже ссылки, и пытался конвертировать из innodb в myisam, но код почему-то не работает. Подскажите, что не так?
SELECT CONCAT('ALTER TABLE ',TABLE_NAME,' ENGINE=MyISAM;')
FROM INFORMATION_SCHEMA.TABLES
WHERE ENGINE='InnoDB'
AND table_schema = 'mydatabase';

второй код:
SET @DATABASE_NAME = 'name_of_your_db';

SELECT  CONCAT('ALTER TABLE `', table_name, '` ENGINE=MyISAM;') AS sql_statements
FROM    information_schema.tables AS tb
WHERE   table_schema = @DATABASE_NAME
AND     `ENGINE` = 'InnoDB'
AND     `TABLE_TYPE` = 'BASE TABLE'
ORDER BY table_name DESC;

естественно название бд ставил правильное:
в 1м коде table_schema = 'mydatabase';
во 2м SET @DATABASE_NAME = 'name_of_your_db';
в этом участке кода ставил свою бд

A: Создать новую базу с двихком "InnoDB" можно так:
https://dev.mysql.com/doc/refman/5.5/en/create-table.html
CREATE TABLE new_table
  (id INT, INDEX USING BTREE (id))
ENGINE = InnoDB;

Поменять старую:
https://dev.mysql.com/doc/refman/5.7/en/converting-tables-to-innodb.html
ALTER TABLE old_table ENGINE=InnoDB;

PS:
В вашем коде вариант

*

*Вы выбирете таблицы с innodb и создаете строку которая меняет их на MyISAM.

*вы так же выбераете innodb таблицы и создаете запрос который меняет их на innodb.

Ну и запрос(строку) который вам вернёт надо запустить!
Дополнил ваш вариант(
https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html
)
Меняем все innodb на MyISAM
SET @queryString = (
    SELECT GROUP_CONCAT(CONCAT("ALTER TABLE ", TABLE_NAME, " ENGINE='MyISAM';") SEPARATOR '')
        FROM INFORMATION_SCHEMA.TABLES
        WHERE ENGINE= 'InnoDB'
        AND table_schema = "mydatabase"
);

PREPARE q FROM @queryString;
EXECUTE q;
DEALLOCATE PREPARE q;


text:
Q: Host mail server and website on different machines under one domain Is there a way to host mail server for certain domain on different machine.
For example:
If I own website.com and it is hosted on PC1 what are the requirements to make mail.website.com and host it on PC2.
I am planning to use Linux Ubuntu-postfix-squirrel mail...

A: This is fairly normal.
In your DNS config you'll specify one or more MX record types - these are the hosts responsible for handling mail for your domain.   Note that they do not need to be hosts in your domain - ie, you can pay MS or Google for mail service, and you'd set your MX records to point to the MS or Google server.
Then for the website portion, normal A or CNAME records are used to point to a host.


text:
Q: Identifying a plain object in pure JS I'm trying to write a node.js script and want to keep the dependencies on the minimum. I want to make sure that a given argument called config is a plain object, like this:
var config = {
  'key1': 'val1',
  'key2': 'val2',
  'key3': 'val3'
  /* ... */
}

Now the first thing that came to mind was something like this:
if (Object.prototype.toString.call(config) !== '[object Object]') {
  /* ... */
}

Can anyone think of an example where this wouldn't hold? I thought it was better to add:
if (typeof config !== 'object' ||
  Object.prototype.toString.call(config) !== '[object Object]') {
  /* ... */
}

just to be sure! But I'm still not convinced it could be this easy. I need

*

*Critical analysis: is it unsafe, is it an overkill or is it plain wrong! Any reason not to use this.

*A better way: something that you would do instead.

Thank you very much for your time folks.

I had a look at jQuery source, and particularly at the function jQuery.isPlainObject() and it uses a slightly more complex approach. Where I am looking to establish if it's a plain object, jQuery is making sure it's not anything other than a plain object. Have a look here:
isPlainObject: function( obj ) {
    // Not plain objects:
    // - Any object or value whose internal [[Class]] property is not "[object Object]"
    // - DOM nodes
    // - window
    if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
        return false;
    }

    if ( obj.constructor &&
            !hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
        return false;
    }

    // If the function hasn't returned already, we're confident that
    // |obj| is a plain object, created by {} or constructed with new Object
    return true;
}


text:
Q: Zend framework form Decorators i am trying to get the following layout using decorators:
    <form action="/index/login" method="post" id="login_form">

            Username:
            <input type="text" name="username" value="" id="username" class="login_input"  />

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

            <input type="submit" name="login_submit" value="Login" class="login_submit"  />

    </form>

I have got this so far:
    $form = new Zend_Form;

    $form->setAction('/index/login')
         ->setMethod('post')
         ->setAttrib('id', 'login_form');

    $username = $form->createElement('text', 'username');
    $username->addValidator('alnum')
             ->setRequired(TRUE)
             ->setLabel('Username')
             ->setAttrib('class', 'login_input');

    $username->setDecorators(array(
            'ViewHelper',
            'Errors',
            array('Label',array('class' => 'login_label')),
            array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'input_row')
        ));

    $form->addElement($username)
         ->addElement('submit', 'login', array('label' => 'Login'));

How do i place the  tag above the label?
Thanks!

A: I prepared an example that should be helpful in solving your problem. Here it is:
    $form = new Zend_Form;

    $form->removeDecorator('htmlTag');

    $form->setAction('/index/login')
            ->setMethod('post')
            ->setAttrib('id', 'login_form');

    $username = $form->createElement('text', 'username');

    $username->addValidator('alnum')
            ->setRequired(TRUE)
            ->setLabel('Username')
            ->setAttrib('class', 'login_input');

    // anonymous function that will generate your image tag
    $makeImg = function($content, $element, array $options) {
                return ' ';
            };

    $username->setDecorators(array(
        'ViewHelper',
        'Errors',
        array('Label', array('class' => 'login_label')),
        array('Callback',
            array(
                'callback' => $makeImg,
                'img' => 'user_icon.png',
                'class' => 'login_icon',
                'placement' => 'PREPEND'
            )
        ),
        array('HtmlTag', array('tag' => null, 'class' => 'input_row')),
    ));

    $form->addElement($username);

    $submit = $form->createElement('submit', 'login', array(
                'label' => 'Login',
                'class' => 'login_submit'
                    )
    );

    $submit->setDecorators(array(
        'ViewHelper',
        'Errors',
        array('HtmlTag', array('tag' => null, 'class' => 'input_row')),
    ));

    $form->addElement($submit);

The form generates the following html (I did not generated password field as your Zend_Form code does not contain it):
 <form id="login_form" enctype="application/x-www-form-urlencoded" action="/index/login" method="post">

         Username
         <input type="text" name="username" id="username" value="" class="login_input">

         <input type="submit" name="login" id="login" value="Login" class="login_submit">

   </form>

What's worth mentioning is that I used Callback decorator. With this decorator you can call any function that can be used to inject custom html into your forms. In this example I made an anonymous function that I assigned to $makeImg variable (for this you need PHP 5.3 but in older versions of PHP you could do it also, but using e.g. create_function function). This $makeImg variable is my callback. As can be seen the function generates your img html tag.
Hope this will be helpful to you.

A: you can use form decorator
After add element set setDecorators here you can write HTML as you wan to show.
$this->addElements(array(
           $id,
           $group_id,
           $content_name,
           $title,
           $content,
           $tags,
           $status,
           $Publish
       ));

      $this->setDecorators(array(array('viewScript', array('viewScript' => 'admin/articleFormDecorator.phtml'))));

A: You could check out the AnyMarkup decorator:
http://www.zfsnippets.com/snippets/view/id/62/anymarkup-decorator


text:
Q: When setting a font-size in CSS, what is the real height of the letters? There is a similar question here whose answer in essence says:

The height - specifically from the top of the ascenders (e.g., 'h' or 'l' (el)) to the bottom of the descenders (e.g., 'g' or 'y')

This has also been my experiance. I.e. in 14px Arial the height of the letter K (the baseline height) is about 10px.
The specs say nothing about the calculated font-size so I'm guessing this is browser-specific, but I could not find any reference to it.
(Other questions here and here ask roughly the same thing but sadly no answer gives a satisfying explanation..)
Is there any documentation on why the font-size seems to be the size "from ascenders to descendes"?

A: The answer regarding typesetting is excellent, but be aware css diverges from traditional typography in many cases.
In css the font-size determines the height of the "em-box". The em-box is a bounding box which can contain all letters of the font including ascenders and descenders. Informally you can think of font-size as the "j"-height, since a lower case j has both ascender and descender and therefore (in most fonts) uses the full em-box height.
This means most letters (like a capital M) will have space above and below in the em-box. The relative amount of space above and below a capital letter will vary between fonts, since some fonts have relatively larger or smaller ascenders and descenders. This is part of what stylistically sets fonts apart for each others.
You ask why font-size is including ascenders and descenders, ie. why it correspond to the height of the em-box, even though the height of most letters will be less than this. Well, since most texts do includes letters with ascenders and descenders, the em-box height indicates how much vertical space the text require (at minimum), which is quite useful!
An caveat: Some glyphs may even extend beyond the em-box in some fonts. For example the letter "Å" often extend above the em-box. This is a stylistic choice by the designer of the font.

A:
Some background on the subject
Back when letters were created on metal, the em referred to the size of each block that the letter would be engraved on, and that size was determined by the capital M because it usually takes up the most space.
Now a days, font developers create their fonts on a computer without the limitations of a physical piece of metal so while the em still exists, its nothing more than an imaginary boundary in the software; thus prone to being manipulated or disregarded altogether.
Standards
In an OpenType font, the em size is supposed to be set to 1000 units. And in TrueType fonts, the em size is usually either 1024 or 2048.
The most accurate way to define a font style is to use EM that way when you define a font-size for use, the dimension does not refer to the pixel height of the font, but to the fonts x height which is determined by the distance between the baseline and the mean line of the font.
For the record 1 PT is about 0.35136mm.  And PX is 1 "dot" on your screen which is defined by the dots per square inch or resolution of your screen and thus different from screen to screen and is the worst way to define a font size.
Unit conversion
This is a pretty good read if you enjoy literature that makes your eyes bleed like me..  International unification of typopgrahic measurements
1 point (Truchet)                    |  0.188 mm
1 point (Didot)                      |  0.376 mm or 1/72 of a French royal inch
1 point (ATA)                        |  0.3514598 mm or 0.013837 inch
1 point (TeX)                        |  0.3514598035 mm or 1/72.27 inch
1 point (Postscript)                 |  0.3527777778 mm or 1/72 inch
1 point (l'Imprimerie nationale, IN) |  0.4 mm
1 pica (ATA)                         |  4.2175176 mm = 12 points (ATA)
1 pica (TeX)                         |  4.217517642 mm = 12 points (TeX)
1 pica (Postscript)                  |  4.233333333 mm = 12 points (Postscript)
1 cicero                             |  4.531 mm = 12 points (Didot)

Resolutions

µm  :  10.0    20.0    21.2    40.0    42.3    80.0    84.7    100.0    250.0    254.0
dpi :  2540    1270    1200    635     600     317     300     254      102      100

Standards are only worth so much..
The actual size of one fonts glyphs vs another font are always going vary dependent on:

*

*how the developer designed the font glyphs when creating the font,

*and how the browser renders those characters.  No two browsers are going to be exactly the same.

*the resolution and ppi of the screen viewing the font.

Example
As an example of how common it is for font developers to manipulate the geometry.. Back when Apple created the Zapfino script font, they sized it relative to the largest capitals in the font as would be expected but then they decided that the lowercase letters looked too small so a few years later they revised it so that any given point size was about 4x larger than other fonts.
If you don't have a headache, read some more..
There's some good information on Wikipedia about modern typography and origins; and other relevant subjects.

*

*Point (typography)

*Pixels per inch

*Font metrics

*Typographic units
And some first-hand experience
If you want to get more first-hand understanding you can download the free font development tool FontForge which is comparable to the non-free FontLab Studio (either of these two being the popular choice among font developers in my experience).  Both also have active communities so you can find plenty of support when learning how to use them.

*

*Fontlab Studio

*Fontlab Fontographer

*FontForge

*Fontlab Wikibook

*FontForge Documentation

A: After searching for a satisfying answer to a similar question, I found this graphic to be a lot of help...
http://static.splashnology.com/articles/Choosing-the-Best-Units/font-units-large.png

A: I've experimented to pin down exactly what the font-size corresponds to in terms of font-metrics (as shown in the diagram in davidcondrey's answer).
Testing on Safari, Chrome and Firefox on macOS, setting font-size to 100px seems to set the apparent size of difference between the ascender line and descender line to 100px.
Unfortunately, there's multiple meanings for the ascender and descender when talking about different font formats, so to disambiguate in the case of OpenType, we're talking about the 'Typo Ascender' and the 'Typo Descender' from the OS/2 table.
OpenType CSS font-height diagram
An interactive illustration is available on the opentype.js glyph inspector https://opentype.js.org/glyph-inspector.html
When positioning the character (again in terms of OpenType metrics), browsers seem to consider y = 0 to be the Ascender, (which is not the same as the 'ascender line' in davidcondrey's diagram, but instead it's the ascender in the hhea table in OpenType). However, if CSS line-height is not set to normal, the position is offset by some amount but I think the rules here might be a bit more complex.
I expect there's more that factors in and it may be different between operating systems and browsers, however this is at least a good approximation.


text:
Q: How can I access MongoDb in Asp.Net Core with a Username and Password? I have tried connecting to the database following several different tutorials. Each has had their own method for connecting to MongoDb but none of them have shown me how to connect using a username and password. Here is what I am dealing with:
Startup.cs file:
  namespace ShortenUrl
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }

            public IConfiguration Configuration { get; }

            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();

                services.AddSingleton<MongoConfig>(Configuration.GetSection("mongo").Get<MongoConfig>());         // Similar To:    Configuration.GetSection("MongoConfig:Server").Value;
                services.AddSingleton<MongoConnector>();                                                          //                options.Database =
                services.AddSingleton<Database>();                                                                //                Cofiguration.GetSection("MongoConfig:Database").Value;
                services.AddTransient<UsersRepository>();
            }

            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseBrowserLink();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }

                app.UseStaticFiles();

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }

namespace ShortenUrl.Services.Mongo
{
    public class MongoConnector
    {
        public MongoConnector(MongoConfig config)
        {
            Client = new MongoClient(new MongoClientSettings
            {
                Server = MongoServerAddress.Parse(config.Server),
                Credential = MongoCredential.CreateCredential(config.Creds.Db, config.Creds.User, config.Creds.Password),
                UseSsl = true,
                VerifySslCertificate = false,
                SslSettings = new SslSettings
                {
                    CheckCertificateRevocation = false
                }
            });

            Database = Client.GetDatabase(config.Database);
        }

        public IMongoClient Client { get; }

        public IMongoDatabase Database { get; set; }
    }
}

And appsettings.json:
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "mongo": {
    "server": "****************",
    "database": "**********",
    "creds": {
      "db": "**********",
      "user": "**********",
      "password": "**********"
    }
  }

This is my Controller with a post method for adding the user permissions and gain access to the database:
public class UsersController : Controller
    {
        private readonly UsersRepository _repo;

        public UsersController(UsersRepository repo)
        {
            _repo = repo;
        }

        [HttpPost]
        public async Task<IActionResult> Post ([FromBody] string user)
        {
            await _repo.CreateAsync(user);
            return new OkObjectResult(user);
        }

    }
}

And this is the repository:
public class UsersRepository
{
    private readonly Database _db;

    public UsersRepository(Database db)
    {
        _db = db;
    }

    public async Task<User> CreateAsync(string username)
    {
        var user = new User { Username = username };
        await _db.Users.InsertOneAsync(user);
        return user;
    }

Update
Model Config:
namespace ShortenUrl.Services.Configs
{
    public class MongoCreds
    {
        public string Db { get; set; }
        public string User { get; set; }
        public string Password { get; set; }
    }
    public class MongoConfig
    {
        public string Server { get; set; }
        public string Database { get; set; }
        public MongoCreds Creds { get; set; }
    }
}

Connector:
public class MongoConnector
    {
        public MongoConnector(MongoConfig config)
        {
            Client = new MongoClient(new MongoClientSettings
            {
                Server = MongoServerAddress.Parse(config.Server),
                Credential = MongoCredential.CreateCredential(config.Creds.Db, config.Creds.User, config.Creds.Password),
                UseSsl = true,
                VerifySslCertificate = false,
                SslSettings = new SslSettings
                {
                    CheckCertificateRevocation = false
                }
            });

            Database = Client.GetDatabase(config.Database);
        }

        public IMongoClient Client { get; }

        public IMongoDatabase Database { get; set; }
    }
}

A: Added the route attribute and now it works.
namespace ShortenUrl.Controllers
{
    [Route("api/codes")]
    public class ShortUrlsController : Controller
    {
        private readonly ShortUrlRepository _repo;
        //private readonly IShortUrlService _service;

        public ShortUrlsController(ShortUrlRepository repo  /*IShortUrlService service*/)
        {
            _repo = repo;
            //_service = service;
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> Get(string id)
        {
            var su = await _repo.GetAsync(id);

            if (su == null)
                return NotFound();

            return Ok(su);
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody] ShortUrl su)
        {
            await _repo.CreateAsync(su);
            return Ok(su);
        }
   }
}

More information on routing to controller actions can be found HERE!


text:
Q: Java not finding the information I can not get the data to correctly be inserted. Ever one that says NULL should have information in them, ID = 56512, Fist Name = Thomas and so on. This also is a converter, so for the future it most be able to change the information, as long it is sample 1 text
A few thinks i have change the input information
public static void outputXML(String filename, String sampletxt, String dataxml)
    {
        try {
            try (PrintWriter pw = new PrintWriter(filename)) {
                pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                pw.println("<!-- XML Converter byWe-Code-Stuff, LLC.Developer: Benjamin Bolyard -->");
                pw.println("<accounts>");
                pw.println("<account>");
                String Id = null;
                pw.println("<manager employeeId>" + Id);
                String data = null;
                String firstName = null;
                pw.println("<first>" + firstName + "</first>");
                String lastName = null;
                pw.println("<last>" + lastName + "</last>");
                pw.println("</manager>");
                pw.println("<location>");
                String city = null;
                pw.println("<city>" + city + "<city>");
                String state = null;
                pw.println("<state>" + state + "</state>");
                String zip = null;
                pw.println("<zipcode>" + zip + "</zipcode>");
                String count = null;
                pw.println("<companies count>" + count);
                String companyname = null;
                pw.println("<companies>" + companyname + "</companies>");
                pw.println("</companies>");
                pw.println("</location>");
                pw.println("</account>");
                pw.println("</accounts>");
            }
        } catch (FileNotFoundException ex) {
            System.out.println("Error: " + ex);
        }

sample

56512: THOMAS KACI BRADFORD TN 37059
56512: ENCOMPASS SERVICES CORPORATION
56512: BURLINGTON COAT FACTORY WAREHOUSE CORPORATION
56512: WEATHERFORD INTERNATIONAL, INC
56512: CYTEC INDUSTRIES, INC
56512: --END_MANAGER--
10777: ROBINSON BRIONNA HUNTLAND TN 37889
10777: UNITED PARCEL SERVICE, INC
10777: GENERAL CABLE CORPORATION
10777: GENTEK, INC
10777: QUESTAR CORP.
10777: AGILENT TECHNOLOGIES
10777: CHARTER ONE FINANCIAL, INC
10777: KINDRED HEALTHCARE, INC
10777: --END_MANAGER--

Correct information replacing NULL.


text:
Q: How to remove a child from a random array? I have an array that randomly creates 10 dots. However there's a certain area where I do not want them to be created. How can I achieve this? My code gives me error 2025.
"The supplied DisplayObject must be a child of the caller."
It will occasionally output the totalDots as instructed, (trace""+totalDots), but 90% of the time it will give me the error.
public var numDots:Array = [];
public var totalDots:int = numDots.length;
public var box:Box = new Box();

public function addBox():void
{
     box.x = stageWidth/2;
     box.y = stageHeight/2;
     addChild(box);
}
private function addDot():void
{
    for(var i:int = 0; i < 10; i++)
    {
        var dot:Dot = new Dot();
        dot.x = Math.floor(Math.random() * stageWidth);
        dot.y = Math.floor(Math.random() * stageHeight);
        this.addChild(dot);
        totalDots++;
        trace(""+totalDots);

        for(var j:int = 0; j < totalDots; j++)
        {
            if(numDots[j].hitTestObject(box))
            {
                stage.removeChild(numDots[j]);
                numDots.splice(j, 1);
                totalDots--;
            }
        }
    }

}

A: Your problem is your nested loop. With each iteration, you add one new dot, and then loop over all of the existing ones, and remove them if it collides with the box. I don't think that's what you intended to do.
It looks like you just want to make sure the dots are not added within a certain area. In that case, keep it simple with a do while loop:
for(var i:int = 0; i < 10; i++)
{
    var dot:Dot = new Dot();
    this.addChild(dot);
    do {
        dot.x = Math.floor(Math.random() * stageWidth);
        dot.y = Math.floor(Math.random() * stageHeight);
    } while(dot.hitTestObject(box))
    totalDots++;
    trace(""+totalDots);
}

A: You never add any dot to your array.
You add the dot to the display list like so:
this.addChild(dot);

and you try to remove it like so:
stage.removeChild(numDots[j]);

Despite the fact that the dot is never added to the array, this couldn't have worked even if it was. That's because this is not stage. They are two different things.
You should never use stage.addChild() (check the documentation for more info on that). Just call addChild() all the time which is equivalent to this.addChild(). This ensures that you always operate on one and the same DisplayObjectContainer

A: For what it's worth, you can avoid the trial loop altogether by calculating a random value with the proper interval (the difference between the include and exclude areas) and deriving x and y coordinates from that.
The following code (written in a language I do not know, apologies if the syntax is faulty) has two cases.  The if case handles the situation where the dot will appear left or right of the exclusion box, and the range of x values is restricted to being left or right of that box.  The else case is where the dot will appear above or below the box, and the x values are not restricted.
var interval:int = stageWidth * stageHeight - box.w * box.h;
var cut:int = interval - (stageWidth - box.w) * box.h;
for (var i:int = 0; i < 10; i++) {
    var r:int = Math.floor(Math.random() * interval);
    var x:int;
    var y:int;
    if (r >= cut) {
        r -= cut;
        y = r / (stageWidth - box.w);
        x = r - y * (stageWidth - box.w);
        y += box.y;
        if (x >= box.x) x += box.w;
    } else {
        y = r / stageWidth;
        x = r - y * stageWidth;
        if (y >= box.y) y += box.h;
    }
    var dot:Dot = new Dot();
    dot.x = x;
    dot.y = y;
    this.addChild(dot);
    totalDots++;
    trace(""+totalDots);
}

This assumes that box is entirely within stageWidth,stageHeight.
Also notable is that it allows the dots to overlap; same as the original code.
For more complex shapes you can set box to the largest rectangle fully enclosed by that shape so as to avoid many but not all retry cases.  This can be helpful for large shapes and many dots.  Or there are variations which might manage a perfect fit to another shape (eg., an ellipse).


text:
Q: @media css responsive design I have wrote the following media queries for different breakpoints in a css file.
@media all and (max-width: 350px) {}
@media all and (min-width: 350px) and (max-width: 440px) {}
@media all and (min-width: 440px) and (max-width: 768px)  {}
@media all and (min-width: 768px) {}

Will there be conflict between the media query when the width is at 440px or 768px?
Because when I test it on browser, it seems that some of the css font specified in the media queries are not pick up in the browser.
Was thinking of writing it in the following way, is the following okay or are there other way to write the media query in better way?
@media all and (max-width: 350px) {}
@media all and (max-width: 440px) {}
@media all and (max-width: 768px)  {}
@media all and (min-width: 768px) {}

A: there is one another way which i prefer for writing @media queries
it might be not the good way but it comes handy
@media (max-width: 780px){
    // your code here..
}

@media (max-width: 320px){
    // your code here..
}

make sure you go in descending order of max-width i.e. the higher max-width should come first then lower max-width
there must not be two @media query for same max-width if so make it one
hope so this might work for you


text:
Q: Is it possible to host plain HTML files in Google Apps? I'd like to upload a handful of HTML files that I want to replace an existing Google Site.
I know I can edit the HTML for each page in Google Sites, but I can't just upload my HTML files or even copy-paste them.  I have CSS files and JS files as well.
Is it even possible in Google Apps? Or do I have to use a 3rd-party web host?

A: AppEngine can host static files, and can be mapped to a subdomain of your Google Apps domain (ie, if you have example.com, you can make your appengine app be static.example.com, or www.example.com).
You'll need a tiny amount of python (or java) code to make it work.

A: Unfortunately, that's not possible with Google Apps. You can try Microsoft Office Live Small Business. Once signed up (it's free), activate the third-party design tools option to use upload directly into the web folder.

A: I don't think you can host your own html on Google Sites this in any way that I know of. I tried importing an html file as an "attachment" (this is what Google Sites seem to call any files intended for site visitors to download). Here is the screenshot:

Looks like they actively don't want you to use the service this way.
If you want to host a basic site for free, there are several site builders out there (including Google Sites) that let you do this. I checked out the one I use (weebly) and it seems they don't let you load an uploaded html page as a normal page either. Looks like preventing people from uploading content not created via the site builder itself. One workaround might be creating a blank template & uploading all content via the "custom html" tag.
This isn't what free site builders are intended for though & may not work forever. If you want to host an actual site, you'd probably be better off with something built for that purpose.


text:
Q: how to verify if my datatable is empty hello again y have populate my datatable using 1 button an array, next button 2 is going to send my datatable to excel, so what a i do is this using C#, and asp.net:
out side of the button y declare my datable so i can be use in both buttons
    System.Data.DataTable _myDataTable =new System.Data.DataTable();

button 1 fill datatable: for this example lets say only 10 columns, caract=number of cells
for (int k=0; k < 10; k++)
{
    _myDataTable.Columns.Add();
}

for (int j=0; j < 10; j++)
    {
    TableRow r = new TableRow();
    System.Data.DataRow row=_myDataTable.NewRow();
    for (int i = 0; i < caract+1; i++)
    {
        row[i]=(datar[j,i].ToString());
    }
    _myDataTable.Rows.Add(row);
    Table1.Rows.Add(r);
    }

now button 2 allows to the user if he wants to save the data from the datatable to an excel, but first i verifi if the datable is empty
if(_myDataTable !=null || _myDataTable.Rows.Count == 0)
    {

    string name="productos";
    Label2.Text="it has data";
            }
           else{Label2.Text="NO data"; }

no i recibe the text that i have data yupi for me, but when i press button 2 to send the datatable to excel, it creats the document however is empty,
so the next thing i would like to try is to verifi cell by cell if it has the data is supposed to have, but only have no idea how to extract the data from the datatable and to be display in a label.
I appreciate any help

A: Your if condition looks wrong on a couple of points.
This is how I would code it:
if(_myDataTable !=null && _myDataTable.Rows.Count > 0)

The above means - if _myDataTable is a valid object and it contains values.

A: JUAN you can define your DataTable in global scope. Then you can use it in both of your button event handlers.
For example:
namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {
        private DataTable _myDataTable;
        public DataTable MyDataTable {
            get
            {
                return _myDataTable;
            }
            set
            {
                _myDataTable = value;
            }
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        for (int k=0; k < 10; k++)
        {
            MyDataTable.Columns.Add();
        }

        for (int j=0; j < 10; j++)
        {
            TableRow r = new TableRow();
            System.Data.DataRow row = MyDataTable.NewRow();
            for (int i = 0; i < caract+1; i++)
            {
                row[i]=(datar[j,i].ToString());
            }
                MyDataTable.Rows.Add(row);
                Table1.Rows.Add(r);
        }

    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        if(MyDataTable !=null || MyDataTable.Rows.Count == 0)
        {

            string name="productos";
            Label2.Text="it has data";
        }
        else
        {
            Label2.Text="NO data";
        }
    }
}

}

A: I know this is an old question but there is an easy way to solve this right now as follows:
if ((dataTableName?.Rows?.Count ?? 0) > 0)


text:
Q: Call different list with similar name in a for loop I have a few lists that are with names: group1, group2, group3...
I need a for loop (lets say for (int i=1; i<=6; i++) and right now I check for example if i is 1 then use group1, if i is 2 use group2 etc... My question is, can I call the list with the 'i' in the end? Like groupi and when i is 1, its group1, when i is 2, its group2 etc. Here is the code:
for (int i = 0; i < groupNum; i++)
{
    if (i == 0)
    {
        foreach (Player p1 in group1)
        {
            foreach (Player p2 in group1)
            {
                if (p1 != p2)
                {
                    if (group1.IndexOf(p1) > group1.IndexOf(p2))
                    {
                        Game game = new Game(tournamentID, p1.id, p2.id);
                        game.status = "Pending";
                        gm.CreateGame(game);
                    }
                }
            }
        }
    }

    else if (i == 1)
    {
        foreach (Player p1 in group2)
        {
            foreach (Player p2 in group2)
            {
                if (p1 != p2)
                {
                    if (group2.IndexOf(p1) > group2.IndexOf(p2))
                    {
                        Game game = new Game(tournamentID, p1.id, p2.id);
                        game.status = "Pending";
                        gm.CreateGame(game);
                    }
                }
            }
        }
    }

    else if (i == 2)
    {
        foreach (Player p1 in group3)
        {
            foreach (Player p2 in group3)
            {
                if (p1 != p2)
                {
                    if (group3.IndexOf(p1) > group3.IndexOf(p2))
                    {
                        Game game = new Game(tournamentID, p1.id, p2.id);
                        game.status = "Pending";
                        gm.CreateGame(game);
                    }
                }
            }
        }
    }

    else if (i == 3)
    {
        foreach (Player p1 in group4)
        {
            foreach (Player p2 in group4)
            {
                if (p1 != p2)
                {
                    if (group4.IndexOf(p1) > group4.IndexOf(p2))
                    {
                        Game game = new Game(tournamentID, p1.id, p2.id);
                        game.status = "Pending";
                        gm.CreateGame(game);
                    }
                }
            }
        }
    }

    else if (i == 4)
    {
        foreach (Player p1 in group5)
        {
            foreach (Player p2 in group5)
            {
                if (p1 != p2)
                {
                    if (group5.IndexOf(p1) > group5.IndexOf(p2))
                    {
                        Game game = new Game(tournamentID, p1.id, p2.id);
                        game.status = "Pending";
                        gm.CreateGame(game);
                    }
                }
            }
        }
    }

    else if (i == 5)
    {
        foreach (Player p1 in group6)
        {
            foreach (Player p2 in group6)
            {
                if (p1 != p2)
                {
                    if (group6.IndexOf(p1) > group6.IndexOf(p2))
                    {
                        Game game = new Game(tournamentID, p1.id, p2.id);
                        game.status = "Pending";
                        gm.CreateGame(game);
                    }
                }
            }
        }
    }

As you can see, the code for different if statements is literally the same but the only difference is in using different lists with similar name (group1, group2..).

A: In General
This comes up a lot. No; you cannot programmatically build a variable name. By the time the code is compiled the variable names are gone anyway
If you ever have variables with names like
something1
something2
something3

etc, then this is a candidate for using an array but remember arrays start from 0
var something = new Thing[3];

(In your case the Thing is e.g. a Player)
Now you can have a fixed part and a varying part in your name:
Before you had    Now you have
--------------    ------------
something1        something[0]
something2        something[1]
something3        something[2]

Arrays can be looped over with a for or foreach, and they can be accessed at random with hard coded indexes like above. Just like your code only having 3 variables named somethingX your array also has a fixed number of 3 values. Arrays don't grow
If you need something that works like an array but does grow, use a List:
var something = new List<Thing>();

This is a list of Thing, just like before you had an array of Thing.

Also, don't forget about dictionaries, which are like lists, in that they grow, but they can be indexed by anything, so you can programmatically build an index, and unlike arrays/lists which are indexed by an incrementing integer, a dictionary can skip out some indexes:
var dict = new Dictionary<int, Thing>();

This means "a dictionary indexed by an int and holding a Thing"
Now, this is possible:
dict[1] = new Thing();
dict[2] = new Thing();
dict[4] = new Thing(); //we skipped

The key can be anything, for example a string:
var dict = new Dictionary<string, Thing>();
dict["something1"] = new Thing();
dict["something2"] = new Thing();
dict["sometheng4"] = new Thing(); //watch out for typos!

You can programmatically build the key:
int x = 1;
dict["something"+x].SomePropertyOfThing = "Hello";

The only thing to note is that dictionary doesn't necessarily store it's contents in any kind of order. If you foreach it you might get the entries out in something2, sometheng4, something1 order. If you need order, you either have to sort the dict.Keys and then use it to access the dictionary, or you use a SortedDictionary or OrderedDictionary depending what you want

In summary, those are the main kinds of collections we use in C#; they have different strengths and weaknesses and choosing which to use in a situation is often an important engineering decision
Final point of note; strive to use plural names when working with collections, as it makes the code easier to reason about
Specifically in this case
In your particular case you're actually looking for an array of arrays, and a bit of LINQ might make your code easier to deal with:
var groups = new []{ group1, group2, group3 };

foreach(var g in groups)
  foreach(var p1 in g)
    foreach(var p2 in g.Where(p => p.id > p1.id))
      gm.CreateGame(new Game(tournamentID, p1.id, p2.id){status = "Pending"});

If you want to make just one tournament for a particular group N, replace the foreach(var g in groups) with var g = groups[N]

This logic you have of "for each player 1, for each player 2, if they aren't the same player, find the index of the player 1, find the index of the player 2, if the one index is less than the two index" contains redundant logic, and it wastes resources finding things it has already found
Saying "for every player1 in the group, for every player2 whose id is greater than player1" cuts all that out. Player 2 must be a different player to Player 1 because their id is greater. There is no need to look up the index; you could shortcut your code to comparing the IDs rather than doing a notequals check then finding indexes then comparing
If your ID values aren't intrinsically comparable in a greater than sense for some reason (I assumed they would be ints) you can use a bit more linq to assign an index i to each player p in a group:
var groups = new []{
  group1.Select((p,i) => (p,i)),
  group2.Select((p,i) => (p,i)),
  group3.Select((p,i) => (p,i))
};

This make a tuple of the player, and the index they're at, so a similar logic as before can work:
foreach(var g in groups)
  foreach(var p1t in g)
    foreach(var p2t in g.Where(pt => pt.i > p1t.i))
      gm.CreateGame(new Game(tournamentID, p1t.p.id, p2t.p.id){status = "Pending"});

This time the Where demands the index i be greater for player 2
You should name your properties using PascalCase, not camelCase

A: As has already been suggested, you could collect all your groups in an array, and then iterate over that group array:
List<Player>[] groups = new[] { group1, group2, group3, group4, group5, group6 };

foreach (var group in groups)
{
    // play games
}

I would like to suggest a simplification of your logic as well. You can achieve the same result using fewer nested loops by only looping through the necessary combinations of player 1 and player 2 in each group.
One way to do this is to:

*

*loop over the players' list indices rather than the Player objects in the lists (i.e. replace your nested foreach (Player p*) loops with nested for (int i*) (player index) loops)

*let the outer loop (looping over the indices for player 1) iterate over the current group from 0 to the second-to-last-index

*let the inner loop (looping over the indices for player 2) iterate over the current group from one index larger than the index of player 1 to the very last index

Implementation:
foreach (var group in groups)
{
    for (int i1 = 0; i1 < group.Count - 1; i1++)
    {
        Player p1 = group[i1];

        for (int i2 = i1 + 1; i2 < group.Count; i2++)
        {
            Player p2 = group[i2];

            Game game = new Game(tournamentID, p1.id, p2.id);
            game.status = "Pending";
            gm.CreateGame(game);
        }
    }
}

If we refer to the index of player 1 simply as 1 and the index of player 2 simply as 2, the iterations over a group containing four players can be visualized as follows:

1 2 _ _
1 _ 2 _
1 _ _ 2

_ 1 2 _
_ 1 _ 2

_ _ 1 2

If you rather want the games to be created in the exact same order of player combinations as is done in your original post, the index conditions need to be altered so that p2 always comes before p1 in the group:

2 1 _ _

2 _ 1 _
_ 2 1 _

2 _ _ 1
_ 2 _ 1
_ _ 2 1

This can be achieved by altering the for loop statements slightly:

*

*the index of player 1 goes from 1 to the very last index in the group

*the index of player 2 goes from 0 to one index smaller than the index of player 1
foreach (var group in groups)
{
    for (var i1 = 1; i1 < group.Count; i1++)
    {
        //

        for (var i2 = 0; i2 < i1; i2++)
        {
            //
        }
    }
}

To ensure you are not trying to perform invalid looping on any of the groups, you could alter the foreach statement to consider the length of each group; either by using .Skip(1).Any() from the System.Linq namespace:
//using System.Linq;

foreach (var group in groups.Where(gr => gr.Skip(1).Any()))
{
    // play games
}

or by counting the items in each group:
foreach (var group in groups.Where(gr => gr.Count > 1))
{
    // play games
}

We're checking that the number of items in each group is greater than 1 (i.e. the number of items is at least 2), seeing as we want to play games with two players at a time.

A: create a list of grpups
 var groups = new List<Group>(){
     group1, group1, group3};

now you can do
  if(group[i].Indexof.....)

etc

A: Just make an array of your groups, assuming they are List<Player> below, and iterate over that:
foreach(var grp in new List<Player>[] {group1, group2, group3, group4, group5, group6}) {
    foreach (Player p1 in grp)
    {
        foreach (Player p2 in grp)
        {
            if (p1 != p2)
            {
                if (grp.IndexOf(p1) > grp.IndexOf(p2))
                {
                    Game game = new Game(tournamentID, p1.id, p2.id);
                    game.status = "Pending";
                    gm.CreateGame(game);
                }
            }
        }
    }
}


text:
Q: How to merge dictionaries in np.ndarray into one dictionary? Following my question on Convert Dataframe to Nested Dictionary in Python, I have been trying to convert a Pandas dataframe into a nested dictionary.
Current challenge is merging multiple dictionaries inside a np.ndarray into one.

*

*My current output dkl is
array([{0.7863340563991272: 0.0002639915522703274},
       {0.7863340563991272: 0.0006863780359028511}], dtype=object)

Which when checked for type results numpy.ndarray.

*I need to get dkl to be
{0.7863340563991272: 0.0002639915522703274,
 0.7863340563991272: 0.0006863780359028511}

I am failing to get the desired results. I tried to turn dkl into a l1 = list(dkl), resulting in:
[{0.7863340563991272: 0.0002639915522703274},
 {0.7863340563991272: 0.0006863780359028511}]

I am now able to get the two elements of the list above which are it1 = {0.7863340563991272: 0.0002639915522703274} and it2 = {0.7863340563991272: 0.0006863780359028511}, which I am trying to merge into one dictionary. I tried:
 dict(it1.items() + it2.items())

resulting in:
TypeError                                 Traceback (most recent call last)
<ipython-input-150-4422fd31b345> in <module>
----> 1 dict(it1.items() + it2.items())

TypeError: unsupported operand type(s) for +: 'dict_items' and 'dict_items'

In short, I need to get from 1 to 2.
Update: Ref to mention in comments that this shape of output is not possible in dict, I am tyring to understand how this comes about:
Reason being that I have a dataset I need to replicate that is structured as shown above in my desired output, and if not possible with dict, I have no idea how it's been created...

A: In [10]: dkl=np.array([{0.7863340563991272: 0.0002639915522703274},
    ...:        {0.7863340563991272: 0.0006863780359028511}], dtype=object)
In [11]: dkl
Out[11]:
array([{0.7863340563991272: 0.0002639915522703274},
       {0.7863340563991272: 0.0006863780359028511}], dtype=object)

An object dtype array is for (most) practical purposes a list.  Your list(dkl) does that explicitly, or tolist():
In [12]: alist = dkl.tolist()
In [13]: alist
Out[13]:
[{0.7863340563991272: 0.0002639915522703274},
 {0.7863340563991272: 0.0006863780359028511}]

One way way to merge dictionaries is update:
In [14]: d1 = alist[0]
In [15]: for d in alist[1:]: d1.update(d)
In [16]: d1
Out[16]: {0.7863340563991272: 0.0006863780359028511}

In your case both have the same key, so the result is last dictionary in the list.
{0.7863340563991272: 0.0002639915522703274,
 0.7863340563991272: 0.0006863780359028511}

is impossible since keys of a dictionary are unique.
Other possible mergers include adding values with matching keys, or a list with values.  I'm not sure I should spend time on those since you don't seem to know what you really need.
You try adding the items; using the py3 list(items), we get a list of lists of tuples:
In [20]: [list(d.items()) for d in dkl]
Out[20]:
[[(0.7863340563991272, 0.0002639915522703274)],
 [(0.7863340563991272, 0.0006863780359028511)]]

where the tuples contain the key and value.  But apart from concatenating I don't know what you want to do with those tuples.
In sum, you have a bunch of dictionaries, which may or may not have matching keys.  There's nothing special, numpy-wise here.


text:
Q: Why it's more difficult to walk in an inclined plane than in a causal road my question is about something very casual , but when i tried to solve that , it was not easy at all . My question is : "Why when we walk in an inclined plane we get tired more than when we walk in casual road, when angle = 0 . This question came to me when i was  climbed up. I know that is something about angle and friction force but i cant solve this . I need your help .

A: For each step in walking;
On a horizontal road: $F=ma$
And on an inclined road: $F-mg\sin\theta=ma$
So you need more power (greater $F$) when you are walking up a hill. It may be useful that we know maximum force $F$ we can use when we are walking is the limiting friction force.
Figure below shows free body diagram for walking on a horizontal road.


text:
Q: Intel Proset/Wireless Software fails to install I have a samsung laptop with window 7 Home Premium. I wanted to update my WiFi driver coz previous version get corrupted. I downloaded the Intel Proset/Wireless Software 15.0.0.75 from Samsung website. When i execute the setup, installation did start. It continues for few mins then give error "iChain.exe has stop working" and the installation ends without completion.
please help


text:
Q: Referring to contents of folder 1 to folder 2 I wish to offer my website in different languages and still keep everything on the same domain. Subdomains is not an option, unfortunately. I want to be able to tell people to go to a subfolder to choose the language of their wish.
For example:
Go to http://www.example.com/es/ to use the Spanish version or go to http://www.example.com/sv/ to use the Swedish version.
I want to build the website from one place, so all the code is located in the base folder. All the folders I create in the website (like "es", "sv" and so on) just needs to reference to the base folder. How do I do that in ASP Classic (VB)?
My folder structure looks something like this:
/base/
    default.asp
    join.asp
    ...
/es/
    -- Get code from the base folder --
/sv/
    -- Get code from the base folder --
...

I have searched throughout Stackoverflow but I can't seem to find the answer to this one. I hope someone can help me solve this!

A: You can add a virtual folder in IIS that points to your /base/ folder. Create one folder for every language you want to support.
Virtual folders are like Windows shortcuts, just a link to a different location on the harddisk (or even on the network). This way you can add folders for every language, and they all point to the /base/ folder.
If your virtual folder has a global.asa file, it becomes an application in IIS and you can overrule the default global.asa in it. However, in your case just adding virtual folders would do the trick.
Hope this helps,
Erik


text:
Q: XML drawable having different behavior on 4.3 and 4.1.2 I have the folowing drawable,
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <corners android:radius="3dp"/>
    <padding android:left="1dp" android:right="1dp" android:top="1dp" android:bottom="1dp"/>
     <stroke android:width="1dp" android:color="#e4e4e4"/>

</shape>

"It supposed" to draw a border when set on background, actually on (Android 4.3 /goole nexus 7) it does , but unfortunately on (Android 4.1.2/ Samsung galaxy tab 10") it just fill all the background with the color
If someone can tell me what I'm doing wrong, or if someone has an xml drawable for border,
I will be very thankful :=)

A: here is the solution with the same drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@android:color/transparent" />
    <corners android:radius="3dp"/>
    <stroke android:width="1dip" android:color="#e2e2e2"/>
</shape>

I needed just to specify  solid color :
 <solid android:color="@android:color/transparent" />

A: code of a border drawable that works better on both versions :
<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- This is the line -->
    <item android:top="1px" android:right="1px" android:left="1px" android:bottom="1px">
      <shape>
            <solid android:color="@android:color/transparent" />
            <corners android:radius="3dp"/>
            <stroke android:width="1px" android:color="#e4e4e4" />
      </shape>
    </item>

</layer-list>


text:
Q: using chef-server-ctl sql to modify node permissions Sometimes chef client nodes cannot update the chef server and the permissions need be changed.
Since I'm not allowed to enable the Web GUI, is there a way to do it with
chef-server-ctl sql ?

A: You can use the knife-acl plugin to modify the ACLs using knife acl on your workstations.


text:
Q: Spring @Value not able to get value from YAML I have the follow YAML file
git.username: myusername
git.password: mypassword

And in my Java Source file, I have the following annotation
@Value("${git.username}")
private String username;
@Value("${git.password}")
private String password;

Everything works fine till this point. However, it is not able to retrieve the value when I changed the format of the YAML to the following.
git:
  username: myusername
  password: mypassword

How should I reference the yaml value in this format? @Value(???)


text:
Q: What determines whether an app is eligible to be stored on external storage? I received an email today from a user asking me to make it possible for her to transfer my app itself (not its data) to external storage. Since I don't use external storage personally, I was unaware this is an issue.
I'm unable to find anywhere in Android documentation or what determines which apps are eligible to be transferred to external storage. I considered the WRITE_EXTERNAL_STORAGE permission but that doesn't mention the app itself.
Does anyone know the criteria for storing the app itself on external storage?

A: In the manifest file add to the manifest tag something like
android:installLocation="auto" | "preferExternal".

See https://developer.android.com/guide/topics/data/install-location
Indeed the WRITE_EXTERNAL_STORAGE permission has nothing to do with it.


text:
Q: Looker studio / google data studio formula for count columns with a condition How to make a formula in Looker Studio to count column channel where the column products did not contain words "Cicilan"?
I used this formula :
COUNT(Channel) WHERE NOT CONTAINS_TEXT(Product,"Cicilan")
and it give an error msg "Invalid Formula"

A: In looker the syntax is a little different, try it this way:
count(CASE WHEN product = 'cicilan' THEN (channel) END)


text:
Q: How to fix infinite loop of redirects from http to https on nginx for WordPress site? I need help. Nginx, frontend web server,  by default redirects from
http -> https.

WordPress falsely redirects from some reason from https -> http
It creates an infinite loop.
I have a clean WordPress installation, with default .htaccess.
On the site's database, wp_options table's siteurl, home are set to https.
What have I forgotten? Any help is very appreciated!

A: Ok, you are not clear if the issue is coming from NGINX or from WORDPRESS. So the first thing would be troubleshooting wordpress:

Here are the troubleshooting steps (check the site after each one is done):
1. Rename .htaccess
2. Rename the plugins folder
3. If renaming the plugins folder does the trick, then look for any plugin causing the issue
4. Delete /wp-content/cache folder if exists.
For NGINX troubleshooting:
Execute this command, and locate the virtualhosts affecting the site
apache2ctl -S   [On Debian/Ubuntu]
apachectl -S    [On CentOS/RHEL]
OR
httpd -S
Paste the virtualhosts so I can see if something is wrong.


text:
Q: Python windows service error(import win32serviceutil ModuleNotFoundError: No module named 'win32serviceutil') I have developed a windows service in python that installs fine but gives that error when I start it.
It seems that the windows is unable to access the venv folder,How do I rectify this?
I have deleted the Venv and reinstalled the dependacies pywin32 included but nothing has changed.
here is the code example
import os
import sys
import win32serviceutil
import win32service
import win32event
import servicemanager
import requests
import mysql.connector
from mysql.connector import Error

class AmanoReportingService(win32serviceutil.ServiceFramework):
    _svc_name_ = "AmanoReportingService"
    _svc_display_name_ = "Amano Reporting Service"
    _svc_description_ = "Windows service that retrieves data from Amano SOAP API and inserts it into a MySQL database"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.stop_event = win32event.CreateEvent(None, 0, 0, None)
        self.session = requests.Session()

        self.auth_params = {
            "getPrepaid": {
                "username": "EASTRA",
                "password": "E8MVDAMjLkytjD2x"
            },
            "getPayments": {
                "username": "EASTRA",
                "password": "E8MVDAMjLkytjD2x"
            }
        }

        self.prepaid_fields = [
            "transid",
            "card_no",
            "prepaidType",
            "entry_timestamp",
            "entry_gate",
            "paid_on",
            "pay_station",
            "exit_timestamp",
            "exit_gate",
            "amount_payable",
            "amount_paid",
            "payment_method",
            "park_status",
            "trans_description",
            "tag",
            "car_reg"
        ]

        self.payments_fields = [
            "id",
            "dateTimePayment",
            "dateTimeIn",
            "entry_device",
            "entry_lpn",
            "dateTimeOut",
            "exit_device",
            "exit_lpn",
            "paymentType",
            "ticketType",
            "referenceNumber",
            "originalTransactionAmount",
            "discountAmount",
            "transactionAmount",
            "surchargeAmount",
            "finalAmount",
            "deviceId",
            "ticketNumber",
            "validationCode"
        ]

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.stop_event)

    def main(self):
        try:
            cnx = mysql.connector.connect(user='root', password='Pa$$w0rd', host='localhost', database='kaps')

            while True:
                # Get prepaid transactions
                for from_time, to_time in self.get_time_intervals():
                    for trans in self.get_prepaids(from_time, to_time):
                        self.insert_prepaids(cnx, trans)

                # Get parking payments
                for from_time, to_time in self.get_time_intervals():
                    for payment in self.get_payments(from_time, to_time):
                        self.insert_payments(cnx, payment)

                # Sleep for 10 minutes
                if win32event.WaitForSingleObject(self.stop_event, 600000) == win32event.WAIT_OBJECT_0:
                    # Stop signal received
                    break

        except Error as e:
            # Handle database errors
            servicemanager.LogErrorMsg(f"AmanoReportingService: Error connecting to MySQL database - {e}")
        finally:
            # Close database connection
            if cnx.is_connected():
                cnx.close()

    def get_time_intervals(self):
        # Define time intervals
        # Change these values as needed
        from_times = [
            "2023-02-09 11:00:00",
            "2023-02-09 11:10:00",
            "2023-02-09 11:20:00"
        ]
        to_times = [
        "2023-02-09 11:09:59",
        "2023-02-09 11:19:59",
        "2023-02-09 11:29:59"
        ]
        return zip(from_times, to_times)

    def get_prepaids(self, from_time, to_time):
        # Get prepaid transactions from Amano SOAP API
        params = {
            "username": self.auth_params["getPrepaid"]["username"],
            "password": self.auth_params["getPrepaid"]["password"],
            "dateFrom": from_time,
            "dateTo": to_time
        }
        response = self.session.get("http://alex.kaps.co.ke/amanoreporting/API.php?wsdl", params=params)
        data = response.json()
        return data

    def get_payments(self, from_time, to_time):
        # Get parking payments from Amano SOAP API
        params = {
         "username": self.auth_params["getPayments"]["username"],
         "password": self.auth_params["getPayments"]["password"],
         "dateFrom": from_time,
            "dateTo": to_time
        }
        response = self.session.get("http://alex.kaps.co.ke/amanoreporting/API.php?wsdl", params=params)
        data = response.json()
        return data

    def insert_prepaids(self, cnx, prepaid):
        # Insert prepaid transaction into database
        values = []
        for field in self.prepaid_fields:
            value = prepaid.get(field)
            if value is None:
                value = ""
            values.append(value)
        query = f"INSERT INTO prepaid_transactions ({', '.join(self.prepaid_fields)}) VALUES ({', '.join(['%s'] * len(self.prepaid_fields))})"
        cursor = cnx.cursor()
        cursor.execute(query, tuple(values))
        cnx.commit()

    def insert_payments(self, cnx, payment):
        # Insert parking payment into database
        values = []
        for field in self.payments_fields:
            value = payment.get(field)
            if value is None:
                value = ""
            values.append(value)
        query = f"INSERT INTO parking_payments ({', '.join(self.payments_fields)}) VALUES ({', '.join(['%s'] * len(self.payments_fields))})"
        cursor = cnx.cursor()
        cursor.execute(query, tuple(values))
        cnx.commit()

if __name__ == '__main__':`enter code here`
    win32serviceutil.HandleCommandLine(AmanoReportingService)


text:
Q: How to load and plot csv file using altair package in python? I have a csv file which has 200000 lines and I would like to plot the data files using altair packagae. Documentation states that for large files, data needs to be passed as URL. This is what I have till now.
import  altair
alt.data_transformers.enable('csv')
url = 'path/to/data'

chart = alt.chart(url).mark_line.encode(x= 'time:T', y = 'current:Q')
chart.save('name.html')

But this does not seem to work. Am I missing something obvious here?

A: When you pass a dataset by URL and save the chart to HTML, the important thing is that the URL is valid for the web browser you use to view the HTML file.
So if you are viewing the chart locally and want to load a local file, use an appropriate file:// URL. If you plan to view the file within a web server that supports relative URLs for loading resources, pass the relative URL between the location of the HTML file and the location of the data file.
But, as a side-note, you mention your data has 200,000 rows: no matter how you pass the data to the Vega-Lite renderer, it's unlikely to perform well with that much data. My personal rule-of-thumb is to avoid Altair/Vega-Lite for datasets with more than ~10,000 rows or so.

A: Apart from what @jakevdp said, one more thing that I noticed was that in defining your plot, you missed out on the brackets "()" after mark_line in your code.
I tried implementing the code on a smaller dataset with this modification, and it worked great.


text:
Q: I need to add 30 days to a date as a constraint in MySQL I need to add 30 days to a Date Column and store that new date in a Due Date Column, as a constraint before populating the tables. I already created the tables. This is what I have so far:
UPDATE transactions
SET DueDatePayment = DATE_ADD (TransDate, INTERVAL 30 DAY)
Here I don't know what to add to make work.

ALTER TABLE transactions
ADD CONSTRAINT CHECK (ADDDATE ( transDate, INTERVAL 30 DAY);

I have these two statements, both shows error.

A: Just remove the space after DATE_ADD...
UPDATE transactions
SET DueDatePayment = DATE_ADD(TransDate, INTERVAL 30 DAY)
WHERE TransID = 100;

Query OK, 1 row affected (0.02 sec)
Rows matched: 1  Changed: 1  Warnings: 0


text:
Q: How can I change color in a row How can I change color in a row in the listview if it contains the value M?
This is my display adapter, now I have all the black lines, but if you see a value in txt_turno M, I would like the corresponding line highlighted in playback mode in red.
public View getView(int pos, View child, ViewGroup parent) {
        Holder mHolder;
        LayoutInflater layoutInflater;
        if (child == null) {
            layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutInflater.inflate(R.layout.row, null);
            mHolder = new Holder();
            mHolder.txt_giorni = (TextView) child.findViewById(R.id.txt_giorni);
            mHolder.txt_turno = (TextView) child.findViewById(R.id.txt_turno);

A: In your adapter's getView method:
@Override
public View getView(int position, View convertView, ViewGroup parent) {

View rowView = inflater.inflate(R.layout.mainmenu_item, parent, false);

//text in which you want to find "M"
TextView text = (TextView) rowView.findViewById(R.id.text);

if(text.getText().toString().contains("M"){
    rowView.setBackgroundResource(R.color.red);
}
return rowView;

}
You also hava to definde R.color.red in res/values/colors.xml like so:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="red">#FF0000</color>
</resources>


text:
Q: Column is NULL when printed as individual field or column, filled when whole data frame is printed When I create a column of counts using dplyr, it appears to be filled correctly, until I try to use the counts column on its own.
Example:
I create this dataframe:
V1 <- c("TEST", "test", "tEsT", "tesT", "TesTing", "testing","ME-TESTED", "re tested", "RE testing")
V2 <- c("othertest", "anothertest", "testing", "123", "random stuff", "irrelevant", "tested", "re-test", "tests")
V3 <- c("type1", "type2", "type1", "type2", "type3", "type2", "type2", "type2", "type1")
df <- data.frame(V1, V2, V3)

Then, I use dplyr to create a column of counts:
df$counts <- df %>% group_by(V3) %>% mutate(count = n())

This gives the expected result:
> df
      V1           V2    V3  counts.V1    counts.V2 counts.V3 counts.count
1       TEST    othertest type1       TEST    othertest     type1            3
2       test  anothertest type2       test  anothertest     type2            5
3       tEsT      testing type1       tEsT      testing     type1            3
4       tesT          123 type2       tesT          123     type2            5
5    TesTing random stuff type3    TesTing random stuff     type3            1
6    testing   irrelevant type2    testing   irrelevant     type2            5
7  ME-TESTED       tested type2  ME-TESTED       tested     type2            5
8  re tested      re-test type2  re tested      re-test     type2            5
9 RE testing        tests type1 RE testing        tests     type1            3

But, when I try to use the counts.count column in any way, the result is null:
> df$counts.count
NULL

Same result for the other columns created by dplyr.
But the rest of the data frame seems normal:
> df$V1
[1] TEST       test       tEsT       tesT       TesTing    testing    ME-TESTED  re tested  RE testing
Levels: ME-TESTED re tested RE testing test tesT tEsT TEST testing TesTing

I am totally confused about why printing the whole df gives me a different output than printing just the column of interest. What am I missing here?

A: If you rewind and recreate the dataframe and then don't do an assignment but just print the result to the screen you see this:
df %>% group_by(V3) %>% mutate(count = n())

Source: local data frame [9 x 4]
Groups: V3 [3]

          V1           V2     V3 count
      <fctr>       <fctr> <fctr> <int>
1       TEST    othertest  type1     3
2       test  anothertest  type2     5
3       tEsT      testing  type1     3
4       tesT          123  type2     5
5    TesTing random stuff  type3     1
6    testing   irrelevant  type2     5
7  ME-TESTED       tested  type2     5
8  re tested      re-test  type2     5
9 RE testing        tests  type1     3

If you now do the assgnment the structure is rather confused and I think you might have gotten a more informative error if there had been fewer unique values of V1 or V2:
df$counts <- df %>% group_by(V3) %>% mutate(count = n())
# snipped what you already showed
 str(df)
#-----
'data.frame':   9 obs. of  4 variables:
 $ V1    : Factor w/ 9 levels "ME-TESTED","re tested",..: 7 4 6 5 9 8 1 2 3
 $ V2    : Factor w/ 9 levels "123","anothertest",..: 4 2 8 1 5 3 7 6 9
 $ V3    : Factor w/ 3 levels "type1","type2",..: 1 2 1 2 3 2 2 2 1
 $ counts:Classes 'grouped_df', 'tbl_df', 'tbl' and 'data.frame':   9 obs. of  4 variables:
  ..$ V1   : Factor w/ 9 levels "ME-TESTED","re tested",..: 7 4 6 5 9 8 1 2 3
  ..$ V2   : Factor w/ 9 levels "123","anothertest",..: 4 2 8 1 5 3 7 6 9
  ..$ V3   : Factor w/ 3 levels "type1","type2",..: 1 2 1 2 3 2 2 2 1
  ..$ count: int  3 5 3 5 1 5 5 5 3
  ..- attr(*, "vars")=List of 1
  .. ..$ : symbol V3
  ..- attr(*, "labels")='data.frame':   3 obs. of  1 variable:
  .. ..$ V3: Factor w/ 3 levels "type1","type2",..: 1 2 3
  .. ..- attr(*, "vars")=List of 1
  .. .. ..$ : symbol V3
  .. ..- attr(*, "drop")= logi TRUE
  ..- attr(*, "indices")=List of 3
  .. ..$ : int  0 2 8
  .. ..$ : int  1 3 5 6 7
  .. ..$ : int 4
  ..- attr(*, "drop")= logi TRUE
  ..- attr(*, "group_sizes")= int  3 5 1
  ..- attr(*, "biggest_group_size")= int 5

The format you are seeing is how R displays a matrix that is embedded in a dataframe. Objects of class table (and perhaps tbl?)  inherit from the matrix-class.


text:
Q: Libgdx - Transparent color over texture I am attempting to tint a texture a color but I want the texture to show under the tint. For example, I have a picture of a person but I want to tint them a light green and not change the transparency of the actual person itself.
So far I have attempted to use the SpriteBatch method setColor which takes rgba values. When I set the alpha value to .5 it will render the tinting and the texture with that alpha value. Is there any way to separate the alpha values of the tint and the texture?
I know I could draw another texture on top of it but I don't want to have two draw passes for the one texture because it will be inefficient. If there's anyway to do it in raw OpenGL that'd be great too.

A: You could draw it without the alpha right? The lighter the color overlay is the less it shows (by default its Color.White). So if you want to tint it slightly green you could use new Color(.9f, 1f, .9f, 1f) halfway would be new Color(.5f, 1f, .5f, 1f) and full green new Color(.0f, 1f, .0f, 1f).

A: The behavior you described (alpha affects the whole sprite's transparency) is defined by the shader.
The simple way to deal with this is in @MennoGouw's answer, but this always darkens the image. If you want to avoid darkening, you must use a custom shader. You can use a shader that acts somewhat like the Overlay blend mode in photoshop.
Here's an overlay fragment shader you could combine with the vertex shader from SpriteBatch's default shader (look at its source code). Here you can set the tint with the setColor method. To control the tint, you need to blend toward white. This method allows alpha to be preserved for fading sprites in and out if you need to.
tmpColor.set(tintColor).lerp(Color.WHITE, 1f - tintAmount);
tmpColor.a = transparencyAmount;
batch.setColor(tmpColor);

-
#ifdef GL_ES
    #define LOWP lowp
    precision mediump float;
#else
    #define LOWP
#endif

varying vec2 v_texCoords;
varying LOWP vec4 v_color;

uniform sampler2D u_texture;

const vec3 one = vec3(1.0);

void main()
{
    vec4 baseColor = texture2D(u_texture, v_texCoords);
    vec3 multiplyColor = 2.0 * baseColor.rgb * v_color.rgb;
    vec3 screenColor = one - 2.0 * (one - baseColor.rgb)*(one - v_color.rgb);
    gl_FragColor = vec4(mix(multiplyColor, screenColor, step(0.5, baseColor.rgb)), v_color.a * baseColor.a);
}

A: I found the simple solution to be
float light = .5f; //between 0 and 1
batch.setColor(light, light, light, 1);
batch.draw(...);
batch.setColor(Color.White);


text:
Q: HTML Emails: making table clickable using  I am building an HTML email and want to make an entire table clickable.
I have already come up with a JavaScript solution to do this, which works perfectly well however I would prefer to just wrap the table in  tags and not use JavaScript.

This works well enough in Firefox although it is not valid HTML given I'm enclosing a block level element () within an inline one ().
I currently don't have the means to test this on all email platforms so would like to know if there are any known email platforms that will not support this approach?
Any help would be greatly appreciated.
If anyone is looking for a JavaScript solution to perform the same function then here is one below:

                <title></title>

                    This is a
                    test
                    table

A: You cannot do an  around a table. You need to do s inside each td.
I just did this for a client, and tested it in Outlook 2010, so I know this works;
If it has text, make the text clickable.. you can fix the underline with style="text-decoration:none;". In the other fields, I would just put a transparent gif in it. However, the gif needs to be the full width and height of that field in the table... otherwise it wouldn't work.
Not elegant.. but it works.
Now, since you CAN use a background in the table (also in outlook.. there are some sources with code available for this), you can make it as fancy as you like...

A: You wont be able to use javascript in an email... All styles need to be inline, also no javascript, email clients will not render that.

A: Litmus has a range of options for this. One of which using table border and padding as hack:

          I am a button →

Tried and work on most email clients. Although Im still looking for ways to do this without hardcoding the border/padding.
source: https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design

A: This works in Firefox, because in HTML5 you can wrap a link around a block element (which a
 is).
In email, however, you are stuck with HTML4, and a very limited subset of it as well. This includes using JavaScript - that doesn't work in Gmail, Yahoo, Outlook, and all the other big mail clients.
So you have two options:

*

*Save your table as an image, and just wrap the link tag around that. The downside is that your text won't show when the images are turned off.

*Make everything in your table clickable - i.e. repeat your 'a' tag around all the bits of text. The downside here is that any empty space (i.e. areas with no text or images) won't be clickable.

These links might help you:

*

*http://www.campaignmonitor.com/css/

*http://www.sitepoint.com/code-html-email-newsletters/

A: its not that you want the entire table to be clickable its that you want your a href tag overlaid on your table.
here is a quick example using the table you have provided.


text:
Q: how to use Open flash chart (or any library) in flex 3 project? I want to use Open Flash Chart in Flex3/AS3 project?
I mean,
How Can I use Open-flash-chart in Flex application client side.. ??? (I use FlashDevelop)
Can i do that by just adding .swf file?? If yes? then where to add? I am not using FlexBuilder, I am using FlashDevelop OR Command line for compiling..
Or I have to add .swc file.. ??? If yes, then how to generate one for open flash chart..???
Cheers...

A: It is bit complicated than you thing to just add in flex project as Open Flash Chart is not meant to develop for integration in flex. I find a wonderful conversion in here Open Flash Chart 2 as a Flex SWC component with source code
Open Flash Chart 2 is amazing.

A: I make a new SWC base on WebASP's effort, and fixed some issue I met, include the pie tooltip issue,
You can refer my blog post http://www.smithfox.com/?e=87 for deatil

A: Generally speaking, libraries are added by referencing either more code or a SWC.  SWFs are typically used to load whole applications.  The story gets more complicated if one begins to involve Runtime Share Libraries, but that seems beyond what you need to get started.
Using the command line, adding a swc based library is accomplished by modifying the library-path option.


text:
Q: Jquery DatePicker calendar to remembering previous selected date I have 2 date pickers on my page that are formatted to display month and year.  When a user selects the month and year, the page loads data based on the selection.  All this works fine.  The users are complaining that when they go to click on the calendar again, the options are defaulting to the current month and year and not what the user previously selected.  I have tried several option out there regarding trying to set the default date and none seem to work.
Here is what the page looks like on initial load.

After a month is selected and the user has click "Done", the page loads the data.  When the user goes back in to the date picker, it is displaying the current month and not the previous selected month.
Here is should be displaying Feb as the month in the calendar selector.

 //set the date picker default dates
        var startDate = new Date();
        var date = new Date();
        var endDate = new Date(date.setMonth(date.getMonth() + 1));

        //set the top navigation
        $("#InventoryFromDate").datepicker({
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            yearRange: "-5: +00",
            defaultDate: startDate,
            yearRange: "-5: +00",
            onClose: function (selectedDate, inst) {
                $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
                msophysicalinventory.loaddata(selectedDate, toDate);
            }
        });

        $("#InventoryToDate").datepicker({
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,
            dateFormat: 'MM yy',
            yearRange: "-5: +00",
            defaultDate: endDate,
            onClose: function (selectedDate, inst) {
                $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
                var fromDate = $("#InventoryFromDate").val();
                msophysicalinventory.loaddata(fromDate, selectedDate);
            }
        });

How do I get the calendar option to show the last selected date if changed?

A: There is one way that you need to store somewhere previously selected date and that need to set when the user goes back for date picker.
//Set DatePicker to May 05, 2022
$('#InventoryToDate').datepicker("setDate", new Date(2022,5,05) );


text:
Q: CSS: Is it possible to make the horizontal cells in a table row line up verically? Background: I have a client whose website was built by someone else in an old obscure framework that I can't clearly identify by looking through the files. The site has several pages of tabular data used by member organizations.
Structural Challenge: They want to iframe the content tables into another system. The iframe is working fine, but the tables are too wide for mobile. I could force the tables into a smaller width using CSS, but that would make the information unusable.
Question: I know how to make divs line up in a tabular form. Is it possible, through CSS, to make the  in a row line up underneath each other instead of beside each other, in an outline type hierarchy?

A: You can make them display: block;

td {
  display: block;
}

    cell
    cell
    cell
    cell
    cell

I'm not sure about the browser support for this, but you can make the tr's a flex-column.

tr {
  display: flex;
  flex-direction: column;
}

    cell
    cell
    cell
    cell
    cell