text:
Q: How to Add a tooltip in Radio Buttons when checked in newForm.aspx page I have custom list with a field type of radio buttons with 4 choices. I want to be able to show a box on right hand side when each radio button is checked .How do i do that?
So far i was able to target id of the input field
 $(document).ready(function()
{

var x= document.getElementById('Site_x0020_Type_084a7e58-b428-4e43-98b6-2a7d10bc8941_$RadioButtonChoiceField0');
if(x.checked=true)

{
alert("done");

$(".ms-RadioText").append('
Test description
');
}
});
</script>

This Script adds the paragraph under the choice, but in all choices. I think that is because i am targetting the class which all of those elements share.
What do i do to display the box on right when choice is selected.
Thank You

A: Try this
I am assuming you want to show box as user click on any of the radio button having style set to ms-RadioText
$(document).ready(function(){
    $('body').append('

');
        $('input[id^="Site_x0020_Type_084a7e58-b428-4e43-98b6-2a7d10bc8941_$RadioButtonChoiceField"]').click(function(){
        if($(this).is(':checked')){
            var pos = $(this).position();
            var width = $(this).outerWidth();

            //show the menu directly over the placeholder
            $("#box").css({
                position: "absolute",
                top: pos.top+3 + "px",
                left: (pos.left + 20) + "px"
            }).show();
        }
    });
});

A: here is my mark up taken from IE developer tool.First input control is checked as default in the form.

A: You can edit the NewForm in SharePoint Designer, and add an html select element. In this select, each option will correspond to one of your radio button choice. You will have to use jQuery to update your radio button choices. The soltion should resemble to the one that's described in this post: http://sharepointhowtwo.blogspot.com/2014/10/how-to-add-tooltip-to-sharepoint-choice_27.html.
Regards


text:
Q: Displaying two hrefs into separate columns in a table I have a problem which I am having difficulty with. I have a system which displays video tutorials. My code below displays the name of the video (eNISATQuestion) and the link to the video (eNISATVideo) as one href.
I want to add another column to display to link to a rating page with a similar layout as the section below.

        {$row['eNISATQuestion']}

With values (eNISATRateRef) and (eNISATRating).
Thanks in advance
<?php

session_start();
include_once 'dbconnect.php';

if (!isset($_SESSION['user'])) header("Location: index.php");

$res     = mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow = mysql_fetch_array( $res );

$userID  = $_SESSION['user'];

$query = "SELECT eNISATQuestion, eNISATVideo, eNISATRateRef, eNISATRating FROM enisatquestion INNER JOIN enisatanswer WHERE
    enisatanswer.eNISATID = enisatquestion.eNISATID AND user_id =
    $userID AND eNISAT_watch = 1";

$result = mysql_query($query);

/* A default message if the query fails or there are no records */
$enisatquestion='
Sorry, there are no records
';

if($result) {/* if there is a recordset, proceed and generate html table */
    $enisatquestion = "
";

    while ($row = mysql_fetch_assoc($result)) {
        **$enisatquestion .= "
{$row['eNISATQuestion']}
";**
    }
    $enisatquestion .= "
";
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Welcome - <?php echo $userRow['username']; ?></title>
    <link rel="stylesheet" href="style.css" type="text/css" />

            NHSCT eNISAT Tutorials

                Welcome <?php echo $userRow['forename']; ?> Return to Homepage  Sign Out

Click on the each link to open your tutorial in Windows Media Player

            <?php
                /* output the html table here, below your header */
                echo $enisatquestion;
                /* If the query failed then the default gets displayed */
            ?>

A: Just add another td element and add the new data you fetch from the database.
**$enisatquestion .= "

    {$row['eNISATQuestion']}
    {$row['eNISATRating']}

";**

A: If this line of code...
{$row['eNISATQuestion']}

...is an exact copy/paste from the code you are using, please mind the double quotes.
{$row['eNISATQuestion']}

redpajama_set_name: RedPajamaStackExchange


text:
Q: A question about general topology and convexity in Euclidean spaces Let $m$ be a positive integer and let $E(m)$ be the $m$-dimensional Euclidean space with its standard metric. For any positive integer $n > m$, let $P(1),P(2),\ldots,P(n)$ be a finite set of points of $E(m)$ whose convex hull $H$ has a non-empty interior (with respect to $E(m)$). Let $p$ be any interior point of $H$. Does there always exist a positive real number $e$ such that the following statement is true?

If $Q(1),Q(2),\ldots,Q(n)$ is any finite set of points of $E(m)$ for which the Euclidean distance between $P(i)$ and $Q(i)$ with $i \in \{ 1,2,\ldots,n \}$ is never greater than $e$, then the point $p$ belongs to the convex hull of $Q(1),Q(2),\dots,Q(n)$.

If such a number as $e$ always exists, then it would, of course, have to depend on $H$ and $p$.

A: Yes, this is true.
Since the convex hull of the $P(i)$ is of non-empty interior, I can choose $m+1$ points among the $P(i)$ that form an affine basis of $E(m)$. Up to reindexation, I assume that these points are $P(1),\dots,P(m+1)$ and I show that if $Q(1),\dots,Q(m+1)$ are close to $P(1),\dots,P(m+1)$ then $p$ is still in the convex hull of the $Q(i)$. (I don't need the other points).
I claim that if the $Q(i)$ are close to the $P(i)$, then the $Q(i)$ give an affine basis of $E(m)$. Indeed, this is the affine analogue of the well-known linear fact that if $n$ vectors are close to a basis of a $n$-dimensional vector space, then they still give a basis (use a determinant).
Hence, I can write the $P(j)$ as barycenters in the $Q(i)$. Since $p$ is a barycenter in the $P(j)$, I can write it as a barycenter in the $P(i)$ by associativity of barycenters. The only thing to check is that this barycenter has weights in $(0,1)$ if the $Q(i)$ are sufficiently close of the $P(i)$.
Say that $P(j)$ is a barycenter of the $Q(i)$ with weights $\omega_{ij}(Q_i)$. Then, you can show that $\omega_{ij}(Q_i)$ depends continuously on $Q_i$ (this is essentially solving a linear system). Now, $p$ is a barycenter of the $Q(i)$ (for $Q(i)$ close to $P(i))$ with weights $\nu_i(Q_i)$ and $\nu_i(Q_i)$ depends also continuously on the $Q_i$ (it is given by an explicit formula involving the $\omega_{ij}$ and the weights of $p$ relative to the $P_j$). Since for $Q_i = P_i$, $\nu_i(P_i)$ is in $(0,1)$, this concludes the proof.


text:
Q: How to find EPStatements associated with UpdateListener I was wondering if Esper provides a mechanism to discover all EPStatement objects that an UpdateListener interface implementation is associated with.
The association between EPStatement and UpdateListener is one-way (from EPStatement to UpdateListener) and I cannot see in the API or reference docs if there's a way to discover EPstatement object(s) for a given UpdateListener or would I have to maintain such tracking myself?

A: There is no association from UpdateListener to Statement unless you create one which would be easy.


text:
Q: FindWindowByCaption function finding window handle that doesn't exist yet I am writing a C# application that requires moving gnuplot graphs to specific positions on the user's screen. To do this I am using DllImport to bring in several functions into my program. Specifically FindWindowByCaption and MoveWindow and a few others. This has been working fine for me thus far, but suddenly the graphs have stopped moving.
I figured out that the graphs are taking longer to generate and it tries to execute the MoveWindow function before the window is created so the window is not actually moved. I am not sure why this is a problem now because it was fine in earlier versions of the code.
For some reason the FindWindowByCaption function finds the window handle before the window actually exists.
I have the find window function in a loop that is supposed to try to execute until it finds the proper handle. The name changes for each graph.
IntPtr windowId = IntPtr.Zero;
        while (windowId == IntPtr.Zero)//keeps trying to get the id until it has it
            windowId = FindWindowByCaption(IntPtr.Zero, "p " + polyValue + " s " + (dataLocation + 1));

For some reason it finds the handle for the gnuplot graph before it actually is created and then it tries to run the MoveWindow function too soon, so that when the graph is actually generated it does not go to the right place.
Any suggestions would be helpful
Thanks,
-Jake


text:
Q: I have matrix A and matrix B. I want to get values of A depending on values in B I have matrix
A=magic(4)*10

and matrix
B=[6 6 2 6;  1 1 2 1; 7 7 2 1; 3 3 -1 3 ]

I want to get values of A depending on values in B. For example:
A=
160 20  30  130
50  110 100 80
90  70  60  120
40  140 150 10

B=
6   6   2   6
6   6   2   2
2   6   2   6
6   2   -1  2

I want to start at A(1,1) (value=160). Then, If the corresponding value on B, B(1,1) = 6, I want to get the element that is on the right, A(1,2), and  if B(1,1) = 2, I want to get value that is below, A(2,1). Finally, if the value is -1, I do not want to proceed. In the end I want to get result like this:
result=
160
20
30
100
60

Can anyone help me please?

A: Try the following code:
% Inizialize matices
A=magic(4)*10;
B=[6 6 2 6;  1 1 2 1; 7 7 2 1; 3 3 -1 3 ];

% Inizialize internal variables
contin=1;
row=1;
column=1;
result=[];

while contin==1
    %append value
    result=[result A(row, column)];
    if B(row, column)==6
        column=column+1; %go to the right
    elseif B(row, column)==2
        row=row+1; %go down
    elseif B(row, column)==-1
        contin=0; %break
        result(end)=[]; %delete last value
    end
end

result


text:
Q: Titanium Appcelerator HTTPClient return Array i want to put the httpclient in a separate class and want to return the array of founded data.
My Code
function ServiceRequest(callback){
var data = [];
var xhr = Titanium.Network.createHTTPClient({
    onload: function(e){
        //Ti.API.info("Received text: " + this.responseText);

        var doc = this.responseXML.documentElement;
        var elements = doc.getElementsByTagName("record");
        for (var r=0;r<elements.length;r++){
             var name = elements.item(r).getElementsByTagName("field").item(3).textContent;
             var monteur = elements.item(r).getElementsByTagName("field").item(15).textContent;
             var adresse =elements.item(r).getElementsByTagName("field").item(10).textContent;
             var ort = elements.item(r).getElementsByTagName("field").item(4).textContent +" - "+ elements.item(r).getElementsByTagName("field").item(5).textContent;
             var date = elements.item(r).getElementsByTagName("field").item(8).textContent;
             var termin
             if (date !="") {
                var arrayDate = date.split(".");
                var newdate = arrayDate[1]+"."+arrayDate[0]+"."+arrayDate[2];
                var temptermin = newdate +" - "+ elements.item(r).getElementsByTagName("field").item(9).textContent;
                termin = temptermin;
            };

            data.push({"name":name,"monteur":monteur,"adresse":adresse,"ort":ort,"termin":termin});

             callback( data );
            };

    },
    onerror: function(e){

        Ti.API.debug(e.error);
        alert(e.error);
    }
});

    xhr.open("GET","http://theurltomyxml.com",false);
    xhr.send();

}
module.exports =ServiceRequest;
the code snippet for my initialization
var ServiceRequest = require('ui/common/ServiceRequest');
request = new ServiceRequest(function(data){

});

Ti.API.info(request);

But the request is null, the array in my onLoad function is filled with data.
How can i wait until the httpRequest is ready than return the data array ?

A: You can use your custom function for callback like this way onload : callBack create your own callback function or you can put your callback( data ); after your forloop.
for (var r=0;r<elements.length;r++){//==your code here for parsing
    }
callback( data );


text:
Q: How do I sum a column range in python Here's my data
df

No Name     Address    English  History  Math   Physics  Chemistry  Biology
1  Arthur   New York        80       65   100        89         92       94
2  Barthur  New Mexico      70       60    94        83         82       95

What I did is
df['Science'] = df['Math'] + df['Physics'] + df['Chemistry'] + df['Biology']
My problem is, the actual data is more than 900 column, how do I replace df['Math'] + df['Physics'] + df['Chemistry'] + df['Biology'] to sum from df['Math'] to df['Biology'] (by range)
I hope this question is clear enough

A: I think you need iloc for select by positions:
df['sum'] = df.iloc[:, 3:].sum(axis=1)

Or remove numeric columns which dont need:
df['sum'] = df.drop('No', axis=1).sum(axis=1)

print (df)
   No     Name     Address  English  History  Math  Physics  Chemistry  \
0   1   Arthur    New York       80       65   100       89         92
1   2  Barthur  New Mexico       70       60    94       83         82

   Biology  sum
0       94  520
1       95  484

EDIT:
If need only all columns from 5 to the end:
print (df.iloc[:, 5:])
   Math  Physics  Chemistry  Biology
0   100       89         92       94
1    94       83         82       95

print (df.iloc[:, 3:5])
   English  History
0       80       65
1       70       60

df['A'] = df.iloc[:, 3:5].sum(axis=1)
df['Science'] = df.iloc[:, 5:].sum(axis=1)
print (df)
   No     Name     Address  English  History  Math  Physics  Chemistry  \
0   1   Arthur    New York       80       65   100       89         92
1   2  Barthur  New Mexico       70       60    94       83         82

   Biology    A  Science
0       94  145      520
1       95  130      484


text:
Q: How to check android device codename? Some android devices (models) are released in many versions. I suppose they differ in their firmwares (ROM) which varies according to the region (and the carrier) it has been sold in. The question is how can I check whether my Samsung Galaxy S3 is md0, m0skt or maybe d2spr ? The best would be to check it programmatically. Is it possible?

A: The Build class gives access to various device property strings.

A: On my phone (HTC Incredible) it's just in Settings -> About Phone -> Phone Identity.


text:
Q: TortoiseSVN post-commit.bat doesn't work I am using TortoiseSVN on Windows 7 x64.
I tried to put a post-commit.bat in the hooks folder of a repository, but it doesn't work at all. So I tried to put a pre-commit.bat (the content is exact the same as post-commit.bat) in hooks, and it worked fine.
This is very strange. The .bat file is very simple, I just tried with:
@echo off
setlocal
set REPOS=%1
set TXN=%2
xcopy C:\a C:\b\ /S /F
exit 0

Anyone makes post-commit work with TortoiseSVN?

A: The issue isn't a TortoiseSVN issue, but a server issue. Where is the repository stored? What server are you using? Are you using svnserve or httpd?
I take it that your commit happens anyway. There are several possibilities:

*

*Your hook is being executed, but not doing anything. As long as it exits with a zero exit status, Subversion thinks everything is hunky. Try a Subversion program called pre-commit.bat that contains only the line exit 2. If you can still commit stuff, your hook isn't working at all.

*Your hook isn't being executed. Subversion executes the program pre-commit in the hooks directory. There is an environment variable called PATHEXT on Windows that contains the suffixes that will be appended to a file in order to find the executable. Usually, it tries *.com, *.exe and then *.bat. If there is a pre-commit.exe or pre-commit.cmd in that hooks directory, your pre-commit.bat won't be executed. Check the value of PATHEXT for the user executing your Subversion server, and make sure it is set correctly.

One of the issues is that Subversion's hooks eat STDOUT and will only display STDERR only when the hook fails. This makes hooks pretty uncommunicative for the user, and if you're depending upon printing output while executing, you may get the felling that your hook isn't doing anything.
Print stuff to STDERR and not STDOUT. Have a way to force a hook to fail, so you can see STDERR if you need to.
I also don't recommend writing hooks in batch script on Windows. It simply isn't cut out to do this type of work. Use Python or Perl. Or, if you are really that PC oriented and don't want to install Python or Perl on your server, use PowerShell which is a very powerful, but underutilized programming language for Windows.


text:
Q: After refactor package name everything is gone After easy steps of refactoring and changing the name of package my android studio destroy package folders. Did someone faced that problem?

And error is
Error:(10, 40) error: package com.example.android.shoppinglist does not exist
    Error:(31, 35) error: package R does not exist


text:
Q: Use xls, csv or other type of file to make a float array in Objective-C  Hi all, I'm *very* new at the whole programming thing, but I really like it. Sorry if I do not have enough details
 So pretty much, I have excel files that have columns with numbers ( I can't post a picture because I don't have 10 reputations yet.
 I've been searching for a couple days and I haven't really found an answer to this. I was wondering if there is a way that I could either create multiple arrays from the file - I know we can't make matrices like matlab - that have the numbers in each column, i.e.
float numbers[] =  {1.3, 1.2, 4.2};

Or create the excel file with numbers (the iWork version of excel), and import the numbers file into the xcode project and from there create the arrays
The issue I have is that there's around a thousand numbers so copying it one by one is extremely time consuming
sorry if this is confusing, please let me know if there's anything else I should add as information

A: You mean generate objective-C source from a .csv file? One way to do this would be to use a scripting language like Perl:
#!/usr/bin/perl
use warnings;
use strict;

my @numbers = ();
while (<>) {
    chomp;
    push @numbers, $_;
}

my $numbers = join(', ', @numbers);
print qq(float numbers[] = {$numbers};\n);

This assumes that your .csv file (say foo.csv) has numbers in the first column and nothing else. If the file contains:
1.5
2.5
18842984
-4

And you pipe it to the script (foo.pl in this example):
cat foo.csv | perl foo.pl

It will output this:
float numbers[] = {1.5, 2.5, 18842984, -4};

Is that what you're trying to do?

A: There's two easy ways to do this, even if you are a beginner.
Open MS Excel, input your values, save excel document as .CSV file.
Then grab an objective-c CSV converter like this one here in github and you are done.
The second way, you could declare an array of numbers (in example, 'float matrix[5][5];') and use it however you see fit.
I've done both of my suggestions in seperate projects and both work very well. I used the first method for a 15 page excel document that I needed to use in my app, the second method I used in another app that I needed to constantly change the contents of the 2d array.
Once you declare the 'float matrix[5][5]' this is a 5x5 matrix (a.k.a. table) you can use it however you want. You could have the first array be the column and the second array be the row.


text:
Q: strange(?) module import syntax I've come across the following code in a Python script
from pprint import pprint

why not simply import pprint?
Unless the module pprint contains a function called pprint which is being aliased as pprint (surely, this must be the definition of madness?)

A: It does contain a function pprint, and that is exactly what's going on. I much prefer typing pprint, not pprint.pprint, or decimal.Decimal, or datetime.datetime.now() - wouldn't you?

A: Yes, the syntax is from module import functions, so the first pprint is the module name and the second the function name.

A: Your belief is correct, but it is not "aliased" in any way. It is simply named pprint, which is no violation of any Python style guide.


text:
Q: How to pass in a list of generic Objects? I have an object with the following:
public class ExpenseFilters<T> {
    public ExpenseFilterType Type {get;set;}
    public T Value {get;set;}
}

T can be a string, int, decimal in this case.
I want to create a method that accepts a generic list of ExpenseFilters:
public void DoSomething(List<ExpenseFilters<T>> filterList) {}

Is this possible somehow?
EDIT: Apologies as I wasn't being clear enough.
I want the List of ExpenseFilters to not be constrained to one generic type.
For example, the list should contain
ExpenseFilters<int>

as well as
ExpenseFilters<string>

Is this possible?

A: Make the method generic:
public void DoSomething<T>(List<ExpenseFilters<T>> filterList) { }

When you use this method, the type parameter T can usually be inferred by the compiler, so you don't even need to specify it:
List<ExpenseFilters<int>> list = new List<ExpenseFilters<int>>();
DoSomething(list);

Edit
Turns out it's not what you wanted to do.
It's not possible to do it with generics. The closest thing you might do is to create a non-generic interface or base class implemented/inherited by the generic one.
public interface IExpenseFilters
{
    ExpenseFilterType Type { get; set; }
    object Value { get; set; }
}

public class ExpenseFilters<T> : IExpenseFilters
{
    public ExpenseFilterType Type { get; set; }
    public T Value { get; set; }

    object IExpenseFilters.Value
    {
        get { return Value; }
        set
        {
            if (!(value is T))
                throw new ArgumentException("Incorrect type", "value");
            Value = (T)value;
        }
    }
}


text:
Q: Difference in cumulative sum based on specified values I have a dataframe containing one column (depth, z) in which I am trying to find the difference in the accumulative depth values based on regular depth values. I would like to create a new dataframe with 3 columns: the criteria value, its respective cumulative depth value, and the third column with difference between consecutive cumulative depths, so for example:
z1<-c(1.2, 1.5, 0.8, 0.7, 1.6, 1.9, 1.1, 0.6, 1.3, 1.0)
z<-data.frame(z1)
crit1<-c(0.5,1,1.5,2)

# A loop comes to mind,

for(i in c(0.5,1,1.5,2)){
print( sum(subset(z1,z1<=i)))
}                               # But I get an error, because I cannot use integers

Error in FUN(X[[1L]], ...) :
only defined on a data frame with all numeric variables

Attempting with cumsum
 cumsum(z1)[seq(0.5,2,by=0.5)] # Which doesn't work either

I would like to get a table like this:
Crit     Cumulative      Difference
  0.5        0                0
  1          3.1              3.1
  1.5        8.2              5.1

A: Don't use a for loop here , you should use sapply since you store the result.
y <- sapply(crit1,function(x)sum(z1[z1<=x]))
d <- c(0,diff(y))

data.frame(Crit =  crit1,  Cumulative  =y,    Difference=d)

#   Crit Cumulative Difference
# 1  0.5        0.0        0.0
# 2  1.0        3.1        3.1
# 3  1.5        8.2        5.1
# 4  2.0       11.7        3.5

A: You could try
 Difference <- setNames(c(0,tapply(z1,cut(z1, breaks=crit1,labels=F),FUN=sum)),NULL)
 data.frame(Crit=crit1, Cumulative=cumsum(Difference), Difference)
#    Crit Cumulative Difference
#1  0.5        0.0        0.0
#2  1.0        3.1        3.1
#3  1.5        8.2        5.1
#4  2.0       11.7        3.5


text:
Q: Java - Error with an MD5 string check and REGEX I don't understand why this doesn't work. And where the problem is.
public class MD5hash {
public static void main(String []args){
    String md5hash = "69a329523ce1ec88bf63061863d9cb14";
    System.out.println(md5hash);
    System.out.println(md5hash.matches("[a-f0-9] {32}"));
}}

In order to actually do use md5hash.matches, I needed to compare char by char.
Perhaps I don't understand what the Greedy Quantifier {32} does?
And help would be appreciated,
Thanks.

A: Spaces in regular expressions are significant. The first part of your regex matches a single hex char, and the second part asks it to match 32 spaces. You need to remove the space. You might also want to allow an upper-case variant. So, this should do what you want:
System.out.println(md5hash.matches("[a-fA-F0-9]{32}"));


text:
Q: Facebook timeline like listview The Facebook timeline seems to display all the feeds in the listview vertically. When the user shares his/her multiple photos, then those photos are displayed in horizontal list view. Has anybody any idea, how this actually works. Because I don't think nesting a horizontal listview within vertical listview works. Nor does the horizontal listview functions smoothly within the vertical scrollbar. So, if anybody has any idea about how Facebook implements its views in timeline, do share it here.

A: To use a gallery for the photos check out that example:
https://stackoverflow.com/a/11544447/944070
You may also need an implementation of different list items per case, so this answer would also be helpful https://stackoverflow.com/a/3515221/944070

A: That can be done using custom list view. Below tutorial covers facebook like feed view using volley networking library
Android Facebook like Custom ListView Feed using Volley


text:
Q: "That's got carpet tile written all over it. "? I'm watching a british TV show "The Great British Bake Off" and stumbled upon this conversation.
(One contestant(B) trying to pull out a cake lifter after placing a cake on a stand. Another person(A) overlooking that and says,)

A: "That's got carpet tile written all over it."
  B: "Asking for disaster."

Could someone tell me what is this means please?

A: Since it's being said while someone is doing something that risks the cake's balance, the most likely explanation is that it means the cake is likely to fall (onto the carpet tile). One of the meanings of "written all over it" is to be a perfect match for something; also consider the idiom of "a bullet with his name on it", meaning a bullet destined to be used on a specific person. The person is essentially saying that the cake is destined to hit the carpet tile. The comment "asking for disaster" reinforces this interpretation.

A: A carpet tile is thin. Presumably, the cake had not risen as intended and was as thin as a carpet tile.
The idiom "has x written all over it" can be used in different contexts, but here it means to show a certain characteristic very clearly. Source: Merriam Webster.


text:
Q: How do get rid of Javascript "Undefined" I'm trying to make a calendar which updates with Javascript, but "undefined" shows up at the bottom and I can't see anything wrong.
Here's the javascript:
function calendar(month){
var s= new Date();

var year=s.getFullYear();
var wday= s.getDay();
var mday =s.getDate();

var days = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
 document.write('

\n');

 for (i=0; i<(days.length); i++) {
     document.write('   ' + days[i] + ' 	 ');
 }
 var day=1;
 b=6;

 for ( count = 0; count < (b*7); count++) {

         var start= new Date(year,month,day,0,0,0,0);

         var dayarray = new Array();

          dayarray['mon'] = start.getMonth();// month
          dayarray['yr'] = start.getYear();// year
          dayarray['wday'] = start.getDay();//day of the week
          dayarray['mday'] = start.getDate();// day of the month

         if ((count % 7) == 0) {

                                document.write('

\n');
                        }

                if ((count < (dayarray['wday'])) || (dayarray['mon']!=month)) {

                        document.write (' 	\n');

                } else {
                        document.write(' ' + dayarray['mday'] + '   	\n ');
                         day +=1;

                }

}
document.write('

');
}
function next(c){
    document.getElementById(c).style.visibility="visible";
    document.getElementById((c-1)).style.visibility="hidden";

}

And the Html:

Second question:
why does the calendar only advance one month?

A: The issue lies in the document.write() that you wrap around each of your function calls.

Remove them from around the call to calendar and you don't get the undefined. http://jsfiddle.net/qXARb/2/


text:
Q: Improving a lower bound for the minimum of the maximum frequency of an element in a family of sets Consider a family $\mathcal{F}$ of $n=|\mathcal{F}|$ sets, $\emptyset \not\in \mathcal{F}$ and an universe $U(\mathcal{F})$ of $q=|U(\mathcal{F})|$ elements.
It is known that at least a fraction $r\binom{n}2$, $0 \lt r \lt 1$, of the unordered couples of sets of $\mathcal{F}$, have at least one element in common, i.e. $|\{\{A_1,A_2\}: A_1,A_2 \in \mathcal{F} \land A_1 \not= A_2 \land A_1 \cap A_2 \not= \emptyset \}| \ge r\binom{n}2$.
If we find the lowest $m$ such that:
$$\binom{m}2 \ge \frac{r\binom{n}2}q$$
we can then say that there exists an element belonging to at least $m$ sets of $\mathcal{F}$.
However since those $m$ sets cannot be made of only one element, I think the bound can be improved, i.e. we can say that there is an element in at least $m'$ sets:
$$m' = f(r,n,q) \gt m$$
Any idea for doing that?
EDIT 2023-02-06: now cross-posted at mathoverflow.


text:
Q: Netbeans: Cannot add custom JPanel in Swing Editor I'm having an issue with adding a custom JPanel to a JFrame in the Netbeans Swing Editor.
To rule out other issues, I made a brand new JFrame, and tried to drag my JPanel in (the JPanel is even in the same package). It popped up an error message:

Warning: Cannot Load component Class GUI.(nameofpanel) from project
  ...(path)... The class could not be found. Note the class must be
  compiled and must be part of the sources or dependencies of the
  project where the target GUI form belongs to.

I've successfully added JPanels to frames before using this method, but now it is preventing me from doing so. I get the same error in versions 7.1 and 7.3 of Netbeans.
I thought I might need to build the JPanel class file, but the option to do so is grayed out. I even tried a clean and build to no effect.
Here is my JFrame:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

/**
 *
 * @author chris
 */
public class MainFrame extends javax.swing.JFrame {

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    // End of variables declaration
}

And my JPanel:
package GUI;

import java.awt.Image;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

/*
 * Represents one card graphically /**
 *
 * @author Student-HSLH133
 */
public class CardPanel extends javax.swing.JPanel {

    private Image cardImage;

    /**
     * Creates new form CardPanel
     */
    public CardPanel() {
        initComponents();
        //Set to face down card initially
        //Hey look, some Lisp code, jk
        try {
            cardLabel.setIcon(imageToIcon(ImageIO.read(new File("images/gbCard52.gif"))));
        }
        catch (Exception e){
            System.out.println("Failed to load the image.");
            System.exit(-1);
        }
    }

    public void setCard(Image img) {
        cardLabel.setIcon(imageToIcon(img));
        repaint();
    }

// --------------   end of load_picture ---------------------------
    private ImageIcon imageToIcon(Image img) {
        return new ImageIcon(img);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        cardLabel = new javax.swing.JLabel();

        setMaximumSize(new java.awt.Dimension(72, 102));
        setMinimumSize(new java.awt.Dimension(72, 102));
        setPreferredSize(new java.awt.Dimension(72, 102));
        setLayout(new java.awt.BorderLayout());

        cardLabel.setMaximumSize(new java.awt.Dimension(72, 102));
        cardLabel.setMinimumSize(new java.awt.Dimension(72, 102));
        cardLabel.setPreferredSize(new java.awt.Dimension(72, 102));
        add(cardLabel, java.awt.BorderLayout.CENTER);
        cardLabel.getAccessibleContext().setAccessibleName("card");
    }// </editor-fold>
    // Variables declaration - do not modify
    private javax.swing.JLabel cardLabel;
    // End of variables declaration
}

I am totally lost. What is going on?
Edit: I somehow got it to compile the JPanel, but I still get the same error. Thinking it might be something with the JPanel itself, I made a new custom JPanel, compiled it, and tried to add it, and it worked.
Edit 2: I've tried commenting out the custom stuff I've done in the JPanel class, to no avail.

A: I never did pin this down, but I think it has something to do with faulty file tracking or something that got corrupted regarding my JPanel class file.
Moving the methods and variables to a new JPanel class seems to work fine, so that is the workaround.

A: I've experienced this problem a while ago and cleaning and building my project worked for me.


text:
Q: Creating a variable-sized justified text block I need to create a block of text that looks like this:

Is there a term for this kind of variable-sized justified text? Is there a JavaScript library to size this correctly, or is it possible in CSS?

A: CSS alone won't cater for this. You're after Fittext.js: http://fittextjs.com/


text:
Q: Displaying each element of a varying sized list one at a time I am trying to take a user's input, which will determine as list of results.  I would like to show that list to the user, one result at a time.  Something like the following (which is broken):
Panel[Column[{
   Row[{"How many squares? ", InputField[Dynamic[x], Number]}],
   (*m=1 so that no out of range error for x < m:*)
   Row[{ButtonBox["Squares!", Evaluator -> Automatic,
       ButtonFunction -> (m = 1; (r = Map[#^2 &, Range[x]]) &),
       Appearance -> "DialogBox"] // DisplayForm}],
   Row[{SetterBar[Dynamic[m], Dynamic[Length[r]]]}],
   Row[{r[[m]]}]
   }]]

It seems that the trouble I am running into is setter bar not taking a dynamic range.  I also tried using previous and next buttons which would increment or decrement x modulo m, but Mod[m,x] wasn't happy with a dynamic argument either.  Any help would be greatly appreciated.

A: You can try with Manipulate
Manipulate[Row[{SetterBar[Dynamic[y], Range[x]], Dynamic[y]}],
 {{x, 1,"Squares"}, InputField[#, Number] &}]


text:
Q: MySQL - Обновить таблицу, удалив дубликаты и объединив столбцы прошу подсказать, ПЛИИИЗ!
Необходимо обновить таблицу - удалить дубликаты (уникальность по столбцу ART), предварительно объединив у дубликатов другие столбцы (Poh)

A: Попробуйте так. Создайте новую таблицу, заполните ее по запросу
INSERT INTO
    new_table (id,art,poh)
SELECT
    min(t.id), t.art, group_concat(t.poh)
FROM
    old_table t
group by t.art

Удалите старую таблицу, а новую переименуйте


text:
Q: Why do I ger "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"? I have a Users class like below:
class Users {

  static async findAll(req: Request, res: Response, next: NextFunction) {
    await Pools.execute("SELECT * FROM users")
      .then((rows) => {
        res.status(200).json(rows[0]);
      })
      .catch(err => {
        res.status(404).json({error: err});
        throw err;
        });
    next();

  }
}

And a usersRouter like following:
router.route("/api/users")
  .get(Users.findAll);

When I send a get request to localhost:3000/api/users I get the users list back but alongside with an Error as following:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

PS: The pool is a mysql2/promise pool.


text:
Q: FBSDKAppInviteDialog on iOS 9 & 10 (FB SDK 4.2.0) stopped loading on 'showFromViewController' I'm trying to perform a FBSDKAppInviteDialog request using Facebook's iOS 4.2.0 sdk but the modal share dialog page never loads.
I was able to do this just last week but now every time I call this 'showFromViewController' method, the UIWebView that opens is left blank and loading infinitely.
Has anyone experienced this? I'm encountering the issue on iOS 9 and 10.
FBSDKAppInviteContent *content = [FBSDKAppInviteContent new];
content.promotionText = @"Text";
content.appLinkURL = [NSURL URLWithString:@"url"];
[FBSDKAppInviteDialog showFromViewController:controller
                                 withContent:content
                                    delegate:self];

A: Are you using the deprecated UIActionSheet to open the dialog?  Try opening the dialog without it, or with the new UIAlertController.  That did the trick for me.


text:
Q: Adding a custom template? I have modified a template TFS (Scrum), with dowload held in:
Settings-> Process Template Manager
As shown below.

I'm editing this Template in: Tools-> Process Editor-> Work Item Types-> Open WIT from file.
Now I would like to add this Template in my visual studio, or when I add a New Work Item Product Backlog Item, it appears customized according to what I define.
I have followed this tutorial to the template editing.

A: As you can't upload the process template, I assume you are using Visual Studio Team Service.
If so, you need to follow article Customize a process to do the customization. For example, you want to add a custom WIT, try go to the admin Process page, create an inherited process (You can only customize inherited processes), and then add new work item type. See here for more information.


text:
Q: The Conjugate Beta Prior proof
Hello.
I'm having a problem with trying to figure out this proof that shows the beta
distribution is conjugate to the binomial distribution (picture attached).
I understand it until the third row, but I got confused with this step from the third to the fourth row.
I would appreciate a simple explanation.
Thank you in advance.

A: To go from the third to fourth row just ignore factors that are constant with respect to $\pi$. That is, let
$$\binom{n}{y}\frac{\Gamma(\alpha+\beta)}{\Gamma(\alpha)\Gamma(\beta)}=k$$
so
$$p(\pi|y)=k \cdot \pi^y (1-\pi)^{(n-y)}\pi^{(\alpha-1)}(1-\pi)^{(\beta-1)}$$
or
$$p(\pi|y) \propto \pi^y(1-\pi)^{(n-y)}\pi^{(\alpha-1)}(1-\pi)^{(\beta-1)}$$
The idea's to deal just with the kernel of the probability distribution, knowing you can always put the normalizing constant back in later.


text:
Q: When I rebuild project I get error: incompatible types: ModalEvent cannot be converted to Context But when I'm coding it this appears please click the link to view the image..btw this is a inflateLayout that when I click a button(btnDateTime) in modal_event.xml it will show a DatePickerDialog. ModalEvent.java is not my main activity. ModalEvent.java shows only when I click a item in my NavigationView... please help I need you all :)
this code in my ModalEvent.java
package com.example.khalessi_jb.reminderapplication;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import java.util.Calendar;

public class ModalEvent extends BottomSheetDialogFragment {

TextView txtDateandTime;
Button btnsDateTime;

Calendar calendar;
DatePickerDialog datePickerDialog;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    btnsDateTime = (Button) getView().findViewById(R.id.btnDateTime);
    txtDateandTime =(TextView)getView().findViewById(R.id.txtDateTime);

    View v = inflater.inflate(R.layout.modal_event,container,false);

    return v;

    btnsDateTime.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
           calendar = Calendar.getInstance();
            int daysss = calendar.get(Calendar.DAY_OF_MONTH);
            int monthss =calendar.get(Calendar.MONTH);
            int yearss =calendar.get(Calendar.YEAR);

            datePickerDialog = new DatePickerDialog(ModalEvent.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int mYear, int mMonth, int mDay) {
                    txtDateandTime.setText(mDay +"/" + (mMonth +1)+"/"+mYear);
                }
            },yearss,monthss,daysss);
            datePickerDialog.show();
        }
    });

}

}

and this is my modal_event.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:id="@+id/textView12"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Event" />

<EditText
android:id="@+id/txtEventName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView12"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Event Title"
android:inputType="textLongMessage" />

<EditText
android:id="@+id/txtWhere"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView15"
android:layout_alignStart="@+id/textView13"
android:ems="10"
android:hint="Event Location"
android:inputType="textLongMessage" />

<TextView
android:id="@+id/textView13"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/txtEventName"
android:layout_alignStart="@+id/txtEventName"
android:layout_marginTop="-1dp"
android:text="When" />

<TextView
android:id="@+id/txtDateTime"
android:layout_width="148dp"
android:layout_height="wrap_content"
android:layout_below="@+id/textView13"
android:layout_alignStart="@+id/textView12"
android:layout_marginStart="182dp"
android:layout_marginTop="15dp"
android:ems="10"
android:hint="Date/Time"
android:inputType="time"
android:textSize="15dp" />

<TextView
android:id="@+id/textView15"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView10"
android:layout_alignStart="@+id/textView13"
android:layout_marginStart="4dp"
android:text="Where" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/textView12"
android:layout_alignParentEnd="true"
android:layout_marginTop="216dp"
android:layout_marginEnd="132dp"
android:text="Create" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button"
android:layout_alignParentEnd="true"
android:layout_marginTop="-1dp"
android:layout_marginEnd="15dp"
android:text="Close" />

<TextView
android:id="@+id/textView10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/txtDateTime"
android:layout_alignParentStart="true"
android:layout_marginStart="0dp"
android:layout_marginEnd="21dp"
android:layout_toStartOf="@+id/txtDateTime"
android:text="at" />

<TextView
android:id="@+id/textView14"
android:layout_width="124dp"
android:layout_height="wrap_content"
android:layout_alignStart="@+id/button"
android:layout_alignParentTop="true"
android:layout_marginStart="96dp"
android:layout_marginTop="378dp" />

<Button
android:id="@+id/btnDateTime"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_below="@+id/textView13"
android:layout_alignParentStart="true"
android:layout_marginStart="-4dp"
android:text="Choose Date/Time" />

</RelativeLayout>

this show at the logcat when i click the button
 java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
    at com.example.khalessi_jb.reminderapplication.ModalEvent.onCreateView(ModalEvent.java:30)
    at android.support.v4.app.Fragment.performCreateView(Fragment.java:2439)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1460)
    at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
    at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
    at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
    at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
    at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
    at android.os.Handler.handleCallback(Handler.java:836)
    at android.os.Handler.dispatchMessage(Handler.java:103)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6259)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)

A: You need to pass getContext() or getActivity() instead of ModalEvent.this as first parameter of the DatePickerDialog. Your code would look like this:
datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int mYear, int mMonth, int mDay) {
                txtDateandTime.setText(mDay +"/" + (mMonth +1)+"/"+mYear);
            }
        },yearss,monthss,daysss);

Give it try and let me know
Seems like that part worked, now you just need to do some refactor in your onCreateView method:
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable
ViewGroup container, @Nullable Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.modal_event,container,false);
    btnsDateTime = (Button) v.findViewById(R.id.btnDateTime);
    txtDateandTime =(TextView)v.findViewById(R.id.txtDateTime);

    btnsDateTime.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View view){
       calendar = Calendar.getInstance();
        int daysss = calendar.get(Calendar.DAY_OF_MONTH);
        int monthss =calendar.get(Calendar.MONTH);
        int yearss =calendar.get(Calendar.YEAR);

        datePickerDialog = new DatePickerDialog(ModalEvent.this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int mYear, int mMonth, int mDay) {
                txtDateandTime.setText(mDay +"/" + (mMonth +1)+"/"+mYear);
            }
        },yearss,monthss,daysss);
        datePickerDialog.show();
    }
    });

   return v;
}


