text:
Q: Navigating IE Dynamic Drop Down Boxes with VBA (Excel) I'm currently working on a project to automate some data collection that's currently being done manually.
The data is collected from a website with a simple ctrl + a -> ctrl + c -> ctrl + v series of commands to paste it into an excel document. I've already done a lot of work to automate validations via Excel, but I've run into a hiccup trying to automate the data collection.
At this point I can open up IE, navigate to the webpage, login and then open the correct page from there. My issue is that there are then 6 drop down menus that must be filled before the data can be pulled. Three of the menus are no issue as they have set variables; the issue is with the other three which contain dynamic lists. Here is some of the source code for these menus:
*other menus*
                         FG BA:

                        <select name="CAId" onchange="ChangeFG(); return false;" class="blacksmallnormal">
                            <option value='-1'>Please wait...</option>
                        </select>

*other menus*

Now, I have basically zero experience with website code (html? java? no clue) and honestly only a few weeks with VBA, so I have pretty much no clue what this means. I tried to grab what's relevant but there's a lot of code. I'm guessing that it has something to do with this function, though:
    function ChangeFG()
{
    var objSC = document.getElementById("SCId");
    var objCA = document.getElementById("CAId");

    if (objSC && objCA) {
        var Arr = new Array();
        Arr["SC"] = objSC[objSC.selectedIndex].value;
        Arr["CA"] = objCA[objCA.selectedIndex].value;
        if(Arr["CA"] == "-1")
        {
            alert("Please choose BA");
            return;
        }
        Arr["GetJustFG"] = 1;
        UpdateJustDropDown("<option value='-1'>Please wait...</option>", "FG");
        var url = ".....";
        SendAJAXCommand('UPDT_FLG', url, UpdateFGWithData, "FG", true, Arr);
    }

First, I have no clue how to view the dynamic lists for these menus aside from clicking on them myself; I'm not sure how to determine which is the option I need. Secondly, when I have just stuck a value in for the list the menu ends up blank.
Here is some code of what I've been trying:
Private Sub RetrieveData_Click()

Dim appIE As Object
Dim website As String
Dim UsNa As Object
Dim PsWd As Object
Dim ElementCol As Object
Dim btnInput As Object

Application.ScreenUpdating = False

Set appIE = CreateObject("internetexplorer.application")
appIE.Visible = True

website = "https://www...."

With appIE
    .Navigate website
    .Visible = True
End With

Do While appIE.Busy
Loop

*Login here*

'navigate to actual page to get data from
appIE.Navigate ("https://www...")

Do While appIE.Busy
Loop

DoEvents

Set ElementCol = appIE.Document.getElementsByTagName("select")

For Each btnInput In ElementCol
    If btnInput.Name = "SCId" Then
        btnInput.Value = "8"
        Exit For
    End If
Next

Do While appIE.Busy
Loop

Set ElementCol = appIE.Document.getElementsByTagName("select")

For Each btnInput In ElementCol
    If btnInput.Name = "Direction" Then
        btnInput.Value = "0"
    Exit For
    End If
Next

Do While appIE.Busy
Loop

For Each btnInput In ElementCol
    If btnInput.Name = "FG" Then
        btnInput.FireEvent ("onChange")
        btnInput.Value = "6009"
    Exit For
    End If
Next

I know it's messy code and whatnot; the plan is to clean it up after I figure out how to make it work. It's certainly gotten messier as I kept iterating on this issue.
Anyway, any insight on how to make this work would be greatly appreciated!


text:
Q: Mocking azure blob storage in unit tests Is there anyway I can mock azure blob storage without running the storage emulator?It would be of great help if someone could shed some light on this

A: you can use Microsoft fakes, its simple and easy a free alternative for typemock

A: The Storage Library doesn't have an interface to use for mocking, so if you wanted to really mock this out I think you have two options:

*

*Create an interface yourself and hide the interaction with the storage library behind a class of your own.  Then use your interface for the mocked tests.  This is something I've done a lot of in the past, trying to abstract the use of the storage library away from the rest of the app.  Of course, you can do this abstraction in your own code, or the storage library is out on GitHub.  You could fork it and start adding interfaces to make the mocking easier.  I think you'd have less work to just create an interface in your own code and a concrete implementation that did the necessary work to interact with the storage sub system for the things specific to your scenarios.

*Use a mocking framework that is capable of interception and can mock out types without interfaces.  Something like TypeMock.  There are others out there as well, both free and commercial.

A: It's very easy to mock final things out in case you have Lombok on your classpath. Just extract whatever signatures you need from the azure blob client class to an interface, create a proxy class that delegates to the real azure client, and use the interface throughout our code. This way you can create mocks of the interface and have a little glue code that does not interfere with code coverage since lombok marks code as @Generated.
Here's how:
public interface AzureStorage {

  Mono<Boolean> exists();

  Mono<Void> delete();

  Mono<Response<BlockBlobItem>> uploadWithResponse(BlobParallelUploadOptions options);

  Mono<BlobDownloadAsyncResponse> downloadWithResponse(BlobRange range, DownloadRetryOptions options,
        BlobRequestConditions requestConditions, boolean getRangeContentMd5);
}

These are the methods we use in our project. And here's a class that implements the interface and delegates everything to the real azure blob client:
@lombok.Value
static class AzureStorageDelegate implements AzureStorage {

    @Delegate
    BlobAsyncClient client;

}

Now you can either mock the AzureStorageDelegate with Mockito or inject a mock AzureStorage wherever you see fit.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access file stream of different web application using absolute URL using Server side object model I have below code running on site http://url:94 on 94 port and I want to read the fileStream using openBinrayStream where file is kept on another site running on 92 port, even though I am giving the site url to spsite object it fails to access the file, and error is  Cannot open file filename
using (SPSite prSiteObj = new SPSite(http://url:92))
                            {
                                using (SPWeb prweb = prSiteObj.OpenWeb())
                                {
                                    SPFile file = prweb.GetFile(http://url:92/pathtofile.pdf);
                                    Stream contentStream = file.OpenBinaryStream();
                                    var attachment = new MailAttachment(contentStream, file.Name);
                                    email.Attachments.Add(attachment);
                                    emailAttachmentLogBuilder.Append(file.Name + "|");

                                }
                            }

Is there any way to read file stream of file kept on different web application.

A: Okay, the mistake which I was doing is ignoring the URL after the port number, indeed the file was on different web application but it was in a subsite of the different web application.
I had to modify the code slightly, like a below one.
using (SPSite prSiteObj = new SPSite(http://url:92))
                        {
                            using (SPWeb prweb = prSiteObj.OpenWeb("subsite-name"))
                            {
                                SPFile file = prweb.GetFile(http://url:92/pathtofile.pdf);
                                Stream contentStream = file.OpenBinaryStream();
                                var attachment = new MailAttachment(contentStream, file.Name);
                                email.Attachments.Add(attachment);
                                emailAttachmentLogBuilder.Append(file.Name + "|");

                            }
                        }

Now it's working.


text:
Q: How to increase idle time of "LaunchPad" for SQL Server external scripts? sp_execute_external_script can take a while to initialize when not run for a short time.  How do I set the idle time on the controller Launchpad process to keep it from shutting down too soon?
Note I am not talking about reusing the same Python session as I know each call uses its own session. What I am referring to is that when you execute sp_execute_external_script for a language it takes a while to start up. If you call sp_execute_external_script again in a short time then it runs immediately.  However, if you wait a while and execute it again it takes a while to execute as (I think) the Launchpad controller has reached an idle time and shutdown.  See this article about SQL Server using the Launchpad process to created links to Python, R, and soon Java.
Is there a way to increase this idle time?


text:
Q: AngularJs: Passing search criteria from very large search form to service - create custom model? I have an app with a very large search form (around 45 inputs) and I'm struggling trying to figure out how to best code this up in AngularJS.  I've just begun working with Angular, so this may be obvious, but I'm a bit stumped.  I'm not sure how to pass around the values entered into the form with my service being in an injected factory.
Here's the structure I currently have:
app.js - app module
search.js - search controller
datacontext.js - service factory
search.html - search form view

There is a Search function in the datacontext that runs the search service call:
    function Search(searchForm) {
        var deferred = $q.defer();

        var requestParameters = {
            UserId: 1234,
            IpAddress: '127.0.0.1',
            QuickSearch: true
        };

        var request = {
            SearchParameters: searchForm,
            RequestParameters: requestParameters
        };

        $http.post(url, request)
            .success(function (data, status) {
                deferred.resolve(data);
            })
            .error(function(data, status) {
                deferred.reject(data);
            });
    }

To make that function easier to manage I am just passing in a search object, which contains all of the properties of a search - firstName, lastName, dob, etc.  When I call this function from the search controller, can I just pass in the $scope from the form (i.e. ng-click='RunSearch($scope)')?
One other requirement for this is that I need to count the number of criteria being passed in when the user clicks the search button to prevent searches with no criteria from being run.  Not sure how to implement that in the viewmodel...  Any tips from those who've done this kind of app before that might help point me in the right direction?  Thanks!

A: I think you're on the right path with the search object.  That way when you create your form, you can just bind each field to a property on the search object.
As for passing the scope from the form (i.e. ng-click='RunSearch($scope)'), no, you wouldn't want to do that.  In the view, the "$scope" is implied.  So you would just want to pass in the search object (ng-click='RunSearch(searchObject)') or rely on the fact that RunSearch is in the same controller and so it already has access to the search object by just looking on the scope (ng-click='RunSearch()' with RunSearch() being on the same scope).  It's probably a better practice to pass in the search object.
As for the form validation, I would have the RunSearch function do a traverse of the search object looking for a valid search term.  If none is found, then RunSearch could just set the $invalid flag on the form and then return false.  Then in the view, you could have an error message linked to that invalid flag to tell the user they must enter at least one search term.
Something like this:
<form name="searchform">
  <input ng-model="searchObject.firstName" type="text">
  <input ng-model="searchObject.lastName" type="text">

  <button ng-click="RunSearch(searchObject)">Save</button>
  You must enter at least 1 search term
</form>

In the controller:
$scope.RunSearch = function(searchObject) {
  if(!checkSearchObject(searchObject)) {
    $scope.searchform.$invalid = true;
    return false;
  }
  else performSearch(searchObject)
}


text:
Q: In Yii2 Unable to show custom column from model in gridview Below is the dataprovider query i have used in search function of the UserSearch model, extended from User model. I am trying to show the value of 'entries' in the gridview but unable to access the column 'entries'. Please help.
     $query = User::find()
         ->select("users.Id, users.FirstName, users.LastName, users.EntryId, GROUP_CONCAT(entry.EntryId ORDER BY entry.Id SEPARATOR '<br>') as entries")
         ->join('LEFT OUTER JOIN','entry','entry.CustomerEntryId = users.EntryId')
         ->where(['users.IsActive' =>1])
         ->groupBy('users.Id');

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

User Model code
class User extends \yii\db\ActiveRecord
{
   public $password_repeat;
    public static function tableName()
    {
       return 'users';
    }

     public function rules()
    {
        return [
            [['FirstName','LastName','EmailId','MobileNo','Password','password_repeat'], 'required'],
            ['EmailId', 'email'],
            [['EmailId'], 'unique'],
            ['password_repeat', 'compare', 'compareAttribute'=>'Password', 'message'=>"Passwords don't match",  ],
            ['MobileNo', 'is8NumbersOnly'],
        ];
    }

    public function is8NumbersOnly($attribute)
    {
        if (!preg_match('/^[0-9]{8}$/', $this->$attribute)) {
            $this->addError($attribute, 'must contain exactly 8 digits.');
        }
    }
}

GridView Code
echo GridView::widget([
    'dataProvider'=>$dataProvider,
    'filterModel'=>$searchModel,
    'showPageSummary'=>true,
    'pjax'=>true,
    'striped'=>true,
    ],
    'panel'=>['type'=>'primary', 'heading'=>'Members Report'],
    'columns' => [

          [
            'label'=>'First Name',
            'attribute'=>'FirstName',
            'value'=>'FirstName',
          ],

          [
            'label'=>'Email Id',
            'attribute'=>'EmailId',
            'value'=>'EmailId',
          ],

          [
            'label'=>'Entries',
            'attribute'=>'Entries',
            'value'=>'entries',
          ],

    ],
]);

A: the simple way for manage calculated columns is add  a public var  in your  model class  (User model  in this case)
class User extends \yii\db\ActiveRecord
{
   public $entries

then in you gridview you can simply add  this name the columns
'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        ....
        'entries',
        .....


text:
Q: AngularJS $apply inside scope Is there another approach which could be used to carry out the following?  This jQuery function is used inside the Angular $scope, and it works fine however it throws an $apply error, essentially because it's seen as an $apply inside an $apply. Yet if I remove $scope.$apply() line it stops working.
function myfunction(start, end) {
        // Lots of jQuery code here - omitted from this example

        // Update the scope
        $scope.myf = "abc";
        $scope.myt = "def";
        $scope.$apply();
}

myfunction();

A: Either wrap your code in a $timeout or use $apply(). Note that $timeout is calling  $apply() internally. $apply is specially made to resync external changes (not in angular loop) with angular.
If your function trigger on click or on event. You can bind your function to angular by using the directive ng-click or ng-[event].

A: use $scope.$evalAsync() instead. it would not throw an error and do the same in this case.


text:
Q: как частично преобразовать строковые переменные в списке в числа с плавающей точкой? Есть файл input.txt с таблицей, где первый столбец - дата, остальные проценты с 2 числами после запятой (пример ниже). Подскажите, пожалуйста, как мне получить список следующего содержания:
rates = [
    ['RUB', 'ON', '1D', '2D', '3D', '4D', '5D', '1W', '2W'],
    ['01.01.2020', 1.12, 2.12, 3.12, 4.12, 5.12, 6.12, 7.12, 8.12],
    ['02.01.2020', 1.13, 2.13, 3.13, 4.13, 5.13, 6.13, 7.13, 8.13],
    ['03.01.2020', 1.14, 2.14, 3.14, 4.14, 5.14, 6.14, 7.14, 8.14],
    ['04.01.2020', 1.15, 2.15, 3.15, 4.15, 5.15, 6.15, 7.15, 8.15],
    ['05.01.2020', 1.16, 2.16, 3.16, 4.16, 5.16, 6.16, 7.16, 8.16]
]

где все процентные ставки будут типа float, а все оставшиеся даты и первый список с заголовками останутся строками.
Пример содержимого файла input.txt
RUB         ON      1D      2D      3D      4D      5D      1W      2W

01.01.2020  1,12    2,12    3,12    4,12    5,12    6,12    7,12    8,12

02.01.2020  1,13    2,13    3,13    4,13    5,13    6,13    7,13    8,13

03.01.2020  1,14    2,14    3,14    4,14    5,14    6,14    7,14    8,14

04.01.2020  1,15    2,15    3,15    4,15    5,15    6,15    7,15    8,15

05.01.2020  1,16    2,16    3,16    4,16    5,16    6,16    7,16    8,16

A: import csv

rates  = []
fn = 'input.txt'
with open(fn, newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter='\t')
    rates.append(next(reader, None))
    for row in reader:
        if row:
            rates.append([row[0]] + [float(x.replace(',', '.')) for x in row[1:]])
print(*rates, sep='\n')


text:
Q: Is it actually possible to send some data to remote destination over tcp/ip without any socket? I am studying socket concept. As far as I learned socket is like electrical socket that is created in both end of communicating devices (or processes). Socket can keep itself alive forever to listen some request (this is may be the key concept to make any server program).
However, my curious mind wants to know that is it possible to communicate between two computers without creating any socket (file descriptor) ?
Please help with detail description, I am new in this area.
Thank you in advance!

A: A socket is a standardized programming interface only. In theory one could work directly to the network card (and libraries like DPDK do this) but using the socket API makes it much easier and independent of the specific hardware and network setup.

A: To recieve packets any computer with NIC card, one needs only Layer-2 Mac destination address. Hence Is it actually possible to send some data to remote destination over tcp/ip without any socket?
[Answer] yes, send your packet with the destination MAC address as the desired Computer MAC address. The Packet will be received on the NIC without dropping. This is true if the remote destination is the same LAN or can be reached via the VLAN group or connected peer to peer.
Note: if the question was Is it actually possible to send some data to remote destination (not in the same LAN network) over tcp/ip without any socket?
[Answer] No, if the destination (remote target) is not in your network you can not reach the target machine with just MAC address and/or VLAN.
there are 2 options

*

*if the machines are connected via Layer-2 tunnels like MPLS, VxLAN, PPoP you can encapsulate the original packet (Ethernet MAC + Payload)

*You can use IP or IP encapsualtion, where a router will identify the IP address to MAC conversion and forward through right part making it reach the destination.

note: DPDK, PF_RING, Netmap, XDP are mechanism to bypass Kernel Stack. Using Kernel Bypass you receive or transmit packets from the NIC. But it will depend upon the actual value of L2/L3 where network switch or router will sent or forward packet in network


text: Q: Google Core Reporting API v4 authenticate with services account I'm migrating from Google Core Reporting API v3 to v4. In Google Docs, I can't find a way how to authenticate with a service account token like you can in v3 with Javascript. Is this possible in v4?


text: Q: Не могу разобраться с проблемой отправки сообщений с сайта Обратился в тех.поддержку они подсказали,что проблема в том,что скрипт обращается не по верному пути он ищет файл smart.php в корне,а не в папке домена. А как исправить это ошибку не получается


text:
Q: browser caching express nodejs I'm trying to setup browser caching on my website without any success
There is my code on my server.js file
app.use(function(req, res, next){
res.set({
    Expires: new Date(Date.now() + 2592000000).toUTCString()
});
next();
})

app.use(express.static(path.join(__dirname, '../build/public'),{maxAge:2592000000}));

Whats wrong ?

A: The problem is that maxAge option of express.static use the Cache-Control header.

maxAge: Set the max-age property of the Cache-Control header in milliseconds or a string in ms format.

In the Expires header docs you can find the following:

If there is a Cache-Control header with the "max-age" or "s-maxage" directive in the response, the Expires header is ignored

Therefore, a possible solution is using only the Cache-Control header. Next snippets sets this header inside an express middleware:
app.use((req, res, next) => {
    res.header('Cache-Control', 'max-age=2592000000');
    next();
});


text:
Q: Example of Markov chain modulo $3$ Let $Y_1, Y_2, ...$ be independent identically distributed random variables each taking values in $\{0, 1, 2\}$ with the common distribution $(p_0, p_1, p_2)$.
Let $X_0 = 0$ and define
$$X_{n+1} = X_n + Y_{n+1}  \pmod 3.$$
Then $X_n, n \geq 0$ is a Markov chain with state space $\{0, 1, 2\}$ and transition matrix
$$P = \begin{bmatrix}
p_0 & p_1 & p_2 \\
p_2 & p_0 & p_1 \\
p_1 & p_2 & p_0 \\
\end{bmatrix}
$$
Questions: What is meant by the common distribution?  Why is $P$ the transition matrix?
It appears that the $P(0, 0) = p_0; P(0, 1) = p_1;$ and $P(0, 2) = p_2$. Is this obvious by the common distribution? And why are the other rows calculated in that way?

A: $Y_i$ represents the increment, label $3$ vertices with labels $0$, $1,2$ in clockwise direction. $p_0$ is the probability of being at the same spot, $p_1$ is the probability of moving $1$ step clockwise and $p_2$ is the probability of moving $2$ steps clockwise.
Incrementing by $2$ is equivalent to moving clockwise by $2$ steps, which is also equivalent to moving anti-clockwise by $1$ step. Note that $2 \equiv -1 \pmod{3}$.
Since $p_0$ is the probability of being at the same spot, hence the diagonal entries are $p_0$, and the position to the right (modulo $3$) is $p_1$ and the position to the left of the diagonal (modulo $3$) is $p_2$.


text:
Q: Microsoft dynamics crm learning using azure virtual machines I want to learn basics of dynamics crm 2011 and 2013.
I have MS azure subscription where I do have access to Dynamics CRM virtual machines. These virtual machines have the following flavors for Dynamics CRM
GP 2013 Developer
GP 2013 R12
NAV 2015
GP 2015
Which one of the above 4 virtual machine setup should I use just to learn very basics of Dynamics CRM? Specially the jquery part and some customization.
I am very new at CRM but have lot of back ground in asp.net mvc c# programming.

A: I would use one of the SQL Server images and deploy everything on a single server if you want to test it out. Technically, it is not supported, but for evaluation purposes, this is the cheapest and easiest way.
Here's a tutorial that walks you through the steps for CRM 2013:
http://www.slideshare.net/jukkan/microsoft-dynamics-crm-2013-development-server-installation

A: I would suggest to use trial CRM Online. You can register instance for you using following link - https://www.microsoft.com/en-us/dynamics/crm-free-trial-overview.aspx


text:
Q: Две функции с таймером в рекурсии дают "странный" результат с изменением размера изображения Мне нужно было получить код, который динамически бы менял размер рисунка по нажатию определенной кнопки. В итоге должно было получиться две кнопки "увеличение" и "уменьшение" размера. На каждую кнопку соответственно "вешалась" функция изменения размера рисунка.
Полученный код давал эффект, что при запуске одной функции - размер "рисунка" меняется, но если запустить следом другую - результат "странный", размер не меняется последовательно, а колеблется в рамках указанного изменения в 1 px.
Ниже показан код, который был в последствии изменен и это изменение содержит комментарий.

<!doctype html>

 <title>Картинки</title>

 Растягивание картинки
 Стягивание картинки

A: Обратите внимание на switch. Заверните функции в switch/case и поставьте условие: так вы сможете контролировать вызов функции.


text:
Q: replacing exact or near duplicate names in a dataset with unique names/codes I have daily data with different importer names (more than 100 thousands of observations).
My data set contains more than 100 thousand records and most likely there will be 10,000 importers that occur in the data set multiple times, but with slightly different spelled names.
Does anyone of you have any experience with checking for similarity within the same variable and replace the importer name with one unique name/codes and may I ask what code I should use?
For example
importers <- tibble(V1 = c("3M",
  "3M Company",
  "3M Co",
  "A & R LOGISTICS INC",
  "AR LOGISTICS INC",
  "A & R LOGISTICS LTD",
  "ABB GROUP",
  "ABB LTD",
  "ABB INC"))

I want a column next to V1; as V2 with a unique name/code for the similar names.

A: This may not be satisfactory, but it could give you a start. Most of the solution here is copied from this answer, with some additional explanation.
The hard part is that at some point you have to make a subjective decision about how close two labels should be in order to count as a cluster, and this will be hard to do for a large data set.
First we compute string distances:
s <- importers$V1  ## for brevity
d  <- adist(s)     ## compute Levenshtein distances
dimnames(d) <- list(s,s)

Visualize (obviously impractical for a huge set of names ...)
par(mar=c(6,1,1,6))
heatmap(d,Rowv=NA,Colv=NA,margins=c(12,12))

A human can easily tell that there are three clusters here.  However, there's no easy cutoff in terms of string distance:
par(las=1)
plot(table(d),xlab="string distance",ylab="frequency")

The within-cluster and between-cluster distance distributions overlap ...
Now we do hierarchical clustering:
hc <- hclust(as.dist(d))
plot(hc)
rect.hclust(hc,k=3)  ## select 3 clusters

Once we decide that there are 3 clusters here, the clustering algorithm selects the "correct" elements for each cluster.
Create a new column giving the cluster identity for each row:
importers$code <- cutree(hc,k=3)

As I suggested in comments, it might be better to do this job in OpenRefine: it could be hard to write a reliable, robust, completely automated method for doing this task.
Also: I don't know how badly this will scale to a data set of 10,000 names. Hierarchical clustering is fast, but the distance matrix will be huge (50 million entries), which will take time to compute and space to store.  (There are faster ways to compute Levenshtein distance than the built-in adist() ...)
A few suggestions for making the problem more computationally tractable (although it won't be easy in any case):

*

*you definitely shouldn't try to do the clustering on the full data set. Instead, extract the vector of unique importer names, cluster them, then join (merge) them back with the full data set

*you might be able to do the problem with this (inefficient) batch algorithm:

*

*split the data into subsets of importers (it will probably work best if you alphabetize the vector first); cluster each of these, reduce them to the consensus names within each cluster

*join the subsets and re-cluster


text:
Q: can I get the restaurant name , menus from particular place or city using facebook graph api I am new to Facebook API . how can I get the restaurant name , menus,items,item-images and comments from particular place or city using Facebook graph API like foursquare API. please help me , thanks in advance
I got the access token from Facebook API


text:
Q: How to unmap a insert-key on vim? On vim, command-mode keys can be mapped through the ex command :map <key> <macro> and insert-mode keys can be mapped through :map! <key> <macro>. After mapped, the commands to remove the mapping from the command-mode keys and insert-mode keys are unmap <key> and unmap! <key> respectively.
This works well with command-mode keys, but with insert-mode keys the key expansion also works on the ex command line prompt: trying to type the key end up in the macro expansion taking place resulting in bad argument to the unmap! command (E474: Invalid Argument) or maybe the command might try to unmap some different key from the one intended (E31: No such mapping).
How can someone correctly remove a insert-mode mapped key on vim?

A: While mapping a key, CTRL+V can be used to escape some special characters like ENTER, ESC or some particular control keys.
The same applies when using mapped insert-mode keys: they can be escaped when preceded by CTRL+V both while editing the text and while writing commands to the ex command-line prompt.
If for example, the + insert-key is mapped to some macro and the user wants to unmap it, the key must be escaped while writing the ex command to avoid the macro expansion:
:unmap! + CTRL+V (shows a ^) + <key>
The same can be done if a regular + is needed in the text while editing it in insert-mode.


text:
Q: JHipster - None of the configured nodes are available Jhipster 5.x ElasticSearch I can't insert an instance of my entity AvisRendezVous inside the database. When I click on save, I got the following error from the server :
exception = 'None of the configured nodes are available: [{#transport#-1
}{C6hOYYyORMy7Kbms4pck3g}{localhost}{127.0.0.1:9300}]'

On the JHipster documentation they said we need to start elasticsearch instance with docker-compose, so I did that :

Here is my elasticsearch.yml :
version: '2'
services:
    apspg_elastic-elasticsearch:
        image: elasticsearch:5.6.5
        # volumes:
        #     - ~/volumes/jhipster/APSPG_Elastic/elasticsearch/:/usr/share/elasticsearch/data/
        ports:
            - 9200:9200
            - 9300:9300
        command: -Enetwork.host=0.0.0.0 -Ediscovery.type=single-node

Any ideas ?


text:
Q: Cant display listview in AlertDialog android I want to display ArrayList of object in AlertDialog but my list view dont show. Here is my code.
public class PrzystanekDialog extends DialogFragment {

    private ListView trasaPrzejazdu;
    private ArrayList<Linia> trasaPrzejazduList;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        LayoutInflater inflater = getActivity().getLayoutInflater();

        final View rootView = inflater.inflate(R.layout.dialog_layout, null);

        //ustawienie lisview z wygenerowaną linia
        trasaPrzejazduList = getArguments().getParcelableArrayList("linia");
        trasaPrzejazdu = (ListView) rootView.findViewById(R.id.trasaListView);
        final ArrayAdapter<Linia> adapter = new ArrayAdapter<Linia>(getActivity(),R.layout.listbox_dialog_element, trasaPrzejazduList);
        trasaPrzejazdu.setAdapter(adapter);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        final ViewPager mViewPager;
        mViewPager = (ViewPager) getActivity().findViewById(R.id.pager);

        builder.setView(inflater.inflate(R.layout.dialog_layout, null));
        //getActivity().setContentView(inflater.inflate(R.layout.dialog_layout, null));

        builder.setMessage(R.string.choose)
                .setPositiveButton(R.string.start_trip, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        mViewPager.setCurrentItem(1);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Toast.makeText(getActivity().getApplicationContext(), "Anulowano podróż.", Toast.LENGTH_LONG).show();
                    }
                });
        return builder.create();
    }
}

Here is my ArrayAdapter
public class DialogListAdapter extends BaseAdapter {

private List<Linia> listData;

private LayoutInflater layoutInflater;

public DialogListAdapter(Context context, List<Linia> listData) {
    this.listData = listData;
    layoutInflater = LayoutInflater.from(context);
}

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

@Override
public Linia getItem(int position) {
    return listData.get(position);
}

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

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = layoutInflater.inflate(R.layout.listbox_dialog_element, null);
        holder = new ViewHolder();
        holder.start = (TextView) convertView.findViewById(R.id.przystanekStartowy);
        holder.end = (TextView) convertView.findViewById(R.id.przystanekDocelowy);
        holder.vehicleImage = (ImageView) convertView.findViewById(R.id.line_image);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    //listData.get(position).getHeadline()
    if(listData.get(position).getTypLini().toString() == "bus")
        holder.vehicleImage.setImageResource(R.drawable.autobus_ico);
    else
        holder.vehicleImage.setImageResource(R.drawable.tram_ico);
    holder.start.setText(listData.get(position).getStopPrzystanki().get(0).getNazwa_przystanku());
    holder.end.setText(listData.get(position).getStopPrzystanki().get(listData.get(position).getStopPrzystanki().size()-1).getNazwa_przystanku());

    return convertView;
}

static class ViewHolder {
    ImageView vehicleImage;
    TextView start;
    TextView end;
}

}
And here is my xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/trasaListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

I have no compile errors. Thank you very much for help.
EDIT:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/line_image"
        android:layout_width="50dip"
        android:layout_height="50dip"
        android:src="@drawable/autobus_ico"
        android:layout_marginLeft="5dip"/>

    <TextView
        android:id="@+id/przystanekStartowy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:textStyle="bold"
        android:typeface="sans"
    android:layout_marginLeft="60dip"/>

    <TextView
        android:id="@+id/przystanekDocelowy"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:text=""
        android:textColor="#343434"
        android:textSize="12sp"
        android:layout_marginLeft="60dip"/>

</LinearLayout>


text:
Q: pytorch model state and optimize with float32, forward/backward with bfloat16 I am using pytorch to train a model.
If you naively change the model to bfloat16 and train it, I find that the variables are not weight decayed by the precision of bfloat16. Detailed experiments have been added at the bottom.
So I would like to specify that the following operation be performed

*

*The weight of the model is stored as float32.

*Downcast the model to bfloat16 to create model_bf16

*Calculate model_bf16 forward and backward with bfloat16 type

*Update the model using the gradient obtained from model_bf16

*Back to Step 1

I think there is an efficient way to implement this process.
But torch.cuda.amp.autocast doesn't seem to go through this process.
Is there a way to manage the model's weights with high precision?
(init)
lr = 0.0001
weight_decay = 0.000001
weight = 1

(optimization)
weight *= (1 - lr * weight_decay) # nothing change
weight += lr * grad


text:
Q: How to route a file based on Size in Apache Camel Ok so still busy working with the file to MySQL file consumer. I started running into errors with certain large files and want to send them to another route for processing. So the idea is a simple Content Based Router that will look at the filesize and if it is a big file copy it to another directory and leave it there(once again simple steps to understand how to do it).
So I started reading about the CBR and how to use the simple expression language inside of my camel context. So I added a CBR to the camel-context.xml file and now I cant even run any routes. The build fails with the following error:
Exception in thread "main" org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException:
Line 48 in XML document from class path resource [META-INF/spring/camel-context.xml] is invalid;
nested exception is org.xml.sax.SAXParseException: The content of elements must consist of well-formed character data or markup.

Right so obviously I got some bad XML in there, but for the live of me I cant seem to find the problem maybe some of the more experienced riders can give me some advise here by taking a quick look at my xml file.
 <errorHandler id="defaultEH" type="DefaultErrorHandler">
        <redeliveryPolicy
                 maximumRedeliveries="5"
                 retryAttemptedLogLevel="WARN"
                 backOffMultiplier="1"
                 useExponentialBackOff="true"/>
     </errorHandler>
    <threadPoolProfile id="myDefaultProfile"
        defaultProfile="true"

        maxPoolSize="16"/>

        <threadPool id="myPool" threadName="Cool" poolSize="4" maxPoolSize="4" maxQueueSize="100"/>
        <route handleFault="true">

            <from uri="file://c:/CTest/BadFiles?noop=true&recursive=true&delay=3000"/>
            <choice>
            <when>
                <simple>${file:length}<20000000</simple>
                <threads executorServiceRef="myPool">
                    <to uri="bean://fileToSQL"/>
                </threads>
            </when>
            <otherwise>

                <to uri="file://c:/CTest/outbox"/>

                <stop/>
            </otherwise>
            </choice>
            <!--<to uri="jdbc://timlogdb"/>-->

       </route>

I looked at everywhere and according to my understanding this should be valid XML.

A: I think you need to escape the bigger than sign in the  text; this is XML restriction.
Also the simple language requires that you use space around its operators. So it should be
<simple>${file:length} < 20000000</simple>


text:
Q: How to save AVCaptureMovieFileOutput object into NSSavePanel Hi i have to implement save movie file into custom folder, for this i am using NSSavepanel.
I am new in NSSavepanel so i am not getting idea that how i add AVCaptureMovieFileOutput object to NSSavePanel
My code is
-(void)doSaveDocument
{

    NSSavePanel *savePanel = [NSSavePanel savePanel];

    [savePanel setTitle:@"Save image"];
    [savePanel setNameFieldStringValue:@"AnnotatedImage.mov"];
    if([savePanel runModal] == NSFileHandlingPanelOKButton)
    {
        [self takeScreenRecording:rect saveAtPath:[savePanel URL]];
        [[NSWorkspace sharedWorkspace] openURL:[savePanel URL]];

        [mMovieFileOutput startRecordingToOutputFileURL:[savePanel URL] recordingDelegate:self];
    }

}

A: NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory1 = [paths1 objectAtIndex:0]; // Get documents folder
        NSString *dataPath = [documentsDirectory1 stringByAppendingPathComponent:@"MyVideo"];
        NSError *error;
        if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
            [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];

    NSString *stryourfilename=@"Video1";

    dataPath=[NSString stringWithFormat:@"%@/%@.mp4",dataPath,stryourfilename];
    NSData *dat=[NSData dataWithContentsOfURL:videoURL];

    BOOL ok = [[NSFileManager defaultManager] createFileAtPath:dataPath
                                                      contents:nil attributes:nil];

    if (!ok) {

    } else {
        NSFileHandle* myFileHandle = [NSFileHandle fileHandleForWritingAtPath:dataPath];

        [myFileHandle writeData:dat];

        [myFileHandle closeFile];

    }


text:
Q: What means that kind of declaration in c++? What does this kind of declaration mean in c++?
CSomething & SOMETHING = m_vSOMETHING[m_iSOMETHING];

A: It is a reference variable which is initialized to point to the specified cell in m_vSOMETHING
So a declaration of
int &reftotable = table[42];

Will produce reftotable as a variable which reference cell 42 in the table, similar to what
int *pointertocell = &table[42];

would do.  In the first case with the reference you can assign reftotable like it was a normal variable
reftotable = 37;

where in the other case you will have to do
*pointertocell = 37;

to do the same thing -- that is, in both cases table[42] will contain the value 37 after the assignment.

A: SOMETHING is a reference to a CSomething and you are assigning the m_iSOMETHINGth element of m_vSOMETHING to that reference


text:
Q: Fix Class is not a constructor error when using namespace in TypeScript with WebPack Overview
I'm new to using TypeScript and PIXI.js without a framework. I used to use the language/library for work where we used namespaces with the module keyword. I've been trying to replicate the setup we used as I think it looks a lot better than having loads of import statements.
The Problem
When I run my code in the browser, I get the following error in the windows inspector console:
Uncaught TypeError: MyApp.AbstractModel is not a constructor
    at Main../src/Main.ts.Main.createModel (Main.ts:16)

What I've Found & Attempted Fixes
I have read through the typescript documentation for Namespaces found here and here loads of times but cannot see where I am going wrong.
Initially I thought the issue was that not all files were being loaded by webpack but I fixed that with suggestions found here (namely the "require.context()") and still the error persists.
I've tried importing the namespace from the main file (copied what's in Main to Game.ts, and put the following in Main.ts)
require.context("../src/", true, /\.ts$/);
/// <reference path="Game.ts" />

class Main {

    constructor() {
        console.log("Main.constructor()");
        new MyApp.Game();
    }

}
new Main();

The Structure
My file structure is as follows:
stack-overflow-example
| - .idea
| - dev
| | - dts
| | | <all .d.ts files from tsc compilation>
| | - js
| | | <all .js files and accompanying .js.map files from compiled .ts files>
| | - index.html
| - node_modules
| - src
| | - graphics
| | | - pixi-manager.ts
| | - model
| | | - AbstractModel.ts
| | - Main.ts
| | - refs.ts
| package.json
| package-lock.json
| tsconfig.json
| webpack.config.js

The Code
index.html
<!DOCTYPE html>
<html>
    <head>
        <title>stack-overflow-example</title>
    </head>
    <body>
        <script src="js/Bundle.js" type="text/javascript"></script>
    </body>
</html>

Maint.ts
/// <reference path="refs.ts" />
require.context("../src/", true, /\.ts$/);

namespace MyApp {
    export class Main {

        public static instance: Main = new Main();
        public model: AbstractModel;

        constructor() {
            console.log("Main.constructor()");
            this.createModel();
        }

        protected createModel(): void {
            this.model = new AbstractModel();
        }

        protected addComponent(view: PIXI.DisplayObject): void {
            PixiManager.instance.stage.addChild(view);
        }

        public getModel(): AbstractModel {
            return this.model;
        }
    }
}

AbstractModel.ts
/// <reference path="../refs.ts" />
namespace MyApp {
    export class AbstractModel {

        constructor() {
            console.log("AbstractModel.constructor()");
        }

    }
}

refs.ts
/// <reference path="graphics/pixi-manager.ts" />
/// <reference path="model/AbstractModel.ts" />
/// <reference path="Main.ts" />

package.json
{
  "name": "my-game",
  "version": "1.0.0",
  "description": "",
  "main": "Main.ts",
  "scripts": {
    "start": "webpack-dev-server --content-base dev/ --inline --hot"
  },
  "devDependencies": {...}
}

tsconfig.json
{
  "compilerOptions": {
    "outDir": "./dev/js/",
    "module": "commonjs",
    "target": "ES5",
    "sourceMap": true,
    "declaration": true,
    "declarationDir": "./dev/dts"
  },
  "include": ["./src/*.ts"]
}

webpack.config.js
var path = require("path");
module.exports = {
    entry: {
        namespace: "./src/Main.ts"
    },
    mode: "development",
    devtool: "source-map",
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/,
            },
        ],
    },
    resolve: {
        extensions: [ '.tsx', '.ts', '.js' ],
    },
    output: {
        path: path.resolve(__dirname, "dev/js/"),
        filename: "js/Bundle.js"
    }
};

