text:
Q: Grouping data from multiple tables I have 4 tables for each month; oct, dec, feb, apr. They have the same schema.
I need to extract the data from all the tables using the same query and grouping it for one attribute.
I know how to do it for one table but I would like to combine the results into one query and then dump the output into the file.
Here is my sample query:
select TIMESTAMPDIFF(hour,startTime,endTime) as duration, count(*) from feb
where type='gen' group by duration
into outfile "/feb";

Since I am grouping this for duration attribute, I end up 4 different output files and then merging and sorting the data explicitly is something I would like avoid.
Any help would be appreciated!
Omer

A: You could use a UNION:
select TIMESTAMPDIFF(hour,startTime,endTime) as duration, count(*) from feb
where type='gen' group by duration
UNION
select TIMESTAMPDIFF(hour,startTime,endTime) as duration, count(*) from apr
where type='gen' group by duration
UNION
select TIMESTAMPDIFF(hour,startTime,endTime) as duration, count(*) from oct
where type='gen' group by duration
UNION
select TIMESTAMPDIFF(hour,startTime,endTime) as duration, count(*) from dec
where type='gen' group by duration
into outfile "/all";

Note that you only use the INFO OUTFILE clause at the very end and not on each SELECT statement.

A: Use UNION ALL. It offers better performance than UNION, and it would be wrong to remove duplicates in this case anyway. You can also perform the GROUP BY after putting all of the tables together, so that it is possible for rows to be grouped across tables. That'll give you a count of rows with the same duration added up across all 4 tables.
select everything.duration, count(*)
from
((select TIMESTAMPDIFF(hour,startTime,endTime) as duration
  from feb where type='gen')
 union all
 (select TIMESTAMPDIFF(hour,startTime,endTime) as duration
  from apr where type='gen')
 union all
 (select TIMESTAMPDIFF(hour,startTime,endTime) as duration
  from oct where type='gen')
 union all
 (select TIMESTAMPDIFF(hour,startTime,endTime) as duration
  from dec where type='gen')) everything
group by everything.duration
into outfile "/all";


text:
Q: How can I output an barcode to QLabel without saving it to a file? Tell me how to output an image without saving it to a file? Maybe you can save it to RAM somehow? here is the form code:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>MainWindow</class>
 <widget class="QMainWindow" name="MainWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>849</width>
    <height>677</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>MainWindow</string>
  </property>
  <widget class="QWidget" name="centralwidget">
   <layout class="QVBoxLayout" name="verticalLayout">
    <item>
     <widget class="QLineEdit" name="editNum"/>
    </item>
    <item>
     <widget class="QLabel" name="label">
      <property name="text">
       <string/>
      </property>
     </widget>
    </item>
    <item>
     <widget class="QPushButton" name="btnGenerate">
      <property name="text">
       <string>Сгенерировать</string>
      </property>
     </widget>
    </item>
    <item>
     <widget class="QPushButton" name="btnPrint">
      <property name="text">
       <string>Печать</string>
      </property>
     </widget>
    </item>
   </layout>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

and this is the functionality:
import sys
import os
import barcode
from barcode.writer import ImageWriter

from PyQt5.QtWidgets import QGraphicsView, QGraphicsScene, QMainWindow, QApplication
from PyQt5.QtGui import QPixmap
from PyQt5 import uic
from PyQt5.QtCore import Qt

class BarcodeGenerate(QMainWindow):
    def __init__(self):
        super().__init__()
        uic.loadUi('barcode_design.ui', self)
        self.btnGenerate.clicked.connect(self.generate)
        self.show()

    def generate(self):
        self.eanNum = self.editNum.text()
        self.ean13 = barcode.get('ean13', self.eanNum, writer=ImageWriter())

        self.pixmap = QPixmap(self.ean13.save('barcode'))
        self.label.setPixmap(self.pixmap)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = BarcodeGenerate()
    sys.exit(app.exec())

I don't want to save the image every time and then upload it again. Is there a way to directly output to QLabel?

A: One possible solution is to use io.BytesIO() as an intermediary and use write() instead save():
from io import BytesIO
import os
import sys

import barcode
from barcode.writer import ImageWriter

from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtGui import QPixmap
from PyQt5.uic import loadUi

class BarcodeGenerate(QMainWindow):
    def __init__(self):
        super().__init__()
        loadUi("barcode_design.ui", self)
        self.btnGenerate.clicked.connect(self.generate)

    def generate(self):
        value = self.editNum.text()
        ean13 = barcode.get("ean13", value, writer=ImageWriter())

        fp = BytesIO()
        ean13.write(fp)
        pixmap = QPixmap()
        pixmap.loadFromData(fp.getvalue())

        self.label.setPixmap(pixmap)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = BarcodeGenerate()
    window.show()
    sys.exit(app.exec())

redpajama_set_name: RedPajamaStackExchange


text:
Q: Native iOS WebRTC only seems to connect on Offer I am building the iOS client for a WebRTC based solution and we got stuck fixing the older project that was abandoned by the previous developer. In order to start from a "known good" I created a clean application forking off a demo by Stasel. Then, I would switch between our signaling server and his simple locally running example server.
I started noticing that it always seemed to connect on the Offer, never on Candidates. However the rest of the infrastructure uses trickle and there's a chance their Offers do not contain Candidates.
Is there some kind of switch that allows trickle to work? I see some documentation for the web clients but can't find anything for the native iOS client.


text:
Q: Sort by field value in Django 2.0 This question is like django sorting but I can't make any of the solutions work.
I have the following model:
from django.db import models
from django.contrib.auth.models import User

class Product(models.Model):

    title = models.CharField(max_length=200)
    pub_date = models.DateTimeField()
    body = models.TextField()
    url = models.TextField()
    image = models.ImageField(upload_to='images/')
    icon = models.ImageField(upload_to='images/')
    votes_total = models.IntegerField(default=1)
    hunter = models.ForeignKey(User, on_delete=models.CASCADE)

    def summary(self):
        return self.body[:50]

    def pub_date_pretty(self):
        return self.pub_date.strftime('%b %e %Y')

    def __str__(self):
        return self.title

I would like to sort by votes_total so that when I loop through the database results are ordered by votes_total.
{% extends 'base.html' %}

{% block content %}

{% for product in products.all %}

{{ product.title }}

{{ product.summary }}

    <button class="btn btn-primary btn-lg btn-block"> Upvote {{ product.votes_total }}</button>

<form id="upvote{{ product.id }}" method="POST" action="{% url 'upvote' product.id %}">
  {% csrf_token %}
  <input type="hidden">
</form>
{% endfor %}

{% endblock %}

How do I sort my results?

A: There are basically two ways you can do this:

*

*define the ordering in a view; or

*define a default ordering (an ordering that can be overridden with another ordering) in the model.

The last option is typically used if the model has a sensical (inherent) ordering (for example it is very logical to order a queryset in a certain way, and only occasionally in another way).
Sorting in a view
We can sort a queryset, by using the .order_by(..) function of a queryset. The function takes an arbitrary number of parameters: strings that specify the column names. In case a column name is prefixed with a minus (-) it means we sort in descending order.
For example we can define a view:
def some_view(request):
    my_products = Product.objects.all().order_by('-votes_total')
    return render(request, 'my_template.html', {'my_products': my_products})
then we can use this 'my_products' variable, and iterate over it:
{% extends 'base.html' %}

{% block content %}

{% for product in my_products %}

{{ product.title }}

{{ product.summary }}

    <button class="btn btn-primary btn-lg btn-block"> Upvote {{ product.votes_total }}</button>

<form id="upvote{{ product.id }}" method="POST" action="{% url 'upvote' product.id %}">
  {% csrf_token %}
  <input type="hidden">
</form>
{% endfor %}

{% endblock %}
Define an ordering on a model
In case a certain ordering is quite logical from a model perspective, we can also encapsulate the ordering in the model itself. We specify this wth the ordering attribute of the Meta class of the attribute. In case we want for example to order Product.objects.all() by default by the number of votes in descending order, we can write:
class Product(models.Model):

    title = models.CharField(max_length=200)
    pub_date = models.DateTimeField()
    body = models.TextField()
    url = models.TextField()
    image = models.ImageField(upload_to='images/')
    icon = models.ImageField(upload_to='images/')
    votes_total = models.IntegerField(default=1)
    hunter = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        ordering = ['-votes_total']
So now we can still access Product.objects.all in the template, and the items will be sorted automatically.
Note however that we can define only one such ordering per model, and thus making a certain decision, can not be specified based on a particular view. In case you want to "override" the ordering, you need to user order_by on the queryset.

A: You should sort the queryset in your view and pass it to the template. For sorting it in ascending order
return render(request, template_name,{
    'products': Product.objects.all().order_by('votes_total')
})

For sorting in descending order:
return render(request, template_name,{
    'products': Product.objects.all().order_by('-votes_total')
})

You should use products (not products.all) in your template.


text:
Q: Calculating Average Monthly Consumption I'm working on an self improvement inventory management project in Laravel 4 but can't figure out the best way to perform the average monthly consumption (AMC) calculation.
I have two tables i.e commodities table (id,item_name,price) and stockcard (id, item_id, qty_in, qty_out,transaction_date) from which i should derive the AMC calculation.
FORMULA = (sum of current month's qty_out + sum of previous two month's qty_out) / 3

Can anyone bail me out on how to go about it in plain PHP and mysql?

A: You should be able to do this using conditional aggregation for example
   drop table if exists t;

create table t(item int,qty_out int , dt date);

insert into t values
(1,1,'2018-09-01'),(1,1,'2018-10-01'),(1,1,'2018-11-01');

select item,
         sum(case when year(dt)*12 + month(dt) = year(now()) * 12 + month(now()) then qty_out else 0 end) thismm,
         sum(case when year(dt)*12 + month(dt) = (year(now()) * 12 + month(now()) -1) or
                            year(dt)*12 + month(dt) = (year(now()) * 12 + month(now()) -2) then qty_out else 0 end) last2mm,
         (sum(case when year(dt)*12 + month(dt) = year(now()) * 12 + month(now()) then qty_out else 0 end) +
         sum(case when year(dt)*12 + month(dt) = (year(now()) * 12 + month(now()) -1) or
                            year(dt)*12 + month(dt) = (year(now()) * 12 + month(now()) -2) then qty_out else 0 end)
         ) / 3  amc
from t
where year(dt)*12 + month(dt) >= (year(now()) * 12 + month(now()) -2)
group by item ;
+------+-----------+-------+--------+
| item | thismonth | last2 | amc    |
+------+-----------+-------+--------+
|    1 |         1 |     2 | 1.0000 |
+------+-----------+-------+--------+
1 row in set (0.01 sec)

Note the conversion to month number to simplify where dates go over a year end.
Of course if you are looking for a 3 month rolling average then that would be a different question.