text:
Q: Mysql select for update blocks 1st insert if using NON primary key in where clause Mysql Version : 5.6.33 , ubuntu 64 bit
Table Schema
CREATE TABLE `zone_txn` (
  `id` bigint(20) NOT NULL,
  `bucket_key` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  INDEX `idx_bucket_key` (`bucket_key`)
)

2 sessions are opened and race condition is induced by running 1 statement from each terminal. Statement numbers are mentioned.
Terminal 1
S1: begin;
S3:     select * from zone_txn FORCE INDEX(idx_bucket_key)
            WHERE `bucket_key` = 'b1' FOR UPDATE;
S5:     insert into zone_txn(`bucket_key`) values('b1');
S7: commit;

Terminal 2
S2: begin;
S4:     select * from zone_txn FORCE INDEX(idx_bucket_key)
           WHERE `bucket_key` = 'b2' FOR UPDATE;
S6:     insert into zone_txn(`bucket_key`) values('b2');
S8: commit;

According to doc , select for update "only locks the rows it has passed through just like update".
Question :
Insert query is blocked in the whichever session receives the first insert query.
Insert query after this blocked query ( in second session ) works fine.
In above example S5 blocks, S6 runs fine.
Is it dues to gap lock or next-key lock as specified here where fresh insert is being blocked by Index.
If I put id = <> in where clause , then both insert queries run fine.
Terminal 1
S1: begin;
S3:     select * from zone_txn WHERE `id` = 1 FOR UPDATE;
S5:     insert into zone_txn(`bucket_key`) values('b1');
S7: commit;