The Question
How can I fix the "MyApp.AbstractModel is not a constructor" error while keeping the namespace style rather than using modules?
All help will be really appreciated, thanks for your time.

A: First please check why is not a constructor error is happening: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Not_a_constructor . It seems that probably the AbstractModel is not defined where the error is happening.
You could check it like this:
        protected createModel(): void {
            console.log(typeof AbstractModel);
            this.model = new AbstractModel();
        }

If thats the case then you should change this question to something like: "How to load all classes from directory in TypeScript and WebPack?".
Then, the thing which you wanted to do using require.context(... aproach can be done as described in: Is it possible to import modules from all files in a directory, using a wildcard?
BUT please also read following docs :

*

*How to import all modules from a directory in TypeScript?

*Typescript: export all functions in a namespace

*

*^ Why is "import *" bad?

*the In practice part of this answer: Is it possible to import modules from all files in a directory, using a wildcard?
As you see this is considered a bad practice by some people. I also prefer to explicitly enumerate all dependencies for current file. This way you can see exactly what is used where. Also the IDE should help you with that.
Next problem is <reference path... vs import usage. First you say:

... as I think it looks a lot better than having loads of import statements.

But then in refs.ts you do:
/// <reference path="graphics/pixi-manager.ts" />
/// <reference path="model/AbstractModel.ts" />
/// <reference path="Main.ts" />

so instead of using loads of import statements you have loads of reference statements :) . The number of code lines seems the same as when you would use imports.
Additionally please see again example from doc that you linked in your question: https://www.typescriptlang.org/docs/handbook/namespaces.html#multi-file-namespaces - in the Test.ts file there is <reference for each needed file :
/// <reference path="Validation.ts" />
/// <reference path="LettersOnlyValidator.ts" />
/// <reference path="ZipCodeValidator.ts" />

