text:
Q: How to change port from 8080 of jax ws webservice? I followed https://www.mkyong.com/webservices/jax-ws/deploy-jax-ws-web-services-on-tomcat/ this tutorial and made a webservice running on port 8080.
I saw this option:
jax-ws webservice's endpoint is always localhost
But I want to know if there is another way in setting the port in a configurable file?
I only have sun-jaxws.xml and web.xml. Do I need 1 more file?
I defined it something like this:
@WebService(endpointInterface="com.abc.service.ClassName",portName = "WebservicePort",
serviceName = "ABCFunctions")

Sun jaxws.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<endpoints
  xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
  version="2.0">
  <endpoint
      name="ABCFunctions"
      implementation="com.abc.service.ClassName""
      url-pattern="/ABCFunctions"/>
</endpoints>

web.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems,
Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>
    <listener>
        <listener-class>
                com.sun.xml.ws.transport.http.servlet.WSServletContextListener
        </listener-class>
    </listener>
    <servlet>
        <servlet-name>ABCFunctions</servlet-name>
        <servlet-class>
            com.sun.xml.ws.transport.http.servlet.WSServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ABCFunctions</servlet-name>
        <url-pattern>/ABCFunctions</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>120</session-timeout>
    </session-config>
</web-app>

As of now I can only change it via server.xml Connector config of Tomcat.
Is there a way that the webservice has a separate port??
<Connector port="8080" protocol="HTTP/1.1"
       connectionTimeout="20000"
       redirectPort="8443" />

A: While publishing the web service you can change the port number


text:
Q: How to select from first table if ID exist in second or third table with high efficiency? I have 3 tables in assignment.
First table:
PATIENT:  patid, fname, lname, recordnum.
PATIENTDR:  patid,  drid,
PATIENTCLIN:  patid,  clinid.
I need to select patients by fname, or lname  if "PATID" in table "PATIENT" is found in table "PATIENTDR" if DRID="$docotr->id" OR "PATIENTCLIN" if CLINID="$clinic->clinid"
This is my query
SELECT t1.* FROM patient t1
WHERE patlname like  '{$search_patlname}%'
AND patfname like '{$search_patfname}%'
AND
(
 EXISTS
   (SELECT patid FROM patientdr t2 WHERE t2.drid = '{$doctor->id}' AND t2.patid = t1.patid)

     OR  EXISTS

   (SELECT patid FROM patientclin t3 WHERE t3.clinid = '{$clinic->clinid}' AND t3.patid = t1.patid)
 )
LIMIT 10

The number of patients can be very high, data will be retrieved using ajax  and taking in consideration following note:
"SQL statements that use the EXISTS Condition in MySQL are very inefficient since the sub-query is RE-RUN for EVERY row in the outer query's table. There are more efficient ways to write most queries, that do not use the EXISTS Condition."
Is there a more efficient way to write this query, maybe i should break rules and insert patient fname and lname in tables patientdr and patientclin to reduce response time, or by limiting results to 10 rows is efficient enough ?
Thanks for all kind of help in advance.

A: As mentioned in the comments, this can be solved with a simple INNER JOIN:
SELECT t1.*
FROM patient t1
INNER JOIN (
    SELECT patid
    FROM patientdr t2
    WHERE t2.drid = '{$doctor->id}'
    UNION DISTINCT
    SELECT patid
    FROM patientclin t3
    WHERE t3.clinid = '{$clinic->clinid}'
) i
ON t1.patid = i.patid
WHERE patlname like  '{$search_patlname}%'
AND patfname like '{$search_patfname}%'
LIMIT 10

If you haven't read the documentation on INNER JOIN, it is worth taking the time to do so, and to play around with some queries that use it.
Good luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the default StandardOpenOptions in nio.file? From this oracle java tutorial:

The OpenOptions Parameter
Several of the methods in this section take an optional OpenOptions
  parameter. This parameter is optional and the API tells you what the
  default behavior is for the method when none is specified.

These are the API that they are referring to.
I have not been able to find out what it is the behaviour of a file creation without any StandardOpenOption specified. What are the default StandardOpenOption?
Thanks in advance.

A: As the tutorial says, the individual methods which use OpenOptions define their defaults.
Eg. Files.newBufferedWriter defines the following defaults:

If no options are present then this method works as if the CREATE,
  TRUNCATE_EXISTING, and WRITE options are present. In other words, it
  opens the file for writing, creating the file if it doesn't exist, or
  initially truncating an existing regular-file to a size of 0 if it
  exists.


text:
Q: iOS swift 3 coding tableview edit button using UIButton instead of UIBarButton I wrote the following code. I'm trying to make it so that it functions like act like UIBarButtonItem edit item function, but using a UIButton instead because I have a custom navigation bar, but I'm having several compiling errors. The function is supposed to allow editing when the button is pressed and finish editing when pressed again.
@IBAction func edit(sender: UIButton){
    if [tableView.isEditing] == YES {
        [self.tableView .setEditing(false, animated: false)]
    }
    else{
        [self.tableView .setEditing(true, animated: true)]
    }
}

A: You're mixing up Swift and Objective-C code, should look something like this
@IBAction func edit(sender: UIButton) {
    if tableView.isEditing {
        tableView.setEditing(false, animated: false)
    } else{
        tableView.setEditing(true, animated: true)
    }
}


text:
Q: fail to convert series to a string object I am new to Python, so i understand how basic my question is. The thing is that I seem to have converted a Series into a str object, yet I still can not apply the isupper function tha I guess I need for the package to work.
data_4['sex'] = np.where((data_4['anthro_female']=='male'), 'M', 'F')
#data_4['sex']=helpers.get_good_sex('male')
#data_4["sex"].astype('category')

#data_4.sex.to_string()
#data_4['sex'].astype(str)
#data_4['sex']= data_4['sex'].astype(str)
data_4['sex'] = pd.Series(data_4['sex'], dtype="string")
data_4["sex"]= data_4["sex"].astype(str)
data_4['sex'] = data_4['sex'].astype('|S80')
#data_4['sex'] = pd.Series(data_4['sex'], dtype=pd.StringDtype)
data_4['z_height'] = Calculator.zscore_for_measurement('lhfa', measurement=data_4.length,
                                                       age_in_months=data_4.anthro_age,
                                                       sex = str.isupper(data_4['sex']), indicator = 'lhfa' )
data_4.head(10)

Error:
TypeError                                 Traceback (most recent call last)
<ipython-input-91-7965ec9e2ad5> in <module>
     12 data_4['z_height'] = Calculator.zscore_for_measurement('lhfa', measurement=data_4.length,
     13                                                        age_in_months=data_4.anthro_age,
---> 14                                                        sex = str.isupper(data_4['sex']), indicator = 'lhfa' )
     15 data_4.head(10)

TypeError: descriptor 'isupper' requires a 'str' object but received a 'Series'

UPD:
when typing sex = str.isupper(data_4['sex'].to_string())  instead the following error returns:
AssertionError                            Traceback (most recent call last)
<ipython-input-94-9424df958115> in <module>
     12 data_4['z_height'] = Calculator.zscore_for_measurement('lhfa', measurement=data_4.length,
     13                                                        age_in_months=data_4.anthro_age,
---> 14                                                        sex = str.isupper(data_4['sex'].to_string()), indicator = 'lhfa' )
     15 data_4.head(10)

~\anaconda3\lib\site-packages\pygrowup\pygrowup.py in zscore_for_measurement(self, indicator, measurement, age_in_months, sex, height)
    316     def zscore_for_measurement(self, indicator, measurement, age_in_months, sex, height=None):
    317         assert sex is not None
--> 318         assert isinstance(sex, six.string_types)
    319         assert sex.upper() in ["M", "F"]
    320         assert age_in_months is not None

AssertionError:

A: You should be able to make it work by changing str.isupper(data_4['sex']) to str.isupper(data_4['sex'].to_string()).
Basically, the problem here is that data_4['sex'] is not a string but a Pandas Series that contains a string. If you're familiar with any worksheet software like Excel, you can picture this difference as the difference between a cell and the text that is contained within the cell. Here, you want to give the descriptor isupper the text, i.e. the string, and not the cell, i.e. the Pandas Series object.


text:
Q: ON DELETE cascade alternate I am trying to create a database for 2 Tables like:

Table1 : tb1-id(pk) | tb2-id | other
Table2 : tb2-id(pk) | other
FOREIGN KEY Table2(tb2-id) REFERENCES Table1(tb1-id) ON DELETE CASCADE

Table pseudo-code:
CREATE TABLE Table1 (
tbl1-id        INT PRIMARY KEY
, tbl2-id      INT FOREIGN KEY REFERENCES Table2(tbl2-id) ON DELETE CASCADE
...
)

Table2:
CREATE TABLE Table 2(
, tbl2-id      INT PRIMARY KEY
...
)

There can be 2 records in Table1 that point to a single record in Table2.  If we DELETE 1 of the 2 records pointing to Table2 from Table1 MySQL would also DELETE the referenced record from Table2.  I want the referenced record to be deleted only when both the referencing records in Table1 are deleted.
Is there any other MySQL method/constraint that can fulfill the above requirement.

A: Reading your question literally, "if we delete 1 of 2 records pointing to Table2 from Table1 would also delete referenced record from Table2", you just need an ordinary ON DELETE CASCADE, as you've shown: Table2 references Table1, and deleting a record in Table1 causes all related records in Table2 to be deleted, even if those records are being pointed to by other records in Table1.
However, if your goal is instead to delete from Table2 when there are no more associated records in Table1, whereas there are normally two such records, you'll need something more elaborate.
I think better in concrete terms, so based on your pre-edit question, I'll call Table1 Guardians (because "parents" can be confusing for SQL-heads when they're actually the child half of a relationship) and Table2 Students (similarly, avoiding the word "children").  The goal is to ensure that any students that do not have any guardians get deleted.
If polygamy and divorce are unheard on, one option would be to have two NULLable fields in Students, FatherID and MotherID (or Parent1 and Parent2, to allow for step-parents, gay marriage, etc.).  Set these to reference Guardians with ON DELETE SET NULL, and add an ON UPDATE trigger to Students to delete a record if both fields become NULL.  If Bob's father is deleted but he still has a mother, he's OK, but if his mother is deleted the poor orphan gets wiped from the database.  This assumes that a CASCADE UPDATE event triggers triggers, I don't know that for a fact.
A more robust solution would be to create a third table relating Guardians to Students.  It would include fields GuardianID, StudentID, EffectiveDate (these three making up a candidate key), StopDate, and maybe fields to indicate the rights of the guardian; perhaps only one has legal custody, and the other should not be allowed to remove the student from school grounds.  This would allow for death or divorce: just set the old record's StopDate.  Insert a new record if the remaining guardian ever remarries.  You could create an ON UPDATE trigger and an ON DELETE trigger on this third table, checking to see if there are now any students which lack active guardians.
However, before putting too much engineering into this, consider: do you really need to cascade?  Keep the referential integrity, of course, but just enforce deletion logic in your business logic layer.  For that matter, does it even make sense to delete students?  If you're asked how many students took a specific class in 2011, but you've deleted some because they've subsequently dis-enrolled, you'll have an undercount.


