text:
Q: Installing repos with https breaks yum on CentOS We have a very similar problem to https://stackoverflow.com/questions/48320850/installing-epel-repository-on-centos-7-breaks-yum-functionality/58177576#58177576. I've seen several pleas for help as I've searched the web for an answer with the most common response being "don't use 'https' but that exposes you to MITM attacks". There has to be a better answer or at least an answer on how to use "https" if that is truly the problem; so, I'm re-asking the question:
We just did a fresh install of CentOS Linux release 7.7.1908 (Core) on a server and like others whenever we attempt sudo yum install epel-release, we  break yum. If we remove the epel-release, yum works again. From looking at the files in /etc/yum.repos.d, I see that epel.repo is the only file with an enabled repository that uses https:
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch

We actually ran into (what I believe is) a related problem, when we tried to install MonogDB, which also uses "https":
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/

Here is the epel install:
-bash-4.2$ sudo yum install epel-release
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.sonic.net
 * extras: mirror.fileplanet.com
 * updates: mirror.fileplanet.com
Resolving Dependencies
--> Running transaction check
---> Package epel-release.noarch 0:7-11 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

===================================================================================================================================================================================================================================
 Package                                                     Arch                                                  Version                                             Repository                                             Size
===================================================================================================================================================================================================================================
Installing:
 epel-release                                                noarch                                                7-11                                                extras                                                 15 k

Transaction Summary
===================================================================================================================================================================================================================================
Install  1 Package

Total download size: 15 k
Installed size: 24 k
Is this ok [y/d/N]: y
Downloading packages:
epel-release-7-11.noarch.rpm                                                                                |  15 kB  00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : epel-release-7-11.noarch                                                                                1/1
  Verifying  : epel-release-7-11.noarch                                                                                1/1

Installed:
  epel-release.noarch 0:7-11

Complete!

Now if we even just try to run yum list it fails:
-bash-4.2$ yum list
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile

 One of the configured repositories failed (Unknown),
 and yum doesn't have enough cached data to continue. At this point the only
 safe thing yum can do is fail. There are a few ways to work "fix" this:

     1. Contact the upstream for the repository and get them to fix the problem.

     2. Reconfigure the baseurl/etc. for the repository, to point to a working
        upstream. This is most often useful if you are using a newer
        distribution release than is supported by the repository (and the
        packages for the previous distribution release still work).

     3. Run the command with the repository temporarily disabled
            yum --disablerepo=<repoid> ...

     4. Disable the repository permanently, so yum won't use it by default. Yum
        will then just ignore the repository until you permanently enable it
        again or use --enablerepo for temporary usage:

            yum-config-manager --disable <repoid>
        or
            subscription-manager repos --disable=<repoid>

     5. Configure the failing repository to be skipped, if it is unavailable.
        Note that yum will try to contact the repo. when it runs most commands,
        so will have to try and fail each time (and thus. yum will be be much
        slower). If it is a very temporary problem though, this is often a nice
        compromise:

            yum-config-manager --save --setopt=<repoid>.skip_if_unavailable=true

Cannot retrieve metalink for repository: epel/x86_64. Please verify its path and try again