...

in files LettersOnlyValidator.ts and ZipCodeValidator.ts there is referenced /// <reference path="Validation.ts" /> - but in last file they need to reference /// <reference path="Validation.ts" /> again - so it means that "reference path approach" is not transitive.
This means that you should better rethink this and try to use import (and/or export) where needed.

*

*Typescript ///<reference path="…"> and "Uncaught ReferenceError: exports is not defined"


text:
Q: Double Integral Evaluation Does Not Stop Running I'm trying to evaluate an integral $ \iint_D \frac{1}{1+(x^2+y^2)^2}dxdy$ given the region $ D $ with the following inequalities: $ 1\leq x^2+y^2\leq 4 \text{, } x \geq 0\text{ and } y \geq 0$.
I decided to use the following syntax:
Integrate[1/(1+(x^2+y^2)^2)Boole[1<=x^2+y^2<=4],{x,0,Infinity},{y,0,Infinity}]
What happened was that Mathematica keeps performing calculations, but it never executes the computation. I've been letting it do the job for the past 5 minutes, but still no sign of a solution.
For fun, I did run
Integrate[(1+(x^2+y^2)^2)Boole[1<=x^2+y^2<=4],{x,0,Infinity},{y,0,Infinity}]
which actually yielded $ 6 \pi $!
Is my syntax OK and the Mathematica is unable to perform such computation (which I highly doubt), or is it something wrong with my syntax?