text:
Q: Gulp-sass no mixin error with Bourbon I'm trying to compile my .scss files with gulp-sass.  I'm using Bourbon, Susy, and Breakpoint.  I have installed them all as bower components.
When I run gulp sass task I get this error:
events.js:85
  throw er; // Unhandled 'error' event
        ^
Error: sass/base/_buttons.scss
5:12  no mixin named appearance

Appearance is a Bourbon mixin.  I've tried playing around with different ways of changing the path to Bourbon including adding the entire path in the @import statement in my main.scss file.  If the path isn't right, gulp complains that the file can't be found. So it seems at least the path is right.
Here is my gulp file:
'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var bourbon = require('node-bourbon');
//bourbon.includePaths
bourbon.with('bower_components/bourbon')
var sourcemaps = require('gulp-sourcemaps');
var notify = require('gulp-notify');
var browserSync = require('browser-sync').create();

gulp.task('sass', function () {
   gulp.src('sass/**/*.scss')
    .pipe(sourcemaps.init())
      .pipe(sass({
      style: 'expanded',
      errLogToConsole: true,
      includePaths: require('node-bourbon').includePaths
      }))
     .pipe(prefix(
         'last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'
     ))
     .pipe(sourcemaps.write('../maps'))
     .pipe(notify({
        message: 'Styles task complete'
    }))
    .pipe(gulp.dest('../css'));
    .pipe(browserSync.stream());
});

gulp.task('sass:watch', function () {
  gulp.watch('./sass/**/*.scss', ['sass']);
});

and the dependencies from my package.json:
"devDependencies": {
"browser-sync": "^2.7.13",
"gulp": "^3.9.0",
"gulp-autoprefixer": "^2.3.1",
"gulp-minify-css": "^1.2.0",
"gulp-notify": "^2.2.0",
"gulp-sass": "^2.0.3",
"gulp-sourcemaps": "^1.5.2",
"node-bourbon": "^4.2.3"
}

This is my first time trying to set up Gulp, so any help would be greatly appreciated.


text:
Q: C - how to print only filled rows in 2D array I have 2D array in size of [temp][26] filled with the char '#' or nothing.
some rows are empty, some rows filled with that char.
how I print only the rows that are filled.
this is my start.
for (i=0;i<(temp);i++){
    for (j=0;j<26;j++)
        printf("%c",graph[temp][j]);
    printf("\n");
}

A: Just use a 'if' condition ... I don't see your problem
for (i=0;i<(temp);i++){
    for (j=0;j<26;j++)
        if(graph[temp][j] == '#') printf("%c",graph[temp][j]);
    printf("\n");
}

A: If you meant you want to print only the rows filled with '#' and all of them:
for (i=0;i<(temp);i++)
    if(graph[temp][0] == '#') //check only first character will be enough
        printf("%s\n",graph[temp]); //print all current line
printf("\n");


text:
Q: Filter by zip code, or other location based data retrieval strategies My little site should be pooling list of items from a table using the active user's location as a filter. Think Craigslist, where you search for "dvd' but the results are not from all the DB, they are filtered by a location you select. My question has 2 levels:

*

*should I go a-la-craigslist, and ask users to use a city level location? My problem with this is that you need to generate what seems to me a hard coded, hand made list of locations.

*should I go a-la-zipCode. The idea of just asking the user to type his zipcode, and then pool all items that are in the same or in a certain distance from his zip code.

I seem to prefer the zip code way as it seems more elegant solution, but how on earth do one goes about creating a DB of all zip codes and implement the function that given zip code 12345, gets all zipcodes in 1 mile distance?
this should be fairly common "task" as many sites have a need similar to mine, so I am hoping not to re-invent the wheel here.

A: Getting a Zip Code database is no problem. You can try this free one:
http://zips.sourceforge.net/
Although I don't know how current it is, or you can use one of many providers. We have an annual subscription to ZipCodeDownload.com, and for maybe $100 we get monthly updates with the latest Zip Code data complete with Lat/Longs of the centroid of the zip code.
As for querying for all zips within a certain radius, you are going to need a spatial library of some sort. If you just have a table of zips with lats/longs, you will need a database-oriented mechanism. SQL Server 2008 has the capability built in, and there are open source libraries and commercial libraries that will add such capabilities to SQL Server 2005. The open source database PostgreSQL has a project, PostGIS that adds this capability to that database. It is here: http://postgis.refractions.net/
Other database platforms probably have similar projects, but those are the ones I am aware of. With one of these DB based libraries you should be able to directly query for any zip codes (or any rows of any kind that have lat/long columns) within a given radius.
If you want to go a different route you can use spatial tools with a mapping library. There are open source options here as well, such as SharpMap and many others (Google can help out) that can use the free Tiger maps for the united states as the data source. However, this route is somewhat more complicated and possibly less performant if all you need is a radius search.
Finally, you may want to look into a web service. This, as you say, is a common need, and I imagine there are any number ob web services that you can subscribe to that can provide all zip codes in a given radius from a provided zip code. A quick Google search turned up this:
http://www.zip-codes.com/free-zip-code-tools.asp#radius
But there are MANY resources to be had for the searching on this subject.

A:
how on earth do one [...] implement the function that given zip code 12345, gets all zipcodes in 1 mile distance?

Here is a sample on how to do that:
http://www.codeproject.com/KB/cs/zipcodeutil.aspx

A: Just to be technical... PostGIS isn't a project of the Postgres community... it's a stand-alone project that is built on top of Postgres. If you want help or support with PostGIS, you'll want to go to it's community instead of Postgres.

A: You can use PostGIS. Additionally, I've used deCarta's mapping libraries. They have technology which allows you to geokey any arbitrary data type. Then you can query these spatially.
disclaimer: I work for deCarta

A: Wouldn't it be more efficient to just figure out which cities are within a 1 mile radius and store that information in a table? Then you don't have to do calculations in the database all the time.


text:
Q: SwiftUI List based on @FetchedRequest and filtering computed properties crashes I have such code that has @FetchRequest loading Contacts then I have computed properties doing filter based on @State variable
 @FetchRequest var fetchRequest: FetchedResults<Contact>

    private var contacts : Array<Contact> {

        Array(fetchRequest).filter { contact in
            if self.sectionSelection == 1 {
                return contact.type == "person"
            } else if self.sectionSelection == 2 {
                return contact.type == "company"
            } else {
                 return true
            }
        }
    }

@State private var sectionSelection : Int = 0