Terminal 2
S2: begin;
S4:     select * from zone_txn WHERE `id` = 2 FOR UPDATE;
S6:     insert into zone_txn(`bucket_key`) values('b2');
S8: commit;

UPDATED:
If I make bucket_key as unique index , it works fine. Looks like it only works for unique and Primary keys and not ranges.
UPDATED : Fixed Typo, added "for update" in select statements which were part of the question.
UPDATED : Starting value of zone_txn;
+----+------------+
| id | bucket_key |
+----+------------+
|  1 | b1         |
|  2 | b2         |
+----+------------+

show engine innodb status;
---TRANSACTION 1139415, ACTIVE 11 sec
4 lock struct(s), heap size 1184, 4 row lock(s), undo log entries 1
MySQL thread id 8818, OS thread handle 0x700009268000, query id 1700769 localhost root cleaning up

---TRANSACTION 1139414, ACTIVE 16 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 5 lock struct(s), heap size 1184, 4 row lock(s), undo log entries 1
MySQL thread id 8626, OS thread handle 0x7000092f0000, query id 1700768 localhost root update
insert into zone_txn(`bucket_key`) values('b1')

------- TRX HAS BEEN WAITING 6 SEC FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 1454 page no 4 n bits 72 index `idx_bucket_key` of table `kyc`.`zone_txn` trx id 1139414 lock_mode X locks gap before rec insert intention waiting
Record lock, heap no 3 PHYSICAL RECORD: n_fields 2; compact format; info bits 0
 0: len 2; hex 6232; asc b2;;
 1: len 8; hex 8000000000000002; asc         ;;