A: After changing to polar coordinates, the integral is basic:
Integrate[ρ/(1 + (ρ^2)^2),
          {ρ, 1, 2}, {θ, 0, π/2}]

(* -(1/16) π(π - 4 ArcTan[4]) *)


text:
Q: deleteInBackgroundWithBlock always return true I've been delving into swift and using the Parse SDK and was wondering if anyone could shed some light on the following:
I am trying to delete an object in the Parse DB, and have set the method up to fail - but it fails to fail.
func destroy(onComplete: Bool -> Void) {
    let object = PFObject(className: "ClassName")

    object.deleteInBackgroundWithBlock({
        (success: Bool, error: NSError?) -> Void in
        NSLog("Error: \(error)")
        if let error = error {
            onComplete(false)
            NSLog("Error: \(error)")
        } else {
            onComplete(success)
        }
    })
}

When I set the objectId property the object is destroyed fine, but here I am omitting it so, obviously, nothing is destroyed, but when the closure runs, success is always equal to true, and error is always nil.
Does anyone know if this is intended behaviour, because if no object is destroyed, surely, either success should equal false, or error should be non-nil?
Thanks
Paul


text:
Q: Limiting points subtend right angle at the centre If the limiting points of the system of circles $x^2+ y^2+ 2gx +w(x^2+ y^2+ 2fy + k)=0$ where $w$ is a parameter , subtends a right angle at origin then find value $k/f^2$?
I know that limiting point denotes the point circle i.e. a circle of radius $0$ but I am not able to use that information to find $k/f^2$?