But the List crashes with index out of range error!
 List {

            ForEach(0..<contacts.count) { i in

                ZStack {

                    NavigationLink(destination: ContactDetails(contact: contacts[i])) {


text:
Q: wp_mail not sending when adding headers Emails are being sent successfully but I want to send email to include a footer html template, so i've added the following lines:
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= "Content-type: text/html; charset=UTF-8 \r\n";

Now emails aren't being sent.  How do i solve this?
$emails = array("test@gmail.com");
        $emails = array_unique($emails);
        $subject = $_POST['subject'];
        $message = $_POST['message'];

        $message.="

Tel: +44 203 051 1214

Fax: +44 207 657 3322

E-mail: info@test.co.uk

Web: www.test.co.uk

";
                $headers = 'From: test <info@test.co.uk>' . "\r\n";
                $headers .= 'MIME-Version: 1.0' . "\r\n";
                $headers .= "Content-type: text/html; charset=UTF-8 \r\n";

                $success = wp_mail( $emails, $subject, $message, $headers );  //send emails

A: Firstly, I has seen this code. There is no thing wrong with that header excerpt you don't need this line:
$headers .= 'MIME-Version: 1.0' . "\r\n";

wp_mail will automatic added it for you.
Secondly, Try this code:
    $emails = "yourmail@gmail.com";
    //$emails .= ', ' . 'test2@gmail.com';

    $subject = !empty($_POST['subject']) ? sanitize_text_field($_POST['subject']) : 'test subject';
    $message = !empty($_POST['message']) ? $_POST['message'] : '';

    $message.="

Tel: +44 203 051 1214

Fax: +44 207 657 3322

E-mail: info@test.co.uk

Web: www.test.co.uk

";

    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
    $headers .= 'From: test <info@test.co.uk>' . "\r\n";

    $success = mail($emails, $subject, $message, $headers);

I think there is some mixed here.
If still not work, maybe you should install this plugin here with your gmail information and try your code again. Hope that help!


text:
Q: 3D positively curved space If we consider 2D euclidean surface consists of infinite concentric circles and 3D euclidean surface consists of infinite concentric spheres.
If 2D surface is positively curved the radius of the circles at a distance $r$ from the origin becomes $R \sin(\frac{r}{R})$, where $R$ is the radius of the 2-Sphere.
Similarly for 3D positively curved space the radius of the spheres at a distance $r$ from the origin becomes $R \sin(\frac{r}{R})$,in this case whether $R$ is the radius of the 3-spheres?

A: For 3-Sphere the radius of the Curvature is R. For more information look this
Cosmology Mathematical Tripos
If you look  the equations 1.1.5 and 1.1.14 that you ll see that the author defined a is the radius of the 3-sphere as "a" and used it to desribe the metric.


text:
Q: windows - How to stop cron job of .bat file? i have used it . but now it is pouping up again and  again how to stop it
To create the batch file
Open Notepad.
Paste the line "C:\xampp\php\php.exe C:\wamp\www\index.php"
Click "File" -> "Save As"
Ensure "Save as type:" is set to "All Files"
Save the file as "cron.bat" to your C drive
To schedule the batch file to run
Open Command Prompt
Paste the following "schtasks /create /sc minute /mo 1 /tn "PHP Cron Job" /tr C:\cron.bat"
Press Enter

A: Try
schtasks /Delete

More could be found here
What happened is you created a scheduled task to run each minute. So it is doing what you said it to do. If you want to remove it, use above command.


text:
Q: PHP calculate combinations of a string depends on a character string This is the scenario:
There is characterstring like this:
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';

And I have a method that generates a random string with a variable length depends on the characters variable:
public function generateCodes($length, $qty)
    {
        $codes = [];

        if ($length > 0 && $qty > 0) {
            for ($i = 0; $i < $qty; $i++) {
                $code = '';
                for ($i = 0; $i < $length; $i++) {
                    $code .= $characters[mt_rand(0, strlen($characters) - 1)];

                    if (!in_array($code, $codes)) {
                        $codes[] = $code;
                    }
                }
            }
        }
    }

What I want is to calculate the possible unique codes for a specific $length. But how can I reach this?
This is my attempt so far - but I do not consider something important.
public function calculateCombinations($length)
    {
        $combinations = 0;

        if ($length > 0) {

            for ($i = 0; $i < $length; $i++) {
                $combinations = $combinations + pow(2, $length -1);
            }
        }

        return $combinations;
    }

What is the right formula for this?
Thanks in advance!


text:
Q: Неправильный вывод лабиринта Здравствуйте! Сейчас пытаюсь писать рогалик на си, но, пока что, не могу даже лабиринт отрисовать. Есть такой код:
void draw_region_on(struct Region reg, char* field)
{
    if(reg.left != NULL && reg.right != NULL)
    {
        draw_region_on(*reg.left, field);
        draw_region_on(*reg.right, field);
    }

    else
    {
        for(int x=reg.x; x<reg.w+reg.x; x++)
            for(int y=reg.y; y<reg.h+reg.y; y++)
            {
                if((x>=reg.room->x && x<=reg.room->x+reg.room->w) &&
                   (y>=reg.room->y && y<=reg.room->y+reg.room->h))
                {
                    field[x+y*reg.w] = '.';
                }
            }
    }
}

Эта функция рисует заданный регион (часть лабиринта) на массиве символов.
Алгоритм генерации лабиринта такой:
Изначально есть регион, занимающий собой все пространство. Дальше он начинает делится (вертикально или горизонтально) пополам, а каждая его часть, в свою очередь, может либо также разделится, либо создать в себе комнату.
Генерация останавливается, когда размер следующей комнаты должен был бы быть меньше минимального.
Получается примерно такая картинка (вывод перенаправлен в .txt, который открыт в хроме).

Можно было бы сказать, что неправильно работает сама генерация.
Но, если попытаться вывести тот же самый лабиринт в html:
void draw_region_on(struct Region reg, char* field)
{
    if(reg.left != NULL && reg.right != NULL)
    {
        draw_region_on(*reg.left, field);
        draw_region_on(*reg.right, field);
    }

    else
    {
        struct Region r = *reg.room;
        printf("

\n", reg.room->x, reg.room->y, reg.room->w, reg.room->h);
        for(int x=reg.x; x<reg.w+reg.x; x++)
            for(int y=reg.y; y<reg.h+reg.y; y++)
            {
                if((x>=reg.room->x && x<=reg.room->x+reg.room->w) &&
                   (y>=reg.room->y && y<=reg.room->y+reg.room->h))
                {
                    field[x+y*reg.w] = '.';
                }
            }
    }
}

Картинка (для того же лабиринта) получается значительно больше похожей на правду:

Не могли бы вы помочь исправить функцию draw_region_on?


text:
Q: Control an element whose id matches with href in javascript I am trying to achieve a simple show/hide content by clicking outside of some links. I can achieve it with jQuery. But, I am struggling to achieve that with vanilla javascript. Basically, I get the id from a like this way:
const id = e.target.getAttribute('href');

Now, I want to work with that id, but I can't. So, my problem is in this line:
id.classList.remove('hidden');

My demo:

const texts = document.querySelectorAll('.content p > span');
const links = document.querySelectorAll('.link-block a');
links.forEach(el => {
  el.addEventListener('click', e => {
    texts.forEach(text => text.classList.add('hidden'));
    const id = e.target.getAttribute('href');
    //console.log(id);
    id.classList.remove('hidden');
  });
});
.hidden {
  display: none;
}

      Sample Text for Content 1.
      Sample Text for Content 2.
      Sample Text for Content 3.

    Content 1
    Content 2
    Content 3

A: The id value is a string, not an element.  But that string can be used with document.querySelector to find that element.  For example:

const texts = document.querySelectorAll('.content p > span');
const links = document.querySelectorAll('.link-block a');
links.forEach(el => {
  el.addEventListener('click', e => {
    texts.forEach(text => text.classList.add('hidden'));
    const id = e.target.getAttribute('href');
    //console.log(id);
    document.querySelector(id).classList.remove('hidden');
  });
});
.hidden {
  display: none;
}

      Sample Text for Content 1.
      Sample Text for Content 2.
      Sample Text for Content 3.

    Content 1
    Content 2
    Content 3


text:
Q: prove that the unit circle is isomorphic to the quotient group $\Bbb R/K$, where $K$ is a normal subgroup of $(\Bbb R, +)$ Prove that the circle group $(S,$x$)$
where $S=\{z∈ \Bbb C | |z|= 1\}$
is isomorphic to the quotient group $\Bbb R/K$ where $K$ is a normal subgroup of $(\Bbb R , +)$
I understand the basic definition of isomorphism and how to show it, but I have no idea how to begin to tackle this question. Any hints and help will be appreciated.
Thanks

A: The subgroup is $K=2\pi \mathbb  Z$, and the quotient map sends $\theta\mapsto e^{i\theta}$. Consider this a hint.


text:
Q: Executing a daemon in php I'm programming a website where I want a daemon to be executed when the user click on "execute the background programm". For this, I've developped it with the symfony2 php framework.
For the moment, when I click on the link to execute the daemon, it blocks all the whole website and I can't click other links of my website because the web browser is like searching the page during the execution of the daemon writing "Connexion" as title of the internet page.
My php daemon is written like that :
<?php
while(true) {
//code
sleep(2);
}
?>

And when I click on the link "execute the background programm", it runs this command :
shell_exec('nohup php /my/daemon/daemon.php &');

Is there a way to run a php daemon without have the "Connexion" status during the execution of my daemon which blocks my website ?
Thanks !


text:
Q: How to freeze first row when I clicked the header of column for sort in DataGridView? I have a desktop app and I am using DataGridView on form. I froze the first row. But when I clicked the header of column in DataGridView The location of the first row is also changing. How to ignore the first row while I am sorting.

A: Within the SortCompare event handler for the SortCompare event of the DataGridView, try this:
private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
{
    if (e.RowIndex1 == 0)
    {
        e.Handled = true;
    }
    else
    {
        e.Handled = false;
    }
}

A: Essentially, what you're asking is to be able to sort only a portion of the DataGridView. To my knowledge, there's no easy or standard way to do this, echoed by Filip's response to this question: Sorting selected rows in DataGridView. This doesn't mean it's impossible to achieve the behavior that you want.
Filip offers an implementation, and in this question, Justin offers code that you would have to modify slightly, but that may suit your needs. The question asks how to move a row up or down in a DataGridView, but I think you could modify his implementation to move the row you want to keep static all the way to the top after you sort. Depending on the volume of rows you're sorting, the first row might disappear and reappear. However,  if your data set is relatively small, I can't imagine the brief flash of the first row being sorted to some random position and then added back to the top would cause any major problems.

A:     private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
    {
        int so = 1;
        if (dataGridView1.SortOrder == SortOrder.Ascending)
        {
            so = -1;
        }
        if (e.RowIndex1 == 0 )
        {
            e.SortResult = so;
            e.Handled = true;
        }
        if (e.RowIndex2 == 0)
        {
            e.SortResult = -so;
            e.Handled = true;
        }
    }

This code puts the first line always on top of the sorted list, by setting the sort result of the first row accordingly.


text:
Q: How can I make use of the $scale function in QGIS data defined properties? In QGIS 2.0 I can use with success the $scale function in the labeling expressions.
When I tried to use it for symbolizing in the data defined properties it has a value of 0.
Is there a way to make it perform like it does in labeling (getting the scale)?
As I saw in the expression string builder help that
$scale function
Returns the current scale of the map canvas.
Note: This function is only available in some contexts and will be 0 otherwise.

is there a source where I can read more about this e.g. in what contexts it is available?
Thanks, Tudor

A: The problem was in to use directly with a wrong sintaxis expression.
When I put only $scale in the browser I got:

By using the rule ($scale <= 500)*$scale; where the sintaxis is similar to used in raster calculator. In the image below the rule is not reached ($scale <= 500 = FALSE = 0):

When the rule is reached the scale ($scale <= 500 = TRUE = 1) is displayed if it is used the adequate product; ($scale <= 500)*$scale:

It works.


text:
Q: How to add the SwingLibrary plugin to RobotFramework? I'm trying to execute the SwingLibrary demo available in https://github.com/robotframework/SwingLibrary/wiki/SwingLibrary-Demo
After setting everything up (Jython, RobotFramework, demo app), I can run the following command:
run_demo.py startapp

, and it works (the demo app starts up).
Now if I try to run the sample tests, it fails:
run_demo.py example.txt

[ ERROR ] Error in file '/home/user1/python-scripts/gui_automation/sample-text.txt': Non-existing setting 'Library SwingLibrary'.
[ ERROR ] Error in file '/home/user1/python-scripts/gui_automation/sample-text.txt': Non-existing setting 'Suite Setup Start Test Application'.
==============================================================================
Sample-Text
==============================================================================
Test Add Todo Item                                                    | FAIL |
No keyword with name 'Insert Into Text Field description ${arg}' found.
------------------------------------------------------------------------------
Test Delete Todo Item                                                 | FAIL |
No keyword with name 'Insert Into Text Field description ${arg}' found.
------------------------------------------------------------------------------
Sample-Text                                                           | FAIL |
2 critical tests, 0 passed, 2 failed
2 tests total, 0 passed, 2 failed
==============================================================================
Output:  /home/user1/python-scripts/gui_automation/results/output.xml
Log:     /home/user1/python-scripts/gui_automation/results/log.html
Report:  /home/user1/python-scripts/gui_automation/results/report.html

I suspect that it cannot find swinglibrary.jar, and therefore my plugin installation is probably messed up.
Any ideas?

A: Take a look at these error messages in the report:
[ ERROR ] Error in file '...': Non-existing setting 'Library SwingLibrary'.
[ ERROR ] Error in file '...': Non-existing setting 'Suite Setup Start Test Application'.

The first rule of debugging is to always assume error messages are telling you the literal truth.
They are telling you that you have an unknown setting. It thinks you are using a setting literally named "Library SwingLibrary" and one named "Suite Setup Start Test". Those are obviously incorrect setting names. The question is, why is it saying that?
My guess is that you are using the space-separated text format, and you only have a single space between "Library" and "SwingLibrary". Because there is one space, robot thinks that whole line is in the first column of the settings table, and whatever is in the first column is treated as the setting name.
The fix should be as simple as inserting two or more spaces after "Library", and two or more spaces after "Suite Setup".
This type of error is why I always recommend using the pipe-separated format. It makes the boundaries between cells much easier to see.


text:
Q: Magento2 import update adds new item id into cataloginventory_stock_item I'm trying to update product urls, but the import functionality in Magento 2 adds new item id into cataloginventory_stock_item table for each updated sku and I have to manually delete each duplicate from the table. Does the import update csv require more than sku and url_key? Could that be the reason?

A: The only one required column for CSV is "sku" (http://docs.magento.com/m2/ce/user_guide/system/data-attributes-product.html). Please, check if you are using "Add/update" option when importing.


text:
Q: SQL server virtual memory usage and performance I have  a very large DB used mostly for analytics. The performance overall is very sluggish. I just noticed that when running the query below, the amount of virtual memory used greatly exceeds the amount of physical memory available. Currently, physical memory is 10GB (10238k bytes) whereas the virtual memory returns significantly more - 8388607k bytes. That seems really wrong, but I'm at a bit of a loss on how to proceed.
USE [master];
GO
select
    cpu_count
,    hyperthread_ratio
,    physical_memory_in_bytes / 1048576 as 'mem_MB'
,    virtual_memory_in_bytes / 1048576 as 'virtual_mem_MB'
,    max_workers_count
,    os_error_mode
,    os_priority_class
from
    sys.dm_os_sys_info

A: Are you having general problems on this box or problems with a specific query?  In most cases, query optimization is best asked here, but everything else about general SQL Server performance profiles belongs on serverfault.com, especially OS/Server/hardware configuration.

A:
I have a very large DB used mostly for analytics.

OLAP: Memory and CPU intensive.

Currently, physical memory is 10GB

Small server: Does not compute.

That seems really wrong, but I'm at a bit of a loss on how to proceed

Upgrade server. A Very large dDatabase is 100+Gigabyte - likely these days 1000+ Gigabyte. 10Gb RAM for that uner analytical circumstance: joke, not server.


text:
Q: How to switch activities using spinner How do I create a spinner that gives out three option and on choosing one, corresponding activity opens after clicking a "continue" button.

A: Simply add 3 values in list and set it to your spinner using adapter.
And on button click check spinner selected value. In short if spinner selected = A then go to A else if B else C


text:
Q: How do I update part of a 3D texture efficiently? I am writing a voxel ray caster that implements a form of an N^3 tree.  The voxels are stored in a large chunk pool of size 1024^3 and is segmented into 32^3 chunks.  The chunk pool needs to be updated every frame either once or multiple times.
I have all the rendering working on sample data of a 3D texture I generated with a compute shader.  I just can't seem to figure out how to update N^3 chunks of a 3D texture.
I have come across glMapBufferRange and glTexSubImage3D.  How do I efficiently stream portions of a 3D texture to the GPU?


text:
Q: Having problems while using electron-reload module I am getting the following error while trying to use the electron-reload module. (which I am not able to understand)
Error: Cannot find module 'app'
    at Module._resolveFilename (module.js:455:15)
    at Function.Module._resolveFilename (C:\path\Electron\music-player\node_modules\electron\dist\resources\electron.as
ar\common\reset-search-paths.js:35:12)
    at Function.Module._load (module.js:403:25)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (C:\path\Electron\music-player\node_modules\electron-reload\main.js:1:90)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)

And the main.js has the following for usage of the module
const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
require('electron-reload')(__dirname+'/public')

Can anyone guide me how to resolve the problem ?

A: Looks like you need to update electron-reload to v1.0.0 or later, the release notes claim it was updated to support Electron v1.0.0+.


text:
Q: Automatic Copy of Dependent Files in Qt Creator I've build a program using Qt Creator 2.2.1 and Qt 4.7.4 (32 bit) whose output is an executable. Opening the exe using DependencyWalker it shows that the exe uses following DLLs:

*

*KERNEL32.DLL

*MSVCRT.DLL

*MINGWM10.DLL

*LIBGCC_S_DW2-1.DLL

*QTCORE4.DLL

*QTGUI4.DLL

I want after the build all dependent files (which may be different in some other project) except Windows specific files (the first two in the above list) to be automatically copied in the directory where the exe is located.
How can I do it in Qt Creator or Qt system without using command line scripting? Thanks.

A: I would modify your *.pro file for the project and use INSTALLS.  To actually cause the files to be moved, you will need to run make install.  In Qt Creator, you can add it as part of your normal build process by going into the "Projects" section and adding a new build step.
## This sets MY_LIB_FILES the libs you want and should also correctly resolve
## the location of the libs.

win32 {                ## For Windows builds
    # Note: Check to make sure of file name case

    MY_LIB_FILES += $$QMAKE_LIBDIR_QT/MINGWM10.DLL
    MY_LIB_FILES += $$QMAKE_LIBDIR_QT/LIBGCC_S_DW2-1.DLL
    MY_LIB_FILES += $$QMAKE_LIBDIR_QT/QTCORE4.DLL
    MY_LIB_FILES += $$QMAKE_LIBDIR_QT/QTGUI4.DLL
}

unix {                     ## For unix builds
    # MY_LIB_FILES += $$QMAKE_LIBDIR_QT/...xxxxxx....
}

## Define what files are 'extra_libs' and where to put them
extra_libs.files = MY_LIB_FILES
extra_libs.path = $$DESTDIR

## Tell qmake to add the moving of them to the 'install' target
INSTALLS += extra_libs

A: Even though not totally automatic, you can with little effort do what you want with QtCreator.
Add the "INSTALLS" directive to your project (.pro) file (similar to what was suggested by jwernerny):
win32 {
    libstocopy.files = $$QMAKE_LIBDIR_QT/MINGWM10.DLL \
       ... (add other files)
}

# If using MSVC the code may end up in "release" or "debug" sub dir
# Remove this if that is not the case
win32 {
    CONFIG(debug, debug|release): OUTDIR = debug
    else: OUTDIR = release
}

libstocopy.path = $$OUT_PWD/$$OUTDIR
INSTALLS += libstocopy

In the "Projects" tab of QtCreator (my version=2.4.1) you now add an extra build step:

*

*Hit "Add Build Step"

*Select "Make"

*Leave "Override ..." empty

*Enter "install" at "Make arguments:"

Since these settings are not saved with your project file you have to do the second part (Add Build Step) each time you create a new build configuration (e.g. one each for release and debug) or check out your project to a new location.

A: In QT 5.3, you may be able to use the windeployqt qt tool to automatically copy the needed libraries.
The following additions to the project's .pro file should do the trick, but you might have to make some adjustments based on your particular situation.
isEmpty(TARGET_EXT) {
    win32 {
        TARGET_CUSTOM_EXT = .exe
    }
    macx {
        TARGET_CUSTOM_EXT = .app
    }
} else {
    TARGET_CUSTOM_EXT = $${TARGET_EXT}
}

win32 {
    DEPLOY_COMMAND = windeployqt
}
macx {
    DEPLOY_COMMAND = macdeployqt
}

CONFIG( debug, debug|release ) {
    # debug
    DEPLOY_TARGET = $$shell_quote($$shell_path($${OUT_PWD}/debug/$${TARGET}$${TARGET_CUSTOM_EXT}))
} else {
    # release
    DEPLOY_TARGET = $$shell_quote($$shell_path($${OUT_PWD}/release/$${TARGET}$${TARGET_CUSTOM_EXT}))
}

#  # Uncomment the following line to help debug the deploy command when running qmake
#  warning($${DEPLOY_COMMAND} $${DEPLOY_TARGET})

# Use += instead of = if you use multiple QMAKE_POST_LINKs
QMAKE_POST_LINK = $${DEPLOY_COMMAND} $${DEPLOY_TARGET}

A: No-no-no 0_o :)

*

*Create some directory to deploy files, i.e. "bin".

*In every .pro file write
DLLDESTDIR = ../../myproject/bin (... some dir's struct ...)
QMAKE_POST_LINK = windeployqt --compiler-runtime $$DLLDESTDIR
DLLDESTDIR -- full path with file name TARGET (dll and exe).
End!


text:
Q: T-SQL Query Returning Items It Shouldn't Be Here's the scenario.  The column in question is called 'datein' and it's type is 'datetime'.  I have three rows with the value of '2009-10-01 00:00:00.000' for 'datein'.  Why does this query return the aforementioned rows?
SELECT  *
FROM    t_call AS tc
WHERE   tc.datein >= '2009-09-30 00:00:00.000'
        AND tc.datein <= '2009-09-30 23:59:59.999'

Using
SELECT  *
FROM    t_call AS tc
WHERE   tc.datein BETWEEN '2009-09-30 00:00:00.000'
        AND '2009-09-30 23:59:59.999'

returns the same result

A: It's the lack of precision in the thousandths of a second value.  Try ".997" instead.
MSDN DateTime documentation
Run this and you'll see:
declare @dt datetime

select @dt = '2009-09-30 23:59:59.999'
select @dt

A: The DATETIME accuracy is 0.00333 seconds. So you need to go to '2009-09-30 23:59:59.998' so it doesn't round up to Oct 1st.
For example:
select '2009-09-30 23:59:59.994',
  cast('2009-09-30 23:59:59.994' as datetime)
union all select '2009-09-30 23:59:59.995',
  cast('2009-09-30 23:59:59.995' as datetime)
union all select '2009-09-30 23:59:59.996',
  cast('2009-09-30 23:59:59.996' as datetime)
union all select '2009-09-30 23:59:59.997',
  cast('2009-09-30 23:59:59.997' as datetime)
union all select '2009-09-30 23:59:59.998',
  cast('2009-09-30 23:59:59.998' as datetime)
union all select '2009-09-30 23:59:59.999',
  cast('2009-09-30 23:59:59.999' as datetime)

returns:
2009-09-30 23:59:59.994 2009-09-30 23:59:59.993
2009-09-30 23:59:59.995 2009-09-30 23:59:59.997
2009-09-30 23:59:59.996 2009-09-30 23:59:59.997
2009-09-30 23:59:59.997 2009-09-30 23:59:59.997
2009-09-30 23:59:59.998 2009-09-30 23:59:59.997
2009-09-30 23:59:59.999 2009-10-01 00:00:00.000

A: What is the column type? If it is a datetime, try casting the values you're comparing with to a datetime as well; if it is a string (char, nchar, varchar, nvarchar) what collation etc. are you using for the column?

A: According to MSDN documentation

Date and time data from January 1,
  1753 through December 31, 9999, to an
  accuracy of one three-hundredth of a
  second (equivalent to 3.33
  milliseconds or 0.00333 seconds).
  Values are rounded to increments of
  .000, .003, or .007 seconds, as shown
  in the table.

From the given example in that page, you must end your query with .997 to obtain the results that you expect.

A: The safe way to write these queries is as follows:
SELECT  *
FROM    t_call AS tc
WHERE   tc.datein >= '2009-09-30T00:00:00.000'
        AND tc.datein < '2009-10-01T00:00:00.000''


text:
Q: Migrating to LinkedIn APIs V2 OR Updating LinkedIn permission settings How do I edit App permissions for my current App, as there's no Edit option present  in the Linked Dashboard?
I would like to do this to give necessary permission for version 2.0 as r_basicprofile is now replaced by r_liteprofile which doesn't provide me with company positions.
Reference - https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/migration-faq?context=linkedin/consumer/context

A: You can apply for partner program to use r_basicprofile  with V2
but anyhow you have to migrate API
because in V2 all API Url is change and also response is in different format
Means using r_basicprofile with V1 and r_basicprofile with V2 both are different implementation


text:
Q: Is the QVTD (declarative) plugin eclipse already in a version stable? I want to realize a transformation from DMN to BPMN. I think to use the QVTD (declarative) plugin eclipse already but is it in a version stable ?

A: Absolutely not. The Oxygen (June 2017) release of QVTc/QVTr is only suitable for research purposes. Lack of support for Overriding is a serious omission. Lack of support for In-place may be a problem. Lack of support for copy (not in the spec) may also be a problem.
Regards
Ed Willink


text:
Q: Running DHCP for ipv4 and ipv6 on different servers in the same network I have a network where ipv4 addresses are assigned via DHCP on the router.
The router, however, is capable of routing ipv6 but does not support ipv6 DHCP.
Would running 2 DHCP servers (one for ipv4 and one for ipv6) on separate machines (router + server) cause any issues?

A: IPv4 and IPv6 are independent enough that the setup you describe should work just fine.
In fact you can even run IPv4 and IPv6 through two different ISPs. That would give some of the benefits from dual homing without needing to work with routing policies or BGP announcements.
But you don't need DHCPv6, if you only have a single network segment.
Your router can advertise itself with a /64 allocated for the LAN. That way SLAAC can be used to configure IPv6 addresses on the LAN without needing DHCPv6. This is AFAIK supported by more clients than DHCPv6 is.
The point where DHCPv6 gets interesting is how does the router know which /64 to advertise on the LAN. Your router could have a DHCPv6 client to request a prefix from a DHCPv6 server operated by the ISP. If DHCPv6 is not used for this, your router would need to be configured with a static IPv6 prefix.

A: There should be no issues with this setup, since DHCP runs over IPv4 and DHCPv6 over IPv6. Since your router doesn't react to DHCPv6 messages, it is all right.


text:
Q: Extend Entity from vendor folder I have an entity in \vendor folder, that I cannot change/touch, but when I use it in project, I need to add one more parameter to that object (description).
So I have code:
namespace SoftNation\Sylius\MyExtendBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use SoftNation\Sylius\ExtendBundle\Entity\ExtendTranslation;

/**
 * @ORM\Table(name="softnation_sylius_extend_translation")
 */
class MyExtendTranslation extends  ExtendTranslation
{
    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * @return string
     */
     public function getDescription()
     {
          return $this->description;
     }

     /**
      * @param string $description
      */
     public function setDescription($description)
     {
         $this->description = $description;
     }
}

now when I try:
bin/console doctrine:migrations:diff

I get next error:
[Doctrine\DBAL\Schema\SchemaException]
The table with name
'shop_beta_dev.softnation_sylius_extend_translation' already exists.

All I want is that I can do:
$extend = new ExtendTranslation;
$extend->setDescription('StackOverflowRocks');

A: Exactly like @ccKep suggested ->
Check extending models here: http://docs.sylius.org/en/latest/customization/model.html


text:
Q: Continuous integration and software versioning I like the idea of automatically versioning my builds but I'm not sure what the right way is to get the AssemblyInfo.cs change back into source control (or should it not go into source control?). Is this something the CI server should be committing automatically for each build?
Using Bamboo at the moment.

A: We are using Teamcity as our CI server, and it comes with a feature called AssemblyInfo patcher
What this does, is temporarily add the teamcity build number in Assemblyinfo.cs, build generate the artifact and then revert the change. This way the generated artifact has the same version as the build number.
Source control can have the assemblyinfo.cs version entry as the current revision the developers are working on, with '*' as the build number. This can be updated after every release.
Edit 1:
Since you are using Bamboo, here is a link that describes one way of setting the build number in the generated artifact in bamboo, without having to check-in the AssemblyInfo.cs.

A: I'm sort of confused by your question. If you want the changes to persist you'll have to commit AssemblyInfo.cs after it gets edited by the build job. However, most build systems attempting to solve these problems do not persist the changes. They simply check out the file and edit the local version before kicking off the build task.


text:
Q: How to create context menu for RecyclerView using Kotlin i want to popup context Menu on long click RecyclerView items using Kotlin code

A: You can try like this in onBindViewHolder cvCarIcon can be replaced with rootlayout of your row. or even you can handle with long clicklistener
holder.cvCarIcon.setOnClickListener{
            val popup = PopupMenu(mContext, holder.cvCarIcon)
            popup.inflate(R.menu.options_menu)
            popup.setOnMenuItemClickListener(object : PopupMenu.OnMenuItemClickListener() {
                fun onMenuItemClick(item: MenuItem): Boolean {
                    when (item.getItemId()) {
                        R.id.menu1 ->
                            return true
                        else -> return false
                    }
                }
            })
            popup.show()
        }

A: I solved this by adding this code to ViewHolder class to show popup menu with two items delete and cancel with resource file(menu xml file) named click_menu
init{
        V.tV.setOnLongClickListener {
           // V is View variable and tv is name of textView

            val pop= PopupMenu(V.context,it)
            pop.inflate(R.menu.click_menu)

            pop.setOnMenuItemClickListener {item->

                when(item.itemId)

                {
                    R.id.delete->{ }

                    R.id.cancel->{ }

                }
                true
            }
            pop.show()
            true
      }
}


text:
Q: Generating Columns in GridView ( C#, LINQ ) The situation is, that i need to create table in grid view looking like this:
----------| ID---|---Name--|--1/2002--|--2/2002--|--1/2003--|........| 2/2009 |
Cust1--|
Cust2--|
:
:
I have two tables in db - Customers and orders, throught LINQ to SQL DataContext
ID and Name of the customers i´m getting from a simple query
var custInfo = from cust in db.Customers
               select new { ID = cust.Id,
                            FullName = cust.FirstName + " " + cust.LastName }

dataGridOrdersPreview.DataSource = custInfo;

And i need some clue, how to generate that columns in format t/year where t indicates the first or second half of the year, and assign to that generated columns each Customer´s orders in that session of the year ( displaying only costs )
[edit]
As far as now, i´m attempting to something like this:
var orders = from ord in db.Orders
             group ord by ord.Id_cust into grouped
             let costs = grouped
               .Where( s => s.YearSession == session && s.Year == year)
               .Select(a => new { Costs = a.Cost ) } )

             select new { ID = grouped.Key,
                          Name = custInfo
                             .Where( a => a.ID == grouped.Key)
                             .Select( j => j.Name).Single(),
                          Cost = ExtensionLibrary.Sum(costs, "\n")
                      };

( in Cost getting only the summed costs in that year session for each customer )
and then i think about iterating throuhgh the years and sessions and getting
somehow the query results to corresponding columns
while (year <= DateTime.Today.Year)
        {
            year++;
            while (session < 2)
            {
                session++;
                dataGridOrdersPreview.Columns.Add(session +"/"+ year);
                col.Add((session +"/"+ year),
                         orders.Select( a => a.Cost ).ToList() );
                /* col is Dictionary<string, List<string> > */

            }
            session = 0;
        }

Here i have generated columns that i want and i have orders in Dictionary where Key is column name and Value are orders in that column, but i need some help binding it to that columns

A: The way I've seen it done is to create a class that has the properties that you want, for example,
class CustOrders
{
   public string CustName {get; set;}
   public int Orders2002-1 {get; set;}
   public int Orders2002-2 {get; set;}
   ...
   public int Orders2009-1 {get; set;}
}

Then use the System.Windows.Forms.BindingSource, call it say CustOrdsBindingSource and set its DataSource to a list of your new class.
List<CustOrders> myListOfCustOrders =  new List<CustOrders>();
/* Code to populate myListOfCustOrders */
CustOrdsBindingSource.DataSource = myListOfCustOrders;

In this case you will have to write the code to convert each result of your query results to an instance of CustOrders and store it in myListOfCustOrders.
Finally, the grid view's data source will also have to be set:
gridView1.DataSource = CustOrdsBindingSource;

The big problem I see with this approach is that you will have to change the CustOrders class every year unless there is some voodoo some can suggest to insert properties into the class at run time.
Either way, I hope this gives you a start.

A: As long as there will be no updating/adding/deleting of rows, I think I would just generate that grid manually.
Fetch the list of customers and the count of how many sales in what year/session. And then in the form take that list and create the needed columns.


text:
Q: Nginx: request files without extension How can I request html pages on a nginx server without the extension?
Ie: example.com/about should return example.com/about.html. This should be true for all the html pages.
I have something along the lines of:
try_files $uri $uri.html;
index  index.html;

Which works, but visiting example.com/ causes a 403 Forbidden:
2015/01/20 19:26:11 [error] 32618#0: *373061 access forbidden by rule

And visiting a non existing page (example.com/bla) causes a redirect loop:
2015/01/20 19:26:57 [error] 32620#0: *373065 rewrite or internal redirection cycle while internally redirecting to "/bla.html.html.html.html.html.html.html.html.html.html.html"

updated with complete nginx config:
server {
    listen          [::]:80;
    server_name     example.com;

    access_log  /var/log/nginx/access.log;
    error_log   /var/log/nginx/error.log;
    root   /var/www/example/;
    try_files $uri $uri.html /index.html =404;
    index  index.html;
    expires max;
    autoindex off;

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    location ~ /\.ht {
        deny  all;
    }
}

A: Modify your try_files line to look like the following:
try_files $uri $uri.html /index.html =404;

The reason you are seeing a loop is that try_files will force a redirect to the last entry if no valid location is found during the search.
Further reading and reference: http://wiki.nginx.org/HttpCoreModule#try_files

A: To avoid getting redirected to /index.html instead of your 404 in the case of a wrong url, set try_file like this:
try_files $uri $uri.html $uri/index.html =404;


text:
Q: Enable Button After Page Load in AngularJS Directive I am trying to enable a button after page load in an AngularJS directive. I applied ng-disabled for all my buttons DURING load and I would like to keep certain buttons disabled AFTER load.
I need some direction/advice on:

*

*manipulating the DOM: from ng-disabled="!newAnimal.isDisabled" to ng-disabled="newAnimal.isDisabled"

I appreciate the help. Thanks.
HTML:

        <button class="btn btn-success" ng-disabled="!newAnimal.isDisabled" id="add-animal" loading-animals>
          Add Animal
        </button>

FACTORY:
    var animalFactory = angular.module('app.myFactory',[])

    animalFactory.factory('newAnimal',function(){
        var newAnimal = function(){
              this.animal = "";
              this.totalAnimals = 0;
              this.totalAdopted = 0;
              this.isDisabled = false;
       };
      return newAnimal
   });

CONTROLLER (Modal):
.controller('InformationCtrl', function($scope, $modalInstance, $http) {
    $scope.ok = function(){
        //check if button successfully clicked
        $modalInstance.dismiss('success');

        //the code below was from a directive ('LoadingAnimals') that I was working on

        //check if all data has been loaded from backend
        var loadingPage = function(){
            return $http.pendingRequests.length > 0;
            //when all objects are loaded, manipulate DOM
            //make ng-disabled = "!isDisabled" to "isDisabled"
            element.attr("!newAnimal.isDisabled", "newAnimal.isDisabled);
    }
        loadingPage();
    }

DIRECTIVE:

app.directive('loadingAnimals', ['$http', function($http) {

return {

        restrict: 'A',

        link: function (scope, element, attrs) {

            var addButton = attrs.ngDisabled;
            //console.log(element.attr('ng-disabled'));
            scope.pageLoad = function() {
                return $http.pendingRequests.length > 0;
            };

            scope.$watch(scope.pageLoad(), function (value) {
                if (value) {
                    element.attr("ng-disabled", "newAnimal.isDisabled");
                }
                else {
                    element.removeAttr("ng-disabled");
                }
            })
        }
    }

}]);

UPDATE:
I updated my directive and it works, not the best way of achieving the results but it's one way.
(I would have preferred not to disable the button for 3 seconds but rather to listen to the $http request but since it's a workaround, I won't complain)
Thanks for all the answers. I'll update in the future if I figure out a more efficient way.

DIRECTIVE:

 .directive('loadingAnimals', function() {

       return {

          restrict: 'A',

          link: function (scope, element) {
          var disableLink = (function() {
                element.removeClass('disabled');

            });

            setTimeout(disableLink, 3000);
          }

         }

        }

      ]);

A: Not sure if I'm correct but to do something after page is completely load, you can use angular.element(document).ready() (as you can see in this answer).
So you can have a <button> structured like this:
<button type="button" class="btn btn-primary" ng-disabled="!isDisabled || !animal.totalAnimals">Add animal</button>

See the example below:

(function() {
  'use strict';

  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  function MainCtrl($scope) {
    var vm = this;
    vm.animals = [
      {
        "name":"hamster",
        "totalAnimals": 20,
        "totalAdopted": 5,
      },
      {
        "name":"turtle",
        "totalAnimals": 0,
        "totalAdopted": 0,
      },
      {
        "name":"cat",
        "totalAnimals": 9,
        "totalAdopted": 6,
      },
      {
        "name":"dog",
        "totalAnimals": 7,
        "totalAdopted": 2,
      },
      {
        "name":"tiger",
        "totalAnimals": 0,
        "totalAdopted": 0,
      }
    ];

    vm.isDisabled = true;

    angular.element(document).ready(function () {
      console.log('completely load!');
      vm.isDisabled = false;
    });
  }
})();
<!DOCTYPE HTML>

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">

      Name
      #of Animals Added
      #of Animals Adopted

          <button type="button" class="btn btn-primary" ng-disabled="!main.isDisabled || !animal.totalAnimals">Add animal</button>

I hope it helps.

A: You can also use a directive to make changes post page load
<button id="submit" ng-click="test()">Submit</button>
<disable-button></disable-button>

This is how the directive will look like
.directive('disableButton', function () {
            return {
                restrict: 'E',
                compile: function (el, attr) {
                    return {
                        pre: function (scope, el, attr) {

                        },
                        post: function (scope, el, attr) {
                            $('#submit').attr("disabled", true);
                           //add your logic here
                        }
                    }
                }
            }
        })

Refer the demo


text:
Q: Permalink/Custom Post Type issue — unable to solve One of the custom post types I have on a site now no longer works: the database entries still exist but I cannot access the posts. I think this is the known permalinks issue, but having been through a great many posts and having tried the solutions offered, I'm still stuck with the problem.
I have a 'single,php' file with some sorting code which then redirects to three different single files ('single-author.php', 'single-book.php', 'single-event.php').
Things I've tried:

*

*Switching permalink structure and switching back

*Flushing rewrite rules

*Checking rewrite rules in .htaccess

If I create a new entry in this custom post type I can see it in 'preview' but as soon as I publish it I get a 404. The problem does not seem to be affecting the other custom post types I have running on the site. Other than the recent WP update, I've not made any changes to the site.
I attach the relevant code below — any pointers or help would be greatly appreciated as I'm not sure what else to try in order to fix the problem.
Many thanks!
add_action('init', 'authors_register');

function authors_register() {

$labels = array(
    'name' => _x('Authors', 'post type general name'),
    'singular_name' => _x('Author', 'post type singular name'),
    'add_new' => _x('Add New', 'portfolio item'),
    'add_new_item' => __('Add New Author'),
    'edit_item' => __('Edit Author'),
    'new_item' => __('New Author'),
    'view_item' => __('View Author'),
    'search_items' => __('Search Authors'),
    'not_found' =>  __('Nothing found'),
    'not_found_in_trash' => __('Nothing found in Trash'),
    'parent_item_colon' => ''
);

$args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'query_var' => true,
    'rewrite' => true,
    'capability_type' => 'post',
    'hierarchical' => false,
    'menu_position' => 5,
    'supports' => array('title','thumbnail','revisions','excerpt'),
    'taxonomies' => array('category', 'post_tag')
  );

register_post_type( 'author' , $args );

}

Sorting/switching code in single.php:
<?php if ('post_type=book') { include (TEMPLATEPATH . '/single-book.php'); }

elseif ('post_type=event') { include (TEMPLATEPATH . '/single-event.php'); }

elseif ('post_type=author') { include (TEMPLATEPATH . '/single-author.php'); }

else { include (TEMPLATEPATH . '/single-post.php'); } ?>

A: <?php if ('post_type=book') { include (TEMPLATEPATH . '/single-book.php'); }

elseif ('post_type=event') { include (TEMPLATEPATH . '/single-event.php'); }

elseif ('post_type=author') { include (TEMPLATEPATH . '/single-author.php'); }

else { include (TEMPLATEPATH . '/single-post.php'); } ?>

Will always return single-book.php
'post_type=books' will always return true. You must have the post_type in a variable and check for each
<?php
$post_type =  get_post_type();

if ( $post_type == 'book') { include (TEMPLATEPATH . '/single-book.php'); }
elseif ($post_type == 'event') { include (TEMPLATEPATH . '/single-event.php'); }
elseif ($post_type == 'author') { include (TEMPLATEPATH . '/single-author.php'); }
else { include (TEMPLATEPATH . '/single-post.php'); } ?>

Also, author is not a reserved post type. The reserved post types are:
post
page
attachment
revision
nav_menu_item


text:
Q: Do achievements/awards give any reward? In World of Tanks, you receive rewards, accolades, achievements, etc during games where you perform well.
For example, you will earn Top Gun if you get at least 6 kills in a single game.
My question is do these rewards give you any boost in XP/credits, or are they simple "ego-boosters"?
if there is a chart/database somewhere on how much these awards actually earn you(seeing as there is quite a bit)... that'd be great too (I couldn't find one)

A: No, in most cases these awards give you no other reward than looking nice on your profile. So they are in effect "ego-boosters"
One important exception is that sometimes Wargaming has events where achieving an award during a battle will give you an immediate bonus. (For example a top gun reward getting you 50,000 credits). However, these special events happen infrequently and the reward you get for an award is not known until Wargaming makes the announcement which usually happens a few days before the event.


text:
Q: GetAdaptersInfo Get Media Status and Detect WiFi Type I am using code similar to this one:
Link

*

*How do I get media status (connected or disconnected)?

*How do I know if adapter is wireless type?

Prashant

A: There is the Native WiFi API. (For XP requires SP2/3, min server 2k8)
You can list enabled adapters with WlanEnumInterfaces.
You can fetch state with WlanQueryInterface with wlan_intf_opcode_interface_state to request the state in a WLAN_CONNECTION_ATTRIBUTES struct.
An alternative are the MSNDIS WMI Classes.


text:
Q: $.ajax() function working in IE but not in Chrome and FF I guess this question is not asked in this forum before, tried searching alot but none matched or worked for me. Below is the JSFiddle link of code:
JSFiddle
Everything is working well in IE8 and IE9 but not in any other browsers. I tried looking for the problem in Chrome from which I got
XMLHttpRequest cannot load http://v3.actisku.com/GetUserPostData?pid=Test-37&surv=1170. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers

I tried searching for necessary solution i.e CORS but couldn't figure out the solution. I am side by side looking for the same.
EDIT:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<html><head>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            var contents = $.ajax({
                url: 'http://v3.actisku.com/GetUserPostData?pid=Test-37',
                cache: false,
                crossDomain: true,
                dataType: 'html',
                data: { surv: '1170'},
                async: false
            }).responseText;

            var test = contents;
            alert(test);
            test = test.replace(/\t/g, ';');
            alert(test);
            test = test.replace(/\n/g, 'break');
            alert(test);
            $('#contentArea').attr('value', test);
        });
    </script>
</head>

<body>
<textarea id="contentArea" rows="10" cols="50"></textarea>
</body>
</html>

Can we manually add headers so that the server feels like it is getting request from IE itself.
Regards,
icr

A: ok as says there... "Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers" all AJAX/XHR requests are blocked by the server. Please try to contact the server administrator about the server configuration
the IE uses a different way to send ajax request(so they were not blocked) because they are using ActiveXObject("Msxml2.XMLHTTP") or ActiveXObject("Microsoft.XMLHTTP") which the server maybe reads them differently as they are passed to the headers.

A: There is nothing in your code, to create Browser incompatibility. In fact they ware working fine in Firefox, and chrome. However, This seems unnecessary.
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
}

As mentioned by Mahan, this looks to be like Server Configuration problem.


text:
Q: Variation of Hubble constant in cosmological timescales Although the Hubble constant appears to be a constant, it is not really a constant.
Is the Hubble constant decreasing over cosmological timescales?


text:
Q: Which algorithm Rsync uses for delta encoding? Rsync documentation says what "it uses delta encoding when appropriate". But I can't find witch algorithm it uses for delta encoding. I cannot find it from source. Can anyone help me?

A: Rsync uses a peculiar version of a rolling checksum. Check out a full description for the details.


text:
Q: Camera stays blank on Oxygen4 (Android Nougat) with an OnePlus 3 I've the problem that some users with an Oneplus3 and the most recent Oxygen 4 version (Android Nougat) don't see any camera preview image anymore (it stays blank/black). The UI elements are still visible.
They also said in previous versions of oxygen OS the app was working correctly. I found out, that other apps got the same behaviour and fixed it, recently (i.e. Google's Cardboard Camera). But I don't know how to fix it and don't have a test device like the OP3.
I'm using the min SDK version 14 and the Camera API v1 with a SurfaceView to show the camera preview. On my phone (LG G4 with Marshmallow) the app works as expected.
Is somebody of you familiar with that issue and know how to fix it? What else can I try to solve that problem? Can you reproduce that issue on others phones with Android N, too?
You can find the source here: https://github.com/kloener/visor-android
For testing you can directly download it from Google Play (https://play.google.com/store/apps/details?id=de.visorapp.visor) or on github-releases (https://github.com/kloener/visor-android/releases)
kind regards and thanks

A: They need to give camera permission from application settings. I know they accept it while setting up app. But for Nougat user need to give an extra permission.


text:
Q: Resizing div width to automatically fit paragraph's width I have a div and within it a paragraph:

          This is my first line in the paragraph. This line cannot be broken.

          This is my second line in the paragraph. This line cannot be broken.

        This is another line within the paragraph. This line cannot be broken.

As seen above, my paragraph has a lot of line. Each line ends with a new line. Some of the end with two new lines.
I would like div's width to be resized automatically to the longest paragraph line width.
How can I do this?

Note: I do not want lines to be broken into separate lines until  is reached.
    Div's width must be resized to the longest line width.

A: Set the display of the div to inline-block and to prevent wrapping of lines add white-space: nowrap; for the paragraphs:
#MyDiv{
    display: inline-block;
}

#MyDiv p{
    white-space: nowrap;
}

Fiddle here: http://jsfiddle.net/LMB6L/6/

A: Is this what you mean?
#MyDiv {outline:1px solid red;display:inline-block;}

http://jsfiddle.net/62CQt/

A: I would suggest width:auto; or inherit in the paragraph modification


text:
Q: Issue testing a directive in angular This is my directive spec file. I'm using angular 6.
import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { TestBed, ComponentFixture, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';

import { KeyboardInputDirective } from './keyboard-input.directive';

@Component({
  selector: 'kiosk-app-test-component',
  template: `<input type="text" name="wu-input" class="wu-input" id="standard" [kioskAppKeyboardInput]="'true'">`
})
class TestStubComponent { }

describe('Directive: KeyboardInputDirective', () => {
  let component: TestStubComponent;
  let fixture: ComponentFixture<TestStubComponent>;
  let directiveEl: DebugElement;

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [TestStubComponent, KeyboardInputDirective],
      schemas: [NO_ERRORS_SCHEMA]
    });

    TestBed.compileComponents().then(() => {
      fixture = TestBed.createComponent(TestStubComponent);
      component = fixture.componentInstance;
      directiveEl = fixture.debugElement.query(By.directive(KeyboardInputDirective));
    });

  }));

  fit('should create an instance', () => {
    fixture.detectChanges();
    expect(directiveEl).not.toBeNull();
  });
});