And here is /etc/yum.repos.d/epel.repo:
-bash-4.2$ cat epel.repo
[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7

[epel-debuginfo]
name=Extra Packages for Enterprise Linux 7 - $basearch - Debug
#baseurl=http://download.fedoraproject.org/pub/epel/7/$basearch/debug
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-debug-7&arch=$basearch
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1

[epel-source]
name=Extra Packages for Enterprise Linux 7 - $basearch - Source
#baseurl=http://download.fedoraproject.org/pub/epel/7/SRPMS
metalink=https://mirrors.fedoraproject.org/metalink?repo=epel-source-7&arch=$basearch
failovermethod=priority
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
gpgcheck=1

So is the problem with the repository we're trying access or the fact that we are trying to access using the "https" protocol? If the former, how do I find the right repository? If the latter, how do we go about diagnosing the underlying problem? This is a pretty fresh install -- all we've really done is installed autofs and mounted the home directory, installed rvm and created some users and groups.
FWIW, yum check-update doesn't report anything and yum update curl (with or without "--disablerepo=epel") didn't do anything either.
I've been banging my head against this for a day now and need professional help. ;-/
As noted above, we ran into a similar problem while trying to install MongoDB using these instructions: https://docs.mongodb.com/v4.0/tutorial/install-mongodb-on-red-hat/#using-rpm-packages-recommended
We created /etc/yum.repos.d/mongodb-org-4.0.repo with the contents:
[mongodb-org-4.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc

and then tried to install MongoDB and got a somewhat different error:
-bash-4.2$ sudo vi /etc/yum.repos.d/mongodb-org-4.0.repo
-bash-4.2$ sudo yum install -y mongodb-org
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirror.keystealth.org
 * extras: mirror.fileplanet.com
 * updates: mirrors.sonic.net
https://repo.mongodb.org/yum/redhat/7/mongodb-org/4.0/x86_64/repodata/repomd.xml: [Errno 14] curl#60 - "Peer's Certificate issuer is not recognized."
Trying other mirror.
It was impossible to connect to the CentOS servers.
This could mean a connectivity issue in your environment, such as the requirement to configure a proxy,
or a transparent proxy that tampers with TLS security, or an incorrect system clock.
You can try to solve this issue by using the instructions on https://wiki.centos.org/yum-errors
If above article doesn't help to resolve this issue please use https://bugs.centos.org/.

 One of the configured repositories failed (MongoDB Repository),
 and yum doesn't have enough cached data to continue. At this point the only
 safe thing yum can do is fail. There are a few ways to work "fix" this:

     1. Contact the upstream for the repository and get them to fix the problem.

     2. Reconfigure the baseurl/etc. for the repository, to point to a working
        upstream. This is most often useful if you are using a newer
        distribution release than is supported by the repository (and the
        packages for the previous distribution release still work).

     3. Run the command with the repository temporarily disabled
            yum --disablerepo=mongodb-org-4.0 ...

     4. Disable the repository permanently, so yum won't use it by default. Yum
        will then just ignore the repository until you permanently enable it
        again or use --enablerepo for temporary usage:

            yum-config-manager --disable mongodb-org-4.0
        or
            subscription-manager repos --disable=mongodb-org-4.0

     5. Configure the failing repository to be skipped, if it is unavailable.
        Note that yum will try to contact the repo. when it runs most commands,
        so will have to try and fail each time (and thus. yum will be be much
        slower). If it is a very temporary problem though, this is often a nice
        compromise:

            yum-config-manager --save --setopt=mongodb-org-4.0.skip_if_unavailable=true

failure: repodata/repomd.xml from mongodb-org-4.0: [Errno 256] No more mirrors to try.
https://repo.mongodb.org/yum/redhat/7/mongodb-org/4.0/x86_64/repodata/repomd.xml: [Errno 14] curl#60 - "Peer's Certificate issuer is not recognized."

However, now after various attempts at fixes, if I try this I get the "(Unknown)" error.
Any guidance on how to diagnose and fix this problem would be greatly appreciated.


text:
Q: How do I create a table that will accept members to register their shops numbers as alpa-numeric as end-user I am working on Table called (Shops_Table).
This table will accept registration from the shops owners, some of these shops identifies  numerically (INT), Example... shop No 1, shop No 2, shop No3, and on 1000s.
And other shops identifies Alphanumeric (Char),Like shop No 1a, shop No 1b, shop No 1c,  shop No 1b and on 1000s
Now..
I found this code below here in stackoverflow, can is do the job??
DECLARE @Base10ToBase36 AS TABLE (
ID      TINYINT NOT NULL IDENTITY(0,1) PRIMARY KEY,
Symbol  CHAR(1) NOT NULL CHECK(Symbol LIKE '[0-9,A-Z]')
)
INSERT INTO @Base10ToBase36(Symbol)
VALUES  ('0'), ('1'), ('2'), ('3'), ('4'), ('5'), ('6'), ('7'), ('8'), ('9'),
('A'), ('B'), ('C'), ('D'), ('E'), ('F'), ('G'), ('H'), ('I'), ('J'),
('K'), ('L'), ('M'), ('N'), ('O'), ('P'), ('Q'), ('R'), ('S'), ('T'),
('U'), ('V'), ('W'), ('X'), ('Y'), ('Z')
SELECT  TOP (1)
pos1.ID * 36 + pos0.ID AS Base10Number,
pos1.Symbol,
Pos0.Symbol,
CONCAT(pos1.Symbol, Pos0.Symbol) AS Base36
FROM    @Base10ToBase36 AS pos0
CROSS JOIN @Base10ToBase36 AS pos1
ORDER BY NEWID()    -- random

redpajama_set_name: RedPajamaStackExchange


text:
Q: Triggering Azure Pipelines Build Deletion I am tasked to verify why expired builds are not deleted in my company's locally hosted Azure DevOps server.
When querying the SQL Database I find that there are very few deleted builds and most of those were manually triggered.
Most of the builds aren't actively retained.
I found this question which asks pretty much the same question I am asking but does not seem to have an answer. To me it looks like there is an infrequently found bug for cases like this, which has not yet been diagnosed. My question is: is there a way, for instance via REST API to trigger the deletion of Builds as defined via the DevOps Admin interface?
On further review, I discovered that what actually seems to be happening is that DevOps, though updated to the latest release, seems to be applying per-Pipeline rules. One of the pipelines has this custom rule:  and I have evidence that tells me that the builds are being deleted as per that rule.

A: I found the answer in the Developer Community at Visual Studio. Seems to have been a problem that was fixed in their 2020.0.1 Patch 2 Release. I should note, however, that even though the issue is officially closed, there have been a couple of dissenting votes as of this date.


text:
Q: Correct logic and set of time for variable I have 3 functions work(), timeLimits(), and search(). I'm trying to do some check in timeLimits() and if some of the returns are true the script becomes blocked for a certain time.
Everything works fine with checks and blocks. What isn't working is updating the variable which holds the time until when will be blocked and checking when the block ends.
So, here are the functions:
const TOTAL_BLOCK_TIME = 20; // sec
const TOTAL_OPERATING_TIME_BEFORE_BLOCK = 10; // sec

    private $worker;
    private $startTime;
    private $afterBlock;
    private $isBlocked = false;

    public function __construct()
    {
        $this->worker->addServer();
        $this->worker->addFunction("myfunction", array($this, "search"));
        $this->startTime = time();
        $this->afterBlock = time() - 1;
    }

public function work()
{
   while (true) {
      $this->worker->work();
   }
}

public function timeLimits()
{
    $currentTime = time();
    $timePassed = $currentTime - $this->startTime;

    if ($timePassed > self::TOTAL_OPERATING_TIME_BEFORE_BLOCK) {
       $this->afterBlock = $currentTime + self::TOTAL_BLOCK_TIME;
       return true;
    }
    return false;
}

public function search($job)
{

    if ( $this->timeLimits() ) {
        return 'Blocked until:'.$this->afterBlock;
    }
    // db query, the rest of the code
    // it wont be executed if $this->timeLimits() return true
}

The problem: When timeLimits() return true and the script is blocked each new request updates the $this->afterBlock again. I guess is because I have $this->afterBlock = $currentTime + self::TOTAL_WORKER_SLEEP_TIME; in the if condition and each time it is in the condition the variable gets an update.
What I don't know is how to update this variable only once e.g. when it is entered in the condition, not every time I call if ( $this->timeLimits() ) { ... }
Can anyone help here?

A: You can add a flag to keep track of the block status and update the $this->afterBlock only when the flag is false.
const TOTAL_BLOCK_TIME = 20; // sec
const TOTAL_OPERATING_TIME_BEFORE_BLOCK = 10; // sec

private $isBlocked = false;

public function work()
{
   while (true) {
      $this->work();
   }
}

public function timeLimits()
{
    $currentTime = time();
    $timePassed = $currentTime - $this->startTime;

    if ($timePassed > self::TOTAL_OPERATING_TIME_BEFORE_BLOCK && !$this->isBlocked) {
       $this->afterBlock = $currentTime + self::TOTAL_BLOCK_TIME;
       $this->isBlocked = true;
    }
    return $this->isBlocked && $currentTime < $this->afterBlock;
}

public function search($job)
{

    if ( $this->timeLimits() ) {
        return 'Blocked until:'.$this->afterBlock;
    }
    // db query, the rest of the code
    // it wont be executed if $this->timeLimits() return true
}


text:
Q: pyhdf links in PyPI going to server that is offline? (with workaround) I am trying to use pip to add the package pyhdf in python3.
I'm working in a virtualenv and have the prereq packages there:
% pip list

numpy (1.9.2)
pip (7.0.3)
requests (2.7.0)
setuptools (17.0)
wheel (0.24.0)

If I ask pip to get the latest/default version of pyhdf, I believe it searches this index page
https://pypi.python.org/simple/pyhdf/

This appears to trip up pip, as it tries to FTP the egg for v.0.7.x (not the latest) from a server that is not presently responding:
ftp://nordet.qc.dfo-mpo.gc.ca/pub/soft/pyhdf/pyhdf-0.7-1.tar.gz
I've been through the whole mess that the 'requests' package doesn't accept FTP URLs like this one, and that pip now strongly discourages getting external/unverified packages even though they are listed at PyPI. I settled on this workaround, getting the latest build directly from the authors' site:
wget http://hdfeos.org/software/pyhdf/pyhdf-0.9.0.tar.gz
To build the python package from a downloaded egg, you need to get the source headers for libhdf before running setup.py (via pip or manually.) The following I did outside the venv, though they might work within one too
sudo apt-get install libhdf4-0
sudo apt-get install libhdf4-dev libhdf4-doc

Finally, back in the venv, the actual pip install syntax that worked for me to install pyhdf from the tar.gz that I had downloaded:
pip install --global-option=build_ext --global-option="-I/usr/include/hdf" --no-index --find-links=file:pyhdf-0.9.0.tar.gz pyhdf

after which pip list yields:
numpy (1.9.2)
pip (7.0.3)
pyhdf (0.9.0)
requests (2.7.0)
setuptools (17.0)
wheel (0.24.0)

Yay!
Since I'm posting my workaround that got me pyhdf okay, to make this an actual question I will ask:
Is there an official proper way that users can do to contact either PyPI admins or the authors of the pyhdf package to report that the "best match" link at the project page is:

*

*no longer the latest release, and

*points to an FTP server that is apparently offline (at least currently)
making pip install pyhdf basically infeasible without much extra manual intervention (which if permanent, ought to be documented by the maintainers)


text:
Q: New row by enter button in input (ASP.NET MVC) I have text input in my View
Here is code
 @Html.TextAreaFor(model => model.Detail, new { @class = "greeting2", data_bind = "textInput: Detail", id = "Detail", placeholder = "Описание" })

And  where i show text via KnockoutJS
Here is code of span

Here is knockoutJS code

When I write text all okay and spaces are checking. But when I click enter text will go on new row. But it in one row, like on screenshot.
Screen
How I can make new row by enter?

A: This is actually just a styling issue, adding white-space: pre-wrap to styling for the span element should fix the issue:


text:
Q: How to pass configuration into indexTransform in angular-cli? I'd like to use the indexTransform functionality in an angular 8 (angular-cli) project, but the configuration property of targetOptions remains empty.
I've tried the example project here: https://github.com/just-jeb/angular-builders/tree/master/packages/custom-webpack/examples/full-cycle-app
But in the example project the configuration is empty, too.
module.exports = (targetOptions, indexHtml) => {
    targetOptions.configuration // configuration is empty
}

Where can I define the configuration that should be passed into the callback function?

A: configuration reflects value passed to --configuration=configurationName options in ng build, so in development mode is always empty.
if you build with --prod flag (that is an alias of --configuration=production) you can see configuration properly filled
Below you can find an usage example. This code adds in head element a meta tag element with api service location.
const allSettings = {
    development: {
        apiUrl: "http://localhost:8000"
    },
    production: {
        apiUrl: "https://myapiserver/"
    }
}

module.exports = (targetOptions, indexHtml) => {
    const i = indexHtml.indexOf('</head>');

    // if empty assumes 'development'
    const configuration = targetOptions.configuration || "development";

    // load settings (by configuration)
    const settings = allSettings[configuration];

    // build meta tag
    let customHead = "";
    customHead += `<meta name="apiUrl" content="${setting.apiUrl}">`;

    // add customHead before head end tag
    return `${indexHtml.slice(0,i)}
            ${customHead}
            ${indexHtml.slice(i)}`
}


text:
Q: Creating site-wide search in a Rails app I'm trying to create a search form that retrieves results based on a user's query for a restaurant's name. So far I've setup its route, controller, and index view.
routes.rb
resources :search, :only => [:index]

search_controller.rb
class SearchController < ApplicationController
  def index
    if params[:query].present?
      @restaurants = Restaurant.search(params[:query])
    else
      @restaurants = Restaurant.all
    end
 end
end

search/index.html.erb
<% @restaurants.each do |restaurant| %>
    <%= restaurant.name %>
<% end %>

Here is how the search for is setup:

layouts/_header.html.erb
<%= form_for search_index_path, method: :get do |f| %>
  <%= text_field_tag :query, params[:query] %>
  <%= submit_tag "Search", name: nil %>
<% end %>

Right now I'm running into two problems. The first being that if I enter a query and submit, the page doesn't go to the index page. All it does is append the query to the current page I'm on:
localhot:3000/restaurant?utf8=✓&query=pizza

Second is that I'm getting every restaurant in my db on the index page (as expected). Is there a way that I can make it so the page is blank for anything other than on search requests?

A: Question 1
Use form_tag instead of form_for, since the latter is used to handle specific model objects and this is not the case.
Question 2
You can achieve that by:
if params[:query].present?
  @restaurants = Restaurant.search(params[:query])
else
  @restaurants = [] # or Restaurant.none if you need a chainable scope
end


text:
Q: Paste cells into Outlook then convert table to text in Excel I'm trying to build a macro that grabs a selection of cells from an Excel spreadsheet, pastes the cells into a new outlook email, then changes the format of the cells.
Specifically I want to convert the table to text, then change the font to Arial size 10.
The code below does the above, but I haven't been able to figure out how to convert the table to text, then change the text font.
Can anyone help?
Sub Email_test()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
Set rng = Sheets("Master").Range("A1:B99").SpecialCells(xlCellTypeVisible)
If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected. " & _
           vbNewLine & "Please correct and try again.", vbOKOnly
    Exit Sub
End If
With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
    .To = "User@company.com"
    .CC = ""
    .BCC = ""
    .Subject = "Cells as text "
    .HTMLbody = RangetoHTML(rng)

    ' In place of the following statement, you can use ".Display" to
    ' display the e-mail message.

    .Display
End With
End Sub

A: This will work for you, instead of HTMLbody use body also removed your range to html function
Sub Email_test()
    Dim rng As Range
    Dim OutApp As Object
    Dim OutMail As Object
    Set rng = Nothing
    Set rng = Sheets("Master").Range("A1:B99").SpecialCells(xlCellTypeVisible)
    If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected. " & _
               vbNewLine & "Please correct and try again.", vbOKOnly
        Exit Sub
    End If
    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With
    Dim v As Variant: v = rng.Value
    Dim tempStr As String: tempStr = ""
    For i = LBound(v, 1) To UBound(v, 1)
            For j = LBound(v, 2) To UBound(v, 2)
                If j = 2 Then
                    tempStr = tempStr & v(i, j) & vbCrLf
                Else
                    tempStr = tempStr & v(i, j) & " "
                End If
            Next j
        Next i
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    With OutMail
        .To = "User@company.com"
        .CC = ""
        .BCC = ""
        .Subject = "Cells as text "
        .body = tempStr

        ' In place of the following statement, you can use ".Display" to
        ' display the e-mail message.

        .Display
    End With
End Sub

Please mark as an answer if you are satisfied with reply

A: The Outlook object model provides three main ways for working item bodies:

*

*Body -  a string representing the clear-text body of the Outlook item.

*HTMLBody - a string representing the HTML body of the specified item.

*Word editor - the Microsoft Word Document Object Model of the message being displayed. The WordEditor property of the Inspector class returns an instance of the Document class from the Word object model which you can use to set up the message body.
You can read more about all these ways in the Chapter 17: Working with Item Bodies. It us up to you which way is to choose.


text:
Q: Entity Framework - Update/add value to existing value In Entity Framework is it possible to add a value to existing value in the database?
Currently I have this:
var ent = this.repository.GetSingle(id);
var moreQuantity = 5; // This is calculated in application logic
ent.quantity = ent.quantity + moreQuantity;
this.repository.SaveChanges();

It is possible to do the same in a single database interaction? I mean something like this in SQL:
UPDATE table SET quantity = quantity + {moreQuantity} WHERE id = {id}

Without using ExecuteSqlCommand or ExecuteStoreQuery.
The reason I am asking this is because there is a significant amount of time between the GetSingle and SaveChanges in my application, so I run with some concurrency problems. I manage to solve it with RowVersion and ConcurrencyCheck but I was looking for a better implementation.
Thanks in advance.

A: There is a nice library EntityFramework.Extended
Install it and write:
context.repository.Update(e => e.id == id, e2 => new entity { quantity = e2.quantity + moreQuantity });

A: Current version of EntityFramework Extended (6.1) has deprecated the overload indicated in the accepted answer. The filtering and the actual update should be separated now. This is a good thing, since filtering can be easily dynamically constructed.
For the actual question, the query should like the following:
context.repository
    .Where(e => e.id == id)
    .Update(e2 => new entity { quantity = e2.quantity + moreQuantity });


text:
Q: getting Null value + probably query isn't working Actually I'm following mvc-3 tier architecture to my application.and here is my Search option's implementation.
In my servlet(controller) I'm doing this :
        String select = request.getParameter("select");  // getting value
        String search = request.getParameter("search");  // getting value
        request.setAttribute("select", select);
        request.setAttribute("search", search);
        System.out.println("Select : "+select+" Search : "+search);

        int page = 1;
        int recordsPerPage = 20;
        if(request.getParameter("page") != null)
            page = Integer.parseInt(request.getParameter("page"));
        SearchDAO searchDAO=new SearchDAO();
        List<User> list1=searchDAO.searchAllUsers((page-1)*recordsPerPage,recordsPerPage,select,search);  //getting null value,doing SOP of list1
        int noOfRecords = searchDAO.getNoOfRecords();  //getting null value,doing SOP
        int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);  //getting null value,doing SOP
        session.setAttribute("noOfRecords", noOfRecords);
        request.setAttribute("searchList", list1);
        request.setAttribute("noOfPages", noOfPages);
        request.setAttribute("currentPage", page);

and in the SearchDAO is:
public class SearchDAO {
private int noOfRecords;
Connection connection;
Statement stmt;

    public List<User> searchAllUsers(int offset ,int noOfRecords,String select,String search){
    private static Connection getConnection() throws SQLException,ClassNotFoundException{
    Connection con = ConnectionFactory.getInstance().getConnection();
    return con;  //ConnectionFactory is class for making the connection to DB.
}
     String query="select SQL_CALC_FOUND_ROWS * from info where '"+select+
"' like '%"+search+"%' order by serialNo asc limit
" + offset + " , " + noOfRecords;

    List<User> list1 = new ArrayList<User>();
    User user1=null;

    try {
        connection = getConnection();
        stmt = connection.createStatement();
        ResultSet rs=stmt.executeQuery(query);
        while(rs.next()){
        user1=new User();
        user1.setSerial(rs.getInt(1));
            user1.setName(rs.getString(2));
            user1.setEmail(rs.getString(3));
            list1.add(user1);
            }

        rs.close();
        rs = stmt.executeQuery("SELECT FOUND_ROWS()");
        if(rs.next())
            this.noOfRecords = rs.getInt(1);

    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }finally
    {
        try {
            if(stmt != null)
                stmt.close();
            if(connection != null)
                connection.close();
            } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    return list1;

}

public int getNoOfRecords() {
    return noOfRecords;
}
}

*

*Editted
Feel free to comment & please rectify me if I'm not following the proper mvc architecture.

A: *

*check if you are able to retrieve parameters in your
request.getParameter(); call in your servlet

*check if you are able to store parameters in request scope like
request.setAttribute() call

A: Your concern is right,:
'%"+request.getParameter("search)+"%'

*

*Firstly, you never initialized request in SearchDAO, and you are
calling getParameter on its instance, Thus NullPointerException

*Secondly, how would your seachDAO get the request ??, it isnt a
servlet, its just aplain POJO

A: AFAIK, create a bean class and with the help of the class, you can communicate between controller and DAO, you could not do it by using request.getAttribute(which is in your DAO).


text:
Q: Send CTCP Messages I'm currently working on a project for an introductory class on C#. The idea is to make a basic irc client that connects to a single channel on a single irc server. Most things have been easy to implement, however, I've hit a brick wall when attempting to send CTCP messages.
The format is supposed to be: PRIVMSG target : /U+0001ACTION message/U+0001
I am able to identify these messages as they come in, using the Unicode control character, but whenever I try to send my own "ACTION message" is received.
Here's the code I'm using to send the message:
    private TcpClient irc; //declarations of properties of irc class

    private NetworkStream stream;

    private string _inputLine;

    StreamReader reader;

    StreamWriter writer;

    public void Connect() //connects to the irc server in _server on port _port
    {
        irc = new TcpClient(_server, _port);
        stream = irc.GetStream();
        reader = new StreamReader(stream);
        writer = new StreamWriter(stream);

        Send("NICK " + Nick);
        Send("USER " + Nick + " 0 * :" + Nick);

        Listen();
        OnConnect();
    }

    private void button1_Click(object sender, EventArgs e) //method is from a windows form
    {

        if (txtMessage.Text.StartsWith("/me"))//sends contents of textbox to SendCTCP if it is an action message
        {
            test.SendCTCP("ACTION " + txtMessage.Text.Remove(0, 3));
            OnAction(test.Nick, txtMessage.Text.Remove(0, 3)); //method OnAction is within the widows form and outputs the message in a textbox for messages sent/received to the channel
        }
        else
        {
            test.SendMessage(txtMessage.Text);
            ChannelTest(test.Nick, txtMessage.Text, null);
        }
        txtMessage.Text = "";
    }

public void SendCTCP(string message) //formats message with /U+0001 characters
{
    char control = '\x01';
    Send("PRIVMSG " + _channel + " : " + control.ToString() + message + control.ToString());
}

    public void Send(string message) //sends message to server using StreamWriter writer
    {
        writer.WriteLine(message);
        writer.Flush();
    }

The Send method uses a StreamWriter to send the message to the server.
I've tried with and without the ToString(). I've tried the character itself within the Send block, rather than in control. I've tried every representation of the character I've been able to find, but I've been unable to make it work. Any help would be appreciated.
Sending the test message "/me tests" through the client results, when the server sends it to other clients in the same channel, in the message: IRCTest!IRCTest@mask PRIVMSG #Channel : ACTION  tests
Which is interpreted by every client I can find as: :  ACTION  tests
edit: I've updated the code with, I hope, all the relevant variables and methods

A: Well, I feel like an idiot, but at least I figured it out. I've changed it to use '\u0001' as the character, and (wait for it. . .) I deleted the space between the : and the control character. It now functions perfectly.


text:
Q: python setup.py install not working in Windows due to admin? I tried to run python setup.py install in Windows cmd, but got this error. In MAC I just change to sudo python setup.py install, but in Windows not suod. I tried runas also not working. I also tried python setup.py install --user the installation didn't report error but the function did not work.
Does anyone have any suggestions? Thanks
    C:\Users\ccc\Desktop\pyrbdome-master>python setup.py install
Python development and setuptools have been installed...
running install
error: can't create or remove files in install directory

The following error occurred while trying to add or remove files in the
installation directory:

    [Errno 13] Permission denied: 'C:\\Program Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\\Lib\\site-packages\\test-easy-install-2820.write-test'

The installation directory you specified (via --install-dir, --prefix, or
the distutils default setting) was:

    C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.496.0_x64__qbz5n2kfra8p0\Lib\site-packages\

Perhaps your account does not have write access to this directory?  If the
installation directory is a system-owned directory, you may need to sign in
as the administrator or "root" account.  If you do not have administrative
access to this machine, you may wish to choose a different installation
directory, preferably one that is listed in your PYTHONPATH environment
variable.

For information on other options, you may wish to consult the
documentation at:

  https://setuptools.readthedocs.io/en/latest/easy_install.html

Please make the appropriate changes for your system and try again.

A: The problems is the package I need to install requires Linux enviroment. So I have to run it by Ubuntu or Linux server. Windonws dose not work in any way. Hope can help!


text:
Q: Using Modifiers of Perl-compatible Regex (PCRE) in grep According to grep --help and man grep, we can use the -P option in order to interpret the pattern as a Perl regular expression (PCRE, to be precise), instead of the default POSIX basic regular expressions (BRE).
In Perl language, various Modifiers can be added to the expression, in order to adjust the pattern interpretation (in the syntax of /pattern/modifiers).
So, how can someone add modifiers to the grep's Perl regular expression? I tried some variations like grep -P "/^got.it$/ms" [FILE] but the search results were wrong.
However, about the PCRE interpretation, the manual points out that:

This is highly experimental and grep -P may warn of unimplemented features.

Is it possible that the grep tool does not support modifiers at all?
By the way, I noticed that one can perform case-insensitive pattern matching by using the -i option, which is an example of a modifier.

A: For the modifiers imsxadlup you can use the (?X) for as described in Extended Patterns:
$ echo FOO | grep -P '(?i)foo'
FOO


text:
Q: What does "RC" mean in `=SUM(A4:INDIRECT("RC" & G4, 0))`? I have =SUM(A4:INDIRECT("RC"&G4,0)) in total weight. I understand what it does but I am not able to find what

*

*"RC",

*0 in ("RC"&G4,0)stands for

If you have any ideas, please let me know.

A: You need to read the documentation of the INDIRECT function

INDIRECT(ref_text, [a1])
The INDIRECT function syntax has the following arguments:

*

*Ref_text: Required. A reference to a cell that contains an A1-style reference, an R1C1-style reference, a name defined as a reference, or a reference to a cell as a text string. If ref_text is not a valid cell reference, INDIRECT returns the #REF! error value.

*

*...

*A1: Optional. A logical value that specifies what type of reference is contained in the cell ref_text.

*

*If a1 is TRUE or omitted, ref_text is interpreted as an A1-style reference.

*If a1 is FALSE, ref_text is interpreted as an R1C1-style reference.

Since your a1 is 0, the reference is now in R1C1-style. In this style RxCy refers to row x column y, so R1C2 is equivalent to B1. If you omit the row number then RCx is the cell in the same row in the xth column
For more information about the RC-style read

*

*The beauty of the R1C1 Reference Style

*A1 or R1C1 Notation

*Columns and rows are labeled numerically in Excel

*Excel – R1C1 Reference Style vs. A1

*Reference cells and ranges

*ADDRESS function
In the A1-style RC1 is still valid though. If you scroll to the right then you'll see that after column Z is column AA, AB,... AZ, BA,..., BZ... all the way until the last column (XFD for column 16384). RC1 means the cell in the 470th column of the first row


text:
Q: Mysql connection pool performance loss I've a Java application that can run either in Jboss and Glassfish.
I've used Hibernate to handle the DB and hikariCP as connection pool.
All works perfectly but I've noticed a performance loss.
To make a stress test I've created a test servlet that select from DB a row using hibernate.
With JMeter I've set 500 simultaneusly request per sec to this servlet, while JMeter is running i've tryed to use the application and the behavior is the following:
When I set maximumPoolSize to 10 the application responds after very long time (~10 sec).
When I set the maximumPoolSize to 1 the application responds as expected (after 2 or 3 sec)
Another thing I've noticed is that when I run JMeter with 500 threads and 10 maximum connection pool, the apllication JMeter become freeze while with 1 maximum connection pool the application JMeter never become freeze.
What is the reason of this behavior? I've missed some configuration on mysql?
Hibernate config
    <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
    <property name="hibernate.connection.provider_class">com.zaxxer.hikari.hibernate.HikariConnectionProvider</property>
    <property name="hibernate.hikari.dataSourceClassName">com.mysql.jdbc.jdbc2.optional.MysqlDataSource</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.search.autoregister_listeners">false</property>
    <property name="hibernate.connection.CharSet">utf8</property>
    <property name="hibernate.connection.characterEncoding">utf8</property>
    <property name="hibernate.connection.useUnicode">true</property>
    <property name="hibernate.hikari.idleTimeout">15000</property>
    <property name="hibernate.hikari.maxLifetime">900000</property><!-- 15 min -->
    <property name="hibernate.hikari.leakDetectionThreshold">5000</property>
    <property name="hibernate.hikari.validationTimeout">1000</property>
    <property name="hibernate.hikari.minimumIdle">1</property>
    <property name="hibernate.hikari.maximumPoolSize">10</property>
    <property name="hibernate.hikari.dataSource.cachePrepStmts">true</property>
    <property name="hibernate.hikari.dataSource.prepStmtCacheSize">250</property>
    <property name="hibernate.hikari.dataSource.prepStmtCacheSqlLimit">2048</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.jdbc.batch_size">50</property>
    <property name="hibernate.hikari.dataSource.url">jdbc:mysql://localhost:3306/myDb?transformedBitIsBoolean=false&tinyInt1isBit=false&UseUnicode=true&characterEncoding=utf8</property>


text:
Q: GMap MouseOver seems not to work Anybody familiar with GMap? Im trying to make use of the Mouse over event but appearantly im doing something wrong. This even there suppose to be a good example here on Stackoverflow which I tried to use.
public partial class frmMap : Form
    {

        public void gmap_MouseMove(object sender, MouseEventArgs e)
        {
        base.OnMouseMove(e);
        double lat = gmap.FromLocalToLatLng(e.X, e.Y).Lat;
        double lng = gmap.FromLocalToLatLng(e.X, e.Y).Lng;
        lblLatLng.Text = "lat= " + Convert.ToString(lat) + "   lng= " +
        Convert.ToString(lng);

        // mouseY = e.Location.Y;
        // mouseX = e.Location.X;
        // lblLatLng.Location = new Point(mouseX, mouseY + 10);
    }

public frmMap()
    {
        InitializeComponent();

        gmap.MapProvider = GoogleMapProvider.Instance;
        GMaps.Instance.Mode = AccessMode.ServerOnly;
        GMapControl gMap = new GMapControl();
        gmap.MouseDown += gmap_MouseDown;
        gmap.MouseWheel += gmap_MouseWheel;
        gmap.SetPositionByKeywords(Area);
        gmap.DragButton = MouseButtons.Left;
        gmap.Zoom = 9.5;
    }

Above the code im trying to use. My GMap is further working so I have placed the references allready. I just wanted to show in the lblLatLng the current latitude and longitude from the position of the mouse. I beleive this is possible.
Anybody willing to help me?
Thanks in advance


text: Q: Android навигационное приложение mapkit. Найти расстояние по дороге между точками делаю навигационное приложение с помощью mapkit. Нужно найти расстояние между точками по дороге, не по прямой, нужно учитывать саму дорогу. Как это можно сделать?


text:
Q: Typescript: Get Type of Method Parameters from Generic Is it possible to get the type of parameters of methods from a generic?
For example if I have:
interface Keys {
  create: any;
  ...
}

type MethodNames<T> = { [P in keyof Keys]: keyof T; }

Then is it possible to get the type of parameters of those Methods?
type MethodParams<T> = { [P in keyof Keys]: Parameters<T[???]>; }

Playground Link to Relevant Code

A: The only way I can imagine this working is if MethodParams is not only generic in T, the type of the underlying API, but also in M, the particular MethodNames<T> appropriate for T.  And that could look like this:
type Keys = "create" | "getOne" | "getAll" | "update" | "delete"

export type MethodNames<T> = {
  [K in Keys]: keyof T;
};

export type MethodParams<T, M extends MethodNames<T>> = {
  [K in Keys]: T[M[K]] extends (...args: infer P) => any ? P : never;
};

(Note that I make Keys just a union of string literal types instead of making it an object type with values of type any that we ignore.)
So MethodParams<T, M> iterates over the keys in Keys and then looks up each key in M to get the key of T we want to probe for parameters.  That is, if K is a member of Keys, we want to get the parameters from what we hope is a function type at T[M[K]]. We use conditional type inference to get that.

Let's test to see that it works.  First I'll write a helper function to verify that a proposed method mapper works for a particular type T:
const methods = <T, M extends MethodNames<T>>(api: T, methods: M) => methods;

And now I'll make up a fake api:
interface SomeData {
  id: number,
  a: string,
  b: number,
  c: boolean
}
interface SomeApi {
  change(id: number, data: Partial<SomeData>): SomeData,
  destroy(id: number): boolean
  grab(id: number): SomeData | undefined,
  grabbingSpree(): SomeData[],
  make(data: Omit<SomeData, "id">): SomeData,
}
declare const someApi: SomeApi;

Here's the method mapper:
const someApiMethods = methods(someApi, {
  create: "make",
  getOne: "grab",
  getAll: "grabbingSpree",
  update: "change",
  delete: "destroy"
})

And now I can finally try MethodParams:
type SomeApiMethodParams = MethodParams<SomeApi, typeof someApiMethods>;
/* type SomeApiMethodParams = {
    create: [data: Omit<SomeData, "id">];
    getOne: [id: number];
    getAll: [];
    update: [id: number, data: Partial<SomeData>];
    delete: [id: number];
} */

Looks good.  The type of SomeApiMethodParams is what we expect it to be.

Oh, and this also means that any class or type that needs to compute MethodParams will need to be generic in the appropriate MethodNames type.  For example, your AbstractTestEnv class would be augmented with another type parameter:
export abstract class AbstractTestEnv<S, T, U, M extends MethodNames<S>> {
  public api: S;
  public createDto: T;
  public crudMethods: M;
  protected constructor(api: S, crudMethods: M) {
    this.api = api;
    this.crudMethods = crudMethods;
    this.createDto = this.generateCreateDto(this.resourceId);
  }
  public abstract generateCreateDto(resourceId: string): T;
  public abstract getParams(): MethodParams<S, M>;
  /* snip */
}

Playground link to code


text:
Q: CSS file of a component within a library does not get loaded with the component in angular app I have developed a library in an angular application (which is generated using angular cli) and the library contains a component with its own template file and stylesheet. However, when I load the module in the app.module.ts and run the app (using ng serve for simplicity), the styles within the stylesheet are not rendered.

*

*The library is generated using ng generate library

*The library is contained within the projects directory of the app

*The component is present within <name of the component>/src/lib directory

The app.module.ts file contains the following code:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { GuitarChordGeneratorModule } from 'projects/guitar-chord-generator/src/public-api';

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        GuitarChordGeneratorModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

Below is a snippet from the guitar-chord-generator.component.ts file:
import { Component, OnInit, Input } from '@angular/core';
import { Chord } from './chord';
import { GCSGConfig } from './gcsgconfig';

@Component({
    selector: 'lib-guitar-chord-generator',
    templateUrl: './guitar-chord-generator.component.html',
    styles: ['./guitar-chord-generator.component.css']
})

The image below is the directory structure of the app.

As you can see that guitar-chord-generator.component.css is the CSS file for the component.

A: Your component has
styles: ['./guitar-chord-generator.component.css']

The styles property takes an array of strings that contain CSS code.

You should be using styleUrls
styleUrls: ['./guitar-chord-generator.component.css']


text:
Q: Dojo - ScrollingTabControllerMenuButton freezes TabContainer in Firefox I recently by accident found an issue I have with a web application I have made entirely with dojo.
I have a TabContainer and a toolbar with buttons and each button adds a Tab in the TabContainer.
Each of these new Tabs has as children, created programmatically, one or more of the following BorderContainers, ContePanes, Editors, FilteringSelects, Uploader and Buttons. I should point out that I do not have parseonLoad: true byt false and I call manually the parsers.parse when required. I should point out that in the ContentPanes in the content attribute I put also declarative filteringSelects and ValidationTexts and Uploader I hope that is not a problem.
Everything is working great in all browsers even in IE9 besides one thing in Firefox 12.
When I create many new tabs and the ScrollingTabController gets created (The left/right and dropdown arrows of the tabstrip) when I use the ScrollingTabControllerMenuButton (the down arrow at the far right) the TabContainer behaves wrongly and eventually freezes. Firebug shows weird errors when I select different tabs via this menu of the tab strip. Errors of the buttons that I have in these tabs, weird errors mentioning StackController or ScrollingTabController
[ e.g.
button is undefined
if(this._selectedTab === button.domNode){  StackController.js (line 222) ]

different each time...
This weird behavior only happens in Firefox. IE9 and Chrome do not have any issue at all!
Could anyone have an idea on what might be the problem? Is it a known bug? Is it a problem that I have many widgets in each Tab ?

A: It seems that it is indeed a browser specific bug and as I was told it should be fixed in the following releases
I first reported it to the dojo community and from there they reported it to the Firefox team
http://bugs.dojotoolkit.org/ticket/15496


text:
Q: Alternative of visibility of element located in selenium 2.0 that checks the presence of an element on the DOM? I have a problem in my framework that instead of using static sleeps I try to wait for a visibility of an element. The thing is that visibilty of element checks the presence of an element on the DOM, that will return true but in my system the page is not fully loaded yet. What happens is that as soon as I get true when checking the visibility of element I set values. These values get reset when the actual page get fully loaded.
My question is what can I use instead of static sleeps to wait for the actual page (not only the DOM) to get fully loaded as visibility of element is not working for me?
P.S. I'm using Selenium webdriver with python 2.7
/Adam

A: The expected_conditions.visibility_of_element_located(locator) method will check for both - the presence of the element in the DOM, and its visibility (element is displayed with height and width greater than zero).
Ideally, the driver.get(url) method should automatically wait for the full page to be loaded before moving on to the next line. However, this might not behave as expected, in case, the web application being tested uses ajax calls/actions (as although the page has loaded but the ajax actions are still in progress). In such scenario, we can use something like below to wait for stability before performing action(s) on the desired webelements.
# create the firefox driver
driver = webdriver.Firefox()

# navigate to the app url
driver.get('http://www.google.com')

# keep a watch on jQuery 'active' attribute
WebDriverWait(driver, 10).until(lambda s: s.execute_script("return jQuery.active == 0"))

# page should be stable enough now, and we can perform desired actions
elem = WebDriverWait(driver, 10).until(expected_conditions.visibility_of_element_located((By.ID, 'id')))

elem.send_keys('some text')

Hope this helps..

A: Try ExpectedConditions.elementToBeClickable.
See: https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/ExpectedConditions.html#elementToBeClickable-org.openqa.selenium.By-


text:
Q: How to model a profile picture type of field in user entity in domain driven design? I am developing an application with DDD approach where user is one of the entities.
User entity has the following fields / properties :
public class User : BaseEntity
{
   public FirstName FirstName {get; set;}
   public LastName LastName {get; set;}
   public EmailAddress EmailAddress {get; set;}
   public Password Password {get; set;}
   public Role Role {get; set;}
   public ??? ProfilePicture {get; set;}
}

FirstName, LastName, EmailAddress, etc are all value objects.
There is a registration api using which the profile picture is being uploaded as IFormFile in a multi-part form request.
Q1. What is the proper data type for ProfilePicture?
Q2. Should I create a value object representing the profile picture image? If yes, please suggest how to convert IFormFile to that value object?
If there is a standard way to approach such a case please let me know

A: My suggestion
1- create Picture Class
public class Picture {
 //the type of image like (JPG,PING)
 public string Type {get; set;}
 //the actual data for the image
 public byte[] ImageData {get; set;}
}

2- read data from IFormFile where file is IFormFile
        //Create new object of picture
        Picture p = new Picture();

        //Set the Type of image file
        p.Type = file.ContentType;

        //Set the Image to an empty byte[] with the same length of file
        p.ImageData = new byte[file.Length];

        //Read the file through the stream
        using (var stream = file.OpenReadStream())
        {
            stream.Read(p.ImageData);
        }

A: For how to convert a file to byte array:
public class Picture
{
    public byte[] ImageData { get; set; }
}

Picture p = new Picture();
var filePath = @"wwwroot\image\image1.PNG";
var file = new FileStream(filePath, FileMode.Open);
var memoryStream = new MemoryStream();

file.CopyTo(memoryStream);

p.ImageData = memoryStream.ToArray();

A: I think you need add , edit , delete Picture using URL right ?
1- Create Image Controller
[Route("image")]
public class ImageController : Controller
{
    [Route("image/get/{UserID}")]
    public FileContentResult Index(int UserID)
    {
        //write your way get the user from database
        var user = _repositroy.Users(UserID);

        //Check if User is exist
        if (user != null)
        {
            //Check if has a profile image
            if (user.ProfilePicture.ImageData != null)
            {
                //Return File type
                return File(user.ProfilePicture.ImageData, user.ProfilePicture.Type);
            }
            else
            {
                return null;
            }
        }
        else
        {
            return null;
        }
    }

    [Route("image/edit/{UserID}")]
    public FileContentResult Edit(int UserID , IFormFile NewImage)
    {
        //write your way get the user from database
        var user = _repositroy.Users(UserID);

        //Create new object of picture
        Picture picture = new Picture();

        //Set the Type of image file
        picture.Type = NewImage.ContentType;

        //Set the Image to an empty byte[] with the same length of file
        picture.ImageData = new byte[NewImage.Length];

        //Read the file through the stream
        using (var stream = NewImage.OpenReadStream())
        {
            stream.Read(picture.ImageData);
        }

        //Updae the user with the new image
        user.ProfilePicture = picture;

        //if you like to return the new image
        return File(picture.ImageData, picture.Type);
    }

    [Route("image/delete/{UserID}")]
    public IActionResult Delete(int UserID)
    {
        //write your way get the user from database
        var user = _repositroy.Users(UserID);

        //Delete the image
        user.ProfilePicture = null; //or empty it

        //return what you like
    }
}

3- the api is
https://localhost:5500/image/get/1234 for get image
https://localhost:5500/image/edit/1234 for edit image
https://localhost:5500/image/delete/1234 for delete image


text:
Q: Passing string containing an Html.ActionLink to a view from a controller In my controller I have a string containing C#, something like
 viewModel.Message = 'blah blah <%=Html.ActionLink("","","")%> blah';

and in the corresponding view I have tried

*

*Model.Message

*@Html.Raw(Model.Message)
to get it to display correctly, with no luck - any ideas?

A: You'd have to create an instance of HtmlHelper in your controller for that, and have your message set to
viewModel.Message = "blah blah" + htmlHelper.ActionLink("","","") + " blah";

But do you really want your controller to be concerned with things like rendering HTML links? If you cannot delegate the task to the View entirely, how about just setting a Url property? You are able to access Url.Action("","") from your controller.

A: Could you just call ActionLink in the controller  and add the result top your string -
viewModel.Message = "blah blah " + Html.ActionLink("","","") + " blah";


text:
Q: How to send actions directly to input event? I have a touch screen with events at /dev/input/event12 and /dev/input/event13. /dev/input/event12 is the main touch input, and in essence, I'd like to send instructions to the event directly to control behavior (ie, click location etc).
Tools like xdotool do not want to work because this device is being set as a second pointer (see: https://dwm.suckless.org/multi-pointer/) and the recommendation of using xinput set-cp <window> <master> does not appear to work as expected.

A: A solution was found using Python and Python-evdev. Using evdev you can assign the device and pass parameters within the allowed functions. In my case it is as follows:
device.write(e.EV_KEY, e.BTN_TOUCH, 1)
device.write(e.EV_KEY, e.BTN_TOUCH, 0)
device.write(e.EV_SYN, 0, 0)


text:
Q: Userstyle Overwrite HTML Attribute I have been working on a CSS style sheet for userstyles.org. I have ran into an issue where there are some HTML attributes that need to be overwritten but I have not been able to figure out how to with CSS.
I have tried to do div[style="text-shadow"] and others.
Here is the code in question

         Live Preview

a

I am trying to overwrite the text-shadow attribute in this case.

A: Just add the attributes you want to overide, e.g.
div[style] {
   text-shadow: none !important;
   }


text:
Q: PHP PayPal Adaptive Payments - Chained Payments I have been searching online for an easy to follow tutorial/guide on how to use PayPal Chained Payments. I would really appreciate it if someone could point me in the right direction for finding out how to use this API.
I have read the documentation on PayPal and it is not very helpful or clear. I would really appreciate it if someone could help me out with this as I cannot find a clear and conclusive tutorial on how to use chained payments.
Any help would be greatly appreciated!
Best regards, Harry

A: While I'm not fan of link only answers, PayPal does have their Adaptive Payments developer page here. Chained payments are a subset of Adaptive (something I wish they made clearer).

A: I'm a big fan of copy-paste goodies, and I found out that PayPal blessed us with this nice tool that show us the basic pay call. Enjoy ;)


text:
Q: Translate automatically text inside a code file I have been looking for a while, and the thing is, I need to translate specific text inside a code, he sent it to me in Russian, and I wanted to know if there is a way, to translate the full file, but only translating the Russian parts. For example here.
AddInstructionalStart();
AddInstructionalButton("Следующий режим", 197);
AddInstructionalButton("Предыдущий режим", 196);
AddInstructionalButton("Управление объектом", 194);
AddInstructionalButton("Управление объектом", 195);
AddInstructionalButtonCustom("Увеличить скорость", "t_+");
AddInstructionalButtonCustom("Уменьшить скорость", "t_-");
AddInstructionalButtonCustom("Установить", "t_Y");
AddInstructionalButtonCustom("Отмена", "t_N");
AddInstructionalEnd(1);

Is there an automatic way to do it? Or just suck it up and do it manually?
Thanks!!

A: Code like this should be rewritten to put any translatable string in one or more separate files. Most often .resx files. That way you can just send the files to a translation agency, and there are various tools that help with translation, If you search a bit you should find some that allow automatic translation with the help of online translation services.
Some refactoring tools allow you to move a string to a resx-file with a simple command, but they still need to be given a name, and that might be difficult if you have no idea what the text means. And you still need to decide which strings are UI-strings, and which are meant for logging or other purposes, and I do not think there is any automated way to do that.


text:
Q: how to determine the accuracy of a number in vba? How many decimal places does a number have? I need a way to tell how accurate a number is. For example If I had x=3.14, I need to write code that can tell that 3.14 is accurate up to the 1 one-hundreths. Or if I had x= 31300, I would need to know that x was accurate only to the hundreds place?
EDIT: Maybe accurate was a poor choice of word. I'm using a Bisection algorithm to find the root of a polynomial that I've fit to some x,y coordinates. I need to provide an degree of accuracy (DOA) that tells the algorithm when it has gotten close enough to the actual root to stop. So if the data is given as 12.1, I would want my DOA to be +/- 0.01.

A: Numbers have various representation in computing, and non-integer numbers are either represented with floating points or fixed points.
Unfortunately, there is no native fixed-point type in VBA.
For Single and Double, VBA uses IEEE 754-1985, which uses a base 2 exponent for its internal representation. Therefore, 0.01 for example cannot have an exact value (but VBA hides it from you)
Debug.Print 0.1 * 0.1 = 0.01 ' Prints False

There is another type called Decimal with a base 10 exponent.
Unfortunately you cannot declare a variable of Decimal type, you need to use a Variant.
CDec can be used to convert a String, Integer, Double, etc.., to a Decimal
Debug.Print CDec(0.1) * CDec(0.1) = CDec(0.01) ' Prints True

We know that for Decimal the precision is up to 28 digit after decimal. To determine the position of the first non-zero digit, we just need to divide the number by 10 until the rounding happens
Function ndec(n As Variant) As Variant
    Dim n1 As Variant
    Dim n2 As Variant
    Dim i As Long

    n1 = CDec(n)
    n2 = n1

    If n1 = 0 Then
        ndec = CDec(0)
        Exit Function
    End If

    Do
        n1 = CDec(n1 / 10)
        i = i + 1
    Loop While CDec((n1 * 10 ^ (i Mod 28)) * 10 ^ (i - i Mod 28)) = n2 ' it should be CDec(n1 * 10 ^ i) = n2 but 10^i overflows when i > 28 so we split the operation

    ndec = CDec(10 ^ (i - 29))
End Function

Usage :
ndec(1.34) ' returns 0.01
ndec(12340) ' returns 10

Additionnal information
You need to be very careful though with the precision of floating points as 2 numbers can have the same representation:
Sub test()
    Dim i1 As Long, i2 As Long: i1 = 16777221: i2 = 16777220
    Dim f1 As Single, f2 As Single: f1 = 16777221: f2 = 16777220
    Dim d1 As Double, d2 As Double: d1 = 16777221: d2 = 16777220

    Debug.Print "Integer soustraction : " & i1 - i2 ' printf 1
    Debug.Print "Single soustraction : " & f1 - f2 ' printf 0
    Debug.Print "Double soustraction : " & d1 - d2 ' printf 1
End Sub

More information:
What Every Computer Scientist Should Know About Floating-Point Arithmetic

A: A simpler solution is to use the WorksheetFunction.Round(arg1, arg2).
arg1 is the number to evaluate;
arg2 is the rounding accuracy; positive for right of the decimal, negative for left of the decimal.
Let your algorithm evaluate arg1 (not rounded) and return a new result, arg3(not rounded).  Then compare the rounded algorithm result (arg3), with the rounded original (arg1), using the precision you want (arg2)
The line of code you need for the comparison is

If WorksheetFunction.Round(arg1, arg2) = WorksheetFunction.Round(arg3, arg2) Then
'your next steps here

You can see the effect of the Round function with the code below which passes arg1, increments it to arg3, then compares the rounded arg1 and arg3 values

Public Sub test()

Dim arg1 As Double
Dim arg3 As Double
Dim arg2rounded
Dim arg3rounded

arg1 = 1652.23564
Do While 1 = 1
    arg3 = AlgResult(arg1) 'send a value to your algorithm routine
    Debug.Print "arg1 not rounded = " & arg1 & "  arg3 not rounded = " & arg3
    For arg2 = -4 To 4 'loop through presicion to see effect
        arg1rounded = WorksheetFunction.Round(arg1, arg2)
        arg3rounded = WorksheetFunction.Round(arg3, arg2)
        If arg1rounded = arg3rounded  Then
            Debug.Print arg1rounded & " = " & arg3rounded & " at desired precision of " & arg2
            Else: Debug.Print arg1rounded & " <> " & arg3rounded & " at desired precision of " & arg2
        End If
    Next
    arg1 = arg3
Loop
End Sub

Public Function AlgResult(EvalNum As Double) As Double

    AlgResult = EvalNum + 0.5

End Function

A: B = A / (Left(A, InStr(1, A, ",") - 1) & Mid(A, InStr(1, A, ",") + 1, 30))
or
B = A / Replace(A, ",", "")


text:
Q: Checklist after submitting my app to App Store for reviewing After submitting my app to App Store for reviewing, is there anything that I need to be ready before final approval? And also, would the app be immediately available for downloading once it's approved, can I "reserve" a couple days in between to cleanup/reset the backend database?

A: No, that's it - once it is submitted it is out on its own.
You can set to be immediately available or you can specify the date and release it yourself.

A: 1) Sign in to ITunes Connect
2) Go to Manage Your Application Section.
3) Click on your app.
4) On the top right you will see a section For Price and Release.
There you can set the release date for your app to the app store after review..
There is no need to be ready for anything else before final approval..
Good luck with your app :D


text:
Q: SDWebImage insane memory growth, high virtual memory? High dirty memory size. Video Attached I'm having issues with a very content rich app I'm developing. I'm using SDWebImage for caching and loading images asynchronously to my UIImageViews and UIButtons where applicable. Within this app I have content feeds which are collections views of 3 columns wide of pictures loaded from a server URL.
As I scroll, memory builds up like crazy but does clear itself when it needs to as is the expected behavior of SDWebImage. However, this application is a tabbed application, so if I scroll through one feed partially, switch tabs and scroll through a feed on another tab - memory just builds and is not getting cleared.
The first issue here that I do know is that the image size are very big and being scaled down inside the app rather than being downloaded in the right size of 100x100 PX, instead they are 640x640 px. This is obviously going to be fixed as each image needs multiple sizes for various displays throughout the app, and this will lessen the speed of the growth of the VM, but I don't believe it will solve the underlying issue of memory eventually getting to the point of crashing the app while navigating through different pages.
I notice apps like Wanelo and Path and Facebook all have infinite feeds with massive amounts of content that can scroll and load indefinitely without any noticeable loss in performance of crashes, how are they doing this?
I've also included a video with annotations of me profiling the my application with the allocations template in instruments. I can read the info OK, but I'm not sure if there's something I'm missing as far as allocations / call stack / etc goes that could possibly lead me in the right direction of solving this.
Video of profiling available here: http://youtu.be/J4zici41TMs

A: If you see SDWebImage is the most optimized way of loading images asynchronously. You said you are working on tab based app and at some point your app crashes.
basically SDwebImage downloads the images and keeps them in cache memory (to speed up) and saves images locally. Whenever you move from one tab to another you can clear the cache forcely. This may help you.
try the below code when ever you are switching to a different tab.
[[[SDWebImageManager sharedManager] imageCache] clearMemory];

Also in order to know other caching apis you can check this. I will always prefer SDWebImage as its really good and fast. link.
Hope this will help you. Happy coding :)