A: (See graphics below)
Let us expand the equation of the "linear pencil" of circles, with a division by $1+w$:
$$x^2+y^2+2\frac{g}{1+w} x +2 \frac{fw}{1+w} y +\frac{kw}{1+w}=0$$
that can be written, by "completing the squares":
$$\left(x+\dfrac{g}{1+w}\right)^2-\left(\dfrac{g}{1+w}\right)^2+\left(y+\dfrac{fw}{1+w}\right)^2-\left(\dfrac{fw}{1+w}\right)^2+\dfrac{kw(1+w)}{(1+w)^2}=0$$
or
$$\left(x+\dfrac{g}{1+w}\right)^2+\left(y+\dfrac{fw}{1+w}\right)^2=\dfrac{g^2+f^2w^2-kw(1+w)}{(1+w)^2} \ \ \ (1)$$
By identification with the classical equation of a circle $(x-a)^2+(y-b)^2=R^2$, we deduce that the coordinates of the center $C$ are $$\left(-\dfrac{g}{1+w},-\dfrac{fw}{1+w}\right) \ \ \ (2)$$
Besides, the square of the radius of the circle has to be zero if one considers point-circles, i.e.,
$$(f^2-k)w^2-kw+g^2=0 \ \ \ (3)$$
We can already remark that the product of the roots of (3), considered as a second degree equation in $w$ is:
$$w_1w_2=\dfrac{g^2}{f^2-k} \ \ \ (4)$$
(Thi will prove useful in a short while).
It is time now to to introduce the right angle condition between $\vec{OC_1}$ and $\vec{OC_2}$. It can be written as a null dot product (we take into account the coordinates of point-circles $C_k$ are given by (2)):
$$\left(-\dfrac{g}{1+w_1}\right)\left(-\dfrac{g}{1+w_2}\right) + \left(-\dfrac{fw_1}{1+w_1}\right)\left(-\dfrac{fw_2}{1+w_2}\right)=0\ \ \ (5)$$
(5) yields $$w_1w_2=-\dfrac{g^2}{f^2} \ \ \ (6)$$
This is the product of the roots of equation (3). By identification with (4), we conclude that:
$$\dfrac{k}{f^2}=2 \ \ \ (7)$$
Remark: we have assumed all the way long the existence of two real roots for (3). A posteriori, relationship (7) permits to prove that equation (3) has a positive discriminant.
Graphics in the case $f=2, g=4, k=8$ with $w_1=-3.24, w_2=1.24$.


text:
Q: Trying to access from React to my websocket which is Django channels but it raises error "No route found" My websocket works because i tested it from django side white simple chat app. The route also works which is http://localhost:8000/chat/room. But It doesnt work on react side. It says No route found for path 'chat/myroom'. I've been trying to solve this for 2 hours, as a last hope, I wanted to ask here.
My routing.py file

from django.urls import re_path

from api import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
]

My roomPage.js file
`import React from "react";
import useWebSocket, { ReadyState } from "react-use-websocket";
import { useParams } from "react-router-dom";

export default function RoomPage() {

  const { readyState } = useWebSocket("ws://127.0.0.1:8000/chat/myroom", {
    onOpen: () => {
      console.log("Connected!");
    },
    onClose: () => {
      console.log("Disconnected!");
    }
  });

  const connectionStatus = {
    [ReadyState.CONNECTING]: "Connecting",
    [ReadyState.OPEN]: "Open",
    [ReadyState.CLOSING]: "Closing",
    [ReadyState.CLOSED]: "Closed",
    [ReadyState.UNINSTANTIATED]: "Uninstantiated"
  }[readyState];

  return (

      The WebSocket is currently {connectionStatus}

  );
}`

I tried on django side and it worked! But react side doesn't working