I'm getting below error continuously.
TypeError: Cannot read property 'query' of null

If i console fixture.debugElement value it is always null.
Any help is really appreciated.
package.json
{
  "name": "project-name-xyz",
  "private": true,
  "scripts": {
    "ng": "$(npm bin)/ng",
    "start:web": "$(npm bin)/ng serve web",
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "dependencies": {
    "@angular/animations": "^6.0.3",
    "@angular/common": "^6.0.3",
    "@angular/compiler": "^6.0.3",
    "@angular/core": "^6.0.3",
    "@angular/forms": "^6.0.3",
    "@angular/http": "^6.0.3",
    "@angular/platform-browser": "^6.0.3",
    "@angular/platform-browser-dynamic": "^6.0.3",
    "@angular/router": "^6.0.3",
    "@angular/upgrade": "^6.0.4",
    "@ngrx/effects": "^7.2.0",
    "@ngrx/entity": "^7.2.0",
    "@ngrx/store": "^6.1.0",
    "@ngrx/store-devtools": "^7.2.0",
    "@ngx-translate/core": "^10.0.2",
    "@types/angular": "^1.6.45",
    "angular": "^1.6.9",
    "angular4-translate": "^1.3.5",
    "async": "^2.6.1",
    "child-process-promise": "^2.2.1",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.5.4",
    "fetch-intercept": "^2.3.0",
    "fingerprintjs2": "1.1.0",
    "fs-extra": "^7.0.0",
    "google-libphonenumber": "3.2.6",
    "gulp": "^3.9.1",
    "gulp-remove-code": "^3.0.4",
    "gulp-rename": "^1.4.0",
    "gulp-replace": "^1.0.0",
    "husky": "^3.0.5",
    "jquery": "^3.3.1",
    "lodash": "^4.17.10",
    "moment": "^2.22.2",
    "ngrx-store-localstorage": "^5.1.0",
    "ngx-bootstrap": "^3.3.0",
    "ngx-cookie-service": "^1.0.10",
    "ngx-logger": "^3.3.12",
    "ngx-mask": "^6.1.3",
    "ngx-page-scroll-core": "^6.0.2",
    "ngx-popper": "^5.1.7",
    "popper.js": "^1.14.4",
    "protractor-axe-report-plugin": "^1.1.0",
    "run-sequence": "^2.2.1",
    "rxjs": "6.0.0",
    "rxjs-compat": "^6.2.2",
    "save": "^2.3.2",
    "systemjs": "^0.21.4",
    "systemjs-plugin-babel": "0.0.25",
    "virtual-keyboard": "^1.28.4",
    "web-animations-js": "^2.3.1",
    "zone.js": "^0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.13.1",
    "@angular/cli": "~6.0.8",
    "@angular/compiler-cli": "^7.2.10",
    "@angular/language-service": "^6.0.3",
    "@ngrx/schematics": "^7.2.0",
    "@types/jasmine": "~2.8.6",
    "@types/jasminewd2": "~2.0.3",
    "@types/lodash": "^4.14.118",
    "@types/node": "~8.9.4",
    "chalk": "^2.4.2",
    "codelyzer": "~4.2.1",
    "fancy-log": "^1.3.3",
    "gulp-clean": "^0.4.0",
    "gulp-i18n-lint": "^0.1.1",
    "gulp-tap": "^1.0.1",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "^3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.0",
    "karma-jasmine": "~1.1.1",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-typescript": "^4.0.0",
    "protractor": "^5.4.0",
    "sonarqube-scanner": "^2.4.1",
    "ts-node": "~5.0.1",
    "tslint": "~5.9.1",
    "typescript": "~3.1.1"
  }
}

A: probably you need to move fixture.detectChanges(); inside your describe as follows.
describe('Directive: KeyboardInputDirective', () => {
  let component: TestStubComponent;
  let fixture: ComponentFixture<TestStubComponent>;
  let directiveEl: DebugElement;

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [TestStubComponent, KeyboardInputDirective],
      schemas: [NO_ERRORS_SCHEMA]
    });

    TestBed.compileComponents().then(() => {
      fixture = TestBed.createComponent(TestStubComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
      directiveEl = fixture.debugElement.query(By.directive(KeyboardInputDirective));
    });

  }));

