text:
Q: Плагин TableSorter.js в WordPress Пытаюсь использовать плагин TableSorter.js в WordPress.
wp_register_script('jquery.tablesorter', plugins_url( "js/jquery.tablesorter.min.js", __FILE__ ));
wp_enqueue_script( 'jquery.tablesorter' );
wp_register_script('jquery-latest', plugins_url( "js/jquery-latest.js", __FILE__ ));
wp_enqueue_script( 'jquery-latest' );
wp_register_script('script', plugins_url( "js/script.js", __FILE__ ));
wp_enqueue_script( 'script' );

Подключаю необходимые скрипты - по коду страницы вижу что они подключены, и ссылки на файлы скриптов работают правильно.
Но необходимые действия не выполняются.
В чем может быть причина? Могут ли подключаемые скрипты конфликтовать с существующими?
Спасибо!

A: Проверьте порядок подключения скриптов. Подключение Jquery всегда должно идти самым первым.
Плюс оберните функцию вызова tablesorter в
jQuery(document).ready(function($) {
    //вызов tablesorter
});

A: При регистрации своих скриптов надо использовать третий параметр функции wp_register_script() для указания зависимости скриптов. Это обеспечит их загрузку в правильном порядке. Порядок вызовов функции сам по себе роли не играет.
Попробуйте модифицировать свой код таким образом:
wp_register_script('jquery.tablesorter', plugins_url( "js/jquery.tablesorter.min.js", __FILE__ ), array('jquery'));
wp_enqueue_script( 'jquery.tablesorter' );
wp_register_script('jquery-latest', plugins_url( "js/jquery-latest.js", __FILE__ ), array('jquery', 'jquery.tablesorter'));
wp_enqueue_script( 'jquery-latest' );
wp_register_script('script', plugins_url( "js/script.js", __FILE__ ), array('jquery', 'jquery.tablesorter', 'jquery.latest'));
wp_enqueue_script( 'script' );

В примере кода выше указывается, что:
jquery.tablesorter зависит от jquery
jquery-latest зависит  от jquery и jquery.tablesorter
script зависит  от jquery, jquery.tablesorter и jquery-latest.


text:
Q: PHP E-mail form extracting from array I created an email form using php and want to have it sent to my e-mail. however all the values for the message are in an array. I used the extract function, but it is coming back null this is the code for the e-mail portion of it.
foreach($good_data as $field => $value)
        {
            $good_data[$field] = mysqli_real_escape_string($cxn,$value);
        }
    $to =  "***********";
    $sub = "Cameron Web Design";
    $mess = extract($good_data[$value]);
    mail($to,$sub,$mess);

    include('success.html');

It will send the fields, but not what was put into them.

A: You are using extract() the wrong way, extract() actually creates 1 variable for each element in the array named as the element key name and has the same value of that element, and the function it self returns the number of values imported into a variables.
Maybe what you are looking for is implode()
Ref: PHP: extract()

redpajama_set_name: RedPajamaStackExchange


text:
Q: mysql join get info from 2 rows i have 2 tables:
players
id  |  dni | name
-----------------
1      222    mike
2      333    gerard
3      444    mark
4      555    alfred
5      666    thomas
5      777    nicolas

teams
id  |  dni1 | dni2 | cat
------------------------
1      222    333    1
2      444    555    1
3      666    333    2
4      777    222    2

what i want is to make a select statement depending on the cat. so for
cat=1 should be:
mike gerard
mark alfred
and for cat=2 should be:
thomas gerard
nicolas mike

i tryed many join statements but i cant figure it out, can you help me please?
EDIT to make it more difficult, the players table have a new colum= points
players
    id  |  dni | name | points
    --------------------------
    1      222    mike     1
    2      333    gerard   2
    3      444    mark     3
    4      555    alfred   4
    5      666    thomas   5
    5      777    nicolas  6

now the result give us the sum of the points colums from both players and order by biggest sum number.
cat=1 should be:
mark alfred 7
mike gerard 3

A: select t.cat, p1.name name1, p2.name name2, p1.points + p2.points points
from teams AS t
join players AS p1 ON p1.dni = t.dni1
join players AS p2 on p2.dni = t.dni2
where cat = 1
order by points desc

DEMO


text:
Q: Custom variables initialized in xml: attribute is missing the android namespace prefix I am trying to make this work
<mypackage.Square
         android:id="@+id/imageButton8"
         android:contentDescription="@string/r8"
         android:layout_height="50dp"
         android:layout_width="47dp"
         stringRandom="lalala"/>

where stringRandom is a custom variable from the java class Square located at src/mypackage
this is the java class Square:
public class Square extends ImageButton {
private String stringRandom;

public Square(Context context, boolean iswhite) {
    super(context);
}

public Square(Context context, boolean iswhite, String piece) {
    super(context);
}

public Square(Context context, AttributeSet attrs)
{
    super(context, attrs);
}
}

I found an example here where they make work exactly the same as I am trying to, but I can not figure out why in my case it is not working. However I also found out that if instead of the right variable with the sample given you type anything else that should crash, it doesn't crash but it reports a java.null exception when getting the original variable.
Any clue?


text:
Q: javascript function in ASP.NET Repeater I have a repeater in an ASP.NET UpdatePanel as follows;
<asp:UpdatePanel ID="rptGalleries" runat="server">
<ContentTemplate>
    <asp:Repeater ID="rptAddPhotoGalleries" runat="server">
        <ItemTemplate>
            <div>
                 <input type="checkbox" id="chkNews" data-newsid='<%# Eval("NewsID") %>' runat="server" onclick="javascript:markNews($(this).data('newsid'));" />
            </div>
        </ItemTemplate>
     </asp:Repeater>
</ContentTemplate>

And I use the following javascript within the  element of the HTML;
<script type="text/javascript">
    $(document).ready(function () {
        function markNews(nID) {
          var $span = $('span[data-newsid="' + nID + '"]')
          $span.hide('slow');
        }
    });
</script>

when I click on the resulting checkbox, I get an error in the console as follows;
ReferenceError: markNews is not defined
javascript:markNews($(this).data('newsid'));

Anyone have any ideas?

A: You should define your function outside like in this demo:
<script type="text/javascript">
    function markNews(nID) {
        var $span = $('span[data-newsid="' + nID + '"]');
        $span.hide('slow');
    }
</script>