A: After +10 hours i finally found the solution and I want to kill myself! The only problem is calling websocket without "end slash"
Wrong!
useWebSocket("ws://127.0.0.1:8000/chat/myroom"

Works
useWebSocket("ws://127.0.0.1:8000/chat/myroom/"


text:
Q: Redis - hmset() in hash - efficiency Let us say there is a Redis hash that has 10 key - vals. I read them all into a perl hash ( or any language map/hash/dict ) and need to update 3 of the values. Now I changed the 3 values in the hash, and need to write it back to redis. among (A) & (B) which one will be faster?
(A) $redis_handle->hmset($redis_hash_name,\%perl_hash);
or
(B)  while ( ($k,$val) = each %three_changed_items_in_perl_hash ) {
           $redis_handle->hset($redis_hash_name,$k,$val);
        }
What I am trying to contemplate is :
(A) is one communication to redis with 10 elements. But redis needs to update only 3 of them. Does redis waste time even if values is not changed?
(B) is three communicaitons to redis with 1 element.

A: Fastest would be to send a single HMSET that only has the updated fields and their respective values. Redis will only update these fields and will not do anything with the ones that aren't explicitly mentioned.
(C) $redis_handle->hmset($redis_hash_name,\%three_changed_items_in_perl_hash);


text:
Q: What is the meaning of ##* in shell script? Script:
text="//ABC/REC/TLC/SC-prod/1f9/20/00000000957481f9-08d035805a5c94bf"

echo ${text##*/}

Here, what is the meaning of 2nd line in the above 2 line script?

A: This is Parameter substitution and/or expansion. From the link:
${var#Pattern}

Remove from $var the shortest part of $Pattern that matches the front end of $var.
${var##Pattern}

Remove from $var the longest part of $Pattern that matches the front end of $var.
So ${text##*/} remove from text everything before the last /. It's useful to get the basename of directories for instance.
(There is also ${var%Pattern}/${var%%Pattern} to remove pattern that matches the back end of $var)


text:
Q: PHP Session is NULL when going back to main index.php page <?php
    #this is dbconfig.php : assume all connection values are correct

    session_start();
    $ip = $_SERVER["REMOTE_ADDR"];
    $host = "mysql.example.com"; /* Host name */
    $user = "XXXX"; /* User */
    $pass = "XXXX"; /* Password */
    $dbname = "XXXX"; /* Database name */
    $con = mysqli_connect($host,$user,$pass,$dbname);

?>

<?php
# THIS IS THE MAIN MENU (HOME PAGE)
# THIS PAGE FAILS TO GET SESSION WHEN MOVING TO HERE FROM THE PROFILE PAGE VIA BUTTON

  include 'dbconfig.php';

  var_dump($_SESSION);  # returns NULL, should return same as profile
  if (isset($_SESSION['username'])){
    $username = $_SESSION["username"];
    $password = $_SESSION["password"];
    header('Location: https://example.com/profile');
  }
?>

<?php
# THIS IS THE USERS PROFILE PAGE

include 'dbconfig.php';
var_dump($_SESSION); # This gives CORRECT data and verifies the session is set

$username; $password;
if (isset($_SESSION['username'])){
  $username = $_SESSION["username"];
  $password = $_SESSION["password"];

} else {
  header("Location:https://example.com");
  exit();
}
?>

<button>Logout</button>
<button>Home</button>
# WHEN PRESSING THIS BUTTON IT TAKES YOU TO HOME PAGE
# (ABOVE) EXCEPT IT DOESNT HAVE A SESSION ON THE HOME PAGE FOR SOME REASON

My question is why am I losing the session when I go from Profile page to Home page (no session on home page, I'm confused here.
Thank you!
I tried changing all links to match my host, EX : www.example.com to example.com (correct)
I tried adding session_start(); to all pages
I made sure all files were updated to SFTP correctly
Still I can't get the Home page to keep the session when the user returns to it from their profile page.
when I var_dump($_SESSION) on home page I get NULL


text:
Q: I am not able to create a directory using PHP I am trying to create a directory using mkdir function in PHP. It works just fine when I am running it on the terminal using php a.php, but when I try to run it from the browser as server, I am not able to do it. Why is this?

A: SELinux is preventing httpd from doing so. See the httpd_selinux(8) man page for details.

A: It's because the system user your web server is running as doesn't have permission to mkdir. Give the web server process write access by changing the parent directory's owner or group.


text:
Q: How to inject an NLog custom target with Autofac in MVC5 I've written a custom NLog target
[Target(TargetType)]
public class EmailTarget : TargetWithLayout
{
    public const string TargetType = "NVEmail";
    private const string DefaultLayout = "${longdate} ${level:uppercase=true} ${message}${newline}${aspnet-request-querystring:QueryStringKeys=id}${newline}${exception:format=tostring}";

    public IEmailClient Client { get; set; }

    public string MailSubject { get; set; }
    public string Host { get; set; }

    public static void Register()
    {
        ConfigurationItemFactory.Default.Targets.RegisterDefinition(TargetType, typeof(EmailTarget));
    }

    protected override void Write(LogEventInfo logEvent)
    {
        Layout = DefaultLayout;
        var subject = GetMailSubject(logEvent);
        string message = this.Layout.Render(logEvent);

        SendMail(subject, message);
    }

    public void SendMail(string subject, string message)
    {
        Client.Host = Host;
        Client.SendEmail(subject, message);
    }

    public string GetMailSubject(LogEventInfo logEvent)
    {
        if (!string.IsNullOrWhiteSpace(MailSubject))
        {
            return MailSubject;
        }
        if (logEvent?.Level != null)
        {
            return logEvent.Level.ToString();
        }
        return TargetType;
    }
}

And i'm trying to register it in an MVC project.
I'd like to inject the Client property using Autofac, but i can't seem to figure out how.
I figured out that I can just substitute the ConfigurationItemFactory.Default.CreateInstance method with:
private static object CreateInstance(Type itemType)
{
    if (_container.IsRegistered(itemType))
    {
        return _container.Resolve(itemType);
    }
    return Activator.CreateInstance(itemType);

}

But i get an error at runtime:

Exception thrown: 'System.MissingMethodException' in mscorlib.dll
  Additional information: No parameterless constructor defined for this object.

Which is strange since there should be a default constructor in EMailTarget


text:
Q: Permutations of building density versus campus population I am an architect working on a master plan for a campus of buildings.  The total population of the campus is limited by parking capacity to 1,200 occupants.
The campus has 6 floor plates to consider.  We have developed 3 renovation concepts for the campus:  Low-density, medium-density, and high-density.  I want to determine how many ways the density options can be intermixed floor-by-floor, without exceeding the 1,200 occupant limit.  The floors are not identical, so there is a total of 18 possible values, arranged in 6 sets of 3.
Floor 1:  (140, 165, 179)
Floor 2:  (120, 173, 215)
Floor 3:  (119, 177, 218)
Floor 4:  (128, 181, 214)
Floor 5:  (87, 92, 150)
Floor 6:  (187, 187, 278)
How many permutations of 6 values (1 from each set) yield a sum less than or equal to 1,200?

A: A computer could knock this out pretty easily, but a little bit of thought can solve it pretty easily with enumeration. First note that there are $729=3^6$ possible permutations. Taking the largest option in all cases yields a total of 1,254 occupants, which doesn't work but is only slightly over the limit.
The difference between the high and middle options in the six cases are: 14, 42, 41, 33, 58, and 91. The latter two differences are greater than 54, so any other permutation with more than 1,200 occupants must use the high density option for both the last two cases. But this shows that if we use the high option for all but one case, and the middle option for the other, we are overcapacity in the following cases: MHHHHH, HMHHHHH, HHMHHH, HHHMHH. In the same situation where we use 5 highs and a low, a similar analysis shows only the case LHHHHH is overcapacity.
If we allow two non-high options to be chosen, then the only way we can remain over capacity is if floors 1 and 4 are the chosen pair: choosing MHHMHH gives a total of 1,207 occupants. Lowering any of these options loses more than 7 occupants, so there are no other overcapacity permutations.
Of the 729 possibilities, only 7 are over capacity, so there are 722 permissible options.


text:
Q: How to parse a Quoted Post from vBulletin? Using PHP, how can I transform:
[QUOTE=Username;1234]This is the text being quoted[/QUOTE]

Into:

Posted by: Username
This is the text being quoted.

Notice where the Username, 1234 id, and This is the text being quoted text are mapped to.
I know how to do the beginning and end, by simply replacing (e.g. str_replace) any instance of:
[QUOTE= >>>
< href="./linktopost.php?id=

[/QUOTE] >>>

but I don't know how to extract the Username, Post ID, and the Text being quoted so that I can tie them all together.
If it helps, from what I can tell above, the username can be extracted between the delimiters [QUOTE= and ;, the post id can be extracted between ; and ], and the text can be extracted between ] and [/QUOTE], but I don't know how to extract them.
Also, what happens if there is a quote within a quote?  The solution should also work in those cases as well.
Any ideas?

A: This may help ;)
$str = "[QUOTE=Username;1234]This is the text being quoted[/QUOTE]";

if(preg_match('/\[QUOTE=([^;]+);([0-9]+)\]([^\[]+)\[\/QUOTE\]/i', $str, $matches)){
    echo "
USERNAME : ".$matches[1];
    echo "
POST ID : ".$matches[2];
    echo "
MESSAGE : ".$matches[3];
}


text:
Q: How can i give the full Legend a background color in chart js? I am working on a project and we are using a chart created with chart js. I want to give the legend a background color (the top part thats drawn in the image). After a lot of searching on the internet i stil havent found a solution to my problem so i thought lets try stack overflow. can some one help me Please??>!
the part i want to give a background color
here is part of my code
enter code here

<div>
  <canvas id="myChart"></canvas>
</div>

<script>
  const labels = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
];
const data = {
  labels: labels,
  datasets: [{
    label: 'My First dataset',
    backgroundColor: 'rgb(255, 99, 132)',
    borderColor: 'rgb(255, 99, 132)',
    data: [0, 10, 5, 2, 20, 30, 45],
  }]
};

  const config = {
  type: 'line',
  data: data,
  options: {}
};

  var myChart = new Chart(
    document.getElementById('myChart'),
    config
  );
</script>

A: You can use a custom plugin for this:

const plugin = {
  id: 'legendBackground',
  beforeDraw: (chart, args, opts) => {
    const {
      chartArea: {
        width,
        top,
        left
      },
      ctx
    } = chart;
    ctx.fillStyle = opts.color || 'transparent';
    ctx.fillRect(left, 0, width, top)
  }
}

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3, 5, 2, 3],
      borderColor: 'orange'
    }]
  },
  options: {
    plugins: {
      legendBackground: {
        color: 'pink'
      }
    }
  },
  plugins: [plugin]
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>


text:
Q: How to get more images in Angular? 15 images appear at the beginning from API, the get dogs button has the function of loading an additional 15 images (and so on), but it doesn't work. How to make the button work?
http.service.ts - service with API and HttpClient
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { DogInfo } from '../interface/dogInfo';

@Injectable({
  providedIn: 'root',
})
export class HttpService {

  httpHeaders = new HttpHeaders({
    Authorization: 'YOUR_KEY_HERE',
  });

  DOGS_FETCHED = 0;
  DOGS_TO_FETCH = 15;

  constructor(private http: HttpClient) {}

  fetchDogsFromApi(): Observable<DogInfo[]> {
    const page = (this.DOGS_FETCHED + this.DOGS_TO_FETCH) / this.DOGS_TO_FETCH - 1;

    const url = `https://api.thedogapi.com/v1/breeds?page=${page}&order=desc&limit=${this.DOGS_TO_FETCH}`;

    return this.http.get<DogInfo[]>(url, { headers: this.httpHeaders })
      .pipe((response) => {
        this.DOGS_FETCHED += this.DOGS_TO_FETCH;
        return response;
      });
  }
}

dogsList.component.ts - fetching images from HttpService and getDogs function
import { AfterViewInit, Component } from '@angular/core';
import { HttpService } from 'src/app/service/http.service';

@Component({
  selector: 'app-dogsList',
  templateUrl: './dogsList.component.html',
  styleUrls: ['./dogsList.component.css']
})
export class DogsListComponent implements AfterViewInit {

  constructor(private httpService: HttpService) {}

  doggos: any = [];

  onFetchDogsFromApi(): any {
    this.httpService.fetchDogsFromApi().subscribe(
      (response) => this.doggos = response
    );
  }

  getDogs() {
    this.onFetchDogsFromApi();
  }

  ngAfterViewInit(): void {
    this.onFetchDogsFromApi();
  }
}

dogsList.component.html - list of images with ngFor directive

{{item.id}}

    <button class="btn" (click)="getDogs()">Get dogs</button>

A: you always ask about the same URL.
Use
fetchDogsFromApi(page:number,limit:number): Observable<DogInfo[]> {
   const url = `https://api.thedogapi.com/v1/breeds?page=${page}&order=desc&limit=${limit}`;
..
}

And call to your service as
this.page++;
this.onFetchDogsFromApi(this.page,10);

NOTE: It's better "control" the page from the component, not form the service

A: Looks like you always override existing 15 images with the next 15 images.
Instead of overriding it, you should just add the next 15 images to the existing array. So, instead of this:
this.httpService.fetchDogsFromApi().subscribe(
  (response) => this.doggos = response
);

Do this:
this.httpService.fetchDogsFromApi().subscribe(
  (response) => this.doggos.push(...response)
);

A: You have to append the doggos array with the new response as shown below.
this.httpService.fetchDogsFromApi().subscribe(
  (response) => this.doggos = [...this.doggos, ...response];
);


text:
Q: Completely wrong ressource picked on some devices I have an odd issue with resources in my android app. I have a ListView where I set the background of elements depending on the state of the item. I'm doing this in the getView-Method of my adapter (tv is a TextView):
if (position == currentSelection - 1) {
    tv.setBackgroundResource(R.drawable.list_selector_background_pressed);
    tv.setTextColor(getContext().getResources().getColor(R.color.my_white));
}
else {
    tv.setBackgroundResource(R.drawable.list_selector_background);
    tv.setTextColor(getContext().getResources().getColor(R.color.text_color));
}

list_selector_background contains different items depending on the state (pressed, focused, disabled, etc). Default state is @color/transparent.
list_selector_background_pressed is a 9-patch-image and also used in list_selector_background as the pressed state.
On my Android 4.3 Emulator everything works fine. Same on my 4.3 Device. On my 2.2 Device (lowest supported API version) instead of the list_selector_background drawable a different image out of the drawable-hdpi gets displayed. The if-part works fine. The problem just occurs on the else part of the code.
I know about the issue with library projects and conflicting IDs discussed e.g. here. My problem is similar but in a few details different. It always picks the wrong background for my ListView and it's always the same background. Sometimes it helps when I open a different activity first. Sometimes it doesn't. Clean didn't work. Complete uninstall and install again didn't work a
Any hints would be highly appreciated.
Edit
The complete source code of my getView methode:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;

    if (v == null) {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        v = inflater.inflate(resource, null);
    }

    TextView tv = (TextView) v.findViewById(android.R.id.text1);
    tv.setText(getItem(position));

    if (position == currentSelection - 1) {
        tv.setBackgroundResource(R.drawable.list_selector_background_pressed);
        tv.setTextColor(getContext().getResources().getColor(R.color.my_white));
    }
    else {
        tv.setBackgroundResource(R.drawable.list_selector_background);
        tv.setTextColor(getContext().getResources().getColor(R.color.text_color));
    }

    return v;
}

currentSelection is an integer which is set by the view at a certain time. Then the item is supposed to look highlighted, which works fine on the emulator. It displays the image icon_toolbox of the drawable-hdpi folder. It's not part of the list_selector_background drawable, which looks like this:

<item android:state_window_focused="false"
    android:drawable="@color/transparent" />

<!-- Even though these two point to the same resource, have two states so the drawable will invalidate itself when coming out of pressed state. -->
<item android:state_focused="true" android:state_enabled="false"
    android:state_pressed="true"
    android:drawable="@drawable/list_selector_background_disabled" />
<item android:state_focused="true" android:state_enabled="false"
    android:drawable="@drawable/list_selector_background_disabled" />

<item android:state_focused="true" android:state_pressed="true"
    android:drawable="@drawable/list_selector_background_transition" />
<item android:state_focused="false" android:state_pressed="true"
    android:drawable="@drawable/list_selector_background_transition" />

<item android:state_focused="true"
    android:drawable="@drawable/list_selector_background_focus" />

<item android:drawable="@color/transparent" />

A: Following the comments section:
I think that you have interfering methods, which both influence the TextView - the one being this onClick you're speaking about and the second being the state selector, from the code above.
The android.R.layout.simple_list_item_1 is a default one, as far as I know, thus all the android.R% things, which are sometimes replaced, when you have a problem in the R.java file, that's why it was suspicious for me (if it suits your need, then ok).
But if you defined a XML (manually) for the TextView, then it is defined in the R.java, not in android.R ...


text:
Q: Parse error: syntax error, unexpected 'sonum' (T_STRING) in Please help me to fix the error.
Parse error: syntax error, unexpected 'sonum' (T_STRING) in /aaa/dsearch.php on line 36
if(mysqli_num_rows($result) > 0)
{
    while($row = mysqli_fetch_array($result))
    {
        $output .= '

            '. $row["sonum"] .'
            '. $row["regdate"] .'
            '. $row["salesperson"] .'
            '. $row["company"] .'
            '. $row["status"] .'

            <a href="so.php?edit=<?php echo $row['sonum']; ?>" class="btn btn-info">Edit
            <a href="process.php?delete=<?php echo $row['sonum']; ?>" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this item?');">Delete

        ';
    }
}

A: You include PHP code inside PHP string value, not inside HTML text. For example, instead of
<a href="so.php?edit=<?php echo $row['sonum']; ?>" class="btn btn-info">Edit

you should use:
Edit


text:
Q: Can we use pact-jvm for validation soap xml? I have tried using pact-JVM for an endpoint which returns a soap XML response.
For XML response it looks like it does string comparison, Can we do XML validation against XSD or can we write matchers for XML?
Need suggestion as well, is it a good idea to use pact-JVM to write a contract test case for an endpoint that returns soap XML?
Please share a sample example for it.