text:
Q: "Content-Length" header not included in response from service worker fetch I'm fetching static assets (images, pdfs, etc) from AWS S3 and displaying their download progresses to the client using the service worker api. To do this, I'm reading the "content-length" header in the response. In Chrome Canary (77.0.3821.0) this works fine, but in Firefox (version 67.0) and Chrome (version 75.0.3770.80) there is no "content-length" header in the response.
This answer on SO was helpful in setting the request.mode to "cors" which provided me with some initial success, but so far this only seems to work in Chrome Canary.
function respondWithProgressMonitor(clientId, response) {
  for (const key of response.headers.keys()) {
    console.log(key); // returns only "content-type" and "last-modified" on chrome and firefox, but in Chrome Canary includes "content-length"
  }

  const contentLength = response.headers.get('content-length');

  // ...
}
function fetchWithProgressMonitor(event) {
  const request = new Request(event.request.clone(), {
    mode: 'cors',
    credentials: 'omit',
  });
  return fetch(request).then(response => respondWithProgressMonitor(event.clientId, response));
}

My S3 bucket CORS configuration rules should be exposing the header unless I'm doing something wrong.
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
  <CORSRule>

    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>HEAD</AllowedMethod>
    <AllowedHeader>*</AllowedHeader>
    <ExposeHeader>Content-Length</ExposeHeader>
  </CORSRule>