text:
Q: How to use Nexus' Prisma plugin crud with specific arguments I have an Advertiser graphql type:
type Advertiser {
  createdAt: DateTime!
  id: Int!
  isActive: Boolean!
  name: String!
  updatedAt: DateTime
}

Given the following mutation:
mutationType({
  definition(t) {
    t.crud.createOneAdvertiser();
  }
});

Nexus generates this schema (as expected):
input AdvertiserCreateInput {
  createdAt: DateTime!
  isActive: Boolean!
  name: String!
  updatedAt: DateTime
}

type Mutation {
  createOneAdvertiser(data: AdvertiserCreateInput!): Advertiser!
}

The thing is, what if I want to omit some of the args? For example, I don't want the client to pass createdAt or updatedAt. these columns should be resolved in the server.
See (partial) documentation here - https://nexusjs.org/docs/plugins/prisma/api#example-4

A: Yet again, found the answer right after posting this question. Simply pass computedInputs like so:
t.crud.createOneAdvertiser({
  computedInputs: {
    createdAt: () => DateTime.utc().toString(),
    updatedAt: () => null
  }
});

A: Great question Eliya.
If you're using Nexus to define your GraphQL types, you can use the objectType to define your schema types. When paired with Prisma and nexus-plugin-prisma, you can use t.model to map your schema types to your db models in your objectType. When defining your objectType, you can choose to omit some columns in your database models.
Here's an example Prisma model to demonstrate the concept:
model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  updatedAt DateTime @updatedAt
}