A: There is a PactXMLBuilder that you can use that is namespace aware and you can match on.
Here is an example https://github.com/DiUS/pact-jvm/blob/7ff6491a0923e4709a8f78ab5451a99989559712/consumer/junit/src/test/java/au/com/dius/pact/consumer/junit/xml/TodoXmlTest.java


text:
Q: How to specify "socket_options" in python-requests lib since urllib3 v1.8.3 has been added the "socket_options" feature? urllib3 V1.8.3 has been added the feature "socket_options". For me, I want to specify (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) in requests lib. But I've no idea how.
Here is the version change log of urllib3.
Here is the sample of the new feature in urllib3:
    def test_socket_options(self):
    """Test that connections accept socket options."""
    # This test needs to be here in order to be run. socket.create_connection actually tries to
    # connect to the host provided so we need a dummyserver to be running.
    pool = HTTPConnectionPool(self.host, self.port, socket_options=[
        (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    ])
    s = pool._new_conn()._new_conn()  # Get the socket
    using_keepalive = s.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) > 0
    self.assertTrue(using_keepalive)
    s.close()

If version 1.8.3 is merged into new requests lib, how to specify the parameter.
Any answers will be appreciated.
Here is my code:
import requests
import socket

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager

class SourceAddressAdapter(HTTPAdapter):
    def __init__(self, source_address, **kwargs):
        self.source_address = source_address
        super(SourceAddressAdapter, self).__init__(**kwargs)
    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       socket_options=[(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)],
                                       source_address=self.source_address,
                                       )
http_session = requests.Session()
http_session.mount('http://', SourceAddressAdapter(('0.0.0.0', 1238)))
print http_session.get('http://10.0.10.7')

And here is the error:
    Traceback (most recent call last):
  File "./tt.py", line 27, in <module>
    print http_session.get('http://10.0.10.7')
  File "/usr/local/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/sessions.py", line 468, in get
    return self.request('GET', url, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/sessions.py", line 456, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/local/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/sessions.py", line 559, in send
    r = adapter.send(request, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/requests-2.3.0-py2.7.egg/requests/adapters.py", line 375, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='10.0.10.7', port=80): Max retries exceeded with url: / (Caused by <class 'socket.error'>: [Errno 98] Address already in use)

===============================================================================
I have tried to use urllib3 v1.9 to set the (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1), but it failed. The reason why source port in time_wait state can't be reused may be "(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)" should be configured before "socket.bind". So even I set the REUSEADDR parameter in the "HTTPConnectionPool", src port in time_wait state could NOT be used. So sad..
Here is my try:
#!/usr/bin/python
import socket
from urllib3 import (
    encode_multipart_formdata,
    HTTPConnectionPool,
    )

pool = HTTPConnectionPool('10.0.10.7', 80,
                          socket_options=[(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)],
                          source_address=('10.0.10.11',1239))
r=pool.request('GET','/')

And here is the error:
    Traceback (most recent call last):
  File "./aa.py", line 10, in <module>
    r=pool.request('GET','/')
  File "build/bdist.linux-x86_64/egg/urllib3/request.py", line 68, in request
  File "build/bdist.linux-x86_64/egg/urllib3/request.py", line 81, in request_encode_url
  File "build/bdist.linux-x86_64/egg/urllib3/connectionpool.py", line 579, in urlopen
  File "build/bdist.linux-x86_64/egg/urllib3/connectionpool.py", line 579, in urlopen
  File "build/bdist.linux-x86_64/egg/urllib3/connectionpool.py", line 579, in urlopen
  File "build/bdist.linux-x86_64/egg/urllib3/connectionpool.py", line 559, in urlopen
  File "build/bdist.linux-x86_64/egg/urllib3/util/retry.py", line 265, in increment
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='10.0.10.7', port=80): Max retries exceeded with url: / (Caused by ProtocolError('Connection aborted.', error(98, 'Address already in use')))

A: I couldn't get @Lukasa's answer to work, but I modified it and got the following to work,
import requests
import socket
from requests.adapters import HTTPAdapter
from requests.adapters import PoolManager
from requests.packages.urllib3.connection import HTTPConnection

class SockOpsAdapter(HTTPAdapter):
  def __init__(self, options, **kwargs):
    self.options = options
    super(SockOpsAdapter, self).__init__()
  def init_poolmanager(self, connections, maxsize, block=False):
    print "init_poolmanager"
    self.poolmanager = PoolManager(num_pools=connections,
                                   maxsize=maxsize,
                                   block=block,
                                   socket_options=self.options)

options =  HTTPConnection.default_socket_options + [
              (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1),
          ]

print "build session"
s = requests.Session()
s.mount('http://', SockOpsAdapter(options))
s.mount('https://', SockOpsAdapter(options))

for i in xrange(0, 10):
  print "sending request %i" % i
  url = 'http://host:port' #put in a host/port here
  headers = {'Content-Type':'text/plain', 'Accept':'text/plain'}
  post_status = s.get(url, headers=headers)
  print "Post Status Code = %s" % str(post_status.status_code)
  print post_status.content[0:50]

A: Assuming you've correctly merged urllib3 into requests and that nothing breaks, you'd use a Transport Adapter:
from requests.adapters import HTTPAdapter

class SockOpsAdapter(HTTPAdapter):
    def __init__(self, options, **kwargs):
        self.options = options

        super(SourceAddressAdapter, self).__init__(**kwargs)

    def init_poolmanager(self, connections, maxsize, block=False):
        self.poolmanager = PoolManager(num_pools=connections,
                                       maxsize=maxsize,
                                       block=block,
                                       socket_options=self.options)

And then you use it like this:
import requests
from requests.packages.urllib3.connection import HTTPConnection

options = HTTPConnection.default_socket_options + [
              (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1),
          ]

s = requests.Session()
s.mount('http://', SockOpsAdapter(options))
s.mount('https://', SockOpsAdapter(options))


text:
Q: Decision Trees: Is there always a split that reduces sum of squared errors? I'm learning about regression decision trees and I was wondering if there always exists a split in each of the terminal nodes that will reduce the sum of squared errors (assuming there is more than one data point in the node). If there is, is there a proof?
Edit: I don't mean reduced in the strict sense.

A: No. Imagine the case where all the target values in a leaf are the same, there is no way to (striclty, as stressed by @whuber) reduce the error of this leaf.


text:
Q: Over-writing ActiveRecord association macros I'm building an API for an app that allows users to rate and favorite different ski mountains.  At the moment, my associations are set up as follows:
class Mountain < ApplicationRecord
    has_many :ratings
    has_many :users, through: :ratings
    has_many :favorites
    has_many :users, through: :favorites
end

class Favorite < ApplicationRecord
  belongs_to :mountain
  belongs_to :user
end

class Rating < ApplicationRecord
  belongs_to :mountain
  belongs_to :user
end

class User < ApplicationRecord
    has_many :ratings
    has_many :mountains, through: :ratings
    has_many :favorites
    has_many :mountains, through: :favorites
end

The problem here is that User has many mountains through both ratings and favorites, but calling User.first.mountains will only give me mountains through ratings, since that's listed first.  I'll need to utilize both in the app - any guidance here? Same deal for mountains - has many users through both ratings and favorites.
Thanks in advance for your help!


text:
Q: How to apply pipe (regex OR) to a specific substring of pattern so that it matches groups followed by EITHER a set of characters OR EOL? I have a string of questions and answers, which I want to split question-wise.
s = 'Q1 blah1 Ans BLAH1 Q2 blah2 Ans BLAH2'
re.split('(Q\d.*?)Q\d', s)

The result:
['', 'Q1 blah1 Ans BLAH1 ', ' blah2 Ans BLAH2']

I want to capture the portion which starts with 'Q#' and is followed by either another 'Q#' or the end of the line. So I tried using this:
re.split('(Q\d.*?)Q\d|$', s)
['', 'Q1 blah1 Ans BLAH1 ', ' blah2 Ans BLAH2']

and this:
re.split('(Q\d.*?)(Q\d|$)', s)
['', 'Q1 blah1 Ans BLAH1 ', 'Q2', ' blah2 Ans BLAH2']

But, they don't give me the desired results. It doesn't work in the first case because of improper usage of |, but I don't know how to rectify it. In the second case, the Q2 doesn't get captured along with blah2 Ans BLAH2.
EDIT:
Desired output:
['', 'Q1 blah1 Ans BLAH1 ', 'Q2 blah2 Ans BLAH2']

A: Try splitting on the following pattern:
\s+(?=Q\d+)

This uses a positive lookahead assertion which asserts, but does not consume, that the next question is starting.
s = 'Q1 blah1 Ans BLAH1 Q2 blah2 Ans BLAH2'
print re.split('\s+(?=Q\d+)', s)

['Q1 blah1 Ans BLAH1', 'Q2 blah2 Ans BLAH2']

Demo


text:
Q: ValueError: The `input_spec` is a collections.abc.Mapping (e.g., a dict), so it must contain an entry with key `'x'`, representing the input(s) I'm testing this tutorial with non-IID distribution for federated learning: https://www.tensorflow.org/federated/tutorials/tff_for_federated_learning_research_compression, and using tff.simulation.datasets.build_single_label_dataset() as a way to produce a non-IID distribution for the dataset.
But I faced an error regarding keras values in the input_spec.
The code:
emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data(
    only_digits=False)

emnist_train1 = tff.simulation.datasets.build_single_label_dataset(
  emnist_train.create_tf_dataset_from_all_clients(),
  label_key='label', desired_label=1)

MAX_CLIENT_DATASET_SIZE = 418

CLIENT_EPOCHS_PER_ROUND = 1
CLIENT_BATCH_SIZE = 20
TEST_BATCH_SIZE = 500

def reshape_emnist_element(element):
  return (tf.expand_dims(element['pixels'], axis=-1), element['label'])

def preprocess_train_dataset(dataset):
  return (dataset
          .shuffle(buffer_size=MAX_CLIENT_DATASET_SIZE)
          .repeat(CLIENT_EPOCHS_PER_ROUND)
          .batch(CLIENT_BATCH_SIZE, drop_remainder=False)
          .map(reshape_emnist_element))

emnist_train1 = preprocess_train_dataset(emnist_train1)

import random
NUM_CLIENTS = 100

client_datasets = [
   emnist_train1.take(random.randint(1, CLIENT_BATCH_SIZE))
   for _ in range(NUM_CLIENTS)
]

emnist_train1 = client_datasets

def create_original_fedavg_cnn_model(only_digits=True):
  """The CNN model used in https://arxiv.org/abs/1602.05629."""
  data_format = 'channels_last'

  max_pool = functools.partial(
      tf.keras.layers.MaxPooling2D,
      pool_size=(2, 2),
      padding='same',
      data_format=data_format)
  conv2d = functools.partial(
      tf.keras.layers.Conv2D,
      kernel_size=5,
      padding='same',
      data_format=data_format,
      activation=tf.nn.relu)

  model = tf.keras.models.Sequential([
      tf.keras.layers.InputLayer(input_shape=(28, 28, 1)),
      conv2d(filters=32),
      max_pool(),
      conv2d(filters=64),
      max_pool(),
      tf.keras.layers.Flatten(),
      tf.keras.layers.Dense(512, activation=tf.nn.relu),
      tf.keras.layers.Dense(10 if only_digits else 62),
      tf.keras.layers.Softmax(),
  ])

  return model

input_spec = emnist_train.create_tf_dataset_for_client(
    emnist_train.client_ids[0]).element_spec

def tff_model_fn():
  keras_model = create_original_fedavg_cnn_model()
  return tff.learning.from_keras_model(
      keras_model=keras_model,
      input_spec=input_spec,
      loss=tf.keras.losses.SparseCategoricalCrossentropy(),
      metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])