</CORSConfiguration>

I'm not sure why the content-length header is exposed in the Canary response but not in the current Chrome release or Firefox. Are there some other options I need to include in my request to get back a "content-length" header in the response? Any insights or threads to follow are much appreciated.

A: Not an answer but rather a workaround... Put the content size in another header. Create something like 'x-content-length-visible' for the header name, which probably won't be a name guarded from the serviceworker.


text:
Q: Why Viewbag not show in asp.net mvc view page? I'm beginner in asp.net mvc,write this java script code for fetch any data from controller:
 $.ajax({
    url: '@Url.Action("CallService", "MyScore")',
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: {
        'id': 29
    },
    success: function(color) {
        //alert(color);
    },
    error: function() {
        alert('Error occured');
    }
});

and write this action in controller:
[HttpGet]
        public ActionResult CallService(string id)
        {

            var idNum = Convert.ToInt32(id);

            string color = idNum.ToString();
            ViewBag.Myfamily = "razzaqi";

            return Json(color, JsonRequestBehavior.AllowGet);
        }

in view page write this code:

 Hello Dear @ViewBag.Myfamily

when i run the project
 Hello Dear @ViewBag.Myfamily
 not show me ,but i think show me this output:
Hello Dear razzaqi

A: You are returning JSON not ViewBag. You need to send the "razzaqi" to as part of JSON object.  Set up HTML as

 Hello Dear