When defining your objectType, you can include the the updatedAt column:
import { objectType } from 'nexus'

const Post = objectType({
  name: 'Post',
  definition(t) {
    t.model.id()
    t.model.title()
    t.model.content()
    t.model.published()
    t.model.author()
    t.model.updatedAt()
  }
})

export default Post

updatedAt, in this example, will be resolved by the GraphQL server/Prisma and your client won't be required to pass the argument despite being included in the inputType generated by Nexus.
I hope this answers your question. If you need any further clarifications let me know.


text:
Q: connection to tdsool times out with tsql We are using tdspool and trying to connect to it using tsql locally on the same machine. tdspool seems to open it's connections just fine and starts listening however any client connecting to the pool times out.
pool.conf
[global]
        min pool conn = 5
        max pool conn = 10
        max member age = 120

[sampool]
        user = [REDACTED]
        password = [REDACTED]
        database = [REDACTED]
        server = [REDACTED]
        port = 1313 ;change to a non standard port so we can see the connection details in the debug log

When connecting to 127.0.0.1:1313 using tsql the tdspool output simply says "accepting connection" and nothing else. The freetds.log outputs the following:
dblib.c:1237:tdsdbopen: Calling tds_connect_and_login(0x2b3fec0, 0x2b40580)
iconv.c:328:tds_iconv_open(0x2b3fec0, UTF-8)
iconv.c:187:local name for ISO-8859-1 is ISO-8859-1
iconv.c:187:local name for UTF-8 is UTF-8
iconv.c:187:local name for UCS-2LE is UCS-2LE
iconv.c:187:local name for UCS-2BE is UCS-2BE
iconv.c:346:setting up conversions for client charset "UTF-8"
iconv.c:348:preparing iconv for "UTF-8" <-> "UCS-2LE" conversion
iconv.c:395:preparing iconv for "ISO-8859-1" <-> "UCS-2LE" conversion
iconv.c:400:tds_iconv_open: done
net.c:202:Connecting to 127.0.0.1 port 1313 (TDS version 7.3)
net.c:274:tds_open_socket: connect(2) returned "Operation now in progress"
net.c:313:tds_open_socket() succeeded
util.c:165:Changed query state from DEAD to IDLE
packet.c:740:Sending packet
0000 12 01 00 3a 00 00 00 00-00 00 1a 00 06 01 00 20 |...:.... ....... |
0010 00 01 02 00 21 00 0c 03-00 2d 00 04 04 00 31 00 |....!... .-....1.|
0020 01 ff 09 00 00 00 00 00-02 4d 53 53 51 4c 53 65 |........ .MSSQLSe|
0030 72 76 65 72 00 96 24 00-00 00                   |rver..$. ..|

util.c:322:tdserror(0x2a6b8c0, 0x2b3fec0, 20003, 115)
dblib.c:7897:dbperror(0x2b3f3b0, 20003, 115)
dblib.c:7965:dbperror: Calling dblib_err_handler with msgno = 20003; msg->msgtext = "Adaptive Server connection timed out (127.0.0.1:1313)"
dblib.c:5743:dbgetuserdata(0x2b3f3b0)
dblib.c:7987:dbperror: dblib_err_handler for msgno = 20003; msg->msgtext = "Adaptive Server connection timed out (127.0.0.1:1313)" -- returns 2 (INT_CANCEL)
util.c:352:tdserror: client library returned TDS_INT_CANCEL(2)
util.c:375:tdserror: returning TDS_INT_CANCEL(2)
query.c:3769:tds_disconnect()
util.c:165:Changed query state from IDLE to DEAD
login.c:472:login packet rejected
util.c:322:tdserror(0x2a6b8c0, 0x2b3fec0, 20002, 0)
dblib.c:7897:dbperror(0x2b3f3b0, 20002, 0)
dblib.c:7965:dbperror: Calling dblib_err_handler with msgno = 20002; msg->msgtext = "Adaptive Server connection failed (127.0.0.1:1313)"
dblib.c:5743:dbgetuserdata(0x2b3f3b0)
dblib.c:7987:dbperror: dblib_err_handler for msgno = 20002; msg->msgtext = "Adaptive Server connection failed (127.0.0.1:1313)" -- returns 2 (INT_CANCEL)
util.c:352:tdserror: client library returned TDS_INT_CANCEL(2)
util.c:375:tdserror: returning TDS_INT_CANCEL(2)
dblib.c:1241:tdsdbopen: tds_connect_and_login failed for "127.0.0.1:1313"!
dblib.c:1463:dbclose(0x2b3f3b0)
dblib.c:243:dblib_del_connection(0x7fa27f9644a0, 0x2b3fec0)
mem.c:648:tds_free_all_results()
dblib.c:290:dblib_release_tds_ctx(1)
dblib.c:5845:dbfreebuf(0x2b3f3b0)
dblib.c:743:dbloginfree(0x2b3ef10)
dblib.c:1533:dbexit(void)
dblib.c:1533:dbexit(void)
dblib.c:290:dblib_release_tds_ctx(1)

tsql -C:
Version: freetds v0.95.19
             freetds.conf directory: /etc
     MS db-lib source compatibility: yes
        Sybase binary compatibility: no
                      Thread safety: yes
                      iconv library: yes
                        TDS version: 5.0
                              iODBC: no
                           unixodbc: yes
              SSPI "trusted" logins: no
                           Kerberos: no
                            OpenSSL: no
                             GnuTLS: no

OS: CentOS 6.5

A: I had similar problem. Will try to help you to solve your. First, ensure your /etc/freetds.conf contains valid configuration:
[global]
tds version = 4.2
...
[myserver]
    host = <ip>
    port = 1433
    tds version = 4.2 < this is important

Now, /etc/tdspool.conf
 [sampool]
 user = [REDACTED]
 password = [REDACTED]
 database = [REDACTED]
 server = myserver < important
 port = 1313

Then tdspool sampool should start fine. My errors were as follows:
    1. I thought that server in pool.conf is ip or domain of server, while really that is reference to server in freetds.conf
    2. In freetds.conf I used wrong (too high) tds version. Tdspool supports tds versions up to 4.2, as stated in their docs.
Now, if you try to connect via tsql -S 172.0.0.1:1313, you will still get "accepting connection..." forever. BUT, if you do
tsql -S 127.0.0.1:1313 -U <username> -P <password> -D <database>

you will connect and be able to run queries against your sql server through tdspool.

A: The Software is Bugged
We went to the official mailing list, and asked this question verbatim. The answer seems to be that there isn't one without rewriting the current project.

Client libraries are used and well tested but pool and server are
  really not in a good shape.
The current state of tdspool is.... it compiles! I'm not surprised it
  does not run correctly.
That said it's open source. Any help/suggestion/patch is welcome.

We spent a considerable amount of time trying to figure out what we were doing wrong, so this is kind of a pain. While I'll be looking to make/modify existing SQL Server pools, I'm disappointed that FreeTDS (a wonderful project) ships with such an unstable pool


text:
Q: In what situations does Query.execute() return null in DataNucleus I have not added anything to my Database yet, thus the following query should return a result of 0 by my reckoning.
    Query query = pm.newQuery(Password.class);
    query.setFilter("password == :passwordParam");
    query.setResult("count(password)");
    query.setResultClass(Integer.class);
    Integer result = (Integer)query.execute(password);
    System.out.println("Result: [" + result + "]");

It returns null
Neither the javadocs, nor the result docs, say anything about this method being able to return null. My guess is that I did something wrong.
http://db.apache.org/jdo/api20/apidocs/javax/jdo/Query.html#execute%28%29
http://www.datanucleus.org/products/accessplatform_2_2/jdo/jdoql_result.html

A: When I tried your code with DataNucleus I experienced a similar problem at first.
The bycode enhancer was not running. Once I enabled it the count became 0 has expected.
Perhaps you're having a similar problem.


text:
Q: Laser Solid Interaction Can a continuous output laser fully ionize a surface to produce a plasma? I know of femtosecond laser pulses that do cause Coulomb Explosions, but what about in the case of continuous wave (CW) laser input, not a pulsed input?
In addition, how does CW laser input relate quantitatively to avalanche ionization of the surface?

A: I don't know the answer to your second question, but for the first question I would say that the laser pulses are short due to the high power (there is no laser system in the world that would manage to output TW or even GW laser beams continuously). But theoretically, I see no problem using a continuous wave laser to ionize a solid target as long as you reach the necessary field strengths to ionize via tunnel ionization to get the plasma started.
Since you mentioned that the targets Coulomb explode, I'll just touch lightly upon that also. The reason for this explosion is that the electrons in the plasma are much more mobile and can be accelerated to escape velocity from the positive ions by the laser. Then once the electrons have escaped the ions' mutual repulsion cause the Coulomb explosion you mentioned. There are several acceleration processes, but usually the rapid rise in intensity of a short pulse is involved in accelerating the electrons. Therefore a continuous intensity laser might not be able to make the target Coulomb explode, even though it might be powerful enough to ionize the plasma. (Once you have created a solid density plasma though, it will explode through simple hydrodynamic expansion into the surrounding vacuum.)