Hope this helps, let me know still if you are facing issue.

A: TestBed.compileComponents is not needed in this case but fixture.detectChanges needs to be called before querying the HTML element. You could address (query) the input element directly and interact with it in your test to see if the directive works correctly. Not knowing what your directive really does, the test below obviously needs to be adapted to make it work for you.
describe('Directive: KeyboardInputDirective', () => {

  let component: TestStubComponent;
  let fixture: ComponentFixture<TestStubComponent>;
  let inputElement: HTMLInputElement;

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [TestStubComponent, KeyboardInputDirective]
    });
    fixture = TestBed.createComponent(TestComponent);
    fixture.detectChanges();
    component = fixture.componentInstance;
    inputElement = <HTMLInputElement>fixture.debugElement.nativeElement.querySelector('INPUT');
  });

  ...

  it('#keydown should ...', fakeAsync(() => {

    // given
    spyOn(inputElement, 'setSelectionRange');
    inputElement.value = 'abc';
    const event = new KeyboardEvent('keydown', { key: '' });

    // when
    inputElement.dispatchEvent(event);
    tick();

    // then
    expect(inputElement.setSelectionRange).toHaveBeenCalledWith(0, 3);
  }));


text:
Q: Don't show bibliography heading if there aren't any citations We use LaTeX to generate PDF documents dynamically from the web. Sometimes reports have bibliography citations, and sometimes they don't.
At the end of our LaTeX document, we have a bibliography block, where all citations are automatically listed (we use BibTeX). But what we want to avoid is to show the bibliography heading when it is empty (with no bibliography entries).
Our actual solution is to add the bibliography block also dynamically, after searching for citations in the final document text, and ensuring that we have, at least, one citation.
Is there another way to do that with LaTeX? I'm thinking about some bibliography block setting or something like this ...