text:
Q: SQL - count function not working correctly I'm trying to count the blood type for each blood bank I'm using oracle DB
the blood bank table is created like this
    CREATE TABLE BloodBank (
  BB_ID number(15),
  BB_name varchar2(255) not NULL,
  B_type varchar2(255),CONSTRAINT
  blood_ty_pk FOREIGN KEY
  (B_type) references BloodType(B_type),
  salary number(15) not Null,
  PRIMARY KEY (BB_ID)
);
INSERT INTO BloodBank (BB_ID,BB_name,b_type, salary)
VALUES (370,'new york Blood Bank','A+,A-,B+',12000);
INSERT INTO BloodBank (BB_ID,BB_name,b_type, salary)
VALUES (791,'chicago Blood Bank','B+,AB-,O-',90000);
INSERT INTO BloodBank (BB_ID,BB_name,b_type, salary)
VALUES (246,'los angeles Blood Bank','O+,A-,AB+',4500);
INSERT INTO BloodBank (BB_ID,BB_name,b_type, salary)
VALUES (360,'boston Blood Bank','A+,AB+',13000);
INSERT INTO BloodBank (BB_ID,BB_name,b_type, salary)
VALUES (510,'seattle Blood Bank','AB+,AB-,B+',2300);
select * from BloodBank;

when I use the count function
select count(B_type)
from bloodbank
group by BB_ID;

the result would be like this

so why the count function is not working correctly?
I'm trying to display each blood bank blood type count which is not only one in this case

A: I hope I don't get downvoted for solving the specific problem you're asking about, but this query would work:
select bb_id,
       bb_name,
       REGEXP_COUNT(b_type, ',')+1
from bloodbank;

However, this solution ignores a MAJOR issue with your data, which is that you do not normalize it as @Tim Biegeleisen correctly instructs you to do.  The solution I've provided is EXTREMELY hacky in that it counts the commas in your string to determine the number of blood types.  This is not at all reliable, and you should 100% do what Tim B recommends.  But for the circumstances you find yourself in, this will tell you how many different blood types are kept at a specific blood bank.
http://sqlfiddle.com/#!4/8ed1c2/2

A: You should normalize your data and get each blood type value onto a separate record.  That is, your starting data should look like this:
BB_ID | BB_name             | b_type | salary
370   | new york Blood Bank | A+     | 12000
370   | new york Blood Bank | A-     | 12000
370   | new york Blood Bank | A+     | 12000
... and so on

With this data model, the query you want is something along these lines:
SELECT BB_ID, BB_name, b_type, COUNT(*) AS cnt
FROM bloodbank
GROUP BY BB_ID, BB_name, b_type;

Or, if you want just counts of types across all bloodbanks, then use:
SELECT b_type, COUNT(*) AS cnt
FROM bloodbank
GROUP BY b_type;


text:
Q: How can I keep "approximate" date data points? I'm working on a web app that displays some products with their release date. Some dates are complete (for example, '2017-09-05') and some are not (for instance, 'first 2018 quarter', '2018 september', '2019').
The existing database is built on MySQL and I want to keep requests "simple".
Sometimes I need to request (a) released products, sometimes (b) future products, and sometimes (c) all products.
The questions
How can I (1) retain and (2) manipulate these incomplete date data points? In the same date column? In which format?

A: There is no "standard" way.  You need to invent something, then write app code to handle it.  Some thoughts:

*

*Strings like what you suggest.  Pro: displays nicely; Con: hard to parse.

*Strings, but more like 2018Q1, 201809, or whatever.  Pros/cons:  Somewhat readable; somewhat parsable.

*DATE, with the day of the beginning (or end?) of the period, plus another column that says day or month or quarter or annual.  That could be an ENUM or some other technique.  Pro: somewhat sortable.