Modify You controller to return myfamily as part of JSON object.
[HttpGet]
public ActionResult CallService(int id)
{
    string color = id.ToString();

    return Json(new {
        color = color
        myfamily = "razzaqi"
    }, JsonRequestBehavior.AllowGet);
}

Consume the result like
$.ajax({
    url: '@Url.Action("CallService", "MyScore")',
    type: 'GET',
    dataType: 'json',
    cache: false,
    data: { 'id': 29 },
    success: function (data) {
        $('#familyname').text(data.myfamily)
    },
    error: function () {
        alert('Error occured');
    }
});

A: The Viewbag object is filled into the view, server side when making the view. Your ajax call contacts the server asking about Json data after the view is already made.
So you are too late passing objects to your viewbag if you do it this way...

There are however some workarounds/solutions for this problem:

*

*Let the Controller return the variable in the Json it's returning.

*

*Simple, efficient way to get the data you need

*Html helpers etc. Won't work however and sometimes you just need that horrible viewbag...

*Reload a partialview when doing the ajax call.

*

*Takes more time to implement, You'll have to create a new action and partialview.

*Good when you want more content to change on the call and want to use html helpers etc.


text:
Q: DICOM slicing orders in python I have a question about slices ordering:
I have about 80 pictures of hip joint but there are not arranged from feet to head or head to feet.
Is there any way to arrange them in an intended order?
# pixel aspects, assuming all slices are the same
ps = slices[0].PixelSpacing
ss = slices[0].SliceThickness