A: As jon has suggested in a comment, this is yet another reason to use biblatex. Compare the output of the following two examples -- note that \printbibliography (a biblatex-specific command that replaces \bibliography) is present in both examples.
\documentclass{article}

\usepackage{biblatex}

\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
@misc{A01,
  author = {Author, A.},
  year = {2001},
  title = {Alpha},
}
\end{filecontents}

\addbibresource{\jobname.bib}

\begin{document}

Some text \autocite{A01}.

\printbibliography

\end{document}

\documentclass{article}

\usepackage{biblatex}

\usepackage{filecontents}

\begin{filecontents}{\jobname.bib}
@misc{A01,
  author = {Author, A.},
  year = {2001},
  title = {Alpha},
}
\end{filecontents}

\addbibresource{\jobname.bib}

\begin{document}

Some text.

\printbibliography

\end{document}

You may also be interested in the following question: What to do to switch to biblatex?


text:
Q: Usage of + or ++ in emails I have been seeing and using the symbols + or ++ whenever a new recipient is added to an existing email thread along with the original recipients in To or Cc.
Just curious about how this came into practice. Is there a definitive understanding of how + or ++ is being used in today's email communications?
Raising this question here as am not sure if this is the right site in stackex.
UPDATE: To clarify, the + or ++ symbols are added in the body of the email, not in To or CC.