text:
Q: Rmagic memory use while resizing images When resizing images memory usage increases by 40 MB to 80ish MB. These are on files that vary in size but none of them are bigger then 300 kb.
After a bit of profiling I found the offending method.
def avatar_resize path
  img = Magick::Image.read(path).first
  img.resize_to_fit(200,200).to_blob
end

Is this big increase in memory usage normal or do I need to do something else to eliminate these huge spikes?

A: Do you need to create or composite images? If not you could use using mini magick instead. Rmagick shares memory with rails while mini magick has a separate memory allocation for mogrify.

A: I would probably try and avoid using .to_blob and write the image to file as that is storing your image in memory as is most likely contributing to your high memory usage.


text:
Q: Why does the pre/post increment operator behave wrongly? Why the values of variable in PHP does not have a consistent behavior in following code?
<?php
$piece = 10;
// output is 10 10 10 10 11 12
echo $piece . $piece . $piece . $piece++ . $piece . ++$piece;

$piece = 10;
// output is 10 10 10 11 12
echo $piece . $piece . $piece++ . $piece . ++$piece;

$piece = 10;
// output is 11 10 11 12
echo $piece . $piece++ . $piece . ++$piece;
?>

The question is why is the first output in the last example equal to 11? instead of 10 as it give in above 2 examples.

A: From http://php.net/manual/en/language.operators.precedence.php:

Operator precedence and associativity only determine how expressions are grouped, they do not specify an order of evaluation. PHP does not (in the general case) specify in which order an expression is evaluated and code that assumes a specific order of evaluation should be avoided, because the behavior can change between versions of PHP or depending on the surrounding code.
<?php
$a = 1;
echo $a + $a++; // may print either 2 or 3

$i = 1;
$array[$i] = $i++; // may set either index 1 or 2
?>

In other words, you cannot rely on the ++ taking effect at a particular time with respect to the rest of the expression.


text:
Q: how to change path of multi files c# In this code im getting the filename from the path the user choose and i want to edit the text file and save it to text but i want it to be (filename+new).txt  my code is getting filename.txtnew :
private void button1_Click(object sender, EventArgs e)
{
    folderBrowserDialog1.ShowDialog();

    string[] fileArray = System.IO.Directory.GetFiles(folderBrowserDialog1.SelectedPath);
    foreach (string filename in fileArray)
    {
        richTextBox1.Text = "";
        //string path = @"C:\Users\rabih\Desktop\uni\IR\textNoStopWords"+".txt ";
        string path = filename + "new";
        richTextBox1.Text = System.IO.File.ReadAllText(filename);
        string st = richTextBox1.Text;
        string[] split = st.Split(' ');
        foreach (string s in split)
        {
            if (!Stopwords.Contains(s.ToLower()))
            {
                //richTextBox2.Text += s + " ";
            }
        }
        richTextBox2.Text += path + " \n";
        using (File.Create(path)) ;
        richTextBox2.SaveFile(path, RichTextBoxStreamType.RichText);
    }
}

A: You can split the fileName by . and construct the new FileName, like the following code:
private static string GetNewFileName(string oldFileName)
{
    string[] splitedFileName = oldFileName.Split('.');

    return string.Concat(splitedFileName[0], "new.", splitedFileName[1]);
}

Call the GetNewFileName in your code :
string newFileName = GetNewFileName(filename);

I hope that will help you fix the issue.


text:
Q: Get the ratio of a products uses and price per use. Not sure I am going to ask this well or even if the title is correct.
say you have a dataset like:

*

*59 uses - price per use £0.09p

*43 uses - price per use £0.06p

*59 uses - price per use £0.04p

*66 uses - price per use £0.12p

*62 uses - price per use £0.1p

Obviously visually I can see which one in this small example has the best price to use ratio.
How do I write a formula that will result in a ratio for each item in the dataset?
I would also ask you keep you answer as simple as possible as I am not great at Math.
thanks

Above was confusing and imcomplete so I will add more hopefully it will help - I may be after the perctage im not sure.
Also adding missing data.
[
    {
        "weight" : 215,
        "price": 5.24,
        "weightPerUse": 3.65
    },
    {
        "weight" : 130,
        "price": 2.54,
        "weightPerUse": 3.04
    },
    {
        "weight" : 500,
        "price": 2.17,
        "weightPerUse": 8.5
    },
    {
        "weight" : 120,
        "price": 7.72,
        "weightPerUse": 1.83
    },
    {
        "weight" : 500,
        "price": 5.99,
        "weightPerUse": 8.12
    }
]

This dataset results in

*

*weighting 215 - number of uses 59 with a price per use of 0.09

*weighting 130 - number of uses 43 with a price per use 0.06

*weighting 500 - number of uses 59 with a price per use 0.04

*weighting 120 - number of uses 66 with a price per use 0.12

*weighting 500 - number of uses 62 with a price per use 0.1

I would like to know based on the information provided which has the best price to weight.
really sorry I am unable to explain myself better.

A: What I would do is create a heuristic that increases as number of uses given increases, and decreases as price increases. The simplest one is $\dfrac{uses}{price}$.
If you add exponents to the numerator and denominator, you can change the "weight" you give each value. E.g., $\dfrac{uses}{(price)^3}$ will say a choice is very unfavourable even if the price is a little high and $\dfrac{uses^3}{price}$ will say a choice is very favourable even if you can get only a few more uses.
There is another technique, that I will not explain (you might not understand it) in great detail. We create something called a "loss function" that only looks at factors unfavourable to the problem. The task then is finding the minimum of this loss expression, invoking some calculus and even linear algebra.
E.g., if all you had a number of entries all of which offered the same number of uses, but at different prices, the loss function is easy $loss = {weightage} \times {price}$ (loss increases as price increases). Finding the minimum price here doesn't need any calculus or linear algebra, one merely has to look for the lowest price. In certain cases, the loss function that we arrive at is a curvy line than something that steadily increases or decreases: we use higher mathematical ideas there.


text:
Q: Veracrypt, what is the purpose of the small EFI partition, beyond the boot manager? I have Veracrypt full disk encryption under windows. I have 100MB partition which appears to store the EFI software and a 450mb windows recovery partition.
Does this EFI partition and its software do anything else.
Specifically, does it contain any keys needed for decryption or configuration information about the encrypted partition?
I currently backup only my encrypted C drive and not the other partitions, on the basis that I think I only need the C drive because the other are generic.


text:
Q: Repeat a set of numbers over a column pandas dataframe Let's say we have two variables X and Y. I want to generate Y by repeating a set of numbers (1, 2, 3, 4, 5) or 1:5 over the rows. How can we generate column Y?
X   Y
20  1
95  2
86  3
95  4
9   5
19  1
4   2
26  3
66  4
72  5
26  1
5   2
2   3
73  4
73  5
88  1
51  2

A: Use np.tile
>>> df['Y'] = np.tile(np.arange(1, 6), len(df))[:len(df)]

A: Doing
df['New'] = df.index%5 + 1
df
Out[21]:
     X  Y  New
0   20  1    1
1   95  2    2
2   86  3    3
3   95  4    4
4    9  5    5
5   19  1    1
6    4  2    2
7   26  3    3
8   66  4    4
9   72  5    5
10  26  1    1
11   5  2    2
12   2  3    3
13  73  4    4
14  73  5    5
15  88  1    1
16  51  2    2

A: itertools to the rescue.
>>> import itertools
>>> X = [20,95,86,95,9,19,4,26,66,72,26,5,2,73,73,88,51]
>>> result = list(zip(X, itertools.cycle((1,2,3,4,5))))
>>> result
[(20, 1), (95, 2), (86, 3), (95, 4), (9, 5), (19, 1), (4, 2), (26, 3), (66, 4), (72, 5), (26, 1), (5, 2), (2, 3), (73, 4), (73, 5), (88, 1), (51, 2)]
>>>

A: One option with add_column from pyjanitor:
# pip install pyjanitor
import pandas as pd
import janitor

df.add_column(value = [1,2,3,4,5], column_name = 'new', fill_remaining=True)
Out[106]:
     X  Y  new
0   20  1    1
1   95  2    2
2   86  3    3
3   95  4    4
4    9  5    5
5   19  1    1
6    4  2    2
7   26  3    3
8   66  4    4
9   72  5    5
10  26  1    1
11   5  2    2
12   2  3    3
13  73  4    4
14  73  5    5
15  88  1    1
16  51  2    2


text:
Q: Shifting enumerate list with custom made bullets to the right I have problems with shifting my enumerate list to the right.
I have the following code with custom made bullet points:
\documentclass{article}
\usepackage{amssymb}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{enumerate,xcolor}
\begin{document}

\begin{enumerate}[{\makebox[0pt][l]{$\square$}\raisebox{.15ex}  {\hspace{0.1em}$\checkmark$} }] % notice the space after "1"
   \item 1
    \item 2
\end{enumerate}

Now when I try with the usual \begin{enumerate}[leftmargin=2cm], I have problems with the custom made bullets. It simply does not work I have tried writing:
\begin{enumerate}[{\makebox[0pt][l]{$\square$}\raisebox{.15ex}
{\hspace{0.1em}$\checkmark$}, leftmargin=2cm }]

and
\begin{enumerate}[{\makebox[0pt][l]{$\square$}\raisebox{.15ex}
{\hspace{0.1em}$\checkmark$} }][leftmargin=2cm]

but nothing worked - it just compiled and the as bulletpoints I had the text "leftmargin" and in option nr.2 the list completely disappeared.
I have attached a picture of the list as it looks now.
Hope someone can point me in the right direction.
Best Husky

A: No math mode needed – a simple \Checkmark from bbding and enumitem will do:
\documentclass{article}
\usepackage{amssymb}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{bbding}
\usepackage{enumitem}

\begin{document}

\begin{itemize}[label = {\fboxsep = 0pt\fbox{\scriptsize\Checkmark}}, labelsep = 1em] %
   \item First item
   \item Second item
\end{itemize}

\end{document}

A: Perhaps something like this using the enumitem package?
\documentclass{article}
\usepackage{amssymb}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{enumitem,xcolor}
\newlist{custom}{itemize}{4}
\newcommand\CustomBullet{%
  \makebox[0pt][l]{$\square$}\raisebox{.15ex}{\hspace{0.1em}$\checkmark$}%
}
\setlist[custom]{
  label=\CustomBullet,
  leftmargin=20mm
}

\begin{document}

  \noindent Some words before
  \begin{custom}
   \item 1
   \item 2
  \end{custom}
  Some words after

\end{document}

The code produces:


text:
Q: Perfectly running python script gives error when run from web.py I have the following python script which runs perfectly if run separately:
import arcpy

val = arcpy.GetCellValue_management("D:\dem-merged\lidar_wsg84", "-95.090174910630012 29.973962146120652", "")
print str(val)