ax_aspect = ps[1]/ps[0]
sag_aspect = ps[1]/ss
cor_aspect = ss/ps[0]

# create 3D array
img_shape = list(slices[0].pixel_array.shape)
img_shape.append(len(ct_images))
print(img_shape)

img3d = np.zeros(img_shape)

# fill 3D array with the images from the files
for i, s in enumerate(slices):
    img2d = s.pixel_array
    img3d[:, :, i] = img2d

# plot 3 orthogonal slices
a1 = plt.subplot(2,2,1)
plt.imshow(img3d[:,:,img_shape[2]//2])
a1.set_aspect(ax_aspect)

a2 = plt.subplot(2,2,3)
plt.imshow(img3d[:,img_shape[1]//2,:])
a2.set_aspect(sag_aspect)

a3 = plt.subplot(2,2,2)
plt.imshow(img3d[img_shape[0]//2,:,:].T)
a3.set_aspect(cor_aspect)

plt.show()

SOP Class UID is CT Image Storage.
This is the code and These are the pictures of results.

A: slices = sorted(slices, key=lambda x: x.ImagePositionPatient[2]) is probably what you want, depending on what your SOP Class UID is.


text:
Q: MVC model values not getting passed to controller I am trying out with very basic MVC project using MVC 3.0 and Razor. Referring the turorial at this link.
I have created a strongly typed view for editing the Contacts using my model class called "Contact".
namespace Practice.Models
{
    public class Contact
    {
        public string firstName;
        public string lastName;
        public string mobileNumber;
    }
}

The "Index" method displays all the contacts using a list type view. When I click on "Edit" link against a contact, it displays the contact details in textboxes using an Edit View.
However, when I submit the Edit form, I am not getting the model values in controller action method. It shows null for each property. What exactly I may be missing here in such simple example?
DirectoryController
[HttpPost]
public ViewResult Edit(Contact model)
{
    contactRepository.Update(model);
    return View("Details", model);
}

View
@model Practice.Models.Contact
@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm("Edit","Directory"))
{
@Html.ValidationSummary(true)
<fieldset>
    <legend>Contact</legend>
    @Html.TextBoxFor(m => m.firstName)
    @Html.TextBoxFor(m => m.lastName)
    @Html.TextBoxFor(m => m.mobileNumber)

        <input type="submit" value="Save" />

</fieldset>
}

    @Html.ActionLink("Back to List", "Index")

A: You are missing { get; set; } on your model properties


text:
Q: Establishing ~200 WebSocket connections on 2 WebSockets using Node.js and processing this data I need data provided through Binance. This data is provided via 2 different WebSockets, I must access both at the same time. My request is to run the websocket called ticker in the background and process the most recent data on the ticker with the new data on depth each time new data is received via depth websocket.
As a result of my experiments, I learned that websockets do not cause connection problems, so we do not have ratelimit problems. Also I need to establish ~200 connections on each WebSocket. So on average, 2*200 websocket connections will be established. The same type of data should be returned on the ticker and depth websockets.
In short, I have 2 websockets and hundreds of connections, I need data coming from 2 websockets for the same type of connections.
Example of list of items (symbols) to link to:
{
 "dataJson": [
  "BTCUSDT",
  "BTCBUSD",
  "ETHUSDT",
  "ETHBUSD"
 ]
}

The following WebSocket.js file is linked to the app.js main file.
const WebSocket = require("ws")

const {dataJson} = require('data.json');

module.exports = (data, wss) => {
  for (const symbol of dataJson ) {
    try {

      const tickerWS = new WebSocket("wss://fstream.binance.com/ws/" + symbol.toLowerCase() + "@ticker");
      tickerWS.on("message", tickerData => {
        const tickerJsonData = JSON.parse(tickerData)
      });

      const depthWS = new WebSocket("wss://fstream.binance.com/ws/" + symbol.toLowerCase() + "@depth5@0ms");
      depthWS.on("message", depthData => {
        const depthJsonData = JSON.parse(depthData)
      });

    } catch (e) { console.error("Error!", e) }
  }
}


text:
Q: Click event nested span I´m trying to get the text with a click-event of some nested spans in an order closest to widest below my specific span 'annotation-container'. With my current code I get only the text of the clicked span. I need the text of every span below the span 'annotation-container'. After every text, I have to fire a function. Thank you for your hints.
Example 1 - click on 'test' (lowest level of nested span):
1st iteration text: This is a test (highest level of nested spans)
2nd text: a test (next lower level...)
3rd text: test (clicked span)

$('body').on('click', 'span.annotation', function(e) {
  var text = $(e.target).closest('span').text();;
  console.log(text);
  e.preventDefault();
});

              This is
                   a
                       test

              One more
                   great
                        test
                            !

A: Use e.stopPropagation() instead of e.preventDefault() to stop event bubbeling. And possible this instead of e.target.
And notice that you closed the span after great in your initial example:
great
And why do you set your selector to body if you have a .annotation-container? It would be mutch nicer to use this.

$('.annotation-container .annotation').on('click', function(e) {
  $($(this).parentsUntil('.annotation-container > .annotation').get().reverse()).each(function() {
    console.log($(this).text());
  });

  console.log($(this).text());
  e.stopPropagation();
});

    This is
      a
        test

    One more
      great
        test
          !


text:
Q: Randomizing an array inside a ng-Repeat I have an array of object which I use ng-repeat to iterate over. However, every object has 2 properties - a country (string) and cities (array). How can I randomize this array of cities on some button click or page refresh. An example:
$scope.package = [{
  country: 'Sweden',
  cities: ['aaa', 'bbb']
}, {
  country: 'Sudan',
  cities: ['yyy', 'zzz']
}]

$scope.showNext = function() {
  // shows next slide but randomize the cities
}

{{pack.country}}

      {{pack.cities}}

<button ng-click="showNext()"> Next Country </button>

NOTE: It's not required that the button do the randomizing. The button just jumps to next country slide but that the cities name should be shuffled every time.

A: You can apply a randomize() function to pick a random city in cities:

{{pack.country}}

    {{randomize(pack)}}

You can try with the following snippet:

function MyCtrl($scope) {
    $scope.package = [
        {country: 'Sweden', cities: ['aaa', 'bbb']},
        {country: 'Sudan', cities: ['yyy', 'zzz']}
    ];

    $scope.randomize = function(country) {
        return country.cities[Math.floor(Math.random() * country.cities.length)];
    }
}

{{pack.country}}

      {{randomize(pack)}}

A: You can use random function for random data and limitTo for only one random city.
Updated:
I have updated snippet, instead of calling random function from page (which will call function every-time when page refreshes), you can call it on page load and when you call next button.

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
  $scope.random = function() {
    return Math.random();
  }
  $scope.package = [{
    country: 'Sweden',
    cities: ['aaa', 'bbb', 'ccc']
  }, {
    country: 'Sudan',
    cities: ['xxx', 'yyy', 'zzz']
  }]

  function generateRandom() {
    angular.forEach($scope.package, function(country) {
      country.random = country.cities[Math.floor(Math.random() * country.cities.length)];
    })
  }
  $scope.showNext = function() {
    generateRandom();
    // shows next slide but randomize the cities
  }
  generateRandom();

}

{{pack.country}}

        {{pack.random}}

    <button ng-click="showNext()"> Next Country </button>


text:
Q: how to align icon inside edittext i want to align icon and text hint inside Edittext. but the icon overlap the left boundry.i want to align it at some distance from left side and the text hint start after a small gap.Here is my code but it is not working properly. For Example like google search option. Please suggest me how to do it. Thanks in advance.
 <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40sp"
        android:layout_marginRight="40sp"
        android:layout_marginTop="10sp"
        android:background="@drawable/round_edittext"
        android:gravity="left"
        android:hint="Mobile Number"
        android:drawableStart="@drawable/mobile_icon">
    </EditText>

A: set android:drawablePadding="5dp" for EditText.

A: use that code
<EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40sp"
        android:layout_marginRight="40sp"
        android:layout_marginTop="10sp"
               android:padding="5dp"
        android:background="@drawable/round_edittext"
        android:gravity="left"
        android:hint="Mobile Number"
        android:drawableStart="@drawable/mobile_icon">
    </EditText>


text:
Q: Why didn't I get notified when I got unaccepted? I got unaccepted for some question (I know this as I had 1360 rep yesterday night, and now I have 1345). According to Notification when my answer is unaccepted? I should've been notified, but I didn't. I searched through most of my history, and yet I can still not find it.
Why is this?

A: No, they are not supposed to create an inbox notification.
They are, however, recorded on your reputation page for the day.
What I suspect did happen, however is that someone accepted then immediately unaccepted an answer. You will not see this removal reflected on the top bar, but at the same time since the time between the accept/unaccept was short either of these will not be recorded in the history.

A: Well, it happened in this question, see its timeline:

Nick said here:

Starting with the next build, this will show in your reputation history, shown as a -15 on the day it occurs (except if it's re-accepted in the same day)

So apparently it's two-way, meaning that if it was accepted then unaccepted in the same day you won't see it in the reputation history. Not sure if it's a bug or not but your case is proof enough it does happen.


text:
Q: Distributing a CD with MP4 videos We would like to distribute some CDs with MP4 videos and have these wishes:

*

*play in easy form (best idea in web browser)

*codecs included on CD

*video must be able to pause, play. The best way: seek (move in video).

*not using Flash or specific video software!

*playlist

*must be function from Windows XP (slow PC) and higher

Our idea is to ship a portable Firefox with HTML5 support. Is HTML5 video support demanding on computer performance? Would there be any problems with this approach?
(If we go the web browser way, I guess the playlist will be HTML coded myself.)

A: *

*While opening in a browser might work, it will be pretty clunky, awkward looking and a bit confusing.("why are they giving me a browser to play a video?") Additionally, if that computer has its own browser already open, you can't have 2 copies of Firefox running.

*While you can include codecs on such a CD, it is probably not a good idea. You did not describe what type of audience will be using these CDs, but installing codecs almost always requires administrator privileges. If this is a business environment chances are pretty high that your users will not be able to install these codecs without involvement of their IT department, which might be really hesitant installing some random codec that somebody sent them. And then if something happens during that install or at some later point and it will screw up your (potential?) customers' computer, they won't be happy. You might lose business or even worse...

*If your video file is properly encoded, afaik all local video players will give you play/stop/seek ability.

*You can create a playlists or if your CD will have multiple video parts, why not encode them all in a single file.

*Unless such a computer has some sort of accelerated hardware decoding and rendering, your video of 1440x1080@60fps AVC1 will be almost a slide-show on older/slower PCs. Hardware acceleration sometimes works only on 'standard' resolutions. It varies by specific hardware and drivers.
I think your best bet is to actually stream your videos. I don't know how good internet connection in Poland is, but you can have video with progressive bitrate and resolutions. Or have a fixed bitrate and resolution and if viewer's bandwidth is not enough, they will see 'buffering' for a bit. There are services that offer such features using Flash, Silverlight or even html5(like vimeo). If you use streaming, if you suddenly spot some mistake in your videos, you can always reupload corrected file..You can't do that shipped media.
If you still want to ship physical media, don't use CDs/DVDs. They can be damaged, scratched, broken. After watching your CD a few times they will simply forget it or throw it away. A better approach would be to ship a branded USB drive. It might(don't know for sure) cost a bit more, but after they finish watching your videos, they can delete the files and reuse usb drive for something else, while your branding will still be on the drive. :)

A: I have no idea if this will work but you could try installing Portable VLC on the CD and then creating a web page with details of all the videos. Each of these videos would be hyperlinked to a different batch file.
This batch file then plays the correct video using Portable VLC.
If you wanted to be really clever, it could be some VBScript that uses the scripts own filename to determine the correct video to play (eg. video1.vbs plays videos\video1.mp4) and only opens the portable version of VLC if the mp4 file type hasn't been associated with another program.


text:
Q: Makefile does not see my implicit rule I am trying to make worlds simplest (relatively generic) Makefile. I can use to drive a small series of tests to learn C. For some reason, Makefile refuses to understand my implicit rule to make object files form c: %.o: %.c, I get no rule to make target %.o needed by test1.exe. Below is my Makefile in entirety:
INC     = sglib
CC      = gcc
LD      = gcc
LDFLAGS =
# On MS-Windows, say "make os=win" to set proper extensions
os  =
SO  =
EXE =

ifeq ($(os), win)
SO  = dll
EXE = .exe
# -fPIC is a no-op on Windows, but causes a compiler warning
CFLAGS  = -std=gnu99 -ggdb3 -Wall
else
SO  = so
CFLAGS  = -std=gnu99 -ggdb3 -Wall -fPIC
endif

all: test1$(EXE)

test1$(EXE): %.o
    $(LD) $< -o $@

lib-test.$(SO): %.o
    $(LD) -shared $(LDFLAGS) -o $@ $<

%.o: %.c
    $(CC) $(CFLAGS) -I$(INC) -c $< -o $@

check:
    echo Nothing yet!

.PHONY: all clean

clean:
    rm -f *.o *.$(SO) test1$(EXE)

I am using msys on windows 20 with gnu make 4.2.1 and gcc 6.2.0. I am puzzled what is wrong there. it is probably something simple but I seem to be blind at the moment.

A: This:
test1$(EXE): %.o

defines a rule which states that the prerequisite of the target test1 is the file %.o. Not some wildcarded list of object files. Specifically the file named %.o. You have no other rule in your makefile to create that file, and it doesn't currently exist, hence the error that you get.
% only acts as a placeholder in Pattern Rules (and similar functions like patsubst), which are rules where % appears in the target. So your:
%.o : %.cpp
    $(CC) $(CFLAGS) -I$(INC) -c $< -o $@

is a pattern rule, because of the % in %.o. This does not create a rule building the target %.o, but rather any file with suffix .o. This would apply when trying to build target foo.o - we'd create an implicit rule with preqrequiste foo.cpp, with the stem % matching foo.
What you actually want is to wildcard your object files. There's a function for that:
test1$(EXE) : $(wildcard *.o)

But this doesn't actually work either. When you try to build the first time, there aren't any object files that exist yet. Clearly. So $(wildcard *.o) would return an empty string, and you end up with nonsense. So you can't wildcard them. You need to explicitly provide that string:
test1$(EXE) : $(object_files)
    $(LD) $< -o $@

Now we just need to come up with that list:
source_files := $(wildcard *.c)
object_files := $(source_files:.c=.o)

Now if you have source files like foo.c, bar.c, and  baz.c, the $(wildcard) function will find them and set source_files to foo.c bar.c baz.c. The substitution on the next line will set object_files to foo.o bar.o baz.o. So we end up with test depending on those three object files, and you already have a pattern rule to build those object files.

A: You seem to be thinking that in rules like this:
 test1$(EXE): %.o

the % sign is a wildcard character which cause filename expansion - it isn't. If you want to create a list of .o files, you should use the built-in wildcard function.
I have a couple of blog articles on generic makefiles starting at https://latedev.wordpress.com/2014/11/08/generic-makefiles-with-gcc-and-gnu-make/ which may (or may not) be useful.


text:
Q: Function on open disc proof
Prove that a continuous real valued function on an open disc that has a single zero at the center of the disc must be either always positive away from the zero, or always negative

So we have a function $f(x,y)$ defined on $D = \{(x,y):x^2+y^2 <1\}$ where $f(0,0)=0$ is the only zero for our function.
The fact that we are working on a domain on the disc is hindering my advancement. The idea makes intuitive sense, but I am not sure how to show this. I had the idea to perhaps argue proof by contradiction and use the intermediate value theorem, but I am not certain if this applies on the open disc.
Any hints or help appreciated, thank you.

A: Suppose $f(n) < 0 < f(p)$ where $n,p \in D$.
We know that neither $n,p$ are the origin. Let $\gamma$ be a continuous path from $n$ to $p$ that does not pass through $0$. Since $f\circ \gamma ([0,1])$ is connected we must have some $t \in (0,1)$ such that $f(\gamma(t)) = 0$, which is a contradiction.
There are many ways to construct such a path. One way is to start at $n$ and rotate around the origin until one hits the ray from $0$ that passes through $p$ and then
join to $p$ be a straight line.

A: If you remove  the origin from the disk you get a connected set. Continuous image of a connected set is connected. Since the image of the punctured disk is an interval in the real line, if it contains both positive and negative values it would contain $0$ contradicting the hypothesis.


text:
Q: Как проверить наличие некоторых символов в строке? В строке:
{"ID":"53fddc6f-e356-42db-82dc-78e0c3311ece","auth_email":"#fastreg_7f03fc6d092d"}

нужно проверить только наличие
ID, auth_email, #fastreg

Как это можно сделать?
Получается только по отдельности каждое слово, например:
String w = (String) js.executeScript("return sp.getResult()");
CharSequence searchStringResult = "ID";
boolean f = w.contains(searchStringResult);

A: пример поиска символа а будет чтото вроде
bool isContains = ID.toLowerCase().contains("a".toLowerCase())


text:
Q: Array element is maybe not set In this method below I set string smdrext to tmp[3]. However, tmp[3] seems to sometimes be empty because I get "Index was outside the bounds of the array.". Before I set it, can I change that it really exist to make sure the program does not halt again due to this?
public void WriteToCSV(string line, string path)
{

    string[] tmp = line.Split(',');
    string smdrext = tmp[3];

    if (ext.Contains(Convert.ToString(smdrext)))
    {

      File.AppendAllText(path, line + "\n");

    }

}

A: Please try with the below code snippet.
public void WriteToCSV(string line, string path)
{
    if (!string.IsNullOrEmpty(line))
    {
        string[] tmp = line.Split(',');
        if (tmp.Length > 3)
        {
            string smdrext = tmp[3];

            if (ext.Contains(Convert.ToString(smdrext)))
            {
                File.AppendAllText(path, line + "\n");
            }
        }
    }

}

Let me know if any concern.


text:
Q: There are pairs (type_id, element_id), like (1,1), (1,2), .. (5,3). How to exclude type_id from result if I need to get type ids without element_id 1? I have the next table x:
id | type_id | element_id
-------------------------
1  |    1    |     1
2  |    1    |     2
3  |    1    |     3
4  |    2    |     1
5  |    3    |     1
6  |    4    |     2
7  |    5    |     3

I need to get all type ids which meet condition element_id != 1, in other words how to get the next type_ids: [4, 5]?
If I simply do SELECT type_id FROM x WHERE element_id != 1, I receive [1, 1, 4, 5].

A: You can try to use the condition aggregate function in HAVING which didn't contain any element_id = 1 from type_id
SELECT type_id
FROM x
GROUP BY type_id
HAVING COUNT(CASE WHEN element_id = 1 THEN 1 END) = 0

sqlfiddle
Or using filter clause with aggregate function
SELECT type_id
FROM x
GROUP BY type_id
HAVING COUNT(*) FILTER (WHERE element_id = 1 ) = 0


text:
Q: Is this a good design for a table? Each user/person could know one or more languages.
All I can think is a table like
+----------+------+-----+------------+-----+-----+-----+-------+
| PersonID | Java | PHP | Javascript | C++ |  C  | CSS | HTML  |
+----------+------+-----+------------+-----+-----+-----+-------+
|        1 | Yes  | Yes | No         | Yes | No  | Yes | No    |
|        2 | No   | Yes | Yes        | No  | Yes | No  | No    |
|        3 | Yes  | No  | Yes        | Yes | Yes | Yes | No    |
+----------+------+-----+------------+-----+-----+-----+-------+

Considering I'm going to need at least 100 columns for all the languages, is it normal to have that many columns? Something tells me this is the wrong approach.
Thank you very much and sorry about my english!

A: I would suggest you to create three tables.
One table contains the information of the Person like his Name etc.
Second table contains two columns LanguageId and Language name.
+------------+-----------+
| LanguageID | Name      |
+------------+-----------+
| 1          | Javascript|
| 2          | C         |
| 3          | C++       |
+------------+-----------+

Third table contains the Id, PersonId, LanguageID. In this table you can join the above two tables record.
+---+----------+------------+
|ID | PersonID | LanguageID |
+---+----------+------------+
|1  |        1 | 1          |
|2  |        2 | 2          |
|3  |        3 | 3          |
+---+----------+------------+

Reasons to support my answer:

*

*In future if you want to add any new language in your table then it
would be easier to add that in the main table.

*You can join the two tables easily and get the result

A: A little improvement we can do over Rahul Tripathi response is to remove the "Known" column. You need only two tables for this case. One containing PersonId and LanguageId the person knows. The second table is for the languages only.
You know what languages one person knows by joining both tables. For example if you need to know the list of known languages you can do:
SELECT p.PersonId, l.Name
FROM Person p INNER JOIN Language l ON (p.LanguageId = l.LanguageId)
WHERE (p.PersonId = theIdYouNeedToKnow)


text:
Q: Databricks streaming "A file referenced in the transaction log cannot be found" So whenever i am trying to read from a source with stream i get this error "A file referenced in the transaction log cannot be found" and it points to a file that does not exist.
I have tried:

*

*Changing the checkpoint location

*Changing the start location

*Running "spark._jvm.com.databricks.sql.transaction.tahoe.DeltaLog.clearCache()"

Is there anything else i could do?
Thanks in advance guys n girls!

A: So! I had another stream that was running and it had the same parent directory as this stream.. this seems to have been a issue.
First stream was looking in:  .start("/mnt/dev_stream/first_stream")
Second stream was looking in: .start("/mnt/dev_stream/second_stream")
Editing the second stream to look in .start("/mnt/new_dev_stream/new_second_stream") fixed this issue!


text: Q: Immersive reader deactivate javascript Can we deactivate or prevent the immersive reader from Edge browser using Javascript? For instance, for an article on our website, we would like to disable immersive reader mode.