A: There is slight difference I have observed in usage of + and ++.

*

*'+' Usually follows a name, to be informed or to action on.

*'++' I disagree that this is a programming jargon despite I being a programmer. ++ usually does not follow a name. This is used when more than one person has been added to email. Sometime, It may be followed by names if possible. But mostly, it is to indicated that additional peoples have been added but need to specifically mention the names is not required  or it is not possible to mention the names.

A: I would agree with instinct71. It's used as follows:
- say an email is sent to a list of recipients, but someone was omitted or the topic needs to include other recipient(s).  The new recipient(s) are added to the To: or CC: fields and their names are also added to the body of the email with a ++ or + , just to inform everyone on the current distribution that others have been added to the discussion.
"++" came from C programming and non-programmers decided to reduce that to a simple "+"

A: I have usually seen either "+SimpleMan" or simply "++". My guess is that this comes from computer programming jargon.
In programming "++" is a shorthand for "add 1 to a variable". For example: "a++" increases a's numerical value by 1. With emails, the variable under consideration is the list of email recipients. "+SimpleMan" (although not legal programming AFAIK) is specifically adding SimpleMan to the list of recipients.


text:
Q: JavaScript/node.js: Getting NULL when trying to access an object's property outside a certain function I have the code snippet bellow which actually is a function that makes a query on a SQL database(used tedious for that).
All I want is to get the data from DB and use them on a web-page.
The issue is that: inside the request.on()... I'm calling date.setMyData() function. Still inside the request.on('row', function(columns)....if calling console.log(date.getMyData()) it successfully returns my data.
BUT, if trying to call date.getMyData outside the request.on('row', function(columns) ...I get NULL...
Is there anything that I'm missing here?
  var date = new DBData();

    function executeStatement() {
  request = new Request(queryString, function(err, rowCount) {
    if (err) {
      console.log(err);
    } else {
     console.log(rowCount + ' rows');
    }
    connection.close();
  });

  request.on('row', function(columns) {

   columns.forEach(function(column) {
      if (column.value === null) {
        console.log('NULL');
      } else {
          date.setMyData(columns);

          //WHY THIS CODE RETURNS MY DATA?
          console.log(date.getMyData());

      }
    });
  });

  request.on('done', function(rowCount, more) {
    console.log(rowCount + ' rows returned');
  });

  connection.execSql(request);
}

function DBData(){
    var myData = null;

    this.setMyData = function(obiect){
        myData = obiect;
    };

    this.getMyData = function(){
        return myData;
    };
};

 console.log(date.getMyData()); //WHY I GET 'NULL' HERE?

A: When you run that code, the order of execution will be
var date = new DBData()
console.log(date.getMyData()) //  null at this point

// end of execution

The function executeStatement() gets defined, but it is not executed right away. It will be presumably executed at a later time when you call it, at which point it will populate your 'var date', hence it will display the correct data correctly when you console.log(date.getMydata()) inside the callback of executeStatement().


text:
Q: "Mailto:" doesn't send email I wrote this simple code:
var email;
do {
     email = prompt('Inserisci il tuo indirizzo eMail');
     if ((email.indexOf("@") == (-1)) || (email == "") || (email == undefined)) {
            alert("Inserisci un indirizzo mail valido");
        }
    }
while ((email.indexOf("@") == (-1)) || (email == "") || (email == undefined));

var subject = ('My Armchair');

var body = new Array();
body[0] = sessionStorage.getItem('imuno');
body[1] = sessionStorage.getItem('imdue');
location.href = "mailto:babini.francesco@queensrl.net" + email + '?subject=' + subject + '&body=' + body[0] + body[1];
location.href = "../index.html";

The check is ok, but it doesn't send the email, someone knows why? Thank you!

A: The browser won't navigate to the new URL until the function has finished running, by the time that happens you have overwritten the mailto: URL with an HTTP URL.
Remove the last line.

A: OK, first you cannot send emails in (browser) javascript. You are going to need server-side code to do so.
At most, doing location.href = "mailto:[…]"; will open the visitor's default mail application with part of it pre filled, but the visitor will still need to click on the send button. And the sender of the email will be the visitor, not you/your website.
If that's what your looking for (the website visitor is actually manually sending the email, not you), you could open a popup for the mailto: link instead of using window.href: window.open("mailto:[…]")
Otherwise, you'll need a server-side language (PHP, Node.js, etc.) with the code to send the email and add ajax request telling your server to do so in your current JS script.
You should look for PHPMailer (PHP) : https://github.com/PHPMailer/PHPMailer
or
Nodemailer (Node.js) : https://nodemailer.com/


text:
Q: Trouble using Sylow's theorems
So, I found part (a) fairly easy, and also managed part (c) assuming (b) to be true.
Any help with (d) and especially (b) would really be appreciated.
My issue with part (b) is understanding which of Sylow's theorems to apply and how. I tried first to apply part (a) to find that, since Sylow $p$-subgroups by definition are non trivial (have $p$ as a factor of their order), then $$1<S\leq K \implies N_K(S) = N_G(S).$$ I was hoping doing this would allow me to somehow apply Sylow's second theorem as conjugation naturally comes up in the problem, but I can not see how I would go about using it.

A: For (b) let $P_0$ be a Sylow $p$-subgroup of $K$, and let $P$ be a Sylow $p$-subgroup of $G$ which contains $P_0$. Then $Z(P)$ normalises $P_0$ so by (a), with $Q=P_0$, we have that $Z(P)\leqslant K$. Now $P$ normalises $Z(P)$, so by (a), with $Q=Z(P)$, we have that $P\leqslant K$.
For (d), there are $|G:N(K)|=|G:K|$ conjugates of $K$. These don't overlap except in the identity, so together they contain $1+|G:K| (|K|-1)$ elements. This leaves $|G:K|-1$ outside.


text:
Q: Show row unicode character without emoji convertion I try to display unicode character without emoji on iOS.
I read this article, but when I try it on some example, the result was like:

I output next code:
   str1 = "\u{25B6}\u{0000FE0E} "
   str2 = "\u{25B6} "
   str3 = "\u{1F310}\u{0000FE0E} "
   str4 = "\u{1F310} "

How can I fix this? I expect that it will return raw white-black unicode character.

A: I can't find right solution, but for obtain grayscale image (in my case for background image for UIButton), we can draw this character and use color filter on it.
        var text = NSString(string: "\u{1F310}")
        var font = UIFont.systemFontOfSize(22)
        var size = text.sizeWithAttributes([NSFontAttributeName : font])
        UIGraphicsBeginImageContext(size)
        text.drawAtPoint(CGPointMake(0.0, 0.0), withAttributes: [NSFontAttributeName : font])
        var symbolRawImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        UIGraphicsBeginImageContext(symbolRawImage.size)
        var fillCtx = UIGraphicsGetCurrentContext()

        //Chose color for that sign
        textColor.setFill()
        CGContextTranslateCTM(fillCtx, 0, symbolRawImage.size.height)
        CGContextScaleCTM(fillCtx, 1.0, -1.0)
        CGContextSetBlendMode(fillCtx, kCGBlendModeNormal)
        var fillRect = CGRectMake(0, 0, symbolRawImage.size.width, symbolRawImage.size.height)
        CGContextDrawImage(fillCtx, fillRect, symbolRawImage.CGImage)
        CGContextClipToMask(fillCtx, fillRect, symbolRawImage.CGImage);
        CGContextAddRect(fillCtx, fillRect);
        CGContextDrawPath(fillCtx,kCGPathFill);
        var outputImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

So now we can choose right color.

A: str1 =@"\u25c0\U0000FE0E"; works for me.


text:
Q: Apparmor DENIED ACCESS to soft links I am using Ubuntu 20.04 (Focal Fossa) but this issues has been happening since I am using an old Ubuntu (19.04 & 19.10). So I have 2 hard disk drives - one is an SSD (small size), the other a SATA (big size). The reason I attached a big SATA disk is that I have to host a large MySQL database.
So the SATA hard is mounted at /mnt/sata/ and I created the following symlinks:
/var/lib/mysql -> /mnt/sata/mysql

I am doing this because I don't want to change the default configuration for MySQL and AppArmor. But when I try to start the mysql service, I am getting the following error from apparmor.
Apr 29 20:45:26 home kernel: [17678.024673] audit: type=1400 audit(1588189526.914:156): apparmor="DENIED" operation="mknod" profile="/usr/sbin/mysqld" name="/mnt/sata/mysql/mysqld_tmp_file_case_insensitive_test.lower-test" pid=58497 comm="mysqld" requested_mask="c" denied_mask="c" fsuid=125 ouid=125

So it means apparmor prevents MySQL from accessing the data directory which is /var/lib/mysql and then symlinked to /mnt/sata/mysql. If I add the following rules to the /etc/apparmor.d/usr.sbin.mysqld, the issue is gone.
/usr/sbin/mysqld {
    ...

    # Allow data dir access (existing)
    /var/lib/mysql/ r,
    /var/lib/mysql/** rwk,

    # Allow symlinks as well (added for symlink)
    /mnt/sata/mysql r,
    /mnt/sata/mysql rwk,
    ...
}

As you can see, the apparmor profile for MySQL already allows for access to /var/lib/mysql which is, in my case, then symlinked to /mnt/sata/mysql. So it looks like apparmor followed the symlink and tried to look for rules for the symlink's target.
Any solution that allows me to start the mysql server without having to add the access rules for the symlinks to the apparmor profile?
Thanks!!!

A: Use a bind-mount instead of a soft link:
mount -bind /mnt/sata/mysql /var/lib/mysql

You can also put this in /etc/fstab
/mnt/sata/mysql /var/lib/mysql none bind


text:
Q: Java Regular Expressions: How to express a string that can be ANYTHING? I've been working with an online regular expression tester to develop a Java regular expression.
What I would like is a regular expression that will match a particular pattern at the start of a strong, a particular pattern at the end of a string, and ANYTHING in between in that string.
For example it would file names structured like this
^StartOfAFileName_middleOfAFileName_EndOfAFileName.java$

The "_middleOfAFileName_" can literally be anything.
I tried this something similar to this in the regular expression tester, but it failed:
^StartOfAFileName_**\***_EndOfAFileName.java$

Any idea what the Java regex equivalent of a "*" or any string/any pattern would be?

A: It is .*.  The . is "any character and the * is any number of them.
https://docs.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html

A: Here it is in code/context:
String str = "StartOfAFileName_middleOfAFileName_EndOfAFileName.java";
String pattern = "^StartOfAFileName.*EndOfAFileName.java$";
System.out.println(str.matches(pattern) ? "\nMATCHES" : "\nDOESN'T MATCH");