I want to expose this as a web service and so I installed web.py and wrote the following code for code.py. but it gives errors(when invoked. compiles fine).
import web
import arcpy
urls = (
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:
    def GET(self, name):

        val = arcpy.GetCellValue_management("D:\dem-merged\lidar_wsg84", "-95.090174910630012 29.973962146120652", "")
        return  str(val)

if __name__ == "__main__":
    app.run()

When i invoke this using http://localhost:8080, i get the following error:
<class 'arcgisscripting.ExecuteError'> at /
ERROR 000582: Error occurred during execution.

Python  C:\Program Files (x86)\ArcGIS\Desktop10.0\arcpy\arcpy\management.py in GetCellValue, line 8460
Web GET http://localhost:8080/
Traceback (innermost first)

C:\Program Files (x86)\ArcGIS\Desktop10.0\arcpy\arcpy\management.py in GetCellValue
          be returned."""
    try:

        retval = convertArcObjectToPythonObject(gp.GetCellValue_management(*gp_fixargs((in_raster, location_point, band_index), True)))
        return retval
    except Exception, e:
        raise e ...
@gptooldoc('GetRasterProperties_management', None)
def GetRasterProperties(in_raster=None, property_type=None):
    """GetRasterProperties_management(in_raster, {property_type})
        Returns the properties of a raster dataset.

I have tried Debugging it in many ways, the code .py runs fine if i just return a "hello".  The library i am using is a ArcGIS Geoprocessing toolbox library.
Any ideas as to what might be wrong?

A: That looks like an error from the third party module. Try finding out what that error code (000582) actually means to the application.


text:
Q: Hacer lo que hago en MySQL pero en PDO con PHP Estoy tratando de aprender PDO, manejo PHP, pero con mysql_query quise migrar a PDO, pero da un error, ya probé insertando pero no me funciona ahora, quiero probar haciendo una consulta pero no me sale alguien sabría el porque no me deja consultar.
El error que me sale es:

Fatal error: Call to a member function query() on null in
  C:\xampp\htdocs\PDOJEFFERSON\models\agregarUser.php on line 5

Código:
function ConexionMySql(){
    $cadenaHost='mysql:Server=localhost;dbname=basebyjefferson';
    $nombre_user_db='root';
    $pass_user_db='';
    try {
        $conectar=new PDO($cadenaHost,$nombre_user_db,$pass_user_db);
        $conectar->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    } catch (Exception $e) {
        echo "ERROR: " . $e->getMessage();
    }
}
<?php
    include '../conexion.php';
    $cn=ConexionMySql();
    $sql= "SELECT * FROM tbluser";
    $query = $cn->query($sql);
    while($r=$query->fetch()){
        echo json_encode($r);
    }
?>

A: tu problema esta en que tu función de conexión no te esta regresando una instancia de la base de datos.
Lo que te falta agregar a tu código de conexión es un return para obtener la instancia a la base de datos.
function ConexionMySql(){
   $cadenaHost='mysql:Server=localhost;dbname=basebyjefferson';
   $nombre_user_db='root';
   $pass_user_db='';
       try {
         $conectar=new PDO($cadenaHost,$nombre_user_db,$pass_user_db);
         $conectar->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
         return $conectar;
       } catch (Exception $e) {
          echo "ERROR: " . $e->getMessage();
       }
}

A: Hay varios errores que solucionar.
Por una parte, creo recordar que la dsn mysql:Server= es errónea. Debería ser mysql:host=. Con mysql:Server=localhost da un poco igual por que es ignorado por PDOy usa el default que es mysql:host=localhost, pero si quieres conectar a una base de datos externa mediante una ip concreta igual te daría errores.
En segundo lugar, la función debe de retornar la instancia de la conexión para continuar trabajando con ella. Si no, retorna un valor nulo, y por lógica, al no "existir" la conexión, el script lanzará el error correspondiente.
<?php

function ConexionMySql()
{
    // $cadenaHost = 'mysql:Server=localhost;dbname=basebyjefferson';
    // cambiar por:
    $cadenaHost     = 'mysql:host=localhost;dbname=basebyjefferson';
    $nombre_user_db = 'root';
    $pass_user_db   = '';
    try {
        $conectar = new PDO( $cadenaHost, $nombre_user_db, $pass_user_db );
        $conectar->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    }
    catch( Exception $e ) {
        echo "ERROR: " . $e->getMessage();
    }

    return $conectar;
}

include dirname(__DIR__) . '/conexion.php';

$cn    = ConexionMySql();
$sql   = "SELECT * FROM tbluser";
$query = $cn->query( $sql );

while( $r = $query->fetch() ) {
    echo json_encode( $r );
}

PD.: No lo he probado. Si hay errores, un comentario y seguimos.

A: Hola tu ciclo esta mal hecho. Debería ser así:
foreach ($query as $querys)
{
    echo json_encode($r);
}

A: El problema está en tu función ConexionMySql, no está devolviendo valor alguno.
Intenta agregar:
return $conectar;

Antes de terminar la función, puede ser adentro de la sección try.
Por otro lado, en el código de agregarUser.php deberías comprobar que el valor que regresa la función ConexionMySql es válido antes de utilizarlo, por ejemplo:
if ($cn != null) {
    $query = $cn->query($sql);
} else {
    echo "¡Objeto PDO es nulo!";
}


text:
Q: I want to merge data using lodash [
{
    "label": "google_da_desktop_1",
    "data": [
        0,
        22.596473199939744,
        32.932481810474904,
        41.05015952885718,
        47.99635538700579,
        54.183927487925395,
        59.82719604246855,
        65.0546652236101,
        69.95069924256464
    ],
    "week": 1,
    "group": "google_da_desktop",
    "groupNo": 0
},
{
    "label": "google_da_desktop_2",
    "data": [
        0,
        22.596473199939744,
        32.932481810474904,
        41.05015952885718,
        47.99635538700579,
        54.183927487925395,
        59.82719604246855,
        65.0546652236101,
        69.95069924256464
    ],
    "week": 1,
    "group": "google_da_desktop",
    "groupNo": 0
}
]

I want to group these data into groups and sum the data, but is there any way?
I tried using lodash groupBy but it didn't work


text:
Q: DocuSign Powerform: how to set different custom URL for each Powerform? I currently have 2 Powerforms and 2 Brands. I tried to set different redirect URL for each Powerform through "Bands > destination URLs > Signing Completed" (I already chose the brand for each template). Unfortunately, it didnt work.
It only works if I set the URL in "signing settings > in-session landing pages -> Signing Completed", however it will apply to all the Powerforms wiht the same URL.

A: When you create a Powerform there is an option to check Require Email Validation. Whiche means that Signer must verify their identity through email before accessing and signing the PowerForm. Recipient provides email address and then receives a validation code for the PowerForm. Recipient must retrieve the code and provide it in order to sign.
Please check https://support.docusign.com/guides/ndse-user-guide-create-a-powerform to see how to create an email powerform
So if you make an Email Powerform then it uses Brand and your Brand's Destination URL will be called. But when you use Direct Powerform then  in-session landing pages will be called.

A: My bad, answered the wrong question... This might be relevant though so i'll leave it here.
My question was: DocuSign: Is it possible to send a custom payload via PowerForm link and get it back via webhook?
So according to this documentation: https://support.docusign.com/guides/ndse-user-guide-populate-custom-document-fields-in-a-web-powerform
You can set various fields. My mistake was  that I was trying to set custom fields of the template - which have to be added to the document at some point and are visible.
The solution is simple - set an envelope custom field which are dynamic and can be created on the fly.


text:
Q: "treating the interference as noise" or "treating interference as noise"? Which one is the proper term to use when talking about interference in wireless networks "treating the interference as noise" or "treating interference as noise"?
When I check google scholars the second one is used more, but it seems we need "the" there.
Example: While treating interference as noise is optimal in some scenarios, decoding interference is optimal in others.

A: "the interference" refers to some known, previously mentioned interference (e.g. atmospheric interference or general interference)
"interference" means "any interference that may exist"


text:
Q: Dynamic PHP Methods I am working on a custom DB Table Mapper in PHP.
Is it possible in PHP to make something like "virtual methods" to access the properties? Like Methods, that don't really exist.
For Example: A class "user" has the property "$name", i don't want to create a "Get" Method for this one, but i want to access the property via a virtual Method, like this: $user->GetName();
I was thinking of working with Conventions. So everytime a "virtual" Method has been called, you catch it, and check if it has the prefix "Get" or "Set".
If it has the prefix "Get" you strip the part after "Get" and make it lowercase, so you have the property you want to access.
My Idea (Pseudo Code):
public function VirtualMethodCalled($method_name)
{
   //Get the First 3 Chars to check if Get or Set
   $check = substr($method_name, 0, 3);

   //Get Everything after the first 3 chars to get the propertyname
   $property_name = substr($method_name, 3, 0);

   if($check=="Get")
   {
       return $this->{$property_name};
   }
   else if($check=="Set")
   {
       $this->{$property_name};
       $this->Update();
   }
   else
   {
       //throw exc
   }
}

A: You can use a magic method to achieve this, example:
class A {

    private $member;

    public function __call($name, $arguments) {
      //Get the First 3 Chars to check if Get or Set
      $check = substr($method_name, 0, 3);

     //Get Everything after the first 3 chars to get the propertyname
     $property_name = substr($method_name, 3);

     if($check=="Get")
     {
       return $this->{$property_name};
     }
     else if($check=="Set")
     {
       $this->{$property_name} = $arguments[0]; //I'm assuming
     }
     else
     {
         //throw method not found exception
     }
    }
}

I'm mainly using the code you provided for the contents. You can obviously extend this to also handle things like function name aliases or whatever you need.


text:
Q: mutate new column based on conditions in another row in R I am working with a dataset of animal behaviors, and am trying to create a new column ("environment") based on conditions fulfilled in another row. Specifically, I want the new column to return "water" if the behavior falls between the start/stop times of the behavior "o_water", and "land" if it falls outside these bounds. If this is unclear here is a minimal example:
library(dplyr)
library(magrittr)

otters <- data.frame(
  observation_id = 1,
  subject = 1,
  behavior = c("o_water", "swim", "float", "o_land", "walk", "o_water", "float"),
  start_time = c(1,1,2,6,6,11,11),
  stop_time = c(5,3,4,10,9,15,14)
)

#this does it, but manually. need to go over very large dataset and search for conditions
otters <- otters %>%
  group_by(subject, observation_id, behavior) %>%
  mutate(environment = ifelse((start_time >= 1 & stop_time <= 5) |
                                (start_time >= 11 & stop_time <= 15), "water", "land"))

This is the output desired.
Groups:   subject, observation_id, behavior [5]
  observation_id subject behavior start_time stop_time environment
           <dbl>   <dbl> <fct>         <dbl>     <dbl> <chr>
1              1       1 o_water           1         5 water
2              1       1 swim              1         3 water
3              1       1 float             2         4 water
4              1       1 o_land            6        10 land
5              1       1 walk              6         9 land
6              1       1 o_water          11        15 water
7              1       1 float            11        14 water

The second set of commands is sort of what I want, but I need this to search out and apply it to an entire dataset rather than typing out each parameter. The grouping is so the functions are performed over the applicable rows; in the full dataset, there are multiple subjects and observation_id's.
I've tried using when() and case_when() to no avail, but I am very novice level at R so would appreciate any help!
Apologies for any missteps I've done. I haven't been able to find a problem quite like this elsewhere on stackoverflow.

A: Great job on your question.
I think rearranging your dataset will help a lot here. I'd suggest rearranging it so that each time point has only one record (per individual otter, perhaps), and individual behaviors each have their own column, with binary data indicating whether or not that behavior is occurring at each time point.
There's a lot of rearranging that happens in the first few lines; I'd suggest stepping through the code one line at a time just to see how each line moves the data around.
Using the data you provided:
library(tidyverse)

otters_wide <- otters %>%
  # first pivot to a longer form, so the time values are all in one column
  pivot_longer(cols = c("start_time", "stop_time"), names_to = "start_stop", values_to = "time", names_pattern = "(.*)_time") %>%
  # then pivot to w wider format, so each behavior has its own column.
  pivot_wider(names_from = "behavior", values_from = "start_stop") %>%
  #Then arrange everything in order of time.
  arrange(time) %>%
  #Fill behavior columns downward
  fill(o_water, swim, float, o_land, walk) %>%
  #change all "start"s and the first "stop" in each series to "yes", and all other "stop"s to "no"
  mutate_at(.vars = c("o_water", "swim", "float", "o_land", "walk"), ~ if_else(. == "start" | lag(.) == "start", "yes", "no")) %>%
  # this column is a little redundant now, but here's the water/land column, at last.
  mutate(environment = if_else(o_water == "yes", "water", "land"))

otters_wide

# A tibble: 11 x 9
   observation_id subject  time o_water swim  float o_land walk  environment
            <dbl>   <dbl> <dbl> <chr>   <chr> <chr> <chr>  <chr> <chr>
 1              1       1     1 yes     yes   NA    NA     NA    water
 2              1       1     2 yes     yes   yes   NA     NA    water
 3              1       1     3 yes     yes   yes   NA     NA    water
 4              1       1     4 yes     no    yes   NA     NA    water
 5              1       1     5 yes     no    no    NA     NA    water
 6              1       1     6 no      no    no    yes    yes   land
 7              1       1     9 no      no    no    yes    yes   land
 8              1       1    10 no      no    no    yes    no    land
 9              1       1    11 yes     no    yes   no     no    water
10              1       1    14 yes     no    yes   no     no    water
11              1       1    15 yes     no    no    no     no    water

In this alternate format you could go even further and include time points that weren't explicitly recorded (e.g. times 7, 8, 12 & 13, in this example) which, once filled in, would make summarizing things like total time spent on each behavior much more straightforward.
Since the behavioral data is binary, those columns could certainly contain logical data rather than character data, but because they started as character data, keeping them that way seemed simplest.
Hope this helps.

A: Here is another approach with dplyr that also uses fuzzyjoin package.
You can separate your o_water behavior rows from otters and designate the environment as water.
Then, with fuzzy_left_join, merge the o_water rows with the rest of your data, where the start_time and end_time fall between the o_water range.
The remaining NA in environment will be non-merged rows, which can be land or other designation.
library(dplyr)
library(fuzzyjoin)

otters_water <- otters %>%
  filter(behavior == "o_water") %>%
  mutate(environment = "water") %>%
  select(-behavior)

otters %>%
  fuzzy_left_join(otters_water,
                  by = c("subject", "observation_id", "start_time", "stop_time"),
                  match_fun = list(`==`, `==`, `>=`, `<=`)) %>%
  replace_na(list(environment = "land")) %>%
  select(c(observation_id.x:stop_time.x, environment))

Output
  observation_id.x subject.x behavior start_time.x stop_time.x environment
1                1         1  o_water            1           5       water
2                1         1     swim            1           3       water
3                1         1    float            2           4       water
4                1         1   o_land            6          10        land
5                1         1     walk            6           9        land
6                1         1  o_water           11          15       water
7                1         1    float           11          14       water

A: Here is another approach, in which I extract all the start_ and stop_times of each behavior of o_water into a list. As there are 2 entries for o_water these lists have two elements.
With the help of purrr I create a list pu of vectors which span the start_ and stop_time for each entry.
purrr also helps to find which row in otters falls within the sequences defined in pu. l_true is the sum of all columns which have a FALSE/TRUE, it contains either a 1, if there is one entry matching the time sequence or a 0 if it does not.
This list is bound to otters and with ifelse the new column is named.
library(tidyverse)

otters <- data.frame(
  observation_id = 1,
  subject = 1,
  behavior = c("o_water", "swim", "float", "o_land", "walk", "o_water", "float"),
  start_time = c(1,1,2,6,6,11,11),
  stop_time = c(5,3,4,10,9,15,14)
)
# otters
# find all start_times of 'o_water'
otters %>%
  dplyr::filter(grepl('water', behavior)) %>%
  select(ends_with('time')) %>%
  `[[`(1) -> start
start
#> [1]  1 11

# find all stop_times
otters %>%
  dplyr::filter(grepl('water', behavior)) %>%
  select(ends_with('time')) %>%
  `[[`(2) -> stop
stop
#> [1]  5 15

# bring start and stop_times together in one
# list per 'o_water'
pu <- purrr::map2(start, stop, ~ .x : .y)
pu
#> [[1]]
#> [1] 1 2 3 4 5
#>
#> [[2]]
#> [1] 11 12 13 14 15

# check with pu, if start_ and stop_time of each row is
# in pu, and combine the row of FALSE/TRUE into a list
l_true <- map_dfc(pu, ~ otters$start_time %in% . & otters$stop_time %in% .) %>%
  mutate(l = rowSums(.[1:ncol(.)])) %>% `[[`(ncol(.))

otters %>%
  cbind(., l_true) %>%
  mutate(ev = ifelse(l_true == 1, 'water', 'land'))
#>   observation_id subject behavior start_time stop_time l_true    ev
#> 1              1       1  o_water          1         5      1 water
#> 2              1       1     swim          1         3      1 water
#> 3              1       1    float          2         4      1 water
#> 4              1       1   o_land          6        10      0  land
#> 5              1       1     walk          6         9      0  land
#> 6              1       1  o_water         11        15      1 water
#> 7              1       1    float         11        14      1 water


text:
Q: How to click post button in Facebook groups?, webdriver Java I also cannot click this button with the below code, i've tried:
    driver.navigate().to(groupname);
    Thread.sleep(3000);
    driver.findElement(By.name("xhpc_message_text")).sendKeys(LinkYT+"\n");
    Thread.sleep(3000);
    driver.findElement(By.xpath("\\button\\span[.=\"Post\"]")).click();

I've used also waits and cssSelectors but cannot manage to click the button. I'm surely doing something wrong
Do you you have a suggestion?
<button class="_1mf7 _4jy0 _4jy3 _4jy1 _51sy selected _42ft" data-
testid="react-composer-post-button" type="submit" value="1">Post</button>

ex for one of my tries, all have same no such element exection. so xpath,css selector etc i get them wrong for this button...
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no
such element: Unable to locate element:
{"method":"xpath","selector":"//button[@type='submit']
[contains(text(),'Post')]"}
(Session info: chrome=61.0.3163.100)
(Driver info: chromedriver=2.30.477700
(0057494ad8732195794a7b32078424f92a5fce41),platform=Windows NT 10.0.15063
x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 46 milliseconds
For documentation on this error, please visit:
http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.4.0', revision: 'unknown', time: 'unknown'
System info: host: 'INTERN2017-37', ip: '10.6.220.24', os.name: 'Windows
10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false,
mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome=
{chromedriverVersion=2.30.477700 (0057494ad8732195794a7b32078424f92a5fce41),
userDataDir=C:\Users\LUCIAN~1.PAT\AppData\Local\Temp\scoped_dir19996_28709},
takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false,
handlesAlerts=true, hasTouchScreen=false, version=61.0.3163.100,
platform=XP, browserConnectionEnabled=false, nativeEvents=true,
acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true,
browserName=chrome, takesScreenshot=true, javascriptEnabled=true,
cssSelectorsEnabled=true, unexpectedAlertBehaviour=}]
Session ID: 2bbb3a860bbafbca888b4a9c5af20029
*** Element info: {Using=xpath, value=//button[@type='submit']
[contains(text(),'Post')]}
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)