text:
Q: How to create simple volume from unallocated partition I'm trying to open a place on my harddisk to store some licensing files.
So far I have tried diskpart. It looks easy to use but I could not format the unallocated partition with diskpart. I have found a way to create the unallocated space but I have to format it to use(correct me if I am wrong here. I'm really new on disk partition stuff)
This is my method to select the right volume. I've take it from here and it's working good. Link : C# and diskpart: how to select by disk label and not by a number? and the code I am using is this :
public int GetIndexOfDrive(string drive)
{
    drive = drive.Replace(":", "").Replace(@"\", "");

    // execute DiskPart programatically
    Process process = new Process();
    process.StartInfo.FileName = "diskpart.exe";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.CreateNoWindow = true;
    process.StartInfo.RedirectStandardInput = true;
    process.StartInfo.RedirectStandardOutput = true;
    process.Start();
    process.StandardInput.WriteLine("list volume");
    process.StandardInput.WriteLine("exit");
    string output = process.StandardOutput.ReadToEnd();
    process.WaitForExit();

    // extract information from output
    string table = output.Split(new string[] { "DISKPART>" },         StringSplitOptions.None)[1];
    var rows = table.Split(new string[] { "\n" }, StringSplitOptions.None);
    for (int i = 3; i < rows.Length; i++)
    {
        if (rows[i].Contains("Volume"))
        {
            int index = Int32.Parse(rows[i].Split(new string[] { " " }, StringSplitOptions.None)[3]);
            string label = rows[i].Split(new string[] { " " }, StringSplitOptions.None)[8];

            if (label.Equals(drive))
            {
                return index;
            }
        }
    }

    return -1;
}

once I get the index I run my own code to shrink that selected volume with this code :
Process DiskPartProc = new Process();
DiskPartProc.StartInfo.CreateNoWindow = true;
DiskPartProc.StartInfo.UseShellExecute = false;
DiskPartProc.StartInfo.RedirectStandardOutput = true;
DiskPartProc.StartInfo.FileName = @"C:\Windows\System32\diskpart.exe";
DiskPartProc.StartInfo.RedirectStandardInput = true;
DiskPartProc.Start();
DiskPartProc.StandardInput.WriteLine("select volume "+index);
DiskPartProc.StandardInput.WriteLine("shrink desired=16 minimum=16");
DiskPartProc.StandardInput.WriteLine("exit");
string output = DiskPartProc.StandardOutput.ReadToEnd();
DiskPartProc.WaitForExit();

Once I do this the result is like this :
http://prntscr.com/mjwg0t (Picture of an unallocated partition only)
I can right click on it and create new simple volume from that unallocated partition but I have to do this with diskpart commands.
Can someone tell me which diskpart commands do I have to use to achieve this?
And how can I get detailed information about this volume?

A: I have solve my problem. This is my final code:
int index = GetIndexOfDrive(Path.GetPathRoot(@"E:\"));

Process DiskPartProc = new Process();
DiskPartProc.StartInfo.CreateNoWindow = true;
DiskPartProc.StartInfo.UseShellExecute = false;
DiskPartProc.StartInfo.RedirectStandardOutput = true;
DiskPartProc.StartInfo.FileName = @"C:\Windows\System32\diskpart.exe";
DiskPartProc.StartInfo.RedirectStandardInput = true;
DiskPartProc.Start();
DiskPartProc.StandardInput.WriteLine("select volume " + index);
DiskPartProc.StandardInput.WriteLine("shrink desired=16 minimum=16");
DiskPartProc.StandardInput.WriteLine("create partition primary size=16");
DiskPartProc.StandardInput.WriteLine("format fs=ntfs label=\"MyPlace\" quick");
DiskPartProc.StandardInput.WriteLine("exit");
string output = DiskPartProc.StandardOutput.ReadToEnd();
DiskPartProc.WaitForExit();

The problem was something about my own disk. I have put another spare one and did all my test on it and it work perfectly, now I can create a disk volume inside a disk and format it and then I can access it with its volume ID. I still have to find a way to do it in C#. I can do the last part from windows not from C# yet. I need a way to access that volume now. I tried Directory.Exist but it did not worked out.
EDIT : I found a way to check. Since I put only 1 file and nothing else in my volume I use this code :
Process MountProc = new Process();
            MountProc.StartInfo.CreateNoWindow = true;
            MountProc.StartInfo.UseShellExecute = false;
            MountProc.StartInfo.RedirectStandardOutput = true;
            MountProc.StartInfo.FileName = "mountvol";
            MountProc.StartInfo.RedirectStandardInput = true;
            MountProc.Start();
            MountProc.StandardInput.WriteLine("mountvol");
            MountProc.StandardInput.WriteLine("exit");
            string MountOutput = MountProc.StandardOutput.ReadToEnd();
            MountProc.WaitForExit();

            string VolumeGUID = string.Empty;
            List<string> VolList = MountOutput.Split(new string[] { "Possible values for VolumeName along with current mount points are:" }, StringSplitOptions.None)[1].Split('\n').Where(x => x != "\r").Where(x => x != "").ToList();
            List<string> ClearList = VolList.Select(s => s.Trim().Replace("\r", "")).ToList();
            for (int i = 0; i < ClearList.Count; i++)
            {
                if (ClearList[i].StartsWith(@"\\?\Volume") && ClearList[i + 1].StartsWith("***"))
                {
                    string tmpPath = ClearList[i].Replace(@"\\?\", @"\\.\");
                    if (Directory.Exists(tmpPath))
                    {
                        string[] DirectoryList = Directory.GetDirectories(tmpPath, "*.*", SearchOption.TopDirectoryOnly);
                        string[] FileList = Directory.GetFiles(tmpPath, "*.*", SearchOption.TopDirectoryOnly);

                        if(DirectoryList.Length==0 && FileList.Length==1)
                        {
                            if (Path.GetExtension(FileList[0]) == ".license")
                            {
                                Console.WriteLine("\n\n\n\t\rLicense file found in : " + FileList[0]);
                                File.Copy(FileList[0], "LIC.license", true);
                                Console.WriteLine("\n\t\rContent of license file : " + File.ReadAllText("LIC.license"));
                                File.Delete("LIC.license");
                            }
                        }
                    }
                }
            }
            Console.ReadKey();

The reason why I copied the file to another location and open it there is I can't open it with File class if it's accessed with it's ID(e.g. \.\Volume{UNIQUE_ID}\)


text:
Q: Spring Cloud Kubernetes, Gateway Route Mapping I am learning Spring boot kubernetes and trying to setup spring cloud gateway for my services. I believe with Spring cloud gateway we don;t have to use ribbon for load balancing any more. So If I don;t use ribbon then the configuration for routes changes as well. I looked over the sites for suggestion and following is what I found :-
routes:
- id: department_route
  uri: http://departmentservice:4200 #
  predicates:
  - Path=/*

In this case the uri has a hardcoded value of port at which the service is available. Is this is recommended approach ?
And then there is another flavor of the configuration which looks like this and Not sure what url-expression trying to do :-
spring:
  application.name: gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          url-expression: "'http://'+serviceId"
  server.port: 8080

Is it not possible to do a service discovery by name and append the predicate after that?

A: I am Still working on fixing the Spring Cloud Gateway project of main but following has worked for me. I have configured the routes via Zuul so make sure your dependencies and configuration related to it matches :-
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-kubernetes-all</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-sleuth</artifactId>
    </dependency>

**Config :: application.yaml ::**

    zuul:
      routes:
        shopping-cart-service:
          path: "/shopping-cart-service/**"
        item-service:
          path: "/item-service/**"


text:
Q: Angular 4 error: There are multiple modules with names that only differ in casing I am getting following error in my Angular 4 project after ng serve command.

./src/app/Utils/config.service.ts
  There are multiple modules with names that only differ in casing.
  This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
  Use equal casing. Compare these module identifiers:
  * D:\ANGULAR\siteprice.org\node_modules\@ngtools\webpack\src\index.js!D:\ANGULAR\siteprice.org\src\app\Utils\config.service.ts
      Used by 1 module(s), i. e.
      D:\ANGULAR\siteprice.org\node_modules\@ngtools\webpack\src\index.js!D:\ANGULAR\siteprice.org\src\app\utils\email.service.ts
  * D:\ANGULAR\siteprice.org\node_modules\@ngtools\webpack\src\index.js!D:\ANGULAR\siteprice.org\src\app\utils\config.service.ts
      Used by 2 module(s), i. e.
      D:\ANGULAR\siteprice.org\node_modules\@ngtools\webpack\src\index.js!D:\ANGULAR\siteprice.org\src\app\app.module.ts

config.service.ts file:
import { Injectable } from '@angular/core';

@Injectable()
export class ConfigService {

  _apiURI : string;

  constructor() {
      this._apiURI = 'http://www.example.com/xyz/api/';
    }

    getApiURI() {
        return this._apiURI;
    }

    getApiHost() {
        return this._apiURI.replace('api/','');
    }

}

email.service.ts:
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import {Observable} from 'rxjs';
import 'rxjs/add/operator/map';
import { ConfigService } from '../Utils/config.service';
import { Email } from '../Models/email';

@Injectable()
export class EmailService {

  apiRoot: string = '';

  constructor(private http: Http, private configService: ConfigService) {
    this.apiRoot = configService.getApiURI();
  }

I checked casing of the service names and they are correct.

A: I found the issue and I think it may be a bug in CLI.
The Utils folder name should be utils. So the first letter is lower case.
utils folder in my windows directory is created with lower case.
So I changed this:
import { ConfigService } from '../Utils/config.service';

to:
import { ConfigService } from '../utils/config.service';

Edit:
It looks like this is a known issue, one of the suggested solution is using kebap case file, folder names in windows.
https://github.com/AngularClass/angular-starter/issues/926


text:
Q: Detect silence during recording mac os x sdk I have been struggling to detect silence during recording.
I am successful in recording and playing recorded audio, but getting no idea for silence detection.
For recording, I had used : https://github.com/darcyliu/CocoaSampleCode/tree/master/AVCaptureToAudioUnitOSX
which works on core audio api.
Any help would be a boon for me.
Thank You

A: You can use AVAudioRecorder but that's not a perfect way to solve your problem.
NSDictionary *settings =@{AVSampleRateKey:@(22050.0),
                          AVFormatIDKey:@(kAudioFormatLinearPCM),
                          AVNumberOfChannelsKey:@(1),
                          AVEncoderAudioQualityKey:@(AVAudioQualityMax),
                          AVLinearPCMBitDepthKey:@(32),
                          AVLinearPCMIsBigEndianKey:@(NO),
                          AVLinearPCMIsFloatKey:@(NO)};
AVAudioRecorder *recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL fileURLWithPath:@"/dev/null"] settings:setting error:nil];
[recorder prepareToRecord];
[recorder setMeteringEnabled:YES];
[recorder record];
NSTimer *levelTimer = [NSTimer scheduledTimerWithTimeInterval:0.3f target:self selector:@selector(levelTimerCallback:) userInfo:nil repeats:YES];

Then in levelTimerCallback: method
[recorder updateMeters];
CGFloat peak = [recorder peakPowerForChannel:0]
CGFloat average = [recorder averagePowerForChannel:0];


text:
Q: Need to use timeout inside Observable subscription to get accurate data I have two Observables in a container called settings and settingsLoading. I have an API call that retrieves some settings, and once that call completes, settingsLoading will be set to true and settings will contain the data from the API. I am passing the settings data to a component and passing settingsLoading to the same component as an Observable.
In that component, as seen below, I am subscribing to the settingsLoading Observable, and once loading is false, I make a couple of console logs so I can look at the settings data that should now be set. The console log always returns null unless I wrap it in a timeout of 0 seconds. Why do I need to do this? Is this a reliable way of handling this? Is there a better way to do this so I can avoid the timeout?
In the code below, the first console log will always return null and the second seems to always have the data I'm expecting:
subscribeToLoadSettings() {
    this.settingsLoading.subscribe(loading => {
        if (!loading) {
            // This doesn't work
            console.log('settings', this.settings);
            setTimeout(() => {
                // This works
                console.log('settings', this.settings);
            }, 0);
        }
    });
}

A: When one observable is depend on the result of other observable then you can use RxJS operator such as switchMap.

A: If you do a subscribe into another subscribe, that will work fine, without timeout !!!
But for refactor code, you can use mergeMap or switchMap.
See code in: How to refactor a subscribe inside a subscribe in rxjs
Regards!


text:
Q: Ipywidgets select multiple not working? Version 4.1.1 and 5.1.4 a=widgets.SelectMultiple(options = df.columns.tolist(),description = 'X Axis',value=['Totpop'])
display(a)

This correctly displays the list of columns in a select multiple widget
a.value

When run directly after displaying the widget, it properly displays the starting value. However, if I change the selection in the widget to anything else (or even if I change it and then change it back to the initial value), a.value returns an empty list.
I first noticed this because I have a tool I use that interacts with a bokeh plot and some other statistical outputs, but all of a sudden selecting new values caused it to bomb.
I have tried updating to version 5.1.4 and I get the same result.  Any help would be greatly appreciated!
Thank you!

A: Update.. I was using IE (silly work computer). Switched to chrome and everything works again..


text:
Q: Compare Strings read from txt file in java I read a string from a txt file and I want compare this string with my reference. But it displays "not ok" and I don't know why.
public class ReadFile {
    public static void main(String[] args) {
        try {
            File file = new File("nh.txt");
            FileReader fileReader = new FileReader(file);
            StringBuffer stringBuffer = new StringBuffer();
            int numCharsRead;
            //char[] charArray1 = new char[1024];
            char[] charArray = new char[1024];
            while ((numCharsRead = fileReader.read(charArray)) > 0) {
                stringBuffer.append(charArray, 0, numCharsRead);
            }

            String resultat = new String(charArray);
            String resultat1 = resultat.replaceAll("\\s", "");
            System.out.println(resultat1);
            String a="Nihao";
            if(a.equals(resultat1)){System.out.println("ok");}
            else System.out.println("not ok");

            fileReader.close();
            System.out.println("Contents of file:");
            System.out.println(stringBuffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

A: This is because the string resultat1 is a 1024 char length, its possible to a java string to have \0, its in memory like this (if the file contains Niaho):
Nihao\0\0\0..

And because \0 is not a whitespace, this will not make any change:
resultat.replaceAll("\\s", "");

So you need to replace this char \0 with nothing:
resultat.replaceAll("\0", "");

or simply compare the reference string a to stringBuffer.toString() which is numCharsRead length:
if(a.equals(stringBuffer.toString())){System.out.println("ok");}
            else System.out.println("not ok");


text:
Q: How to get a value from a textbox and assign it to a variable using TimeValue() Im coding in vba in ms-access and Im wondering how to address a value that appears in a text box in my mai form and put that value in a variable.TimeValue ("value") for example..... I tried with this code but it doesn't work..
    dDuration = TimeValue("me.text101.text")

me.text101.text = is the textbox holding the value, the value is in minutes:seconds...
dDuration = the variable that will be asigned the value from texbox101.text..I also tried me.textbox101.value... but it just freezes, meaning that it goes to an infinite loop calculating...Is this the correct method?

A: This should work:
dDuration = TimeValue(Me.text101)

Freezing is another issue, not related to this code.


text:
Q: Complex expressions in python reduce Is there a smart way to sum a list, but actually perform a map type function prior to summing.
I'm trying to combine these functions into one function that uses the lambda:
xlist = [1, 2, 3, 4]
sum(map(lambda x: (x - 1.0)**2, xlist))

# result = 14.0

I'm trying this:
reduce(lambda x, y: x + (y - 1.0)**2, xlist)

# result = 15.0

But it is not the same result. What is the smartest way to solve this. I'm kind of curious, I know I can use sum(map()) but I wonder if reduce can be used in this way.

A: Yea, you just need to pass an initial value of 0:
>>> xlist = [1, 2, 3, 4]
>>> reduce(lambda x, y: x + (y - 1.0)**2, xlist, 0)
14.0
>>>

Keep in mind though that reduce is generally hated by Python programmers because of how unreadable it is.  You would probably be better off using the first approach.
Or, even better, use a generator expression:
sum((x - 1.0)**2 for x in xlist)

This is a lot easier to read and is also more efficient because map creates an unnecessary list.


text:
Q: Is there any way to Stream Map Filter & Map back to original object in Java 8? Is there any way to Stream the list --> map --> filter --> map back to original object type of list?
There is solution if we are doing it using foreach as below:
List<Query> updatedQueries = getUpdatedQueries();

List<Query> finalQueries = new ArrayList<>();
updatedQueries.forEach(query -> {

    Period period = getPeriodRequest(query);
    boolean isValidPeriod = periodService.validatePeriodicity(period);
    if(isValidPeriod &&  isMandatory(period)){
        finalQueries.add(query);
    }

});

But is there any way to do it using following way ?
List<Query> updatedQueries = getUpdatedQueries();

List<Query> finalQueries = updatedQueries
        .stream()
        .map(this::getPeriodRequest) //returns the object of type Period
        .filter(period->periodService.validatePeriodicity(period))
        .filter(this::isMandatory)
        //is any way we can map back to Query object (without any object translation  function)
        .collect(Collectors.toList());

A: Try this one
List<Query> finalQueries = updatedQueries
    .stream().filter(query->{
        Period period = getPeriodRequest(query);
        return periodService.validatePeriodicity(period )&& isMandatory(period))
    })
    .collect(Collectors.toList());

A: You can expand the filter as:
    List<Query> finalQueries = updatedQueries
            .stream()
            .filter(query -> {
                Period period = getPeriodRequest(query);
                return periodService.validatePeriodicity(period) && isMandatory(period);
            })
            .collect(Collectors.toList());

A: First of all your actual result is of type List<Period> finalQueries because of that map(this::getPeriodRequest). Simply use some "longer" lambdas:
 updatedQueries.stream()
               .filter(q -> periodService.validatePeriodicity(q.getPeriodRequest()))
               .filter(q -> isMandatory(q.getPeriodRequest()))
               .collect(Collectors.toList())

You can even compress those two filters into a single one and read q.getPeriodRequest() only once if you really wanted to.
Or you could map to a SimpleEntry for example:
 updatedQueries.stream()
               .map(x -> new SimpleEntry<>(x, x.getPeriodRequest()))
               .filter(e -> periodService.validatePeriodicity(e.getValue()))
               .filter(e -> isMandatory(e.getValue()))
               .map(Entry::getKey)
               .collect(Collectors.toList());

A: No. You have to store original object somehow.
Like this
class Pair<A, B> {
    A a;
    B b;
    // constructors and getters skipped
}

Then you can do following:
list.stream()
   .map(x -> new Pair<>(x, getOtherObject()))
   .filter(x -> checkOther(x.getB()))
   .map(Pair::getA)
   .collect(Collectors.toList());

A: Why use Streams in the first place?
updatedQueries.removeIf(query-> {
    Period period = getPeriodRequest(query);
    return !periodService.validatePeriodicity(period) || !isMandatory(period));
});

This removes all elements from updatedQueries which don't match the filter. Behaves the same, but doesn't introduce a new List.
The best approach would probably using just a simple for-loop if you care about performance:
for (Iterator<Query> it = updatedQueries.iterator(); it.hasNext(); ) {
    Period period = getPeriodRequest(it.next());
    if(!periodService.validatePeriodicity(period) || !isMandatory(period))) {
        it.remove();
    }
}


text:
Q: how to view a particular user data from database? when user register the data,The data has been inserted into the database but a single user is going to login in the form while login the enter data in the database has been viewed in the user details page.but i need only a particular data of the user. and check my code in case of error so please mention me.
Below Attached database screenshot
in this screen shot two user saved information from the database (ID 1 And ID 10003). if ID=1 user login the details of the particular user need to be viewed but in this case if any one of the user login the whole database users details has been displayed. how to rectify the problem.
DataBase
Error page

Doctor Social Network

                        <asp:HiddenField ID="hdnsocial" runat="server" />

                        <asp:Repeater ID="rptsocial" runat="server">
                               <HeaderTemplate>

                                    Facebook
                                    Twitter
                                    linkedin
                                    Pinterest
                                     GooglePlusID

                                      </HeaderTemplate>
                                    <ItemTemplate>

                                        <asp:Label ID="lblFaceBookID" runat="server" Text='<%# Eval("FaceBookID") %>' />

                                                <a id='<%#Eval("DoctorSocialID")%>' href="javascript:;" class="delete-me" data-toggle="modal" data-target="#Socialdelete<%#Eval("DoctorSocialID")%>">
                                                <a id='<%#Eval("DoctorSocialID")%>' data-toggle="modal" data-target="#Socialedit<%#Eval("DoctorSocialID")%>" href="javascript:;" class="edit-me EditSocial">

                                            <asp:Label ID="lbiTwitterID" runat="server" Text='<%# Eval("TwitterID") %>' />
                                            <asp:Label ID="lbllinkedinID" runat="server" Text='<%# Eval("linkedinID") %>' />
                                             <asp:Label ID="lblPinterestID" runat="server" Text='<%# Eval("PinterestID") %>' />
                                           <asp:Label ID="lblGooglePlusID" runat="server" Text='<%# Eval("GooglePlusID") %>' />

                                                <div class="modal fade bs-example-modal-lg" id='Socialedit<%#Eval("DoctorSocialID")%>' tabindex="-1"
                                                role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="background-color:black;">

                                                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                                        ×</button>

                                                       Edit Social Network

                                                                    FaceBook*

                                                               <asp:TextBox ID="txtFaceBookID" runat="server" onchange="javascript:EditSocialvalue(this);" Text='<%#Eval("FaceBookID")%>' required  class="form-control"></asp:TextBox>

                                                                    Twitter*

                                                                <asp:TextBox ID="txtTwitterID" runat="server" Class="form-control" onchange="javascript:EditSocialvalue1(this);" required Text='<%#Eval("TwitterID")%>' ></asp:TextBox>

                                                                    linkedin*

                                                                <asp:TextBox ID="txtlinkedinID" runat="server" Class="form-control" Text='<%#Eval("linkedinID")%>' onchange="javascript:EditSocialvalue2(this);" ></asp:TextBox>

                                                                    Pinterest*

                                                                <asp:TextBox ID="txtPinterestID" runat="server" Class="form-control" Text='<%#Eval("PinterestID")%>' onchange="javascript:EditSocialvalue3(this);"></asp:TextBox>

                                                                    GooglePlus*

                                                                 <asp:TextBox ID="txtGooglePlusID" runat="server" Class="form-control" Text='<%#Eval("GooglePlusID")%>' onchange="javascript:EditSocialvalue4(this);"></asp:TextBox>

                                                    <input type="button" class="btn btn-success" id="btnEditSocial"
                                                        value="Update" name="<%#Eval("DoctorSocialID")%>" />
                                                    <button class="btn btn-danger" data-dismiss="modal" aria-hidden="true">
                                                        Cancel</button>

                                <div class="modal fade bs-example-modal-lg" id='Socialdelete<%#Eval("DoctorSocialID")%>' role="dialog">

                                                <button type="button" class="close" data-dismiss="modal">×</button>

Delete Confirmation

Are you sure you want to delete this record?

                                            <button class="btn button" data-dismiss="modal" aria-hidden="true">
                                                Cancel</button>
                                                 <input type="button" class="btn btn-danger" id="btnDeleteSocial"
                                                        value="Delete" name="<%#Eval("DoctorSocialID")%>" />

                                   </ItemTemplate>
                                <FooterTemplate>

                                </FooterTemplate>
                               </asp:Repeater>

                                <button type="button" id="AddSocialNetwork">

                                    Add Social Network
                                </button>

Add Social Network

                    Facebook
                    Twitter
                    linkedin
                    Pinterest
                      GooglePlusID

                                    <asp:TextBox ID="txtFaceBookID" runat="server" Class="form-control" placeholder="FaceBook ID"></asp:TextBox>

                                    <asp:TextBox ID="txtTwitterID" runat="server" Class="form-control" placeholder="Twitter ID"></asp:TextBox>

                                    <asp:TextBox ID="txtlinkedinID" runat="server" Class="form-control" placeholder="linkedinID"></asp:TextBox>

                                    <asp:TextBox ID="txtPinterestID" runat="server" Class="form-control" placeholder="Pinterest"></asp:TextBox>

                                    <asp:TextBox ID="txtGooglePlusID" runat="server" Class="form-control" placeholder="GooglePlus"></asp:TextBox>

                                 <input type="button" id="btnSocial" class="btn btn-success" value="Save Social" />

Save database function code:
function SaveDocSocial(response) {
            if (response == null) {
                callAjax({
                    url: pageUrl + '/SaveDocSocial',
                    data: '{"Doctorid": "' + $("#<%=hdnDoctorId.ClientID %>").val() + '","DoctorSocialID" : "' + $("#<%=hdnsocial.ClientID %>").val() + '","FaceBookID" : "' + $("#<%=txtFaceBookID.ClientID %>").val() + '","TwitterID" : "' + $("#<%=txtTwitterID.ClientID %>").val() + '","linkedinID" : "' + $("#<%=txtlinkedinID.ClientID %>").val() + '","PinterestID" : "' + $("#<%=txtPinterestID.ClientID %>").val() + '","GooglePlusID" : "' + $("#<%=txtGooglePlusID.ClientID %>").val() + '"}',
                    action: "SaveDocSocial"
                });
                window.location.reload();
            }
            else {
                loading(false);
                if (response.AjxContactId != null) {
                    $('#<%=hdnsocial.ClientID%>').val(response.AjxContactId);
                }
                msg(true, response.Message);
            }
        }

And Page load
this.BindSocial();
if (iDoctorID > 0)

            {hdnsocial.Value = iDoctorID.ToString();
}

Save Code
[WebMethod]
    public static UserAjax SaveDocSocial(string Doctorid, string DoctorSocialID, string FaceBookID, string TwitterID, string linkedinID, string PinterestID, string GooglePlusID)
    {
        UserAjax oUserAjax = new UserAjax();
        string CDoctorID = string.Empty;
        string DSocialID = string.Empty;
        int iDoctorID = 0;
        int iDoctorSocialID = 0;
        CDoctorID = Doctorid == null ? "" : Doctorid;
        if (Validation.IsShort(CDoctorID))
            iDoctorID = Convert.ToInt32(CDoctorID);
        DSocialID = DoctorSocialID == null ? "" : DoctorSocialID;
        if (Validation.IsShort(DSocialID))
            iDoctorSocialID = Convert.ToInt32(DSocialID);
        string sMessage = string.Empty;
        string sBuild = string.Empty;
        if (sMessage != "")
        {
            oUserAjax.Message = sMessage;
        }
        else
        {
            BD_Doctor iDoctor = new BD_Doctor();
            iDoctor.DoctorID = iDoctorID;
            iDoctor.DoctorSocialID = iDoctorSocialID;
            iDoctor.FaceBookID = FaceBookID;
            iDoctor.TwitterID = TwitterID;
            iDoctor.linkedinID = linkedinID;
            iDoctor.PinterestID = PinterestID;
            iDoctor.GooglePlusID = GooglePlusID;
            iDoctor.SaveSocial();
            //iDoctor.IsDefault = true;
            if (iDoctorID > 0)
            {
                sMessage = "Clinic Information successfully saved!";
                oUserAjax.AjxContactId = iDoctorID.ToString();
                oUserAjax.Message = sMessage;
            }
            else
            {
                sMessage = "Your submission failed!";
                oUserAjax.Message = sMessage;
            }
        }

        return oUserAjax;
    }

View Repeater Code :
private void BindSocial()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Doctorsocialnetwork", con))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    rptsocial.DataSource = dt;
                    rptsocial.DataBind();
                }
            }
        }
    }

A: Yes i done this solution
this.BindSocial(hdnsocial.Value);

Used where condition
#region Bind Social

    private void BindSocial(string hdnsocial)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        BD_Doctor iDoctor = new BD_Doctor();
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Doctorsocialnetwork where DoctorID = '" + hdnsocial + "'", con))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    rptsocial.DataSource = dt;
                    rptsocial.DataBind();
                }
            }
        }
    }

    #endregion


text:
Q: Item analysis with small sample size I gave a 12 item true-false quiz (which I created) to my 19 students.
I noticed that some questions were very obviously easier than others, so I decided to run an item analysis. By looking at the item difficulty results, it does seem like that's the case. I am thinking of re-administering the quiz and excluding items with item difficulty below 0.5.
But with such a small sample size, should I even bother with item analysis?

A: With this sample size (and number of items/questions), any statistical analysis would be questionable. However, from a purely descriptive perspective, the item analysis might suggest which are the easiest and the hardest. It probably would not let you do any more refined ranking of the item-difficulty.


text:
Q: How to input a password in Travis CI while deploy to DigitalOcean via ssh I am setting up CI from my github repo to Digital Ocean droplet.
Following instructions from internet i created SSH key, encrypt it and config my .travis.yml file
But during Job Travis requires password to deploy code to droplet.
Link to one of my builds:
https://travis-ci.com/KletskovG/kletksovg.tech/builds/132806624
I try to install expect package in bash and write to my deploy.sh script like this:
expect "password"
send "My_droplet_user_password"
My .travis.yml config

language: node_js

node_js:
  - 10

notifications:
  email: false

addons:
  ssh_known_hosts:
    - kletskovg.tech

before_install:
  - openssl aes-256-cbc -K $encrypted_89e65714f577_key -iv $encrypted_89e65714f577_iv -in travis_rsa.enc -out travis_rsa -d
  - chmod 600 travis_rsa
  - mv travis_rsa ~/.ssh/id_rsa
  - sudo apt-get install -y expect

install:
- cd client
- npm i webpack-cli -g
- npm i

before_script:
  - echo -e "Host kletskovg.tech\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config
  - echo -e "Host github.com\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config

script:
  - npm test

deploy:
  provider: script
  skip_cleanup: true
  user: travis
  password:  TravisDeploy02
  script: cd ../ && chmod +x ./deploy.sh && ./deploy.sh
  on:
    all_branches: true
#
#after_success:
#  - bash ./deploy.sh

Code while deploying:
Deploying application
+echo '#### DEPLOY ####'
#### DEPLOY ####
+'[' master == master ']'
++ssh-agent -s
+eval 'SSH_AUTH_SOCK=/tmp/ssh-zAgy7iJpDFB6/agent.7731; export SSH_AUTH_SOCK;
SSH_AGENT_PID=7732; export SSH_AGENT_PID;
echo Agent pid 7732;'
++SSH_AUTH_SOCK=/tmp/ssh-zAgy7iJpDFB6/agent.7731
++export SSH_AUTH_SOCK
++SSH_AGENT_PID=7732
++export SSH_AGENT_PID
++echo Agent pid 7732
Agent pid 7732
+ssh-add /home/travis/.ssh/id_rsa
Identity added: /home/travis/.ssh/id_rsa (gfgfddglebtravis@gmail.com)
+echo TRYING TO DEPLOY
TRYING TO DEPLOY
+git init
Reinitialized existing Git repository in /home/travis/build/KletskovG/kletksovg.tech/.git/
+git remote add deploy travis@kletskovg.tech:/var/www/kletskovg.tech
+git config user.name 'Travis CI'
+git config user.email gfgfddgleb@gmail.com
+git add .
+git commit -m Deploy
[detached HEAD 4561161] Deploy
 2 files changed, 42 insertions(+)
 mode change 100644 => 100755 deploy.sh
+git push --force deploy master
Warning: Permanently added the ECDSA host key for IP address '138.68.30.170' to the list of known hosts.
travis@kletskovg.tech's password:

How can i  fix this?
Thank you.

A: I just create everything from scratch in a new repo.
Now its working.


text:
Q: validating user input using flask_wtf and sqlalchemy Noob question. I am building a login/registration pages, on the registration page, I am using flask_wtf to verify certain things like length of password, email format and whether the two password a user supplies match. Here is the flask_wtf code I am using to do that.
# import statements omitted for brevity
class RegistrationForm(FlaskForm):
    username = StringField('Username',
                           validators=[DataRequired(), Length(min=2, max=20)])
    email = StringField('Email',validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password = PasswordField('Confirm Password',
             validators=[DataRequired(),Length(min=4, max=20), EqualTo('password')])
    submit = SubmitField('Sign Up')

After checking the input, I am using sqlalchemy to check if the username and email already exists in my DB. The problem I am facing right now is I cant get flask_wtf to verify the form. I can type whatever I want and it will be converted to a sql query. Here are my two flask routes that handle registration and user input validation.
@app.route('/register',methods=['GET','POST'])
def register():

     form = RegistrationForm()

     if form.validate_on_submit():

         return redirect(url_for('check_user_input'))

     return render_template('register.html',form=form)

@app.route('/status',methods=['POST'])
def check_user_input():

    name = request.form.get("username")

    email = request.form.get("email")

    password = request.form.get("password")

    if db.execute("SELECT * FROM DB WHERE username= :username",{"username":name}).rowcount==1:

        return render_template("404.html", message="Sorry username already exists")

    elif db.execute("SELECT * FROM DB WHERE email= :email",
         {"email":email}).rowcount==1:

         return render_template("404.html", message="Sorry email already exists")

    else:
        db.execute("INSERT INTO DB (username,email,password) VALUES
        (:username,:email,:password)",

        {"username":name, "email":email,"password":password})

        db.commit()

        return render_template("success.html")

How can I get flask_wtf form to do its verification first and then hand the input to check_user_input() function?
My register.html contains the following line.
<form class="form-signin" method="POST" action="{{url_for('check_user_input')}}">

Any help would be greatly appreciated.

A: A way is to add a custom validation to the form :
class RegistrationForm(FlaskForm):
    username = StringField('Username',
                           validators=[DataRequired(), Length(min=2, max=20)])
    email = StringField('Email',validators=[DataRequired(), Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password = PasswordField('Confirm Password',
             validators=[DataRequired(),Length(min=4, max=20), EqualTo('password')])
    submit = SubmitField('Sign Up')

    def validate(self):
        rv = FlaskForm.validate(self)
        if not rv:
            return False

        if db.execute("SELECT * FROM DB WHERE username= :username",{"username":self.username.data}).rowcount>0:
            self.username.errors.append('Sorry username already exists')
            return False
        if db.execute("SELECT * FROM DB WHERE email= :email", {"email":self.email.data}).rowcount>0:
            self.email.errors.append('Sorry email already exists')
            return False
        return True


text:
Q: How can I manage count of swiped cards? I'm implementing Swipe stack demo from here. Now I want track progress of swiped cards. I already made my own logic, and it's working pretty fine. but I've one more functionality, which is while clicking on previous button, user can see one by one all swiped cards in reverse order.
But my swiped card progress stack is not working in that case. How can I do this?
Explain: not total swiped cards count, but which one card is currently I'm seeing like 4 Out of 10
DisplayCardActivity:
package com.jimmytrivedi.cardswipedemo.Activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jimmytrivedi.cardswipedemo.Adapter.SwipeStackAdapter;
import com.jimmytrivedi.cardswipedemo.Data.FetchDataFromUriAsyncTask;
import com.jimmytrivedi.cardswipedemo.Listener.JSONDataListener;
import com.jimmytrivedi.cardswipedemo.R;
import com.jimmytrivedi.cardswipedemo.View.SwipeStack;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

public class DisplayCardActivity extends BaseActivity implements SwipeStack.SwipeStackListener, View.OnClickListener, JSONDataListener {
    public static final String TAG = DisplayCardActivity.class.getSimpleName();

    @BindView(R.id.previous)
    ImageButton mPrevious;
    @BindView(R.id.next)
    ImageButton mNext;
    @BindView(R.id.swipe_stack)
    SwipeStack mSwipeStack;
    @BindView(R.id.fab)
    FloatingActionButton mFAB;
    @BindView(R.id.card_progress)
    TextView cardProgress;

    private FetchDataFromUriAsyncTask dataFromUriAsyncTask;
    private ProgressDialog progressDialog;
    private ArrayList<String> mData;
    private ArrayList<String> mTempData;
    private int mCurrentCardPosition = 1, lastSwipedPosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_display_card;
    }

    private void init() {
        ButterKnife.bind(this);
        setClickListener();
        mTempData = new ArrayList<>();
        mPrevious.setEnabled(false);
        mPrevious.setColorFilter(getResources().getColor(R.color.colorGray));
        dataFromUriAsyncTask = new FetchDataFromUriAsyncTask(this, this);
        dataFromUriAsyncTask.setJSONDataListener(this);
        progressDialog = new ProgressDialog(this);
        loadDataFromUrl();
    }

    private void setClickListener() {
        mPrevious.setOnClickListener(this);
        mNext.setOnClickListener(this);
        mFAB.setOnClickListener(this);
    }

    private void loadDataFromUrl() {
        //Showing progress dialog
        progressDialog.setMessage("Fetching Data from...");
        progressDialog.setCancelable(false);
        progressDialog.show();
        dataFromUriAsyncTask.execute();
    }

    private void changePreviousButtonStatus(int positionValue) {
        if (lastSwipedPosition == positionValue) {
            mPrevious.setEnabled(false);
            mPrevious.setColorFilter(getResources().getColor(R.color.colorGray));
        } else {
            mPrevious.setEnabled(true);
            mPrevious.setColorFilter(getResources().getColor(R.color.colorBlack));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.previous:
                changePreviousButtonStatus(1);
                lastSwipedPosition = lastSwipedPosition - 1;
                if (lastSwipedPosition >= 0) {
                    mTempData.clear();
                    for (int i = lastSwipedPosition; i < mData.size(); i++) {
                        mTempData.add(mData.get(i));
                    }
                    mSwipeStack.resetStack();
                    setCurrentCardPosition(lastSwipedPosition);
                } else {
                    lastSwipedPosition = 0;
                }

                break;

            case R.id.next:
                changePreviousButtonStatus(1);
                mSwipeStack.swipeTopViewToRight();
                break;

            case R.id.fab:
                mPrevious.setEnabled(false);
                mPrevious.setColorFilter(getResources().getColor(R.color.colorGray));
                lastSwipedPosition = 0;
                mTempData.clear();
                mTempData.addAll(mData);
                mSwipeStack.resetStack();
                if (mData != null)
                    cardProgress.setText(getResources().getString(R.string.default_count) + mData.size());
                break;
        }
    }

    @Override
    public void onViewSwipedToLeft(int position) {
        mCurrentCardPosition = position + 2;
        setCurrentCardPosition(mCurrentCardPosition);
        lastSwipedPosition = position + 1;
        changePreviousButtonStatus(0);
    }

    @Override
    public void onViewSwipedToRight(int position) {
        mCurrentCardPosition = position + 2;
        setCurrentCardPosition(mCurrentCardPosition);
        lastSwipedPosition = position + 1;
        changePreviousButtonStatus(0);
    }

    @Override
    public void onStackEmpty() {
        cardProgress.setText("No card in stack");
    }

    @Override
    public void onClickData(ArrayList<String> getData) {
        // Dismiss the progress dialog
        if (progressDialog.isShowing())
            progressDialog.dismiss();

        mData = new ArrayList<>(getData);
        mTempData.addAll(mData);
        setCurrentCardPosition(mCurrentCardPosition);
        SwipeStackAdapter mAdapter = new SwipeStackAdapter(mTempData);

        mSwipeStack.setAdapter(mAdapter);
        mSwipeStack.setListener(this);
    }

    @Override
    public void onJSONParsingError(String error) {
        if (progressDialog.isShowing())
            progressDialog.dismiss();

        showToast(getString(R.string.user_error), Toast.LENGTH_LONG);
    }

    private void showToast(String message, int length) {
        Toast.makeText(this, message, length).show();
    }

    private void showLog(String msg) {
        Log.d(TAG, msg);
    }

    private void setCurrentCardPosition(int currentPosition) {
        cardProgress.setText(currentPosition + " Out of " + mData.size());
    }

}

Adapter:
package com.jimmytrivedi.cardswipedemo.Adapter;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.jimmytrivedi.cardswipedemo.R;

import java.util.List;

public class SwipeStackAdapter extends BaseAdapter {

    public static final String TAG = SwipeStackAdapter.class.getSimpleName();

    private List<String> mData;

    public SwipeStackAdapter(List<String> data) {
        this.mData = data;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public String getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card, parent, false);
        TextView textViewCard = convertView.findViewById(R.id.textViewCard);
        textViewCard.setText(mData.get(position));

        return convertView;
    }

    private void showLog(String msg) {
        Log.d(TAG, msg);
    }
}

Problem:
Use case: I've 10 cards (001, 002..010). And there are total 5 things.
1. Left swipe
2. Right seipe
3. Previous button
4. Next button
5. Reset button
If I start right swiping 001 then 002 now I pressed next button for 003 and 004. Now I pressed previous button then again next and again previous,. That time order is not mainting.

A: Hold a global variable and increment it on SwipeLeft and SwipeRight callback
private int totalCardsSwiped = 0;

@Override
public void onViewSwipedToLeft(int position) {
totalCardsSwiped++; }

@Override
public void onViewSwipedToRight(int position) {
totalCardsSwiped++; }

A: Why are you doing this in swiped callback methods?
mCurrentCardPosition = position + 2;
I think here is the problem.
or you can call this  setCurrentCardPosition() method with the current position
@Override
public void onViewSwipedToLeft(int position) {
    mCurrentCardPosition = position + 2;
    setCurrentCardPosition(position);
    lastSwipedPosition = position + 1;
    changePreviousButtonStatus(0);
}

@Override
public void onViewSwipedToRight(int position) {
    mCurrentCardPosition = position + 2;
    setCurrentCardPosition(position);
    lastSwipedPosition = position + 1;
    changePreviousButtonStatus(0);
}

Edited

int currentPosition = 1;
After Adding Data in list
txtCardProgress.setText("1 out of " + mData.size());

in onClick
@Override
public void onClick(View v) {
    if (v.equals(mButtonLeft)) {
        swipedLastPosition = swipedLastPosition - 1;
        currentPosition =currentPosition -1;
        if (swipedLastPosition >= 0) {
            mTempData.clear();//clear all data
            for (int i = swipedLastPosition; i < mData.size(); i++) {
                mTempData.add(mData.get(i));
            }
            mSwipeStack.resetStack();
            if (swipedLastPosition == 0) {
                Toast.makeText(this, "hide back button", Toast.LENGTH_SHORT).show();
            }
            currentPosition =currentPosition -1;
            setCardProgress(currentPosition);
        } else {
            swipedLastPosition = 0;
            currentPosition = 0;
            setCardProgress(currentPosition);
        }

    } else if (v.equals(mButtonRight)) {
        mSwipeStack.swipeTopViewToRight();
    } else if (v.equals(mFab)) {
        swipedLastPosition = 0;
        mTempData.clear();
        mTempData.addAll(mData);
        mSwipeStack.resetStack();
        setCardProgress(swipedLastPosition);
    }

Callback Methods
@Override
public void onViewSwipedToRight(int position) {
    swipedLastPosition = position + 1;
    setCardProgress(position);
}

@Override
public void onViewSwipedToLeft(int position) {
    swipedLastPosition = position;
    setCardProgress(position);
}

Update Progress method
void setCardProgress(int position) {
    if (position == mData.size()-1) {
        currentPosition = mData.size();
        txtCardProgress.setText(currentPosition + " out of " + mData.size());
    } else {
        currentPosition++;
        txtCardProgress.setText(currentPosition + " out of " + mData.size());
    }
}


text:
Q: Опримизация чтения/записи на диск Программа должна делать следующее:

*

*считать следующий блок из входного потока данных

*обработать его

*записать в выходной поток

В плане взаимодействия с файловой системой, действия программы похожи на работу архиватора.
Как реализовать такой функционал, чтобы алгоритм работал на скорости чтения-записи на диск? Пока на ум приходит кольцевой буфер и два потока - producer/consumer. Но ведь в современных архиваторах уже как-то решена эта проблема, и, возможно, существуют какие-то более эффективные архитектурные решения?
A: Интересный вопрос. Предположим, что речь идет о 2-х файлах на диске (в файловой системе).
Если размер (и структура) выходного файла определяются при открытии входного, то я наверное попробовал бы сделать так.
Открываем входной файл и делаем mmap() на него с madvise() MADV_SEQUENTIAL. Также поступаем с выходным (здесь мы должны знать его размер). Запускаем N потоков (по числу потоков поддерживаемых аппаратурой). Каждый из них читает, обрабатывает и пишет свою последовательность блоков (через N блоков, т.е. для N=4 обрабатывает блоки 0,4,8,12 ...).
Если с выходным файлом такая штука не проходит (mmap для него делать не будем), то можно организовать список блоков результатов, который обрабатывается потоком записи. Здесь важно, чтобы этот поток делал "реально большие" (допустим 1MB) блоки для записи.
Не буду фантазировать дальше без деталей алгоритма обработки.

UPD @dm_panyushkin, у меня лимит комментариев закончился, поэтому на Ваш вопрос в комментарии отвечаю здесь
а какие "подводные камни" бывают при записи в файл с помощью mmap()?

Основной "подводный камень" это необходимость знать максимальный размер результата (файла, куда будете писать) при вызове mmap(). Перед mmap для файла в который Вы будете писать надо задать размер файла (после open), например вызывая ftruncate(), а потом вызвать mmap с этим размером. Естественно после занесения всех данных размер файла можно скорректировать (тем же ftruncate).
IMHO MADV_SEQUENTIAL для записи не слишком критично, т.к. запись на диск происходит не сразу (если не создавать файл с флагами O_SYNC, O_DIRECT, вызывать fsync() и т.п.), система все равно будет пытаться оптимизировать доступ к диску с учетом IO операций всех процессов.
Кстати, при mmap для чтения-модификации тоже есть "камешек". Если файл нулевой длины, то работать не будет. Как ни странно, mmap() проходит нормально, а вот потом при обращении к данным - SIGBUS. Так что нулевую длину надо отслеживать о программировать отдельно.


text:
Q: Arithmetic/Logical operations with long long data type  Given long long int x, y;, I want a function that can compare x & y and returns T/F Flag, which is a normal int 32-bit. I tried this, but it confused me
#include <stdio.h>
int main() {
 long long n,i;

 scanf("%l64d", &n);
 i=42;

 printf("%l64d", n);
 printf("%l64d", i);
 printf("\ni<=n --> %d\n",i<=n);
 return;

}

A: Maybe what you are seeking is exemplified by this (which returns true/1 or false/0 depending on whether x is greater than (gt) y):
int ll_compare_gt(long long x, long long y)
{
    return(x > y);
}

Repeat for the other comparisons...
Arithmetic is more problematic - often, the result of adding two long long values is too big to fit into a 32-bit int.
However, your question is very sketchy on details and this might be quite wide of the mark.  You should explain what you really want much more clearly.


text:
Q: Why is my notification getting cleared? I have tried .setAutoCancel(false) and .setOngoing(true); but why does my notification still get cleared when I swipe it? here is my code-
        Notification.Builder builder = new Notification.Builder(this)
            .setSmallIcon(R.drawable.download)
            .setContentTitle("Download[ROOT]")
            // .setContentText("This is a test notification")
            .setAutoCancel(false).setOngoing(true);
    Intent notificationIntent = new Intent(this, DownloaderRoot.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    // Add as notification
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(111, builder.build());

I have tried adding flags as well-
// Add as notification
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notif = builder.build();// add flag support
        notif.flags |= Notification.FLAG_ONGOING_EVENT;
        notif.flags |= Notification.FLAG_NO_CLEAR;
        manager.notify(111, builder.build());

A: Try this
Notification notif = builder.build();
notif.flags |= Notification.FLAG_ONGOING_EVENT;
manager.notify(111, notif);


text:
Q: How do I get the most accurate GPS coordinates of my device using JavaScript? I want to get the most accurate GPS coordinates of my device using JavaScript. I have tried searching around but I can't find a solution that is accurate enough. I have tried using the HTML5 Geolocation API but it gives me the wrong values. The values are about 10KM off.
I think it is returning the coordinates of my wifi provider server or something. What I want it to do is to return the coordinates of my device instead. I think this can only be accurately achieved using the device's GPS.
I haven't found a way to make the geolocation API to explicitly use GPS in its positioning. I have read that, it prioritizes the GPS method on mobile but I haven't tried it. Anyway, I want a way to always use the GPS method for positioning even on my laptop and tablet. The app I am working on depends on high location accuracy.
If there is no way to make the Geolocation API to explicitly use the GPS method to return my device's coordinates, Are there other accurate methods I can use? Please help!
NOTE: I have already tried providing the { enablesHighAccuracy: true } option.

A:
I have tried using the HTML5 Geolocation API but it gives me the wrong values. The values are about 10KM off.

The Geolocation API will give you the highest accuracy available provided by the device.  Without seeing your code, it isn't possible to tell you what the problem is.  All I can suggest is ensure that you're using watchPosition(), to give the underlying GPS time to get a fix.  (And of course, enableHighAccuracy as you say you are already doing.)

I haven't found a way to make the geolocation API to explicitly use GPS in its positioning.

It's not possible.

Anyway, I want a way to always use the GPS method for positioning even on my laptop and tablet.

I don't know of any desktop browsers that utilize a GPS for location.

If there is no way to make the Geolocation API to explicitly use the GPS method to return my device's coordinates, Are there other accurate methods I can use?

I suppose you could always write a browser extension to execute some native code and get you the raw data.  The upcoming Serial Port API may also be of interest to you.


text:
Q: GCC Shared Library Problems I'm trying to create a shared library on ubuntu using gcc
I just have one simple class(shared.h and shared.cpp) and one client to use it (main.cpp)
This is my makefile and I'm still not able to to get the program to compile.
all:
    #compile object(fPIC: creates position independent code)
    gcc -fPIC -Wall -g -c shared.cpp

    #compile shared library
    gcc -shared -Wl,-soname,libshared.so.1 -o libshared.so.1.0.1 shared.o -lc

    #link shared library
    gcc -g -o main main.cpp -L. -lshared

*

*I'm confident the first line is correct

*I am unsure what "-lc" does.  I think it passes something to the linker?

*I don't want to install the library, I just want to be able to link it from the current directory.  I have tried: export LD_LIBRARY_PATH=.
but it does not seem to make a difference. Everything is in the current directory.

ERROR: /usr/bin/ld: cannot find -lshared

how do I get the compiler to check the current directory for my library?

A: The problem is not that it's not looking in the directory, the problem is that you've named the library "libshared.so.1.0.1".  When you use -lshared, it's looking for a file named 'libshared.so' or 'libshared.a' in the library search path.
Most of the time, when using versioned system libraries, you'll provide a link to the latest one as 'libshared.so', even if you have installed 'libshared.so.1' or 'libshared.so.1.0.1'.
In your case, if you continue to leave the file named 'libshared.so.1.0.1', you'll want to create 2 symbolic links:

*

*libshared.so - So that the library can be found using ld

*libshared.so.1 - Since you declared the SO name as libshared.so.1 when building it, you need to provide this link, otherwise, the executable will not be able to find the proper shared library at runtime.

A: You don't write any dependencies, which is the purpose of Makefile-s. And you probably need to force the run path Perhaps something like
 .PHONY: all clean
 CXX=g++
 CXXFLAGS=-g -Wall
 all: main
 main: main.o libshared.so
        $(LINK.cpp) -o $@ $< -Wl,-rpath,. -L. -lshared
 libshared.so: shared.pic.o
        $(LINK.cpp) -shared -o $^ $<
 main.o: main.cc shared.hh
 %.pic.o: %.cc
        $(CXX) $(CXXFLAGS) -fPIC -c -o $@ $<
 #
 clean:
        rm -f *.o *.so main *~


text:
Q: How to use a multi value converter for a field in xamdatagrid? I want to convert a list to comma separated string. For that purpose I am using multivalue converter.
But I dont know how to bind it to a field in xamdatagrid.
Thanks.

A: Could this work for you?
      <igDP:Field Name="Property"">
                    <igDP:Field.Settings>
                        <igDP:FieldSettings>
                            <igDP:FieldSetting.CellValuePresenter>
                                <Style TargetType="{x:Type igDP:CellValuePresenter}">
                                    <Setter Property="Content">
                                        <Setter.Value>
                                            <MultiBinding Converter="{StaticResource myConverter}">
                                                <Binding Path="DataItem.Property1" />
                                                <Binding Path="DataItem.Property2" />
                                            </MultiBinding>
                                        </Setter.Value>
                                    </Setter>
                                </Style>
                            </igDP:FieldSetting.CellValuePresenter>
                        </igDP:FieldSettings>
                    </igDP:Field.Settings>
                </igDP:Field>

I'm not so sure property "Content" works, but I can't test it right now, If it is not you can just define a template inside you CellValuePresenter and bind the converter to a textbox or any other control you want to use
Hope this helps


text:
Q: How can I show never ending dots ("...") in a while loop Is it possible to show something like this in Python?

Checking.
Checking..
Checking...
Checking.

I want it to just show one line of this while the script is running, but stop when it's done. The script I want to add it to is here: https://github.com/brandonusher/Python-Scripts/blob/master/check_port.py

A: Output the text with no newline character, then flush stdout. Output a \r to make the cursor go back to the beginning of the line. Repeat until done. Don't forget to overwrite existing text.
while True:
  sys.stdout.write('\rfoo.  ')
  sys.stdout.flush()
  delay(100)
  sys.stdout.write('\rfoo.. ')
  sys.stdout.flush()
  delay(100)
  sys.stdout.write('\rfoo...')
  sys.stdout.flush()
  delay(100)


text:
Q: Jaccard Similarity with Binary Data I have 5400 rows of data and 3211 columns of attributes.
The first 4 columns are ID/Name/ParentID/ObjectType - the rest of the 3207 columns are the attributes that are to be used for similarity measures.
Huge dimensionality, I know, but I wanted to (as a first step) just see how this data clusters and finds similarity between all attributes.
I converted all attributes values to "0" if there was no value, and "1" if there was a value. I thought it'd be an easy first step to get me started with a clustering visual and similarity metric if I converted the values to binary.
Jaccard similarity seems to be a good measure for binary, but I'm stumped as to how to implement this (in Python) when I don't have any lists for comparison. Am I supposed to hard code each variable into the algorithm (3207 variables)?
I'm not sure where to start. Also, if there's a better way of doing this, I'm all ears. I've been researching how best to tackle this problem and there's so many similarity metrics that can be used, but I'm stuck on how to start since I there are so many columns that need to be used.
Added update:
This is for retail product data. Each product has a mixture of boolean/categorical/numerical/meta data, and can have up to 3200+ attributes; however, not all of the attributes have a value.
The question needing research is whether or not similar attributes can define the category to which the product should live.
Jaccard Similarity to find similarities between sets. I view the columns in my dataset as the separate sets because I'm wanting to see if two products in the dataset are similar due to the attributes having the same binary value, or not (i.e.: productA has attributes 1,2,3,6 = 1; productB has attributes 1,2,3,5 = 1 - this could mean there's a 75% chance these two products are similar and could be put into the same category).

A: Python is cool, but... Use R!
library(philentropy)
X <- matrix(rnorm(50), ncol = 5)
X[1, 2] <- NA
X[3, 5] <- NA
X[7, 5] <- NA
(X <- ifelse(is.na(X), 0, 1))
D <- distance(X, method = "jaccard")
(k_means <- kmeans(D, centers = 2, nstart = 100))


text:
Q: Fit html page width in WebBrowser control I have a lot of local html pages which I open in a WebBrowser control in my app.
I would like the page to initially open to fit the width of the control and ideally to change its width to fit the control after a user resize.
As there are a lot of pages, I would prefer a c#, js or css solution which doesn't require modifying the html files.
I searched high and low, tried tens of solutions (many of them here on SO) but nothing seems to work.
Win 7, IE 11, VS 2022
Thanks in advance

A: Since you're using Win7 and IE11, I have a hunch you're using WinForms.  The DOM can be accessed through the WebBrowser control's Document property where we can add the CSS.  Put this in your WebBrowser.DocumentCompleted event handler:
webBrowser1.Document.Body.Style += ";width:100%;";

The Style property is just like an HTML style= attribute, that is, a string of CSS styles separated by semicolons.  The appended string starts with a semicolon in case the existing styles don't end with one.
For WPF, first see Accessing DOM from WebBrowser.  Then you can put this in your WebBrowser.LoadCompleted event handler:
var document = webBrowser1.Document as mshtml.HTMLDocument;
document.body.style.width = '100%';


text:
Q: How handle multiple functions in puppeteer-cluster? I have a two step program :

*

*Get a list of href from a page

*Loop infinitely on each page of this list, get an element and display it in console

I try to use function with Puppeteer-Cluter but it doesn't work properly.
const { Cluster } = require('puppeteer-cluster');
const fs = require("fs");
const { addExtra } = require("puppeteer-extra");
const vanillaPuppeteer = require("puppeteer");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");

var moment = require('moment');
var regexTemps = /(\d+)\s(\w+)$/;
const urlsToCheck = [];

TZ = 'Europe/Paris'
process.env.TZ = 'Europe/Paris'

(async () => {
  const puppeteer = addExtra(vanillaPuppeteer);
  puppeteer.use(StealthPlugin());

  const cluster = await Cluster.launch({
    puppeteer,
    puppeteerOptions: {
        headless: false,
        args: ['--no-sandbox'],
    },
    maxConcurrency: 10,
    concurrency: Cluster.CONCURRENCY_CONTEXT,
    monitor: false,
    skipDuplicateUrls: true,
    timeout:30000,
    retryLimit:10,
  })

  cluster.on('taskerror', (err, data, willRetry) => {
      if (willRetry) {
        console.warn(`Encountered an error while crawling ${data}. ${err.message}\nThis job will be retried`);
      } else {
        console.error(`Failed to crawl ${data}: ${err.message}`);
      }
  });

  const getElementOnPage = async ({ page, data: url }) => {
    console.log('=> Go to URL : ',url);
    await page.goto(url);

    while (true) {
      console.log('=> Reload URL : ',page.url())
      await page.reload();
      await page.waitForTimeout(1000);
      let allNews = await page.$$("article.news"); // [] if nothing
      let firstNews = allNews[0];
      await page.waitForTimeout(1000);
      let info = await firstNews.$eval('.info span', s => s.textContent.trim());

      console.log(new Date(), 'info : ',info);
    }
  };

  const getListOfPagesToExplore = async ({ page, data: url }) => {

    console.log(new Date(), 'Get the list of deal pages to explore');
    await page.goto(url, {waitUntil: 'domcontentloaded'});
    await page.waitForTimeout(500);

    const hrefsToVisit = await page.$x('//a');

    let idxTab=0;
    for( let hrefToVisit of hrefsToVisit ) {
        var link = await page.evaluate(el => el.getAttribute("href"), hrefToVisit);
        console.log(new Date(), 'adding link to list : ', link);
        idxTab++;
        urlsToCheck.push(link);
    }
  };

  cluster.queue('https://www.apagewithsomelinks.com', getListOfPagesToExplore);
  await cluster.idle();
  await cluster.close();

  console.log(urlsToCheck);
  //Display correctly several link in an array

  for( let url of urlsToCheck ) {
      console.log('Push in queue : ',url);
      cluster.queue(url, getElementOnPage);
  }

  await cluster.idle();
  await cluster.close();

})();

When I launch it, it retrieve the links to scrap.
It display "Push in queue : ..." for each URL.
But then, the method getElementOnPage is launched only for the first URL, and runs infinitely like asked. But why the other URL are note launched ??
Before that, I don't use function, I used one unique task with :
await cluster.task(async ({ page, data: url }) => {
But how combine function and this thing ?


text:
Q: Logging into a page Jsoup I am trying to log in and fetch data from this page https://www.workplaceonline.com.au/c2/signin/ using jsoup
Here's what I have tried so far:
 Connection.Response loginForm = Jsoup.connect("https://workplaceonline.com.au/c2/signin/")
                .method(Connection.Method.GET)
                .execute();

    Document doc = Jsoup.connect("https://workplaceonline.com.au/c2/signin/")
            .data("cookieexists", "false")
            .data("account", "myAccount")
            .data("username", "myUsername")
            .data("password", "MyPassword")
            .data("task", "Sign+In")
            .cookies(loginForm.cookies())
            .userAgent("Mozilla/5.0")
            .post();

    System.out.println(doc);

When I run the code it prints the HTML for the login screen, indicating that it has failed to login properly
This is what is shown in the network panel when successfully logged in: http://imgur.com/aWSL4Zp


text:
Q: Taking input from user within a printed text I want to take input from the user in between the () in the given "cout" statement, in place of the '_'
cout<<"Warning! you are going to resize, which may result in loss of data are you sure you want to continue: Y/N(_)";

How may I be able to do it? Are there any escape sequence for doing it? Or any other way?

A: Use this code fragment:
scanf("(%s)",&str)


text:
Q: GSON : How to convert Object (which itself contains JSON) to JSON I have a different use case where fields in POJO itself stores JSON data, basically grouping of all data.
Now i want the complete JSON generated from above POJO.
At present i am using this method
private static Gson gson = new Gson();
public static String convertObjectToJSON(Object object) throws Exception {
    String jsonResponse = gson.toJson(object);
    return jsonResponse;
}

But getting output with escape characters around double quotes like below
 { \"_id\" : 234242, \"name\" : \"carlos\"}

I tried various options in GsonBuilder, but not working.
Basically, i am just grouping multiple JSON data and sending it across.
Could you please do the needful help to get rid of the escape characters around double quotes.
UPDATE:
Question is : I have 3 JSONs and need to combine them into a single JSON and need to pass it to html5 client through Spring MVC. As of now i am added the 3 JSONs into a POJO and trying to convert the same to JSON. Same is explained above.
Thanks & Regards
Venkat

A: I have tried below sample code and it doesn't have any escape characters around double quotes.
class MyPOJO{
    private int _id;
    private String name;
    // getter & setter
}

String json="{ \"_id\" : 234242, \"name\" : \"carlos\"}";
MyPOJOobj=new Gson().fromJson(json, MyPOJO.class);
System.out.println(new Gson().toJson(obj));

output:
{"_id":234242,"name":"carlos"}

EDIT
If you want to combine 3 JSON string then It will be stored as List of object as illustrated below:
sample code:
String json = "[" +
                    " { \"_id\" : 1, \"name\" : \"A\"}," +
                    " { \"_id\" : 2, \"name\" : \"B\"}," +
                    " { \"_id\" : 3, \"name\" : \"C\"}" +
                "]";
Type type = new TypeToken<ArrayList<MyPOJO>>() {}.getType();
ArrayList<MyPOJO> obj = new Gson().fromJson(json, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));

output:
[
  {
    "_id": 1,
    "name": "A"
  },
  {
    "_id": 2,
    "name": "B"
  },
  {
    "_id": 3,
    "name": "C"
  }
]


text:
Q: ДЕСТРУКТУРИЗАЦИЯ В ЦИКЛАХ (автопроверки)

Первый способ:
const colors = [
  { hex: "#f44336", rgb: "244,67,54" },
  { hex: "#2196f3", rgb: "33,150,243" },
  { hex: "#4caf50", rgb: "76,175,80" },
  { hex: "#ffeb3b", rgb: "255,235,59" },
];

const hexColors = [];
const rgbColors = [];

for (const {hex, rgb} of colors) {
  hexColors.push(color.hex);
  rgbColors.push(color.rgb);
}

Второй способ:
const colors = [
  { hex: "#f44336", rgb: "244,67,54" },
  { hex: "#2196f3", rgb: "33,150,243" },
  { hex: "#4caf50", rgb: "76,175,80" },
  { hex: "#ffeb3b", rgb: "255,235,59" },
];

const hexColors = [];
const rgbColors = [];

for (const color of colors) {
  const { hex, rgb } = color;
  hexColors.push(color.hex);
  rgbColors.push(color.rgb);
}

Пишет, что в цикле 'for...of' не используется деструктуризация объекта.
Не могу понять, что от меня хотят эти автопроверки. Вроде все правильно делаю, как в конспекте разными вариантами.

A: В первом способе задача выполняется
for (const {hex, rgb} of colors) { // деструктуризация объекта

однако в теле цикла
hexColors.push(color.hex);
rgbColors.push(color.rgb);

используется необъявленная переменная color.
Вместо этого нужно было напрямую использовать переменные hex и rgb
hexColors.push(hex);
rgbColors.push(rgb);


text:
Q: How to traverse a nested dict structure with Ansible? I have the following dict structure variable in an ansible playbook:
apache_vhosts:
- name: foo
  server_name: foo.com
  server_aliases:
    - a.foo.com
    - b.foo.com
    - c.foo.com
- name: bar
  server_name: bar.com
  server_aliases:
    - d.bar.com
    - e.bar.com
    - f.bar.com

I need to create a symlink for each of the server_name and server_aliases domains, e.g.:
/tmp/foo.com     ->   /var/www/foo
/tmp/a.foo.com   ->   /var/www/foo
/tmp/b.foo.com   ->   /var/www/foo
/tmp/c.foo.com   ->   /var/www/foo
/tmp/bar.com     ->   /var/www/bar
/tmp/d.bar.com   ->   /var/www/bar
/tmp/e.bar.com   ->   /var/www/bar
/tmp/f.bar.com   ->   /var/www/bar

I have the following task which works for the server_name:
- name: Add a domain symlinks /tmp for server_name.
  file:
    src: "/var/www/{{ item.name }}"
    dest: "/tmp/{{ item.server_name }}"
    state: link
  with_items: apache_vhosts

But I'm not sure how I can do the same for the array of server_aliases.
I'm happy to use two separate tasks if necessary, but I'm keen to avoid having to add a separate domains variable which duplicates the list of domains in a flat structure.
This Google Groups post is close, but I can't work out how to make it work for multiple virtual hosts.
Is this possible? Or is this fundamentally the wrong approach?

A: You can use with_subelements to loop through the server_aliases. The below snippet
 - name: Add a domain symlinks /tmp for server_name.
    debug: msg="{{ item.server_name }}"
    with_items: apache_vhosts
  - name: Add a domain symlinks /tmp for server_aliases.
    debug: msg="name - {{ item.0.name }} and serverAlias - {{ item.1 }}"
    with_subelements:
     - apache_vhosts
     - server_aliases


text:
Q: SQL Server 2008 R2 - save query results as a SQL statement readable by phpmyadmin? I am working with a database in SQL Server 2008 and I want to export the query results as a SQL statement with the basic format:
CREATE TALBE TableName(columns here)
INSERT INTO TableName (columns here) VALUES (values here)

Now, I know I can export these as a CSV file, however, the issue is that some columns have double quotes in their entries. This presents a problem because if I import this CSV file to phpMyAdmin, using double quotes to identify columns will give me extra or will make me lose columns.
Is there a way to export my query results straight to an SQL File?
Or is there a way to export my query results to CSV in such a way that my columns are enclosed in |?

A: In SSMS right click on your table
Script Table as ==> INSERT TO ==> File
To get the INERT INTO from table result:
Use the free SSMS Tools Pack addin which has "Generate Insert statements from resultsets, tables or database" feature

A: In Microsoft Sql Server Management Studio(MSSMS) right click on your table.


text:
Q: What does "basic upstanding citizen types" mean? In Batman (2022), Batman asks Selina about club:

Batman: Is that where you work?
Selina: No, I just work the bar upstairs. But I see 'em come in.
Batman: Who?
Selina: A lot of guys that shouldn't be there, I can tell you that.
Your basic upstanding citizen types.

What does "basic upstanding citizen types" mean?

A: This is probably sarcasm, as saying that they should not be there and yet saying they are "upstanding citizens" - law abiding citizens/behaving in a good and moral way
So Selina is probably being sarcastic to emphasise how they are not law abiding (not following the law)


text:
Q: Loop stuck while calculating the nearest neighbour I am trying to print out the list of nearest neighbours. I should be getting a list of length 12; however, the list I am getting is of shorter length. When I print out the values for the variable 'a', it is getting stuck at the last element of the list 'path'. I've been trying to debug it, but couldn't find why the value of 'a' is not following the same pattern and why I can't get the other elements.
G is a graph with 11 nodes in total, and what I should be getting is G.NNA(3) = [3, 4, 0, 10, 2, 8, 1, 7, 5, 11, 6, 9]. I am getting the list up until the eighth index [3, 4, 0, 10, 2, 8, 1, 7, 5].
I put print statements inside the two 'if' statements, and the value 'a' clearly gets stuck. It would be amazing if I could fix it. Thanks in advance!
def NNA(self, start):

        path = [start] # Initialize the path that starts with the given point

        usedNodes = [start] # List for used nodes

        currentNode = start

        a = 1

        while len(path) < self.n and a < self.n:
            distances = self.dists[currentNode] # self.dists[3] = [4, 3, 3, 0, 1, 3, 3, 2, 3, 3, 4, 2] and the indeces correspond to the nodes
            nextNode = distances.index(sorted(distances)[a]) # Gets the next node
            if nextNode not in usedNodes :
                a = 1
                path.append(nextNode)
                usedNodes.append(nextNode)
                currentNode = nextNode
                print(currentNode, a)
            elif nextNode in usedNodes:
                a = a + 1 # Check the next smallest value
                print(currentNode, a)
        self.perm = path
        print(path)

# Here is the output
4 1
4 2
0 1
10 1
10 2
2 1
8 1
8 2
1 1
7 1
5 1 # gets stuck at 5
5 2
5 3
5 4
5 5
5 6
5 7
5 8
5 9
5 10
5 11
5 12
[3, 4, 0, 10, 2, 8, 1, 7, 5] # expecting [3, 4, 0, 10, 2, 8, 1, 7, 5, 11, 6, 9]


text:
Q: Stripes in background color drawn by listings package I'm trying to create a verbatim environment with a colored background and which can span across pages (so using a colorbox is not an option). It seemed that the listings package was a good way towards it, but the background is drawn one line at a time, such that, when I view the PDF, I see annoying white-ish "stripes" between the lines as well as where the invisible (0pt) frame rule was not to be drawn:
http://a.imageshack.us/img202/9928/lststrips.png
Here's the minimal code I used to create the output shown in the image:
\documentclass{minimal}
\usepackage[pdftex]{xcolor}
\usepackage[a4paper,hmargin=6cm]{geometry}
\usepackage{listings}
\lstset{backgroundcolor=\color{gray},
  frame=single, framerule=0pt, framesep=5pt}
\begin{document}

\begin{lstlisting}
 if (a < b)
 {
    printf("A is smaller than  B!\n");
 }
 a = b;
\end{lstlisting}

\end{document}

Is there any workaround against these 'stripes'?

A: A simple workaround would be to not specify a color for the listings themselves, put instead use a \colorbox, but for that to work, you either need to use \lstinputlisting or store the result in a box using e.g. lrbox.
\newbox{\mybox}
\begin{lrbox}{\mybox}
\begin{minipage}{\linewidth}
\begin{lstlisting}
 if (a < b)
 {
    printf("A is smaller than  B!\n");
 }
 a = b;
\end{lstlisting}
\end{minipage}
\end{lrbox}
\colorbox{gray}{\usebox{\mybox}}

UPDATE: However, a more beautiful solution is to use Donald Arseneau's framed.sty, which also allows the source-code to span multiple pages.
\documentclass{minimal}
\usepackage[pdftex]{xcolor}
\usepackage[a4paper,hmargin=6cm]{geometry}
\usepackage{listings}
\usepackage{framed}
\begin{document}

\definecolor{shadecolor}{named}{gray}
\begin{shaded}
\begin{lstlisting}
 if (a < b)
 {
    printf("A is smaller than  B!\n");
 }
 a = b;
\end{lstlisting}
\end{shaded}

\end{document}