federated_averaging = tff.learning.build_federated_averaging_process(
    model_fn=tff_model_fn,
    client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02),
    server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0))
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-7661a3b7dc92> in <module>()
      3     model_fn=tff_model_fn,
      4     client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.02),
----> 5     server_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=1.0))

6 frames
/usr/local/lib/python3.7/dist-packages/tensorflow_federated/python/learning/keras_utils.py in from_keras_model(keras_model, loss, input_spec, loss_weights, metrics)
    176           'The `input_spec` is a collections.abc.Mapping (e.g., a dict), so it '
    177           'must contain an entry with key `\'{}\'`, representing the input(s) '
--> 178           'to the Keras model.'.format(model_lib.MODEL_ARG_NAME))
    179     if model_lib.MODEL_LABEL_NAME not in input_spec:
    180       raise ValueError(

ValueError: The input_spec is a collections.abc.Mapping (e.g., a dict), so it must contain an entry with key 'x', representing the input(s) to the Keras model.

What does that mean? How can I solve it?


text:
Q: В Listview не работают колонки В Listview настроил хедеры. Все отлично работает. Думал аналогично добавить и сами строки - но тут как то коряво все отображается

<ListView x:Name="listView" Grid.Column="0" HorizontalAlignment="Stretch"  VerticalAlignment="Top">
            <ListView.HeaderTemplate>
                    <DataTemplate>
                        <Grid  Background="Gray">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="*"/>
                                <ColumnDefinition Width="*"/>
                            </Grid.ColumnDefinitions>

                            <TextBlock Text="Блюдо" Grid.Column="0"         VerticalAlignment="Top" HorizontalAlignment="Left" Margin="7,2,0,0" FontWeight="Bold"  FontSize="18" ></TextBlock>
                            <TextBlock Text="Цена" Grid.Column="1"          VerticalAlignment="Top" HorizontalAlignment="Left" Margin="7,2,0,0" FontWeight="Bold"  FontSize="18" ></TextBlock>
                            <TextBlock Text="Количество"  Grid.Column="2"   VerticalAlignment="Top" HorizontalAlignment="Left" Margin="7,2,0,0" FontWeight="Bold"  FontSize="18" ></TextBlock>
                        </Grid>
                    </DataTemplate>
            </ListView.HeaderTemplate>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid >
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <TextBlock Text="{Binding bludo}" Grid.Column="0"    FontSize="18" ></TextBlock>
                        <TextBlock Text="{Binding tsena}" Grid.Column="1"    FontSize="18" ></TextBlock>
                        <TextBlock Text="{Binding kol}"   Grid.Column="2"    FontSize="18" ></TextBlock>

                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        </Grid>

A: Вы неправильно выравниваете ваши колонки, нужно ведь общую группу в Grid задать (SharedSizeGroup). Но проще и правда воспользоваться View=GridView, если вам нужен скучный табличный лэйаут:
<ListView ItemsSource="{Binding}">
    <ListView.Resources>
        <Style TargetType="{x:Type GridViewColumnHeader}">
            <Setter Property="Background" Value="Gray" />
            <Setter Property="HorizontalContentAlignment" Value="Left" />
            <Setter Property="TextBlock.FontWeight" Value="Bold" />
            <Setter Property="Padding" Value="5" />
        </Style>
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Название" DisplayMemberBinding="{Binding Name}"/>
            <GridViewColumn Header="Цена" DisplayMemberBinding="{Binding Price}"/>
            <GridViewColumn Header="Количество" DisplayMemberBinding="{Binding Quantity}"/>
        </GridView>
    </ListView.View>
</ListView>

У меня получилось:

Обновление.
Окей, в UWP всё сложнее. У меня получилось растянуть колонки так:
<ListView ...>
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListView.ItemContainerStyle>
    <!-- всё остальное -->

A: Добавьте ItemsContainerStyle к ListView с таким содержимым:
<Style
        x:Key="MyListViewItemsContainerStyle"
        TargetType="ListViewItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>


text:
Q: Running script that (might) take very long to finish in PHP I am running a php script as a cron job that might take very long time to finish. It will create a massive xml file and save it.
What should I think of if I implement it?
One thing I do is set max_execution_time for a long time:
ini_set('max_execution_time', 300);

Is there anything else I should do? Increase memory limit?
Does it help if put header "keep-alive"?
What can I do to make sure the script will always run until everything neccessary is done?

A: You can remove the execution time limit by using the set_time_limit function passing 0 as parameter:
set_time_limit(0);

Adding HTTP headers won't help because as it is a cronjob script, you are not dealing with a browser.


text:
Q: Pandas dataframe isolate row below a keyword I have a 1 column dataframe
df = pd.read_csv(txt_file, header=None)

I am trying to search for a string in the column and then return the row after
key_word_df = df[df[0].str.contains("KeyWord")]

I dont know how you can then every each time the keyword is found, isolate the row below it and assign to a new df.

A: You could use the .shift method on an indexer. I've split this into multiple lines to demonstrate what's happening, but you could do the operation in a one-liner for brevity in practice.
import pandas as pd
# 1. Dummy DataFrame with strings
In [1]: df = pd.DataFrame(["one", "two", "one", "two", "three"], columns=["text",])

# 2. Create the indexer, use `shift` to move the values down one and `fillna` to remove NaN values
In [2]: idx = df["text"].str.contains("one").shift(1).fillna(False)
In [3]: idx
Out [3]:
0    False
1     True
2    False
3     True
4    False
Name: text, dtype: bool

# 3. Use the indexer to show the next row from the matched values:
In: [4] df[idx]
Out: [4]
text
1  two
3  two

A: You can use the shift function. Here's an example
import pandas as pd

df = pd.DataFrame({'word': ['hello', 'ice', 'kitten', 'hello', 'foo', 'bar', 'hello'],
                  'val': [1,2,3,4,5,6,7]})

    val word
0   1   hello
1   2   ice
2   3   kitten
3   4   hello
4   5   foo
5   6   bar
6   7   hello

keyword = 'hello'
df[(df['word']==keyword).shift(1).fillna(False)]

    val word
1   2   ice
4   5   foo

A: Here is one way.
Get the index of the rows that match your condition. Then use .loc to get the matching index + 1.
Consider the following example:
df = pd.DataFrame({0: ['KeyWord', 'foo', 'bar', 'KeyWord', 'blah']})
print(df)
#         0
#0  KeyWord
#1      foo
#2      bar
#3  KeyWord
#4     blah

Apply the mask, and get the rows of the index + 1:
key_word_df = df.loc[df[df[0].str.contains("KeyWord")].index + 1, :]
print(key_word_df)
#      0
#1   foo
#4  blah


text:
Q: CICD Pipeline Deployment stage unable to come out after successful deployment Background : Spring boot application deployment using cicd pipeline declarative script
Issue :
The spring boot application jar file is able to launch successfully. After some time we can access application health info also from browser but the build job is unable to exit from deployment stage. It is spinning at this stage continuously.
Action Taken: even we have added timeout=120000 in launch command but no change in behaviour.
Help : please help us how can we make clean exit after deployment stage from jenkin cicd declarative pipeline.
We are ssh'ing and executing our launch command. The code is like:
sshagent([sshAgent]) { sh "scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -v *.jar sudouser@${server}:/opt/project/tmp/application-demo.jar" sh "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null sudouser@${server} nohup '/opt/java/hotspot/8/64_bit/jdk1.8.0_141/bin/java -jar -Dspring.profiles.active=$profile -Dhttpport=8890 - /opt/project/tmp/application-demo.jar ' timeout=120000" }

I need to come out (clean exit) from jenkins build after deployment stage is successful.

A: You need to add the '&' to the start process in backgroud
Example:
nohup '/opt/java/hotspot/8/64_bit/jdk1.8.0_141/bin/java -jar -Dspring.profiles.active = $ profile -Dhttpport = 8890 - /opt/project/tmp/application-demo.jar &

You can also put an 'if' condition for when the log appears 'started in' to exit execution.
Example:
status(){
  timeout=$1
  process=$2
  log=$3
  string=$4
  if (timeout ${timeout} tail -f  ${log} &) | grep "${string}" ; then
    echo "${process} started with success."
  else
    echo "${process} startup failed." 1>&2
    exit 1
  fi
}

start_app(){
   java -jar -dspring.profiles.active=$profile -dhttpport=8890 - /opt/project/tmp/application-demo.jar >> /tmp/log.log 2>&1 &
   status "60" "application-demo" "/tmp/log.log" "started"
}


text:
Q: Matplotlib whole legend leftaligned I would like to align left all the elements of the legend (natively, only the title is left aligned).
Any idea on how to achieve that?
import matplotlib.pyplot as plt, matplotlib
_plot = plt.plot(range(5), range(5), label = 'a')
legend = plt.legend(loc = 'upper left', title = 'this is a long title')

A: Are you looking for something like that ?

if so you can get it with:
x = arange(1.0, 15, 1.0)
plot(x,log(x),label=r'$y=log(x)$')
plot(x,5*x,label=r'$y=5x$')
plot(x,5*x+log(x),label=r'$y=5x+log(x)$')
plot(x,x**2,label=r'$y=x^2$')
legend(loc='upper left')
show()


text:
Q: Retrieve non matching record using join I have two tables, table A and table B.
Both have 4 matching records and table A contains 6 records that do not match.
With the help of join how do I retrieve non matching records?

A: You can use a left outer join and test for B.ID is null. This sample will run in SQL Server 2008 but the query works in versions before that.
declare @TableA table (ID int)
declare @TableB table (ID int)

insert into @TableA values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)
insert into @TableB values (1),(2),(3),(4)

select A.*
from @TableA as A
  left outer join @TableB as B
    on A.ID = B.ID
where B.ID is null

Result:
ID
--
5
6
7
8
9
10

A: Check this posts once
How to retrieve non-matching results in mysql
Returning non-matching records between 2 tables sql server


text:
Q: Struts 2 - Get a complete URL of the Application I'm using a third party API which requires sending a complete URL in one of the JSP. I need to set the URL like
http://localhost:8080/MyWebApp/add.action

I can implement the /MyWebApp/add.action using <s:action/>
But how to get the http://localhost:8080 in Struts2?

A: Use s:url tag. Include the attribute forceAddSchemeHostAndPort="true".