A: manged to do it with:
  WebElement elem = driver.findElement(By.xpath("//button[@type='submit']//span[contains(text(),'Post')]"));
    Actions actions = new Actions(driver);

    actions.moveToElement(elem).click().perform();

A: Your answer is correct but as I guess you can also use xpath using SPAN directly like this
WebElement elem = driver.findElement(By.xpath("//span[contains(text(),'Post')]"));
Actions actions = new Actions(driver);
actions.moveToElement(elem).click().perform();


text:
Q: How Do You Unescape Special Characters In A Python String? From spam\/eggs to spam/eggs
# This isn't working...
str = "spam\/eggs"
s = bytes(str, "utf-8").decode("unicode_escape")

print(s)
>>> spam\/eggs

# How to get "spam/eggs"

A: In python you can't use a '\' because python will think you will add something after it like '\t', '\n', etc. So you can use an extra backwards slash in the string: string = 'spam\\/eggs'
I don't think this is the most effiencient way to do this a differnt way but you can do this:
strs = 'spam\/eggs'
print(strs)
strs = strs.replace('\\','')
print(strs)

I just deleted the \ by replacing it with an empty string.

A: You could use regular expressions.
To remove especifically the special character \ you must specify to regex \ \
import re
myString = "spam\/eggs"
str2 = re.sub(r'\\', "", myString) # remove this character '\'
print(str2)
# spam/eggs

General purpose (remove specific characters) :
import re
myString = "sp&a+m\/eg*gs"
str2 = re.sub(r'[\\&+*]', "", myString) # to remove what you want into the brackets
print(str2)
# spam/eggs

A: str = "spam/eggs"
str2 = bytes(str, "utf-8").decode("unicode_escape")
print(str2)

BTW: you should place the code in the question more carefully; you call a variable str then myString and the second variable str2 then str1


text:
Q: Bootstrap Popover data-content readable for Google How can I make the data-content of a bootstrap popover be readable for google? My Code:

Responsive Webdesign

I have some more tags that need a short description by a popover. So I need a solution for several popover-contents.

First Idea: Is it possible to just add a span with the class sr-only or is this "spam" or even not visible for google:

 data-original-title="" [...]
Responsive Webdesign Data-Content-Text.

Second Idea:
Is it possible to open every popover by visiting the website for two seconds and close it after this two seconds? Would Google read the popover-content that is build by javascript then?

A: For your last question, Google can't read JS or any redirection through it.
Any data you want Google to index it, it must be visible for the user first, you have to treat Google like any regular user.
You need to change in your structure in order to crawl and index them.
Any hidden text will be a threat on your website, be careful.