The jQuery $(document).ready(function () { defines an inner scope, so your function is only accessible inside.

An alternative would be writing an extension:
$(document).ready(function () {
    $.fn.markNews = function (nID) {
        var $span = $('span[data-newsid="' + nID + '"]');
        $span.hide('slow');
    }
});

You can call that function directly on the element like in
<input type="checkbox" id="chkNews" data-newsid='1' runat="server"
       onclick="javascript:$(this).markNews($(this).data('newsid'));" />

Here is a demo.

With that said, this could even be improved by reading the id inside the function (demo):
$.fn.markNews = function () {
    var nID = $(this).data('newsid'),
        $span = $('span[data-newsid="' + nID + '"]');
    $span.hide('slow');
}

My suggestion for a final solution
To avoid unnecessary code, I would use the function in outer (global) scope and call it within a jQuery event:
function markNews() {
    var nID = $(this).data('newsid'),
        $span = $('span[data-newsid="' + nID + '"]');
    $span.hide('slow');
}

$(document).ready(function () {
    $('#Ctl_rptAddPhotoGalleries > input').on('click', markNews);
});

Of course #Ctl_rptAddPhotoGalleries has to be replaced with the rendered id (e.g. '#<%=rptAddPhotoGalleries.ClientID%> > input').
With that, your <input/>s can be as clean as
<input type="checkbox" data-newsid='<%# Eval("NewsID") %>' runat="server" />

Here is a demo.

A: Because you have your function definition wrapped in the document ready event, the html is parsed and rendered before the function is defined.  That is why it gives that error.
You should place it outside of the ready event and anywhere before the element in question that relies on it.

A: The function markNews only existing in the scope of the anonymous function that you pass for ready. Therefore, you can't assign it outside it's scope.
But you don't need to create a named function for this (unless you need to call that function in other places not shown in sample code):
$(function(){
    $("#<%=rptAddPhotoGalleries.ClientId %> span").click(function(){
        $(this).hide('slow');
    });
});

A: You want to input instead of span, because there is no span tag in your repeater control.
<script type="text/javascript">
    function markNews(nID) {
        var $input = $('input[data-newsid="' + nID + '"]');
        $input.hide('slow');
    }
</script>


text:
Q: Ionic route to sibling outlet with id I can find advice how to route to a named outlet, and how to route to a sibling route, and how to route with a dynamic id, but I can't figure out how to combine all three things together. Theoretically some version of this should work:
this.router.navigate([
        { outlets: { detail: ['result', this.system.id] }}],
        { relativeTo: this.activatedRoute.parent });

But I keep getting "Error: Cannot match any routes".
Result module route:
const routes: Routes = [
{
    path: ':id',
    component: SystemResultsPage,
    outlet: 'detail'
}];

app-routing.module (lazy loading):
  {
    path: 'result',
    loadChildren: './pages/main/system-result-page/system-results.module#SystemResultsPageModule',
  },

app.component.html
            <ion-router-outlet class="router" slot="start"></ion-router-outlet>
            <ion-router-outlet name="detail" id="detail"></ion-router-outlet>

So what I'm trying to do is to link from master outlet to detail outlet. If I change the target outlet to master I get the correct result with the id but to the wrong outlet. If I remove the id I get the results to the correct outlet but without the id I don't have the data.


text:
Q: Adding Foreign Key Constraint I'm trying to create a table, but I had a problem with foreign key
this is the script I tried :
CREATE TABLE IF NOT EXISTS note_etudiant(
    num_insc int auto_increment,
    cin int foreign key references T_utilisateur(cin),
    nom varchar(25),
    note float
)Engine=InnoDB DEFAULT CHARSET=latin1;

And this is the error I got :

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
  near 'foreign key references T_utilisateur(cin),
          nom varchar(25),
          no' at line 3

A: You need to list your foreign key constraint after your column creation
cin int,
constraint foreign key (cin) references T_utilisateur(cin),

A: You need to create the foreign key separately from the column. I also recommend creating the index separately so you can control the name of the index.
Try something like this:
CREATE TABLE IF NOT EXISTS note_etudiant(
    num_insc int auto_increment,
    cin int,
    nom varchar(25),
    note float,
    primary key (num_insc),
    key cin (cin),
    constraint fk_note_etudiant_to_t_utilisateur foreign key (cin) references T_utilisateur(cin)
)Engine=InnoDB DEFAULT CHARSET=latin1;


text:
Q: Unexpected behavior by DATETIMEOFFSETFROMPARTS T-SQL Function T-SQL function DATETIMEOFFSETFROMPARTS does not seem to allow non-zero minutes in the offset portion, i.e., the 9-th input parameter.
I have tried various combinations of defining the DateTimeOffset data type with precisions other than zero, all to no avail. Can't think of a workaround except perhaps assembling a character string in datetimeoffset format; that would probably work, but I'd like to see whether DateTimeOffsetFromParts is having a problem, or is it myself?
-- Unexpected behavior by DATETIMEOFFSETFROMPARTS function, SQL Server 2014
DECLARE @sStatus nvarchar(MAX) = 'OK'
DECLARE @sP nvarchar(MAX);
DECLARE @D1 DateTimeOffset(0) = '1901/1/1 01:01:01 -04:30';
DECLARE @D2 DateTimeOffset(0) = '1902/2/2 02:02:02 -04:30';
SET @sP = N'ProductLevel=' +
    CONVERT(nvarchar(25),SERVERPROPERTY('PRODUCTLEVEL')) +
    ', ProductVersion=' +
    CONVERT(nvarchar(25),SERVERPROPERTY('PRODUCTVERSION'));
BEGIN TRY
SET @D1 = DATETIMEOFFSETFROMPARTS(2017, 1, 1, 1, 1, 0, 0, -4, 00, 0);
-- SET @D2 = DATETIMEOFFSETFROMPARTS(2017, 1, 1, 1, 1, 0, 0, -4, 30, 0);
-- When uncommenting the above line, error 289 occurs
SET @sP = @sP + N', @D1=' + CONVERT(nvarchar(30), @D1) + N', @D2=' +
CONVERT(nvarchar(30), @D2);
END TRY
BEGIN CATCH
    SET @sStatus = N'Err Num = ' + CONVERT(nvarchar(12), ERROR_NUMBER());
    SET @sStatus = @sStatus + N', ' + N'Err Severity = ' +
        CONVERT(nvarchar(12), ERROR_SEVERITY());
    SET @sStatus = @sStatus + N', ' + N'Err State = ' +
        CONVERT(nvarchar(12), ERROR_STATE());
    SET @sStatus = @sStatus + N', ' + N'Line Num = ' +
        CONVERT(nvarchar(12), ERROR_LINE());
    SET @sStatus = @sStatus + N', ' + N'Msg: ' + ERROR_MESSAGE();
    SET @sP = @sStatus;
END CATCH
SELECT @sP AS Result;

-- Result with SET @D2 = ... commented out:
-- ProductLevel=RTM, ProductVersion=12.0.2569.0, @D1=2017-01-01 01:01:00.0 -04:00, @D2=1902-02-02 02:02:02.0 -04:30

-- Result with SET @D2 = ... uncommented (remove leading '--'):
-- Err Num = 289, Err Severity = 16, Err State = 6, Line Num = 11, Msg: Cannot construct data type datetimeoffset, some of the arguments have values which are not valid.

When the 9-th parameter to DateTimeOffsetFromParts is not 0, I get error 289: 'Cannot construct data type datetimeoffset, some of the arguments have values which are not valid'. However, offset minutes from 0 to 59 should be valid input, including 30.

A: As ZLK pointed out, input arguments 8 and 9 in DATETIMEOFFSETFROMPARTS need to have the same sign: both positive, or both negative. The proper line in the code is therefore:
 SET @D2 = DATETIMEOFFSETFROMPARTS(2017, 1, 1, 1, 1, 0, 0, -4, -30, 0);


text:
Q: SharePoint 2016 - Create Service Application timed out We have a SharePoint 2016 environment setup which consists of following servers:
1. Wfe with distributed cache server
2. Application server
3. Search server
4. Database server
As part of installation we installed SharePoint 2016 prerequisites, then installed SharePoint 2016 binaries on all SharePoint servers, then ran SharePoint configuration wizard on all servers.
Now we need to create Service Applications as part of configuration, but none of the service application gets created successfully from UI or PowerShell. When we create Service Application from UI it takes long and then it give error: "Request timed out". When we look at created service application in central admin, we can see the service application name with status stopped, no proxy gets created for the service application, database and the application pool does get created.
When we create service application using PowerShell then it takes 3-4 hours but the command to create service application does not complete. Even deleting the service application take 2-3 hours from PowerShell, from UI it just times out.
There are no errors related to this found in ULS logs or Event logs.
Any ideas what could be the issue here, why service applications are not getting created?
Thanks in advances,
Anna
Update - Following errors appeared in ULS Logs when i again tried to create managed metadata service application and word automation service application
(Watson Reporting Cancelled) System.Threading.ThreadAbortException: Thread was being aborted.
 at Microsoft.SharePoint.Administration.SPTimerJobAsyncResult.WaitForCompletion(Object state)
 at Microsoft.SharePoint.Administration.SPTimerJobAsyncResult.End()
 at Microsoft.SharePoint.Administration.SPServiceApplication.ProvisionInstances()
 at Microsoft.SharePoint.Administration.SPIisWebServiceApplication.Provision()
 at Microsoft.Office.ConversionServices.Service.ConversionServiceApplication.Provision()
 at Microsoft.Office.Word.Server.Service.WordServiceApplication.Provision()
Timer 'Word Automation Service': Canceling execution because App 'Word Automation Service' is not online (Status=Provisioning)
MetadataWebServiceApplication 'Managed Metadata Service' create failed. Exception: System.Threading.ThreadAbortException: Thread was being aborted.
 at Microsoft.SharePoint.Administration.SPTimerJobAsyncResult.WaitForCompletion(Object state)
 at Microsoft.SharePoint.Administration.SPTimerJobAsyncResult.End()
 at Microsoft.SharePoint.Administration.SPServiceApplication.ProvisionInstances()
 at Microsoft.SharePoint.Administration.SPIisWebServiceApplication.Provision()
 at Microsoft.SharePoint.Taxonomy.MetadataWebServiceApplication.Provision()
 at Microsoft.SharePoint.Taxonomy.MetadataWebServiceApplication.UpdateData(String sharedAppName, SPIisWebServiceApplicationPool applicationPool, Boolean unpublishAllPackages, String hubUri, Boolean doSetErrorReport, Boolean isErrorReportEnabled, Boolean doProvision)
 at Microsoft.SharePoint.Taxonomy.MetadataWebServiceApplication.Create(String sharedAppName, String databaseName, String databaseServer, String sqlAuthUserName, String sqlAuthPassword, String failoverServer, SPIisWebServiceApplicationPool applicationPool, String hubUriString, Boolean isErrorReportEnabled, Boolean isInDefaultAssociation, Boolean isPartitioned, Int32 cacheCheckInterval, Int32 maxChannelCache, Boolean forceProxyCreation, Boolean fDeferUpgradeActions)
MetadataWebServiceApplication 'Managed Metadata Service' unprovision started.

A: Couple of things to try

*

*If you have installed the Anti-Vrius on the servers, try to to disable it

*check if firewall is causing this issue.

*if you have any auditing or proctection software installed which may cause this issue.

*Try to run the  psconfig -cmd upgrade -inplace b2b force on the all servers and make sure all server report that no action required.

*Sometime applying latest updates fix it.

*Also make sure you login with farm admin account with local admin on the server.


text:
Q: How to get absolute path of a file located in the assets folder with react-native and expo? Simple question. I have an assets folder that is on my root directory, and I have some files there.
Example: assets/doc/wantedfile.pdf
I need to get the absolute path of this file, not the relative one. Probably is something like this: file:///data/expo/(...)/app/assets/doc/wantedfile.pdf
But the project is on expo so the solutions that I found here to this problem for Android and IOS didn't work. The solution must work with expo.
I can't use RNFetchBlob because it needs to link (don't work on expo)
Can't detach of expo because the project is very big and it will require a lot of work.
Don't know if RNFS works with expo, didn't tested yet, if it needs linking then doesn't work.
Any tips ?
I tried to use FileSystem.documentDirectory to get absolute path, but it gives me the path of an empty directory folder (i think that it is the directory folder of the emulator, not the application).
I need to get the abs path of the assets folder.

A: Use Asset module
import { Asset } from 'expo';

...
async render() {
  const pdfURI = await Asset.fromModule(require('.assets/doc/wantedfile.pdf')).uri;
}
...

Check here for detail: https://docs.expo.io/versions/v32.0.0/sdk/asset/#expoassetloadasyncmodules


text:
Q: Automatic storage and C99 VLA array If I have the following:
int *test()
{
    int d = 10;
    int a[d];

    a[0] = 10;
    a[1] = 20;

    printf("%p\n", a);

    return a;

}

int main(void)
{
    int *a = test();

    printf("%p %d\n", a, a[0]);

    return 0;
}

when I return a from test to main the memory allocated for a inside test is not
destroyed. But why? Isn't a an automatic storage variable that die when the block
function exit? In fact when I compile the code the compiler warn me with:
function returns address of local variable [-Wreturn-local-addr]

The same thing happen if I use a static array.

A: The requirement is not for the memory to be "destroyed" (whatever it could mean - filling with zeros?) the standard says only that such code as yours triggers undefined behaviour - and undefined behaviour may mean anything, including the situation in which the memory for some time has the same content. But still it is undefined behaviour and your code is erroneous.

A: There is no requirement in the C standard to "destroy" the data stored in a variable that goes out of scope.
It isn't safe to access a after it has gone out of scope.  The memory is free to use for other purposes. What happens if you access the memory is unspecified. It may return the value you put there, it may return some other (junk) value, it may cause a program crash or it may blow up the island of Manhattan.
The last option is very unlikely though, I haven't come across any C compiler that generates code that does that.

A: a is a local variable. "Local" as in function-local. a doesn't exist any more once test() returns. Thus you return a pointer to an object that doesn't exist any more, and the compiler rightly complains.
You can either pass an array as parameter to test() and fill that array within test(), or you can actively allocate memory on the heap with malloc() within test() and return a pointer to that. Note that the caller then has to free() said memory again to prevent memory leaking.


text:
Q: RxJava wait for single Event, RxJava How do you wait for a single value to come on an observable with a timout?
I am looking for something like:
Observable<Acknowledgement> acknowledgementObservable;
port.send(new Message());
Optional<Acknowledgement> ack = acknowledgementObservable.getFirst(100, TimeUnit.MILLISECONDS);

A: First, convert Observable to CompletableFuture as described in Converting between Completablefuture and Observable:
Observable<Acknowledgement> acknowledgementObservable;
port.send(new Message());
CompletableFuture<T> future = new CompletableFuture<>();
acknowledgementObservable
    .doOnError(future::completeExceptionally)
    .single()
    .forEach(future::complete);

Then, wait for the event using timeout:
Acknowledgement ack = future.get(100, TimeUnit.MILLISECONDS);

It throws TimeoutException if timeout occurs.

A: You can do so by adding .timeout() and .onErrorComplete() .blockingGet()
So in this example it would be:
    Acknowledgement ack = acknowledgementObservable
                              .firstElement()
                              .timeout(3, TimeUnit.SECONDS)
                              .onErrorComplete()
                              .blockingGet();

If the timeout is hit, ack will be null.


text:
Q: MINLP with large number of binary variables I am working on the following formulation.
max $ \Bigg(\sum_{n \in N}\sum_{i \in C}\ y_{in} \bigg(\  f_{in} ( \pmb{\beta}) - g_{in}\bigg) \Bigg)$
such that
$\sum_{i \in C} y_{in} = 1 \qquad \forall n \in N$
$y_{in} \in \{0,1\}$
$\pmb{\beta} \in [\pmb{\beta_{min}}, \pmb{\beta_{max}}]$
where deision variabels are $\pmb{\beta}$ and $y_{in}$. $f_{in}( \pmb{\beta})$ is a concave function and $g_{in}$ is a penalty term which is independent of $\pmb{\beta}$.
Since for large data, I will have NxC $y_{in}$. My questions are:

*

*How can I efficiently solve this problem for a large number of binary variables?

*Can traditional solvers handle this kind of formulation?
I would really appreciate some advice on problem formulation as well as on solution approach.
Thanks!

A: You can try solving each
$$B_{in}=\max_{\beta}f_{in}(\beta)-g_{in}, ~ \forall (i,n)\in C\times N$$
because $f$ is a concave function and have one variable only (well-known problem). After that you return a matrix $B$ of these solution. Your problem is equvalent to:
$$\sum_{n=1}^{N}\max_{i\in C}\{B_{in}\}$$
I think this is efficient enough. I prefer Newton's method, but without more assumptions about $f$ I recommend you use the bisection method.


text:
Q: Where is that question about electricity and RAM? I seem to remember a question (and answer) asking how often an electrical issue affects what is stored in RAM, and the answer was very high. Does anyone have a link to this question?

A: I believe you're thinking of the cosmic rays question (meta discussion).


text:
Q: Lubridate speed up date time operation I'm trying to convert 04/03/2019 07:22:14 -> 2019-04-03 07:22:14 with lubridate package. My approach works good, but it is very slow:
library(dplyr)
library(lubridate)

df <- data.frame(DateTimeStamp=replicate(9e5,"04/03/2019 07:22:14"),
stringsAsFactors = F) %>%
  mutate(DateTimeStamp_Changed=as.POSIXct(unlist(lapply(DateTimeStamp,
function(item) {
    return(as.character(parse_date_time(paste0(
      as.Date(unlist(strsplit(item," "))[1], "%m/%d/%Y"),
      unlist(strsplit(item," "))[2]
    ), orders="ymd HMS")))
  }))))

Is there any way how to speed this up? Thanks for any of your hint.

A: You can use the function ymd_hms() from the library lubridate
library(lubridate)
library(dplyr)

"04/03/2019 07:22:14" %>%
    fast_strptime(format = '%d/%m/%Y %H:%M:%S') %>%
    ymd_hms()
# [1] "2019-03-04 07:22:14 UTC"


text:
Q: Docker container ssh not starting if starting a script or settings LD_PRELOAD I have a Docker image which starts SSH at startup and listen for connections:
FROM nvcr.io/nvidia/deepstream:6.0-triton

# OTHER STUFF HERE
# ....

# SSH AND REMOTE LOGIN FOR DEVELOPMENT PURPOSES
RUN apt update && apt install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:my_password' | chpasswd
RUN sed -i 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config
# SSH login fix. Otherwise user is kicked off after login
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd
ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile
RUN sed -i 's/\(^Port\)/#\1/' /etc/ssh/sshd_config && echo Port 2222 >> /etc/ssh/sshd_config
# Export 2222 for SSH server
EXPOSE 2222

# ENV
# LD_PRELOAD="/src/libmyplugins.so:${LD_PRELOAD}"

# STARTUP
# Disable previous entrypoint.
ENTRYPOINT []
# Set default dir
WORKDIR /src
# Enable SSH for debug on remote server
CMD ["/usr/sbin/sshd", "-D"]

My goal is to be able to add /src/libmyplugins.so to LD_PRELOAD.
I tried a few things, and all of them resulted in the container stopping right after starting:

*

*Add LD_PRELOAD="/src/libmyplugins.so:${LD_PRELOAD}" to the Dockerfile

*Create a script an entrypoint.sh to be run at startup with CMD ["sh", "entrypoint.sh", "&&", "/usr/sbin/sshd", "-D"] with the goal of setting the env variable inside the script file.


text:
Q: Permissions on disk in Gcloud for Jenkins How do I have to configure the permissions for a disk in gcloud:
I have a kubernetes cluster. I created a persistent disk:
$ gcloud compute disks create --size 30GB jenkins-disk --zone europe-west1-c

content of my deployment.yaml:
volumeMounts:
- mountPath: /var/jenkins_home
  name: jenkins-storage
  volumes:
  - name: jenkins-storage
    gcePersistentDisk:
      pdName: jenkins-disk
      fsType: ext4

error:
touch: cannot touch '/var/jenkins_home/copy_reference_file.log': Permission denied

Do I need to give write access to my jenkins user to write to the disk? How do I have to configure this?

A: Use this image of Jenkins Instead of latest in your deployment https://hub.docker.com/r/wsimmonds/jenkins-kubernetes/
Description from this Image :
Trying to run the default Jenkins image (or jenkinsci/jenkins) with a persistent volume mounted to /var/jenkins_home will currently fail:
2016-06-10T13:46:55.617454157Z touch: cannot touch '/var/jenkins_home/copy_reference_file.log': Permission denied
2016-06-10T13:46:55.617955276Z Can not write to /var/jenkins_home/copy_reference_file.log. Wrong volume permissions?
The reason? Kubernetes volumes are currently mounted with root ownership and Jenkins runs as "jenkins" by default (https://github.com/jenkinsci/docker/blob/master/Dockerfile). The temporary workaround runs Jenkins as root - I don't advise production use unless you know what you're doing and have full control of the code you are building.


text:
Q: Getting error 400 on ajax request on Wordpress custom theme I'm writing a Wordpress custom theme and in one of the pages, I have a form with two selects and a submit button. Basically the user can select two cities and check if there's a route between them.
I am using an Advanced Custom Fields Relationship field to link the cities (city is a post type).
The problem is I'm always getting a 400 error and I cannot figure what is the problem.
I have checked different solutions found here but none of them seems to work for me.
admin-ajax.php:
add_action('wp_ajax_check_route', 'check_route');
add_action('wp_ajax_nopriv_check_route', 'check_route');

function check_route() {
    $id_cidade_origem = intval($_REQUEST['cidade_origem']);
    $id_cidade_destino = intval($_REQUEST['cidade_destino']);

    $cidades_atendidas = get_field('regioes_atendidas', $id_cidade_origem);

    $tem_relacao = False;
    foreach ($cidades_atendidas as $cidade) {
        if($cidade->ID == $id_cidade_destino){
            $tem_relacao = True;
            break;
        }
    }
    $data = array(
        'success' => true,
        'tem_relacao' => true
    );
    wp_send_json_success($data);
    $data = array(
        'success' => false
    );
    wp_send_json_error($error_data);
}

scripts.js:
jQuery("#regioes-botao").click(function (){
        console.log("Clicou!");
        jQuery.ajax({
            type: "POST",
            url: "/wp-admin/admin-ajax.php",
            data: {
                action: 'check_route',
                cidade_origem: jQuery('#select-from').find(":selected").val(),
                cidade_destino: jQuery('#select-to').find(":selected").val(),
            },
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (output) {
               console.log('sucesso!')
               console.log(output);
               var resposta = output.tem_relacao;
               if(resposta == true){
                    jQuery('#resposta span').text("Nós fazemos esta rota, entre em contato.")
               }else{
                    jQuery('#resposta span').text("No momento não fazemos esta rota, mas já estamos trabalhando para que seja possível em breve.")
               }
            },
            error: function(output){
                console.log(output)
            }
        });
    });

A: Error code 400 means that your originating request is not understandable for the server. Try the below written code:
$.ajax({
    url: ajax_object.ajax_url, //Used wp_localize_script to pass ajax url to wordpress. Example is at https://codex.wordpress.org/AJAX_in_Plugins
    type: 'POST',
    data: {
        'action': 'check_route',
        'cidade_origem': jQuery('#select-from').find(":selected").val(),
        'cidade_destino': jQuery('#select-to').find(":selected").val(),
    },
})
.done(function(response) {
    console.log(response);
})
.fail(function() {
})
.always(function() {
});

Do note that I have only defined request type, url to call and the data to send. I am pretty sure that this should work as I am using this in many of my projects.


text:
Q: Need help with preg_replace $text = '
hello

';

$text_2 = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $text);

OUTPUT(i have given the html format here):

hello

My problem is all attributes must be removed but not the attributes belongs to table. That is i am expecting the out put exactly like below(HTML FORMAT):

hello

What should i need to modify in the above regular expression to achieve it..
Any help will be thankful and grateful....
Thanks in advance...

A: If you want to avoid using regex, because you really souldn't use regex to work on xml/html structures, try:
<?php
$text = '
hello

';

$dom = new DOMDocument;
$dom->formatOutput = true;
$dom->loadHtml($text);

$xpath = new DOMXpath($dom);
foreach ($xpath->query('//*[not(name()="table")]/@*') as $attrNode) {
    $attrNode->ownerElement->removeAttributeNode($attrNode);
}

$output = array();
foreach ($xpath->query('//body/*') as $childNode) {
    $output[] = $dom->saveXml($childNode, LIBXML_NOEMPTYTAG);
}

echo implode("\n", $output);

Output:

  hello

A: You are very close with your current reg-ex. You need to do a check (think it is a negative look-ahead in this case?)
<(?!table)([a-z][a-z0-9]*)[^>]*?(\/?)>
What that first bit of reg-ex is doing is checking that it does not start with 'table', then it is your regex.

A: Bit of hacky solution, but works .
Try disabling TABLE tags for a while in your code, and enable them again.
It would work.
see : http://codepad.org/nevLWMq8
<?php

$text = '
hello

';

/* temporary change table tags with something not occuring in your HTML  */
$textTemp = str_replace(array("
"),array('###','+++'),$text);

$text_2 = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $textTemp);

echo "\n\n";
 /* restore back the table tags */

$finalText =  str_replace(array("###","+++"),array("
"),$text_2);
echo $finalText ;

?>


text:
Q: Adding a dependency on Spark to a command line Spring Boot application prevents the JVM from exiting I'm building a REST client.  In addition I have Apache Spark in my path.  Without Spark I'm able to run as a normal Spring CommandLineRunner, but when I add Spark I get an issue about competing logger implementations.
In order to fix this I figure I can change the Logger for Spring.  Here are my dependencies:
dependencies {
    compile("org.springframework.boot:spring-boot-starter")
    compile("org.springframework:spring-web")
    compile("com.fasterxml.jackson.core:jackson-databind")

    compile("org.slf4j:slf4j-api:1.7.1")
    compile("org.slf4j:jcl-over-slf4j:1.7.1")
    compile("ch.qos.logback:logback-classic:1.0.7")

//    compile('com.sparkjava:spark-core:2.2')
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

As it it runs.  When I uncomment those lines, the application hangs at the end.  This is the expected output:
This build could be faster, please consider using the Gradle Daemon: https://docs.gradle.org/2.11/userguide/gradle_daemon.html

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.3.RELEASE)

2016-03-07 09:50:36.646  INFO 20150 --- [           main] <packages>.arc.Application            : Starting Application on <machine> with PID 20150 (/Users/carbribi/workspace/code/architecture-pilot/idiom-pilot-arc/build/libs/idiom-pilot-arc-0.1.0.jar started by carbribi in /Users/carbribi/workspace/code/architecture-pilot/idiom-pilot-arc)
2016-03-07 09:50:36.651  INFO 20150 --- [           main] <packages>.arc.Application            : No active profile set, falling back to default profiles: default
2016-03-07 09:50:36.703  INFO 20150 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@4ca638be: startup date [Mon Mar 07 09:50:36 EST 2016]; root of context hierarchy
2016-03-07 09:50:37.391  INFO 20150 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-03-07 09:50:37.529  INFO 20150 --- [           main] <packages>.arc.Application            : Quote{type='success', value=Value{id=8, quote='I don't worry about my code scaling. Boot allows the developer to peel back the layers and customize when it's appropriate while keeping the conventions that just work.'}}
2016-03-07 09:50:37.532  INFO 20150 --- [           main] <packages>.arc.Application            : Started Application in 1.155 seconds (JVM running for 1.507)
2016-03-07 09:50:37.543  INFO 20150 --- [       Thread-2] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@4ca638be: startup date [Mon Mar 07 09:50:36 EST 2016]; root of context hierarchy
2016-03-07 09:50:37.545  INFO 20150 --- [       Thread-2] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

But when I uncomment the lines I get the following:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.3.3.RELEASE)

2016-03-07 09:55:32.039  INFO 20821 --- [           main] <packages>.arc.Application            : Starting Application on <machine> with PID 20821 (/Users/carbribi/workspace/code/architecture-pilot/idiom-pilot-arc/build/libs/idiom-pilot-arc-0.1.0.jar started by carbribi in /Users/carbribi/workspace/code/architecture-pilot/idiom-pilot-arc)
2016-03-07 09:55:32.042  INFO 20821 --- [           main] <packages>.arc.Application            : No active profile set, falling back to default profiles: default
2016-03-07 09:55:32.090  INFO 20821 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1f84341e: startup date [Mon Mar 07 09:55:32 EST 2016]; root of context hierarchy
2016-03-07 09:55:32.674  INFO 20821 --- [           main] org.eclipse.jetty.util.log               : Logging initialized @1288ms
2016-03-07 09:55:32.735  INFO 20821 --- [           main] e.j.JettyEmbeddedServletContainerFactory : Server initialized with port: 8080
2016-03-07 09:55:32.737  INFO 20821 --- [           main] org.eclipse.jetty.server.Server          : jetty-9.2.15.v20160210
2016-03-07 09:55:32.767  INFO 20821 --- [           main] application                              : Initializing Spring embedded WebApplicationContext
2016-03-07 09:55:32.767  INFO 20821 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 680 ms
2016-03-07 09:55:32.821  INFO 20821 --- [           main] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-03-07 09:55:32.823  INFO 20821 --- [           main] o.e.jetty.server.handler.ContextHandler  : Started o.s.b.c.e.j.JettyEmbeddedWebAppContext@58e48ac1{/,file:/private/var/folders/_r/qfqg_c5n0q9c7kl58145q7njb2xtxx/T/jetty-docbase.7881372241529376843.8080/,AVAILABLE}
2016-03-07 09:55:32.824  INFO 20821 --- [           main] org.eclipse.jetty.server.Server          : Started @1439ms
2016-03-07 09:55:33.026  INFO 20821 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-03-07 09:55:33.061  INFO 20821 --- [           main] o.eclipse.jetty.server.ServerConnector   : Started ServerConnector@7d141e3b{HTTP/1.1}{0.0.0.0:8080}
2016-03-07 09:55:33.063  INFO 20821 --- [           main] .s.b.c.e.j.JettyEmbeddedServletContainer : Jetty started on port(s) 8080 (http/1.1)
2016-03-07 09:55:33.626  INFO 20821 --- [           main] <packages>.arc.Application            : Quote{type='success', value=Value{id=5, quote='Spring Boot solves this problem. It gets rid of XML and wires up common components for me, so I don't have to spend hours scratching my head just to figure out how it's all pieced together.'}}
2016-03-07 09:55:33.626  INFO 20821 --- [           main] <packages>.arc.Application            : Started Application in 1.879 seconds (JVM running for 2.242)

Then execution stops and it hangs there.  I can see its starting a Jetty server.  Is this the reason its hanging?  If so, how do I prevent it?  Regardless of the reason, how do I make it end execution?

A:
I can see its starting a Jetty server. Is this the reason its hanging?

Yes. Technically, the JVM hasn't hung but it hasn't shut down as there there are non-daemon threads running. These threads are started by Jetty and are used to handle HTTP requests.

If so, how do I prevent it?

Spring Boot has started an embedded Jetty servlet container as it's found Jetty on the classpath and, therefore, has assumed that you're building a web application. You need to tell it that that is not the case. You can do so in your application's main method by setting web to false:
@SpringBootApplication
public class SampleApplication {

    public static void main(String[] args) throws Exception {
        new SpringApplicationBuilder(SampleApplication.class).web(false).run(args);
    }

}


text:
Q: Clean way to convert CURL to Jquery/Javascript [Instagram] I'm trying to convert the curl command from the instagram api to jquery(ajax/get).

 curl -F 'client_id=CLIENT_ID' \
    -F 'client_secret=CLIENT_SECRET' \
    -F 'grant_type=authorization_code' \
    -F 'redirect_uri=AUTHORIZATION_REDIRECT_URI' \
    -F 'code=CODE' \
    https://api.instagram.com/oauth/access_token

From the doc :

"In order to make this exchange, you simply have to POST this code,
  along with some app identification parameters"

var clientId = "my client id";
var clientSecret = "my client secret";
var redirectURI = "http://localhost:3000/instagram";
var myCode = "my instagram code";
var uri = 'https://api.instagram.com/oauth/access_token?client_id=' + clientId + '&client_secret=' + clientSecret + '&grant_type=authorization_code&redirect_uri=' + redirectURI + '&code=' + myCode;
var url = encodeURIComponent(uri);

$.ajax({
   type: "POST",
   dataType: "json",
   url: '  https://api.instagram.com/oauth/access_token?client_id=' + clientId + '&client_secret=' + clientSecret + '&grant_type=authorization_code&redirect_uri=' + redirectURI + '&code=' + myCode,
   success: function (result) {
      console.log(result);
   }
});

Doesn't seems to work for me...
Getting Cross Origin Block Request [CORS] error.

A: First of all, in order to send values in the query string, use the .data property of the options object you send to jQuery.ajax. And if you want to create the url programatically, do not forget to URL encode the values you send via encodeURIComponent.

A: Try with jsonp. Something like:
function myinstagramfunction (json_object)
{
    // I fetch here the json object that contains the info of all the pictures returned
    console.log("OK");
}
$.ajax({
   type: "GET",
   dataType: "jsonp",
   url: 'https://api.instagram.com/v1/tags/YOUR_HASHTAG/media/recent?access_token=YOUR_ACCESS_TOKEN_HERE&callback=myinstagramfunction',
   success: function (result) {
      console.log(result);
   }
});


text:
Q: Magento 2 - Duplicate Order Issue I am currently running a magento 2 website (ver. 2.2.6).  I have been an issue (pretty frequently) where some customers (not all) are reporting that they are commonly receiving an error upon attempting to submit an order.  The error that they receive is:
sort order field isnull(expiration_date), expiration_date, transaction_id contains restricted symbols

The customer(s) report that this error appears when they click on submit order, and the website never goes to the checkout success page.  Therefore the customer thinks that the website did not receive their order.  They then proceed to click on submit order multiple times, subsequently placing multiple orders.  I catch these with the payment alerts or the customer sends an email reporting that they just placed 8 orders by mistake.  Commonly, the customer reports being on a mobile device, and this happens with both paypal and/or credit card (Stripe processing).
I have also been advised that sometimes they do not get this error, but the site just looks like it does nothing and remains on the checkout page when they click on submit order, also subsequently placing multiple orders.
When I go to the backend of the site, I do see an order placed that matches the payment obtained from the customer, through the payment processor.  The problem is, I can not re-create this issue myself so it has been extremely difficult to trouble shoot.  As I have paid 2 separate developers to try and resolve this, with no success.
I am looking for some help with this issue, as it is causing many issues, and upsetting many customers.  Thanks!  Below is an image of the error, provided by a customer.

A: You should be using Aheadworks_RewardPoints module.
Go to the file /app/code/Aheadworks/RewardPoints/Model/Service/CustomerRewardPointsService.php.
Search for the method private function getCustomerTransactions.
Change ->setField('ISNULL(expiration_date), expiration_date, transaction_id') line
to ->setField('expiration_date').


text:
Q: Clustering and Predicting Subclasses I am trying to work on a  clustering problem where I actually know the sublcass.
Suppose I am trying to predict cluster patients a group of people into male and female where I actually know the label male and female but I take it I don't know
Suppose my clustering method produces subclasses label 1 and 2. Is there a quick method of how to assign which labels 1 and 2 to male or female to maximize my prediction accuracy? Obvious in this case since there are only two cases it is trivial but when the number of subclasses gets big it, trying all the possible combinations can be very time consuming.

A: There is nothing time consuming here, compared to the cost of clustering the data.
You can find the most common label per cluster in O(n) with tiny constant factors, that is as fast as it will get.

A: The automatic cluster assignment problem you're looking for can be solved by the clustering error, or maximum match, measure. It tries to find the best label assignment to the found clusters (even when you have found less/more clusters than the correct number of labels).
Take a look at this video and this scientific paper.


text:
Q: pycharm ssh interpter No such file or directory I am using a macbook pro 15 as local machine and I have a remote server running ubuntu 14.04
I want to use the remote intepreter to run all the computation but I want to write the code from my local machine.
When I try to run a simple file with pycharm I receive this error:
ssh://donbeo@149.157.140.205:22/usr/bin/python3 -u /Users/donbeo/Documents/phd_code/prova.py
bash: line 0: cd: /Users/donbeo/Documents/phd_code: No such file or directory
/usr/bin/python3: can't open file '/Users/donbeo/Documents/phd_code/prova.py': [Errno 2] No such file or directory

Process finished with exit code 2

I saw few people reporting the same problem but I haven't found a good answer so far. Most of the questions are indeed referring to older versions of pycharm.
It is clear that the file is not in my remote machine because I create it with pycharm in my local one. I was expecting pycharm to do some sort of synchronisation between the local and remote machine.

A: To execute your code on remote machine you'll have to perform few steps
Define a remote interpreter for your project

*

*Go to File -> Settings -> Project: {project_name} -> Project Interpreter.

*Click on cog icon and select Add Remote.

*Add your SSH host credentials and interpreter path (on remote machine).

*As a result, you should see new position in project interpreter dropdown selector, spelled like Python Version (ssh://login@host:port/path/to/interpreter). Package list should be populated with records.

Define deployment settings

*

*Go to File -> Settings -> Build, Execution, Deployment -> Deployment

*Create new deployment settings and fill ssh host configuration

*

*Type: SFTP

*SFTP host: same as interpreter host

*Root path: path where files will be uploaded

*Click on button "Test SFTP connection" to check if provided data are correct.

*Go to mappings and configure mapping between local path and deployment path. Deployment path is relative to root path - / is equivalent to /my/root/path, /dir to /my/root/path/dir etc.

Deploy your code

*

*Select Tools -> Deployment -> Upload to {deployment settings name}

*Upload process will be started in background. Wait for upload to complete.

Run your code

*

*Right click on file you want to run and select "Run". Code should run on remote machine.

A: Be sure your interpreter is chosen as SSH which is to compile, not STFP which is for deployment.

A: I'm running PyCharm 2018.3
The Problem:
First, I didn't have the [Errno 2] No such file or directory problem. Then I had the problem out of nowhere.
The issue arose when I did:

*

*Preferences -> Project: {project_name} -> Project Interpreter

*Instead of "Click on cog icon and select Add Remote", I chose a interpreter that I've configured previously (that is working fine previously) from the drop down menu

By doing the steps above, I had [Errno 2] No such file or directory problem.
The reason is that the folder is not automatically synced to the remote server (a bug?), nor could I find a way to configure it to sync. Configuring Deployment and Path Mappings did work, but it's too much manual labor and prone to error.
The solution:
All I had to do is to add a new remote interpreter, despite that identical configurations already exists previously. (To be safe, I did remove the old ssh interpreter and the old deployments, also removed .idea folder) Then everything worked as expected.

*

*I didn't need to configure Deployment

*I didn't need to configure Paths mappings

A: Sometimes you can have everything set up correctly (interpreter, deployment, Path mapping, etc) but PyCharm keeps trying to use your local path on the remote machine.
If this happens, try this 4 fixes:

*

*Go to File->Invalid Caches / Restart
...if the problem is still not fixed:

*Go to Preferences->Python Interpreter->Path Mappings and check the path mappings of the interpreter. They should look more or less like this:

...again, if the previous step didn't work:

*Go to Run->Edit Configurations... and check if the path mappings are correct:

*You can also try to replace the local paths of the script and working directory with the remote ones (as if you were already in that machine).

*If you get ModuleNotFoundError but the connection seems to work, go to Run->Edit Configurations...->Environment Variables and add your project's root path to the PYTHONPATH variable.

A: It can be caused by one of the following:
1. You did not deploy your code on the remote server.!

*

*Make sure that the recent edition of your code is deployed on the server. You can always deploy your code from Tools -> Deployment -> Upload to ..., or by using Ctrl + Shift + Alt + x.

*For setting the deployment path, Go to File -> Settings -> Build, Execution, Deployment -> Deployment, and enter a remote sever details as your deploying machine.

*In the Mappings tab, make sure that the deployment path is defined somewhere on the server where you have permission to read and edit files there.

2. You do not have the permission to read and change files on your deployment path at the remote server.

*

*Go back to File -> Settings -> Build, Execution, Deployment -> Deployment, and change deployment path on the Mappings tab.

A: For those who meet the problem like "miniconda3/envs/gpu/bin/python: can't open file '///home/.../test.py", you can just run the python script file in locality in pycharm rather than run the file in server in pycharm.


text:
Q: Why does Java return null pointer exception on image all of a sudden? I have been trying to create a resizable image by drawing BufferedImage on a panel and redrawing it whenever componentResized happened. However, despite the image loading fine in earlier versions (which either didn't resize at all or didn't do it properly) now Java claims the image isn't there.
The code is as follows
    public class Image extends JPanel{
    BufferedImage img=null;

    public Image{
    try {
        img = ImageIO.read(new File("Untitled.png"));
    }
    catch (IOException e) {
    }
    Dimension d=getSize();
    Graphics g=getGraphics();
    g.drawImage(img, 0, 0, d.width, d.height, null);

even without the component listener, it returns NullPointerException on drawImage. But I know the image isn't null, since it worked previously, which leads me to thinking there's something wrong with the code here

A: If something goes wrong in here:
img = ImageIO.read(new File("Untitled.png")); Then you are drawing on a null reference object here:
g.drawImage(img, 0, 0, d.width, d.height, null);

That is the reason of the NPE

A: This is due to that the Graphics object g may be null.
Graphics g = getGraphics();


text:
Q: PHP CURL: Complete manipulation of HTTP Headers not allowed? I've been working on writing a script which automatically logs me into my school's network, checks if the classes I'm trying to get into are no longer completely full, and if a spot has opened up, registers the class for me. However, I've hit a big snag in just the logging-in process.
Basically, I've been looking at the headers that are sent when I log in and try to replicate them. The problem is I keep getting an error saying "HTTP/1.1 400 Bad Request Content-Type: text/html Date: Sat, 23 Oct 2010 18:42:20 GMT Connection: close Content-Length: 42
Bad Request (Invalid Header Name)".
I'm guessing it has something to do with Host parameter I'm setting being different from what it really is (I set it so it is elion.psu.edu, but when looking at the headers from my script it has changed back to grantbachman.com, where the script is hosted). I guess it'll be best just to show you.
The beginning of the header I'm trying to create:
https://elion.psu.edu/cgi-bin/elion-student.exe/submit

POST /cgi-bin/elion-student.exe/submit HTTP/1.1
Host: elion.psu.edu

The beginning of the header which shows up when I run my script:
http://myDomain.com/myScriptName.php

GET /elionScript.php HTTP/1.1
Host: myDomain.com

Basically, the first line is different, the Host name is different, and it says I'm sending my info with a GET variable instead of a POST variable (even though I set curlopt_post to true). I'm basically looking for any help with altering this info such that the server accepts my script. I'm fresh out of ideas. Thanks.
Oh here's the code I'm using:
$data = array(
    "$userIDName" => '********',
    "$passName" => '********',
    "$submitName" => 'Login+to+eLion',
    'submitController' => '',
    'forceUnicode' => '%D0%B4%D0%B0',
    'sessionKey' => "$sessionValue",
    'pageKey' => "$pageKeyValue",
    'shopperID' => '');

$contentLength = strlen($userIDName . '=*********&' . $passName . '=********&' . $submitName .'=Login+to+eLion&submitController=&forceUnicode=%D0%B4%D0%B0&sessionKey=' . $sessionValue . '&pageKey=' . $pageKeyValue . '&shopperID=');

$ch = curl_init("https://elion.psu.edu/cgi-bin/elion-student.exe/submit");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_COOKIE,'sessionKey="$sessionValue";pageKey="$pageKeyValue";BIGipServerelion_prod_pool="$prodPoolValue"');
curl_setopt($ch,CURLOPT_HTTPHEADER,array(
    'Host: elion.psu.edu',
    'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language: en-us,en;q=0.5','Accept-Encoding: gzip,deflate',
    'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
    'Keep-Alive: 115',
    'Referer: https://elion.psu.edu/cgi-bin/elion-student.exe/launch/ELionMainGUI/Student',
    "Cookie: sessionKey=$sessionValue; pageKey=$pageKeyValue; BIGipServerelion_prod_pool=$prodPoolValue", 'Content-Type: application/x-www-form-urlencoded',
    "Content-Length: $contentLength"));
$contents2 = curl_exec ($ch);

I't also probably important to note that when I run the script, none of the information below the 'Keep-Alive: 115' line is displayed when I view the header.

A: Seems it missing some code in your question but try this :
1- Save your certificate on your server
2- Try this code
$pg = curl_init();
// Set the form data for posting the login information
$postData = array();
$postData["username"] = $username;
$postData["password"] = $password;

$postText = "";

foreach( $postData as $key => $value ) {
$postText .= $key . "=" . $value . "&";
}

curl_setopt( $pg, CURLOPT_URL, $YOUR_URL );
curl_setopt( $pg, CURLOPT_POST, true );
curl_setopt( $pg, CURLOPT_POSTFIELDS, $postText );
curl_setopt( $pg, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $pg, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $pg, CURLOPT_CAINFO, getcwd() . '/web'); //web is the exported certificate

//curl_setopt( $pg, CURLOPT_VERBOSE, true ); // for debug
//curl_setopt( $pg, CURLOPT_RETURNTRANSFERT, true); // if you want a ouput
curl_setopt( $pg, CURLOPT_COOKIEJAR, "cookies.txt" );
curl_setopt( $pg, CURLOPT_COOKIEFILE, "cookies.txt" );
curl_setopt( $pg, CURLOPT_USERAGENT, "Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)" );
curl_setopt( $pg, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $pg, CURLOPT_COOKIE, session_name() . '=' . session_id() );

if( ( $response = curl_exec( $pg ) ) === false ) {
        echo '*Curl erro' . curl_error($pg) . "\n";
}

curl_close($pg)

$YOUR_URL:https://elion.psu.edu/cgi-bin/elion-student.exe/launch/ELionMainGUI/Student
The form using dynamic name so its not simple like "username" and "password". Check on the website to know a "good" one.
Do not forget to add others hidden field like you did in the postData array and update the cookie section too.


text:
Q: Oracle 19 container database with different charactersets Is it possible in Oracle SE2 19.10 (newest patch) to have container database with different database character sets e.g.
First database with character set EE8MSWIN1250
Second database with character set AL32UTF8
Regards,
Groxy

A: For container databases, or stand-alone database you can create them with whatever character set you want.
For pluggable databases within a container, it will depend on what version of Oracle you have. For Oracle 12.2 or later, if the container database has a character set of AL32UTF8, then the pluggable databases within that container may have any character set.
That said, there is no way to create a PDB directly with a different character set than the container DB. You would have to create the PDB in a container with the same character set, then migrate it to a container with a different character set.
See here for all the details: https://oracle-base.com/articles/12c/multitenant-pdb-character-sets-12cr2


text:
Q: Why `margin: 1 auto;` doesn't work? Why margin: 0 auto; works but margin: 1 auto; doesn't? Is there some hackish way to simply fix this?

      .container {
       width: 220px;
       /* margin: 0 auto; */ /* <-- works.*/
       margin: 1 auto; /*<-- error. HOW TO FIX??? */
       padding: 16px;
       display: block;
       border: 2px solid black;
      }

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sint non cumque at minima voluptates totam suscipit, esse vitae recusandae fugit, alias quibusdam odio sunt iure velit, perferendis voluptas ratione quo!

sorry for stupid question
UPD: I'm sure this answer will be useful for the searchers that have similar troubles, plz do not delete.

A: Because 0 is universal, 1 however depends on the unit, and since no unit is specified the browser doesn't know what to do.

A: Because margin-* properties only accept lengths, percentages, and auto. Not integers.

The properties defined in this section refer to the <margin-width>
  value type, which may take one of the following values:

*

*<length>: Specifies a fixed width.

*<percentage>: The percentage is calculated with respect to
  the width of the generated box's containing block.

*auto

Then, 0 works because is a valid length, but 1 isn't.

The format of a length value (denoted by <length> in this
  specification) is a <number> (with or without a decimal point)
  immediately followed by a unit identifier (e.g., px, em, etc.). After
  a zero length, the unit identifier is optional.

It would be valid if you added some unit like 1px, 1cm, 1em, 1vh or whatever.
Therefore, your declaration is ignored:

User agents must ignore a declaration with an illegal value.

A: 0 by itself just means 0, but anything greater or lesser needs a unit. You can't say 1 and expect a length/size/etc.
0 means none and is valid. 1 by itself has no unit and CSS doesn't assume anything.
padding: 0px; /* px is redundant here because 0 means none */

padding: 1; /* error, what is 1? 1 cm? 1 em? */


text:
Q: screen lock ubuntu 11.10 While in ubuntu 11.04 I could disable the lock in screen after suspend this option doesn't exist anymore in 11.10. at least in gconfgeditor the option is not available anymore
As I dont want to fight to reopen the issue, I just edit the question to include the solution I found:
Install dconf editor as part of the dconf tools and start the editor via the dash.
Then navigate to org.gnome.desktop.lockdown and voila


text:
Q: Add a button to open an URL (Preferences Bundle) I'm trying to add a button in my Preferences Bundle to open an URL in Safari (or in the Pref Bundle).
I'm looking this: https://github.com/hbang/NotiQuiet/blob/master/prefs/ADNQListController.m
But I don't understand the else, if eccc...
I want just a button (for example "My website") that open www.mywebsite.com
Thanks all!

A: Add the following dictionary to your preferences plist:
{
    action = link;
    cell = PSButtonCell;
    label = "Google";
}

And the following method to your bundle:
- (void)link {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.google.com"]];
}


text:
Q: Bypass activity output to activity in switch case I like the idea of activity inputs and outputs and prefer them over setting values in the workflow context. However I am now stuck with this approach when using switch cases. My workflow looks like this:
builder
  .ReceiveHttpPostRequest<ImportProducts>("/import")
  .Then<ExtractHttpRequestBodyActivity>()
  .Then<GetShopDataActivity>()
  .Switch(cases => cases
    .Add(
      context => context.GetInput<ShopData>()!.ShopType == "ShopType1",
      @case => @case
        .Then<GetShopType1ProductsActivity>()
        .Then<FilterShopType1ProductsActivity>()
        .Then<ConvertShopType1ProductsActivity>()))
  .Then<DebugActivity>();

Without the switch case the input of GetShopType1ProductsActivity is the output of GetShopDataActivity, but using switch case the input is null.
Is there a way to bypass the output to the first activity of the case?
Edit: I'm using Elsa 2.0.0-preview7.1545

A: There is no way to bypass Elsa form sending activity output automatically to another activity as input.
That being said, it is up to you whether or not you use output/input.
What you can do is this:

*

*Specify a name for GetShopDataActivity (using .WithName). E.g. "GetShopDataActivity1"

*Use the output of GetShopDataActivity Directly as input for GetShopType1ProductsActivity.

To use output from a named activity, use the following code:
context.GetOutputFrom<ShopData>("GetShopDataActivity1");

An alternative approach is to store the output from GetShopDataActivity in a variable, then you can use that variable from other activities.
Tip: when developing custom activities, try to expose their inputs. For example, if the GetShopType1ProductsActivity needs the output from GetShopDataActivity, instead of reading input directly from the activity context within that activity, consider exposing the necessary data using an "input" property, like so:
[ActivityInput] public ShopData ShopData { get; set; }

Then you can update your workflow as follows:
builder
  .ReceiveHttpPostRequest<ImportProducts>("/import")
  .Then<ExtractHttpRequestBodyActivity>()
  .Then<GetShopDataActivity>().WithName("GetShopDataActivity1")
  .Switch(cases => cases
    .Add(
      context => context.GetInput<ShopData>()!.ShopType == "ShopType1",
      @case => @case
        .Then<GetShopType1ProductsActivity>(a => a.Set(x => x.ShopData, context => context.GetOutputFrom<ShopData>(""GetShopDataActivity1)))
        .Then<FilterShopType1ProductsActivity>()
        .Then<ConvertShopType1ProductsActivity>()))
  .Then<DebugActivity>();

This could be cleaned up a bit by adding a couple of extension methods on your GetShopType1ProductsActivity class (more specifically, on ISetupActivity<GetShopType1ProductsActivity> called e.g. WithShopData.
Additionally, if you need the output from GetShopDataActivity in multiple places (like you do already in at least two places), consider creating a an extension method that provides this information.
For example:
public static class ShoppingWorkflowExtensions
{
   public static ShopData GetShopData(this ActivityExecutionContext context) => context => context.GetOutputFrom<ShopData>(""GetShopDataActivity1)!;
}

You could then update your workflow like this:
builder
  .ReceiveHttpPostRequest<ImportProducts>("/import")
  .Then<ExtractHttpRequestBodyActivity>()
  .Then<GetShopDataActivity>().WithName("GetShopDataActivity1")
  .Switch(cases => cases
    .Add(
      context => context.GetShopData().ShopType == "ShopType1",
      @case => @case
        .Then<GetShopType1ProductsActivity>(x => x.WithShopData(context => context.GetShopData()))
        .Then<FilterShopType1ProductsActivity>()
        .Then<ConvertShopType1ProductsActivity>()))
  .Then<DebugActivity>();


text:
Q: CSS code use to make sure that only 2 line sentence to display is not working for IE I have the following css code to make sure that the display sentence is not more then 2 line, if so it will replace the rest of the word to "..."
   .bell-notification-max-words-display{
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

This working fine for chrome, safari and mozilla. However, it's not working for IE. When I inspect the element, error showing like below:

Does anyone know how can I make it work for IE?

A: Have you try all these?
display: -moz-box;
display: -webkit-box;
display: box;
display: -ms-flexbox;

A: The vendor prefix -webkit means that this is specific to the webkit engine which IE does not use. That's why it doesn't work.
You can get the desired result with a bit of line-height tweaking. - Read more about line-height - and by also using overflow: hidden;
Setting  overflow to hidden means the content will be trimmed if it exceeds the dimensions of the div:
Working example:

.parent {
  font-size:16px;
  height: 36px; /* 2x "font-size" +4px clearing */
  line-height: 36px; /* should match your parent div height */
  width: 90%;
  overflow: hidden;
  margin-top: 20px;
}

.child {
  display: inline-block;
  vertical-align: middle;
  line-height: normal; /* reset line height here it here */
}

    Lorem ipsum dolor sit amet, cu ancillae expetendis ius, pro reque laudem facilisis in, dicta euismod qui eu. No pri graecis similique, ei vim nobis veritus argumentum, platonem torquatos vituperata eum eu. Mel purto eros legendos id, saepe laudem at qui,
    te eum semper interesset. Has id admodum deleniti, eu sumo iisque noluisse ius, vix facer partiendo temporibus ut. In civibus consetetur cum, quo atqui omnium periculis ne. Vim nullam nemore ut.

There also another method in which you use a reset html textarea element.
Working example:

textarea {
  all: unset;
  width: 100%
}

.sample {
  overflow: hidden;
  max-width: 80%;
  overflow: ellipsis;
}
<textarea class="sample" rows="2">
Lorem ipsum dolor sit amet, cu ancillae expetendis ius, pro reque laudem facilisis in, dicta euismod qui eu. No pri graecis similique, ei vim nobis veritus argumentum, platonem torquatos vituperata eum eu. Mel purto eros legendos id, saepe laudem at qui,
    te eum semper interesset. Has id admodum deleniti, eu sumo iisque noluisse ius, vix facer partiendo temporibus ut. In civibus consetetur cum, quo atqui omnium periculis ne. Vim nullam nemore ut.
</textarea>

Unfortunately neither methods support ellipsis or "..."
I don't think there are any "non-hacky" methods of combining ellipsis and overflow using CSS alone unless you use hacks or scripts.
An example of such hacks is to use pseudo-elements (this only works if the text is justified)

.sample {
  max-width: 80%;
  overflow: hidden;
  position: relative;
  max-height: 2.2em;
  text-align: justify;
  padding-right: .75em;
}

.sample:before {
  content: "...";
  position: absolute;
  right: 0;
  bottom: 0;
}

  Lorem ipsum dolor sit amet, cu ancillae expetendis ius, pro reque laudem facilisis in, dicta euismod qui eu. No pri graecis similique, ei vim nobis veritus argumentum, platonem torquatos vituperata eum eu. Mel purto eros legendos id, saepe laudem at qui,
  te eum semper interesset. Has id admodum deleniti, eu sumo iisque noluisse ius, vix facer partiendo temporibus ut. In civibus consetetur cum, quo atqui omnium periculis ne. Vim nullam nemore ut.

A: I think the only safe cross-browser solution is to use javascript for line clamping. I've used Clamp.js once and I remember it being easy to use and working very well. You can read some more about the whole "line clamping issue"
 here.
The basic usage of Clamp.js in your case would be something like the following
$clamp(myText, {clamp: 2});

Where myText is the element you want to line clamp and 2 means two lines.


text:
Q: Is there a way to use offline Gmail with Firefox 4+ I want to use offline Gmail with the new versions of Firefox (like 8). Is there a way to get it working? Some way of hacking Gears' addon and changing its max version to make it compatible with the versions? Or someway of using Chrome addon in Firefox? Or any other way?

A: Currently there's no way to use the Gmail offline app on browsers other than Google Chrome. Google has announced they will be releasing the Chrome apps as plugins by the end of December 2011.


text:
Q: Missing plugin library OSGEO ogr_OCI.dll I am working on a project that uses OSGEO. I am trying to make shapefiles using OSGeo.Ogr. The first step involves registering all drivers. I am doing that (as shown in the image below). However, I get the exception as shown in the diagram, even though I have the file ogr_OCI.dll in the specified directory. I dont know if theres something wrong I am doing.
I am using VISUAL STUDIO 2017 and C# programming language.

A: this plugin is used for oracle. Please move the plugin to a different directory and all would be fine. Once you have oracle client installed then can bring it back it will work like charm.


text:
Q: Access button content (which is an image) through code in Windows Phone I have a button that features a grid which in turn contains an image.
   <Button Style="{StaticResource ButtonStyle1}" d:LayoutOverrides="GridBox" Margin="0,0,0,2.667" BorderThickness="3" BorderBrush="Black" Name="btn1" Click="btn1_Click">
                    <Grid>
                        <Image x:Name="img1" Source="Images/Numbers/1.png" Margin="-10,-3,-10,-5" Stretch="Fill"/>
                    </Grid>
    </Button>

I would like to know if there is a way to access the image holder through code without having to explicitly name it as I have above? If I had several buttons and could do it differently it might be easier.
Thanks

A: yes you can:
    var theImage = (Image)((Grid)btn1.Content).Children[0];

you have to make sure though that the button contains a Grid with an Image otherwise you get a cast or null pointer exception.


text:
Q: How to use file_get_contents with proxy? When I use file_get_contents with SSL and Proxy I have the following  errors:

Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages: error:1408F10B:SSL routines:ssl3_get_record:wrong version number in D:\XAMPP\htdocs\instahu\app\vendor\classes\instagram.php on line 154
Warning: file_get_contents(https://www.instagram.com/explore/tags/test/): failed to open stream: Cannot connect to HTTPS server through proxy in D:\XAMPP\htdocs\instahu\app\vendor\classes\instagram.php on line 154

protected function curl_send($url,$post = null,$headers = null) {

    global $settings;
    global $language;
    global $lng;
    global $currentUrl;

    $file = file_get_contents("http://" . $_SERVER['HTTP_HOST'] . "/app/vendor/classes/proxy.txt");

    $file = explode("", $file);
    if (count($file) == 0) {

        include_once __DIR__.'/../../templates/500.php';
        exit();
    }

    $mysqli = new mysqli($settings['db']['host'],
                     $settings['db']['user'],
                     $settings['db']['pass'],
                     $settings['db']['name']);
    $exe_proxies = $mysqli->query('SELECT * FROM `proxy_used`');
    $proxies = [];
    while ($row = $exe_proxies->fetch_assoc()) {
        $proxies[] = $row['proxy'];
    }
    foreach ($file as $proxy) {
        if (!in_array($proxy, $proxies)) {
            $target_proxy = $proxy;
            break;
        }
    }

    if (!isset($target_proxy)) {
        $mysqli->query('DELETE FROM `proxy_used`');
        $target_proxy = $file[0];
    }
    $mysqli->query('INSERT INTO `proxy_used` SET `proxy` = "' . $target_proxy . '"');
    $target_proxy = 'tcp://'.$target_proxy;
    $mysqli->close();
    $headers['user-agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36';

    if ($headers) {
        foreach ($headers as $key => $header) {
            $result[] = $key . ":" . $header;
        }
        $headers = join("\r\n", $result);
    }

    $aContext = [
      'http' => [
        'proxy' => $proxy,
        'request_fulluri' => true,
        //'method' => $post ? 'POST' : 'GET',
        //'content' => http_build_query($post),
        'header' => $headers,
      ],
    ];

    $cxContext = stream_context_create($aContext);

    $server_output = file_get_contents($url, False, $cxContext);
    preg_match('#\d{3}#', $http_response_header[0], $code);

    //var_dump($server_output, $code[0], $aContext, $url); exit();

    return ['server_output' => $server_output, 'httpcode' => $code[0]];
}

A: Sorry guys, I found a solution in my case, all what i change it's change key 'http' to 'https' in $aContext array  and it's work


text:
Q: Spin box only works when up/down indicators are clicked, it does NOT works when it is edited by entering numbers I have this Qt QML spinbox:

The problem is, it actually changes value only when up/down (+/-) indicators are clicked. When edited by entering numbers into spinbox, it does NOT change value. I have tried many things, but I cannot figure out why. Can anybody help?

QML code of the spinbox is this:
StyledSpinBox {
    id: overhangAngleFactorSpinBox
    implicitWidth: 120
    implicitHeight: 30
    to: 1 * 100
    stepSize: 1
    from: 0
    Layout.leftMargin: 8
    contentItem: StyledTextInput {
        inputMethodHints: Qt.ImhFormattedNumbersOnly
    }

    value: 70
    property int decimals: 2
    property real realValue: value / 100.0

    validator: DoubleValidator {
        bottom: Math.min(overhangAngleFactorSpinBox.from, overhangAngleFactorSpinBox.to)
        top: Math.max(overhangAngleFactorSpinBox.from, overhangAngleFactorSpinBox.to)
    }
    textFromValue: function(value, locale) {
        return Number(value / 100.0).toLocaleString(locale, 'f', overhangAngleFactorSpinBox.decimals)
    }
    valueFromText: function(text, locale) {
        return Number.fromLocaleString(locale, text) * 100.0
    }
    onValueChanged: {
        editorScene.overhangAngleFactor = value / 100.0
    }
}

StyledSpinBox.qml contains:
import QtQuick 2.5
import QtQuick.Controls 2.0 as QQC2

QQC2.SpinBox {
    id: control
    font.family: editorContent.labelFontFamily
    font.weight: editorContent.labelFontWeight
    font.pixelSize: editorContent.labelFontPixelSize

    background: Rectangle {
        border.color: editorContent.listHighlightColor
        color: editorContent.paneBackgroundColor
    }

    down.indicator: Rectangle {
        x: control.mirrored ? parent.width - width : 0
        height: parent.height
        implicitWidth: 40
        implicitHeight: 40
        border.color: editorContent.listHighlightColor
        color: editorContent.listHighlightColor
        Image {
            anchors.centerIn: parent
            source: "images/spinbox_down.png"
        }
    }

    up.indicator: Rectangle {
        x: control.mirrored ? 0 : parent.width - width
        height: parent.height
        implicitWidth: 40
        implicitHeight: 40
        border.color: editorContent.listHighlightColor
        color: editorContent.listHighlightColor
        Image {
            anchors.centerIn: parent
            source: "images/spinbox_up.png"
        }
    }
}

A: Problem solved by adding editable: true to spin box. According to documentation, the default value for editable is false:

editable : bool
This property holds whether the spinbox is editable. The default value is false.


text:
Q: How does Ansible determine which vault to use when there are multiple vaults? I have scoured through the web and the ansible documentation, but I have not been able to find an answer for this question.
Say the structure is as follows:
./playbooks/foo.yml
./hosts/HOST_NAME  (Contains IP for a specific host)
./hosts/host_vars/HOST_NAME/vault1
./hosts/host_vars/HOST_NAME/vault2
When I run the command:
ansible-playbook -i hosts/HOST_NAME playbooks/foo.yml

*

*Will ansible use vault1 or vault2 per default?

*If it looks in both, what happens if both vaults have defined the same variable? That is:

*

*vault1 -> username: user1

*vault2 -> username: user2

*If it looks in both, will the command fail if one of the vaults fail the decryption?

A: Q1: "Will Ansible use vault1 or vault2 per default?"
A: Both. In the sort order.

Q2: "What happens if both vaults have defined the same variable?"
A: The last one wins.

Q3: "Will the command fail if one of the vaults fails the decryption?"
A: Yes.

Example: Given the tree
shell> tree ../test-915
../test-915
├── ansible.cfg
├── hosts
├── host_vars
│   └── test_11
│       ├── vault1
│       └── vault2
└── pb.yml

the unencrypted vaults
shell> cat host_vars/test_11/vault1
username: user1
key1: val1
shell> cat host_vars/test_11/vault2
username: user2
key2: val2

and the playbook
shell> cat pb.yml
- hosts: test_11
  tasks:
    - debug:
        msg: |
          username: {{ username }}
          key1: {{ key1 }}
          key2: {{ key2 }}

gives
shell> ansible-playbook pb.yml

PLAY [test_11] **********************************************************************************

TASK [debug] ************************************************************************************
ok: [test_11] =>
  msg: |-
    username: user2
    key1: val1
    key2: val2


text:
Q: Subplots with groupby DataFrame in pandas? I have something like the following CSV:
date,name,area,score
10/15/2015,john,metallurgy,92
10/16/2015,john,metallurgy,84
10/16/2015,nancy,metallurgy,97
10/17/2015,nancy,metallurgy,76
10/18/2015,john,forestry,81
10/18/2015,john,forestry,46
10/19/2015,nancy,forestry,81
10/19/2015,nancy,forestry,74
10/23/2015,nancy,forestry,83

I want to have a plot with subplots for each person (name). I want it to look something like this:

Additionally, as showing in the picture, along with plotting the actual score points, I'd like to be able to plot an exponential weighted moving average (ewma) curve, or a series of linear regression lines, etc.
I think I could do it in Python/vanilla matplotlib with something like the following:
import pandas as pd
import matplotlib.pyplot as plt

plots_per_row = 3  # number of columns
df = pd.read_csv("data.csv")

# get number of plots
nplots = 0
by_name_and_area = {}
nplots_by_name = {}
nrows_by_name = {}

for name, namerows in df.groupby(['name']):
    by_name_and_area[name] = {}
    nplots_by_name[name] = 0

    for area, rows in namerows.groupby(['area']):
        by_name_and_area[name][area] = rows['score']
        nplots_by_name[name] += 1

    # decide number of rows
    nrows_by_name[name] = int(nplots / plots_per_row)
    if nplots % plots_per_row > 0:
        nrows_by_name[name] += 1

    # create figure & subplots and iterate through to plot each
    fig, axes = plt.subplots(nrows, plots_per_row, sharex=True, sharey=True,  squeeze=True)
    # ... etc, etc

but I'd rather do it in pandas since I'm trying to learn that and usually Wes has thought through everything before most of us mortals have.
Any thoughts?


text:
Q: Dlocal Payment HMAC-SHA256 I am integrating a payment gateway to my website and to send the payment signature I need to create a HMAC-SHA256 hash and include it in the header.
The documentation only gives me examples in PHP, Python and Ruby; and my backend is in NodeJs.
image
I created the hash with "crypto":
const body={
"amount": 120.00,
"currency" : "USD",
"country": "BR",
"payment_method_id" : "VD",
"payment_method_flow" : "DIRECT",
"payer":{
    "name" : "Thiago Gabriel",
    "email" : "thiago@example.com",
    "document" : "53033315550",
    "user_reference": "12345",
},
"card":{
    "token": "CV-124c18a5-874d-4982-89d7-b9c256e647b5"
},
"order_id": "657434343",
"notification_url": "http://merchant.com/notifications"
}
const signature = crypto
   .createHmac("sha256", SECRET_KEY)
   .update(X_LOGIN + X_DATE + body)
   .digest("hex");

The example in the documentation, uses a curl request and I changed to fetch , but I get the Signature not mach message, I have already tried with a GET request without adding the bodyRequest as a parameter in createHmac and it works, so I think I am doing something wrong with the body.
Doc:
curl -X POST \
-H 'X-Date: 2018-02-20T15:44:42.310Z' \
-H 'X-Login: sak223k2wdksdl2' \
-H 'X-Trans-Key: fm12O7G9' \
-H 'Content-Type: application/json' \
-H 'X-Version: 2.1' \
-H 'User-Agent: MerchantTest / 1.0 ' \
-H 'Authorization: V2-HMAC-SHA256, Signature: 1bd227f9d892a7f4581b998c21e353b1686a6bdad5940e7bb6aa596c96e0a6ec' \
-d '{body}'
https://sandbox.dlocal.com/payments

My code:
const response = await fetch("https://sandbox.dlocal.com/payments", {
      method: "POST",
      headers: {
        "X-Date": X_DATE,
        "X-Login": X_LOGIN,
        "X-Trans-Key": X_TRANS_KEY,
        "Content-Type": "application/json",
        "X-Version": "2.1",
        "User-Agent": "MerchantTest / 1.0",
        Authorization: "V2-HMAC-SHA256 , Signature: " + signature,
      },
      body: JSON.stringify(body),
    });

Can you help me to solve it?


text:
Q: How to avoid TclError if I want to update the results obtained from entries instantly? I want to add two numbers and add them and update the result instantly without using a button.
I have written this code using after() to do that.
from tkinter import *
root = Tk()
root.geometry("400x400")

label1 = Label(root, text="1st number:")
label1.grid(row=0, column=0)

label2 = Label(root, text="2nd number:")
label2.grid(row=1, column=0)

first_no = IntVar()
second_no = IntVar()

entry1 = Entry(root, textvariable=first_no)
entry1.grid(row=0, column=1)

entry2 = Entry(root, textvariable=second_no)
entry2.grid(row=1, column=1)

def auto():
    try:
        S = first_no.get() + second_no.get()
        label3.config(text="Sum:  " + str(S))
        # call again after 100 ms
        root.after(100, auto)
    except TclError:
        print("there is an Error")

label3 = Label(root)
label3.grid(row=3, column=1)

auto()

root.mainloop()

The code works well. However, if we delete the numbers in the entries using the delete or backspace keyboards this error raises: _tkinter.TclError: expected floating-point number but got "", and if I enter new values the code does not work anymore.
I wondered to know how I avoid this problem??

A: I found the solution. I added another root.after(100, auto) under exception TclError


text:
Q: OpenCV's connectedComponentsWithStats() returns NaN position for first centroid I am using the OpenCV C++ API (version 4.7.0). I have an application where I need to determine the centroid of a laser spot through a camera feed, and to do that I am attempting to use the connectedComponentsWithStats() function.
In my current setup, the image data is defined in a text file as a 2D array. This data is of a binary image, which is expected by connectedCoponentsWithStats(). The size of the image is 625X889. Here is what the binary image looks like:
This is the result of a binary thresholding operation.
Here is my C++ code for computing the centroids of the connected components:
/* Grouping and centroiding implementation using OpenCV's
 * ConnectedComponentsWithStats().
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <iostream>
#include <fstream>

#include <opencv2/opencv.hpp>

using namespace std;

int main()
{
        uint32_t ROWS=625;
        uint32_t COLS=889;
        uint8_t image_array[ROWS][COLS];
        uint8_t *image_data = new uint8_t[ROWS * COLS];
        int i;
        int j;

        //Read data from file and save into image_array[][].
        ifstream fp("./data/binary_image/binary_image1.txt");
        if (! fp)
        {
                cout << "Error opening file" << endl;
                return 1;
        }
        for (i=0; i<ROWS; i++)
        {
                for (j=0; j<COLS; j++)
                {
                        fp >> image_array[i][j];
                        if (! fp)
                        {
                                cout << "Error reading file for element " << i << "," << j << endl;
                                return 1;
                        }
                }
        }

        //Copy data into a 1D array called image_data.
        for (i=0; i<ROWS; i++)
        {
                for (j=0; j<COLS; j++)
                {
                        if (image_array[i][j] == 1)
                        {
                                image_array[i][j] = 255;
                        }
                        image_data[i * COLS + j] = image_array[i][j];
                }
        }

        //Create image object.
        cv::Mat image(ROWS, COLS, CV_8U, image_data);

        //Create output objects.
        cv::Mat labels, stats, centroids;

        //Pass image to connectedComponentsWithStats() function.
        int num_components = cv::connectedComponentsWithStats(image, labels, stats, centroids);

        //Print out the centroids
        for (i=0; i<num_components; i++)
        {
                cout << "Centroid "<< i << ": (" << centroids.at<double>(i, 0) << ", " << centroids.at<double>(i,1) << ")" << endl;
        }

        return 0;
}

Not that is it important, but this is how I compiled the code:
g++ `pkg-config --cflags opencv4` -c opencv_grouping.cpp
g++ opencv_grouping.o `pkg-config --libs opencv4` -o opencv_test

This is the output after running ./opencv_test:
Centroid 0: (nan, nan)
Centroid 1: (444, 312)

I am not really sure why I am getting the nan result, but I suppose this means that the area of that connected component is 0? As for the (444, 312) result, that just corresponds (roughly) to the center of a 625X889 grid, which is the size of the inputted image. So it essentially just computed the center of that grid. I tried with several other input images of the same size that were generated using different thresholds (so the spot size varried), and it yielded exactly the same result.
Does anyone have any insight/suggestions as to what might be going on here? Does OpenCV provide other functions that can be used to compute the centroid of the spot?
--Update--
I think that I found out where the problem is coming from. Something very strange is happening when I am reading in the data from the text file. It's not reading the data correctly at all. It gets to row 440 and then the rest of the data is either 0 or some garbage value (like a really large negative number for example). I am not sure why this is happening. In addition to declaring image_array as uint8_t image_array[ROWS][COLS], I have also tried allocating memory for it with new:
uint8_t **image_array = new uint8_t*[ROWS];
for (i=0; i<ROWS; i++)
        {
                image_array[i] = new uint8_t[COLS];
        }

Both of these run into the same problem. As a sanity check, I created a smaller (19X20) array to test with. It looks like this in a text file:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 255 255 255 255 255 0 0 0
0 0 0 255 255 255 0 0 0 0 0 0 0 255 255 255 0 0 0 0
0 0 255 255 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 255 255 0 0 0 0 0 0 0 0 255 0 0 0 0 0
0 0 0 255 255 255 255 255 0 0 0 0 255 255 255 255 0 0 0 0
0 0 0 0 255 255 255 255 255 0 0 255 255 255 0 0 0 0 0 0
0 0 0 0 0 0 255 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 255 255 255 255 255 255 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 255 255 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

I run this through the code my code (with ROWS=19 and COLS=20) and it actually gives a reasonable output for the centroids:
Centroid 0: (9.63497, 9.22086)
Centroid 1: (3.8, 3.1)
Centroid 2: (14, 2.55556)
Centroid 3: (8.71429, 10.2857)

So the issue is that the larger array is not getting read from the text file correctly. Any suggestions?


text:
Q: Google Analytics Campaign Measurement not working Who can help with error? - "iAd campaign tracking disabled because the current date is past the campaign window."
From log:

VERBOSE: GoogleAnalytics 3.14 __70-[GAIBatchingDispatcher
  checkIAdCampaignAttributionWithHitParameters:]_block_invoke_2
  (GAIBatchingDispatcher.m:768): iAd campaign tracking disabled because
  the current date is past the campaign window.

GoogleAnalytics 3.14
Xcode 7 + iOS 9, Objective C

A: I can see these messages as well, but analytics seems to collect data as usual. There have been two major update to advertising networkds during the last weeks which may not be included in your version of GoogleAnalytics:

*

*Admob has switched to Firebase Analytics and

*Apple has discontinued its own advertising network iAd.

I think you can ignore this verbose message for now.

A: Do you see this question / answer?
Maybe it help you.
The error seem to be the same:
Google Analytics doesn't work in iOS


text:
Q: Get the subcategories of the current product category in Woocommerce archives I'm trying to Show subcategories (not subsubcategories,etc) under current category in Woocommerce like  this Web: http://www.qs-adhesivos.es/app/productos/productos.asp?idioma=en
For Example, Construction is the category, and Sealants & adhesives, waterproofing, plyurethane foams… are subcategories.
Sealants & Mastics is the category, and ACETIC SILICONE SEALANT, NEUTRAL SILICONE SEALANT, ACRYLIC SEALANT… are subcategories…
Already have an archive-product.php in a woocommerce folder under my child theme.
Already tried some code and it applies but it's not what I want.

A: The following code will display the formatted linked product subcategories from current product category for product category archive pages:
if ( is_product_category() ) {

    $term_id  = get_queried_object_id();
    $taxonomy = 'product_cat';

    // Get subcategories of the current category
    $terms    = get_terms([
        'taxonomy'    => $taxonomy,
        'hide_empty'  => true,
        'parent'      => get_queried_object_id()
    ]);

    $output = '
';

    // Loop through product subcategories WP_Term Objects
    foreach ( $terms as $term ) {
        $term_link = get_term_link( $term, $taxonomy );

        $output .= '
slug .'">'. $term->name .'
';
    }

    echo $output . '
';
}

Tested and works.

USAGE EXAMPLES:
1) You can use this code directly in archive-product.php template file.
2) You can embed the code in a function, replacing the last line echo $output . '
'; by return $output . '
';, as for shortcodes, the display is always returned.
3) You can embed the code using action hooks like woocommerce_archive_description:
// Displaying the subcategories after category title
add_action('woocommerce_archive_description', 'display_subcategories_list', 5 );
function display_subcategories_list() {
    if ( is_product_category() ) {

        $term_id  = get_queried_object_id();
        $taxonomy = 'product_cat';

        // Get subcategories of the current category
        $terms    = get_terms([
            'taxonomy'    => $taxonomy,
            'hide_empty'  => true,
            'parent'      => $term_id
        ]);

        echo '
';

        // Loop through product subcategories WP_Term Objects
        foreach ( $terms as $term ) {
            $term_link = get_term_link( $term, $taxonomy );

            echo '
slug .'">'. $term->name .'
';
        }

        echo '
';
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.

To display it after the category description, change the hook priority from 5 to 20 in:
add_action('woocommerce_archive_description', 'display_subcategories_list', 5 );

like:
add_action('woocommerce_archive_description', 'display_subcategories_list', 20 );


text:
Q: Compatible intersecting coordinate patches must map to the same dimensional $\mathbb R^n$. I have a problem where I have to show that for two intersecting open subsets $U$ and $V$ of a topological manifold, if we have two homeomorphisms $\phi : U \to \mathbb R^n$ and $\psi: V \to \mathbb R ^ m$, and $\psi \circ \phi ^{-1} \mid_{\phi(U\cap V)}$ and $\phi \circ \psi ^{-1} \mid_{\psi(U\cap V)}$ are $C^1$, then $n = m$.
It's obvious that this must be true because we have homeomorphisms from open subsets of $\mathbb R^n$ to $\mathbb R^m$, but we don't have access to the topological machinery required to prove that. Also, we have the extra assumption that the maps are $C^1$, which suggests a more differential geometric approach. My problem is that I'm not sure what this approach is. I took vector calculus forever ago and there are so many ways to look at this.
I tried assuming that $n \ne m$ and looking at the Jacobian at a point and showing that it must either fail to be surjective or injective, but this isn't panning out (probably just because of my lack of technical skill), and I'm not sure if it will even work, or if it is the easiest way of going about this. I have a feeling that there is an easy <3 line proof.
This is homework, so suggestions things to try would be better than direct answers.

A: I am elaborating on my comment. You have two maps $\phi\circ \psi^{-1} : \psi(U\cap V) \to \phi (U\cap V)$ and $\psi\circ \phi^{-1} : \phi (U\cap V)\to \psi(U\cap V)$, which are inverses of each other, and $C^1$ smooth. The Jacobian matrix of $\phi\circ \psi^{-1}$ is an $n\times m$ matrix. The Jacobian matrix of $\psi\circ \phi^{-1}$ is an $m\times n$ matrix and by the chain rule this matrix is the inverse of the Jacobian of $\phi\circ \psi^{-1}$. In particular, $n=m$ since the matrices have to be square.

A: Without loss of generality assume $m\leq n$. Let $f=\phi\circ \psi^{-1},$ $g=\psi\circ\phi^{-1}$ on the sets you restricted to. Now $f\circ g$ is the identity on some open subset of $\Bbb R^n$. The chain rule says that
$$J_x(f\circ g)=J_{g(x)}(f)\circ J_x(g)$$
As the derivative of the identity is $I_{\Bbb R^n}$, we have both $J_{g(x)}(f)$ and $J_x(g)$ must be rank $n$. So $n=m$.


text:
Q: websphere work manager work timeout From the official documentation for work manager's work timeout

Specifies the number of milliseconds to wait before attempting to release a unit of work. The timeout interval begins when the unit of work starts, rather than when the unit of work is submitted.

I set the work timeout to 1000 milliseconds and made sure that my thread is engaged for more than that time by calling Thread.sleep(10000). Still nothing happened or no exception was thrown. The thread was engaged for the sleep duration and was returned to pool only after that for other requests.
What does work object is released means then?

A: There is a method on the com.ibm.websphere.asynchbeans.Work interface named release.  This documentation is literally referring to the work manager invoking that method on your Work implementation in response to the work timeout being reached.  You can implement your release to do whatever you like, for example invoking yourWorkThread.interrupt() or setting some flag to indicate to the work that it should stop continuing to do new work.
Here is a link to the Work API JavaDoc:
https://www.ibm.com/support/knowledgecenter/en/SSAW57_8.5.5/com.ibm.websphere.javadoc.doc/web/apidocs/com/ibm/websphere/asynchbeans/Work.html?view=kc#release()


text:
Q: Where do I get the ChromeDriver.exe from? The download link isn't available All the discussions and forums that I have looked at for help point to the following locations:
http://selenium-release.storage.googleapis.com/index.html
http://chromedriver.storage.googleapis.com/index.html
But both the pages are no longer available.
Any other way I can get to download the ChromeDriver.exe?
Thanks in advance!

A: The downloads are hosted here:
https://sites.google.com/a/chromium.org/chromedriver/downloads

A: You can download ChromeDriver.exe from the following URL:
http://chromedriver.storage.googleapis.com/index.html

A: If you want a scripted way to always get the latest version you can get it using a package manager like nuget or NPM
nuget install Selenium.WebDriver.ChromeDriver -ExcludeVersion

Will drop the latests chromedriver in a folder below our current location based on platform, e.g. for windows it would be \Selenium.WebDriver.ChromeDriver\driver\win32\chromedriver.exe
You could do something similar with the latest chromedriver from npm
npm install chromedriver

And if you need a particular version both package manager support version command arguments


text:
Q: I lost my Follower, Frea So I was running around some places, and I had done lots and lots of things without saving.
And then I noticed Frea was gone missing.
She's carrying a lot of my stuff and I don't know her ref ID.
How can i get her back?
I have all the DLC's.

A: Step 1: getting a NPC's Ref Id (credits to TormentedSouL)

*

*Open the console window

*Type save funclist 1 , this will open a txt file with a lot of data.

*Use Ctrl+f to Search for the npc by name. (This case, Frea)

*You should find 2 references for the name, one with the Base ID and one with the Ref ID. (base ID is the same ID that you get when you do help "<npc name>")

*The IDs are the number/letter combination in the left column of the file. (they can be numbers only)

Step 2: Retrieve NPC

*

*Open the console window.

*Type player.moveto <ref ID> to teleport yourself to the NPC.

*OR type prid <ref ID> and hit Enter, then moveto player and hit Enter; To bring the NPC to you.

If the NPC is dead, resurrect them after locating the corpse.
Click their body and open the console window to type in resurrect
Warning: this will reset their inventory and you will have lost the items.