text:
Q: eval command function within ksh script is globbing when I don't want it to Consider the following ksh script "myquery.ksh"
#/usr/bin/env ksh -eu

PROCESS_TYP=$1
PROCESS_DT=$2

#Generate a query
makeSQL()
{
local numfiles=0
local query='SEL \\* FROM TABLE_1_'
case "$1" in
'ABC') query="${query}ABC" ; numfiles=1 ;;
'DEF') query="${query}DEF" ; numfiles=7 ;;
esac
query="${query}_V WHERE LOAD_DT='${2}';"
printf "$query\n"
eval $3="${query}"
eval $4=$numfiles
return 0
}

makeSQL $PROCESS_TYP $PROCESS_DT qry num_files

printf "QUERY: $qry\n"
printf "NUMFILES: $num_files\n"

In the above code, the eval $3="${query}" statement never works correctly.  In all circumstances it seems to attempt to glob the "*" in the "local query="... statement.
./myquery.ksh ABC 2011-01-01

It always returns a message like this:
./myquery.ksh: line 17: \*: command not found

I am pretty sure this is my own user error with how I am applying eval in this situation but have tried nearly every alternate syntax construct for doing that eval $3 assignment but cannot manage to make this work.
I have tagged this as bash because I am pretty sure it would also behave identically there as well...

A: Did you mean:
eval "$3=\$query"
eval "$4=\$numfiles"

Explanation: in your example you want to pass variable names to the function, and these variables are then set. So the statements should look like this:
qry=$query
num_files=$numfiles

Now the question is how to put these strings together. The left hand side comes from the arguments, for example "$3". The right hand side contains a $ that must not be interpreted too early. Therefore I wrote it as \$.
I always pass a single string to the eval command, since that gives me the most reliable results. Not eval echo foo, but eval "echo foo" instead.
Alternatively you could have written:
eval "$3"='$query'
eval "$3="'$'"query"

But the first form I suggested seems the simplest to me.


text:
Q: start callback val acc after specific epoch I have a doubt when implementing a early stopping using validation accuracy.
Suppose I want to stop a training when the validation accuracy does not improve after 50 epochs. However I can get randomly a good validation accuracy in the second epcoch. For instance:
accuracy training: 0.76
accuracy validation: 0.80
Maybe I do not get a better validation accuracy while the accuracy training is improving.
So, when I reach 99% accuracy on training it may happen that the training stops because the 80% of validation accuracy in the second epoch has been too high (epoch = 52).
I would like to insert an offset. For example, early stopping using validation accuracy but starting in epoch = 100.
Is that possible in Keras?
Thanks in advance

A: Keras callbacks are very flexible, so you could simply modify the built-in EarlyStopping callback:
from keras.callbacks import EarlyStopping

class DelayedEarlyStopping(EarlyStopping):
    def on_epoch_end(self, epoch, logs=None):
        if epoch >= 100:
            super().on_epoch_end(epoch, logs=logs)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't login from console after 22.04 upgrade After upgrading to 22.04 LTS, I can no longer login from the console to the user who did the upgrade. I can login to another user.
I also can login to that user from SSH. no error message appears on the console. It just sends me back to the initial screen where all users are listed.
No clue what the issue is.


text:
Q: How to expand environmental variables in JSON into valid JSON notation by PowerShell This question relates to my other question and to this issue.
When I try to read a configuration from a JSON which contains an environmental variable, e.g. %USERPROFILE%\\source an obvious choice [System.Environment]::ExpandEnvironmentVariables($jsonString) expands the JSON string into non-valid JSON notation, e.g. "C:\Users\JohnDoe". The \U is not a valid JSON notation.
The question is how to overcome this problem (with some clean code).

A: If you are performing the replacement on the entire $jsonString then, yes,
$jsonString -replace '\\', '\\' will replace too many backslashes.
You could then beter do this instead:
$match = ([regex] '(%([^%]+)%)').Match($jsonString)
while ($match.Success) {
    $search     = $match.Groups[1].Value
    $replace    = [environment]::GetEnvironmentVariable($match.Groups[2].Value) -replace '\\', '\\'
    $jsonString = $jsonString -replace $search, $replace
    $match      = $match.NextMatch()
}

This will only replace the matched %SomeVar% environment variables by what they expand into doubles all possible backslashes in that.
Test using some bogus JSON:
$jsonString = @"
{
    "Name": "%USERNAME%",
    "UserPath": "%USERPROFILE%\\source"
    "WinDir": "%SystemRoot%"
    "InetPath": "%SystemDrive%\\inetpub\\wwwroot",
}
"@
    $match = ([regex] '(%([^%]+)%)').Match($jsonString)
    while ($match.Success) {
        $search     = $match.Groups[1].Value
        $replace    = [environment]::GetEnvironmentVariable($match.Groups[2].Value) -replace '\\', '\\'
        Write-Host $search
        write-host $replace
        $jsonString = $jsonString -replace $search, $replace
        $match      = $match.NextMatch()
    }

$jsonString

Output:
{
    "Name": "KUTlime",
    "UserPath": "C:\\Users\\KUTlime\\source"
    "WinDir": "C:\\WINDOWS"
    "InetPath": "C:\\inetpub\\wwwroot",
}

A: In is general a bad practice to peek and poke into serialized object strings (as e.g. a Json and XML) using string methods like Replace. Instead it is better to de-serialize the string to an object, make your changes, and serialize it to a string again. This way you prevent pitfalls along with incorrectly replacing a backslash with a special meaning (such as an escape for a double quote or a Unicode character).
As it might be a hassle to recursively craw through a complex object to expand all the strings, I have written a small function for this:
function Expand-String {
    [CmdletBinding()] param(
        [Parameter(ValueFromPipeLine = $True)]$Object
    )
    Process {
        if ($Object -is [string]) { $Object = [System.Environment]::ExpandEnvironmentVariables($Object) }
        elseif ($Object -is [Collections.IDictionary]) {
            Foreach ($Key in @($Object.get_Keys())) { $Object[$Key] = Expand-String $Object[$Key] }
        }
        elseif ($Object -is [Collections.IEnumerable]) {
            for ($i = 0; $i -lt $Object.Count; $i++) { $Object[$i] = Expand-String $Object[$i] }
        }
        else {
            Foreach ($Name in ($Object.PSObject.Properties | Where-Object { $_.MemberType -eq 'NoteProperty' }).Name) {
                $Object.$Name = Expand-String $Object.$Name
            }
        }
        $Object
    }
}

$Json = @'
{
    "Environment Variables": {
        "Name": "%USERNAME%",
        "UserPath": "%USERPROFILE%\\source",
        "WinDir": "%SystemRoot%",
        "InetPath": "%SystemDrive%\\inetpub\\wwwroot"
    },
    "Special  Characters": {
        "Quote": "Hello \"World\"",
        "Unicode": ["\u1F60A", "\u1F44D"]
    }
}
'@

$Object = $Json | ConvertFrom-Json | Expand-String
$Object.'Environment Variables'

Name    UserPath                WinDir     InetPath
----    --------                ------     --------
KUTlime C:\Users\KUTlime\source C:\WINDOWS C:\inetpub\wwwroot

$Json = $Object | ConvertTo-Json -Depth 9
$Json

{
  "Environment Variables": {
    "Name": "KUTlime",
    "UserPath": "C:\\Users\\KUTlime\\source",
    "WinDir": "C:\\WINDOWS",
    "InetPath": "C:\\inetpub\\wwwroot"
  },
  "Special  Characters": {
    "Quote": "Hello \"World\"",
    "Unicode": [
      "ὠA",
      "ὄD"
    ]
  }
}


text:
Q: Решение алгоритма Цезаря с ключом Помогите выяснить, почему не хочет выводить значение зашифрованное, и, если можно, укажите на ошибки в общей программе. Fiddle.
function Cesar(offset, key, str) {
    var ACode = "a".charCodeAt(0),
        alphabetSize = 26;
    var mass_key = [],
        mass_alf = [],
        kon = 97,
        smeh = offset,
        chr;
    for (var i = 0; kon < (ACode + alphabetSize); ++i) { // алфавитный массив
        mass_alf.splice(i, 0, kon++);
    }
    for (var i = 0; key.length > i; i++) { // ключ массив
        mass_key.splice(i, 0, key.charCodeAt(i));
    }
    for (var i = 0; mass_key.length > i; i++) { // исключение повторений в массиве ключа
        for (var l = i + 1; mass_key.length > l; l++) {
            if (mass_key[i] === mass_key[l]) mass_key.splice(l, 1);
        }
    }
    for (var l = 0; mass_alf.length > l; l++) { // исключение повторения в массиве alf
        for (var n = 0; mass_key.length > n; n++) {
            if (mass_key[n] === mass_alf[l]) mass_alf.splice(l, 1);
        }
    }
    for (var i = 0; mass_key.length > i; i++) { // помещение ключа в массив alf
        mass_alf.splice(smeh++, 0, mass_key[i]);
    }
    return mass_alf;
    var code = 0;
    // = (ch+offset-ACode+alphabetSize)%alphabetSize + ACode;
    for (var a = 0; a < str.length; ++a)
    if ((chr = str.charCodeAt(a)) && (chr >= ACode) && (chr - ACode < alphabetSize)) // если больше 1 символа и больше колва алф то.
    for (var i = 0; mass_alf.length > i; i++) {
        if (chr === mass_alf[i]) {
            code = mass_alf[i + offset];
            if (code === undefined) code = mass_alf[(i + offset) % alphabetSize];
            res += String.fromCharCode(code);
        }
    } else res += str.charAt(a); // просто записываем букву которая прийшла
    return res;
}
var c = prompt('Vvedite key', 'academia');
var k = prompt('Vvedite key', 'slovo');
alert(Cesar(3, c, k));

A: Любопытсва ради реализовал этот алгоритм. Вроде, работает.
y^&j0ЮЯЭ=D:o*Ы!k<
(пароль: Кораблекрушение )

Попробуйте разобраться что там к чему, и добавить встроенный в программу ключ, который будет однозначно перемешивать исходный алфавит, чтобы в алфавите не было  очевидных "абвгдеёжз".


text:
Q: How to create DDL trigger to all databases in SQL Server 2005 instance I am going to create a DDL trigger to all databases in SQL Server instance. I'd like to do it in one run instead of many runs for each database.
Below are the two T-SQL statements I need to execute:
-- Create table

use <dbname>
GO
CREATE TABLE dbo.ChangeAttempt
(EventData xml NOT NULL,
AttemptDate datetime NOT NULL DEFAULT GETDATE(),
DBUser char(50) NOT NULL)
GO

-- Create DDL trigger

use <dbname>
GO
CREATE TRIGGER db_trg_ObjectChanges
ON DATABASE
FOR ALTER_PROCEDURE, DROP_PROCEDURE,
 ALTER_INDEX, DROP_INDEX,
 ALTER_TABLE, DROP_TABLE, ALTER_TRIGGER, DROP_TRIGGER,
 ALTER_VIEW, DROP_VIEW, ALTER_SCHEMA, DROP_SCHEMA,
 ALTER_ROLE, DROP_ROLE, ALTER_USER, DROP_USER
AS
SET NOCOUNT ON
INSERT dbo.ChangeAttempt
(EventData, DBUser)
VALUES (EVENTDATA(), USER)
GO

My question is: how can I programmaticaly create DDL trigger in one run?

A: why do you need one run? this is the only way to do it.
Msg 111, Level 15, State 1, Line 2
'CREATE TRIGGER' must be the first statement in a query batch.

run the output generated by this:
DECLARE @DatabaseName varchar(500)
DECLARE @Database_id  int
DECLARE @Query        varchar(8000)
DECLARE @CRLF         char(2)

SET @CRLF=CHAR(13)+CHAR(10)
---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
select @Database_id=MIN(database_id) from sys.databases where database_id IN (5,7,8,6)

WHILE @Database_id IS NOT NULL
BEGIN
    SELECT @DatabaseName=name from sys.databases where database_id=@Database_id
    SET @Query='-- Create table'+@CRLF+@CRLF
                +'use '+@DatabaseName+@CRLF
                +' GO'+@CRLF
                +' CREATE TABLE dbo.ChangeAttempt'+@CRLF
                +' (EventData xml NOT NULL,'+@CRLF
                +' AttemptDate datetime NOT NULL DEFAULT GETDATE(),'+@CRLF
                +' DBUser char(50) NOT NULL)'+@CRLF
                +'GO'+@CRLF+@CRLF
                +'-- Create DDL trigger '+@CRLF+@CRLF
                +'use '+@DatabaseName+@CRLF
                +'GO'+@CRLF
                +'CREATE TRIGGER db_trg_ObjectChanges'+@CRLF
                +'ON DATABASE'+@CRLF
                +'FOR ALTER_PROCEDURE, DROP_PROCEDURE,'+@CRLF
                +' ALTER_INDEX, DROP_INDEX,'+@CRLF
                +' ALTER_TABLE, DROP_TABLE, ALTER_TRIGGER, DROP_TRIGGER,'+@CRLF
                +' ALTER_VIEW, DROP_VIEW, ALTER_SCHEMA, DROP_SCHEMA,'+@CRLF
                +' ALTER_ROLE, DROP_ROLE, ALTER_USER, DROP_USER'+@CRLF
                +'AS'+@CRLF
                +'SET NOCOUNT ON'+@CRLF
                +'INSERT dbo.ChangeAttempt'+@CRLF
                +'(EventData, DBUser)'+@CRLF
                +'VALUES (EVENTDATA(), USER)'+@CRLF
                +'GO'+@CRLF
    PRINT @Query
    ---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
    ---MODIFY THIS TO INCLUDE THE DATABASES THAT YOU WANT TO WORk ON
    select @Database_id=MIN(database_id) from sys.databases WHERE database_id IN (5,7,8,6) AND database_id>@Database_id
END

EDIT
to determine what databases to generate scripts for do the following:

*

*run this query:
select database_id,name  from sys.databases

*find all of the databases you want to run the scripts for

*change my above script in two places (before loop & at bottom in loop) so all of the database_id that you want are in the following code section:
WHERE database_id IN (AAA,BBB,CCC,DDD,....)

A: You could use sp_MSforeachdb.
Something like this
sp_MSforeachdb
'
    CREATE TABLE ?.dbo.ChangeAttempt
        etc. etc. etc.
'
sp_MSforeachdb
'
    CREATE TRIGGER ?.dbo.db_trg_ObjectChanges
        etc. etc. etc.
'

I haven't tested this, in theory I'd expect it to work though. You want to make sure you exclude the system databases though.


text:
Q: Problems whith columns in Python xlrd I am a Python Beginner and I'm trying to make a script to sum all values in a column of a excel spereadsheet, and then write this value. I'm using xlrd and xlwt python packages. It works well for the first columm, but it doesn't works to the second untill the last column. Here is my code. Hope someone can help me.
import xlwt
import xlrd

workbook_page = xlrd.open_workbook('page_level.xlsx')
worksheet_page = workbook_page.sheet_by_name('Daily External Referrers')
num_rows = worksheet_page.nrows - 1
curr_row = 0`
num_cols = worksheet_page.ncols - 1`
curr_col = 1
soma = 0
while curr_col < num_cols:
    curr_col = curr_col + 1
    while curr_row < num_rows:
        curr_row = curr_row + 1
        row = (worksheet_page.cell_value(curr_row, curr_col))
        if isinstance (row, float):
            soma = soma + row
        else:
            pass
       worksheet_page.write(num_rows+1, curr_col, soma)
worksheet_page.save('page_level.xlsx')

A: I don't think you can directly edit the excel workbook you're reading with xlrd, you have to copy it to new workbook and edit that.
Just a prefence as well, but I would also use for loops rather than while loops just for ease.
I can't test it at the moment, but maybe try something more like this?
import xlwt, xlrd
from xlutils.copy import copy

read_workbook_page = xlrd.open_workbook('page_level.xlsx')

workbook_page = copy(read_workbook_page)
worksheet_page = workbook_page.sheet_by_name('Daily External Referrers')

num_rows = worksheet_page.nrows - 1
num_cols = worksheet_page.ncols - 1

for row in range(num_rows):
     column_sum = 0
     for column in range(1, num_cols):
          column_sum += worksheet_page.cell_value( row, column )
     worksheet_page.write(row, num_cols, column_sum )

worksheet_page.save('page_level.xlsx')


text:
Q: Linear differential form not exact I need explanation of the paragraphs with a vertical bar (extracted from Courant Intro to Analysis II):

I'm not sure why it's trying to justify that it makes sense in the first place if L is not 'exact'.  And then I'm confused as to why after using the curve C, L is not exact, when it seems to say that L becomes the differential of that integral - I may have just misinterpreted this.

A: It's an old-fashioned discussion. All that Courant is saying is that you can integrate any differential $1$-form $\omega = A\,dx + B\,dy + C\,dz$ along a parametrized path $C$ (given by $\big(x(t),y(t),z(t)\big)$, $a\le t\le b$) by calculating
$$\int_C\omega = \int_a^b \big(A(x(t),y(t),z(t))\frac{dx}{dt} + B(x(t),y(t),z(t))\frac{dy}{dt} + C(x(t),y(t),z(t))\frac{dz}{dt}\big)dt.$$
The chain rule will tell you that, in fact, the value is independent of how you parametrize $C$.


text:
Q: Como enviar los datos de un ListView con PopupMenuButton a otro ListView de otra vista Estoy haciendo una aplicación en la cual al seleccionar el ListView puedo enviar los datos mediante el siguiente método
onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HimnoDetalle(todo: Himnoslista[index]),
            ),
          );
        },

Pero he agregado un PopupMenuButton el cual de momento tiene 2 opciones, ambos botones mandan a interfaces diferentes lo hice de la siguiente manera
trailing: PopupMenuButton<String>(
          onSelected: _choiceAction,
          itemBuilder: (BuildContext context) {
            return Constants.choices.map((String choice) {
              return PopupMenuItem<String>(
                value: choice,
                child: Text(choice),
              );
            }).toList();
          },
        )

donde _choiceAction es un metodo dentro de la misma clase declarado de la siguiente manera
void _choiceAction(String choice) {
if (choice == Constants.agregarPlay) {
  Navigator.pushNamed(context, "/Play_List");
} else if (choice == Constants.agregarFavorit) {
  Navigator.pushNamed(context, "/Registro");
}

}
Pero mi intención es enviar el nombre a la interfaz que especifique dependiendo de la selección el PopupMenuButton
intente agregar el siguiente metodo dentro del PopupMenuButton pero me da errores..  mi Listview completo queda de la siguiente manera
body: ListView.builder(
    itemCount: Himnoslista.length,
    itemBuilder: (context, index) {
      return ListTile(
        title: Text(Himnoslista[index].tituloHimno),
        // Cuando un usuario pulsa en el ListTile, navega al DetailScreen.
        // Tenga en cuenta que no solo estamos creando un DetailScreen,
        // también le pasamos el objeto Todo actual!
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HimnoDetalle(todo: Himnoslista[index]),
            ),
          );
        },
        trailing: PopupMenuButton<String>(
          onSelected:  Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HimnoDetalle(todo: Himnoslista[index]),
            ),
          ),
          itemBuilder: (BuildContext context) {
            return Constants.choices.map((String choice) {
              return PopupMenuItem<String>(
                value: choice,
                child: Text(choice),
              );
            }).toList();
          },
        ),
      );

Pero me da error en las siguientes lineas que son donde se captura la selección del elemento del PopupMenuButton
onSelected:  Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HimnoDetalle(todo: Himnoslista[index]),
            ),
          ),

A: El error es porque el método onSelected espera un callBack String no un Future que es lo que retorna el Navigator.push.
Cambia esto:
          onSelected:  Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HimnoDetalle(todo: Himnoslista[index]),
            ),
          ),

Por esto:
          onSelected: (val) => Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HimnoDetalle(todo: Himnoslista[index]),
            ),
          ),


text:
Q: JSON encoding issue attempting to load bulk data into ElasticSearch, only from Windows I'm uploading a file to the ElasticSearch /_bulk api to insert/update records. From my local machine (OSX) I've had no problems and continue to be able to send the "problem" data without issue.
From our QA server, which is running Windows Server 2012, ES returns an error for a row that contains a name with a diacritic (accent).
The data is similar to this (changed the name but left the accent): María
The error returned is:

MapperParsingException[failed to parse [name.display]]; nested: JsonParseException[Invalid UTF-8 middle byte 0x61 at [Source: [B@466e94e8; line: 1, column: 194]];

Based on some other stack overflow answers, I'm currently of the opinion that it's some sort of encoding issue.
I'm uploading the file using Adobe ColdFusion 11, with the following code:
cfhttp( method=arguments.method, url=arguments.uri, result="result" ) {
    cfhttpparam( type="body", value="#fileReadBinary( file )#" );
}

Since I suspect an encoding issue, I also added a header to try and force the encoding it to UTF-8, like so:
cfhttp( method=arguments.method, url=arguments.uri, result="result" ) {
    cfhttpparam( type="header", name="Content-Type", value="application/javascript; charset=UTF-8" );
    cfhttpparam( type="body", value="#fileReadBinary( file )#" );
}

No matter what I try, I continue to get the same error message. I'm not sure where to go from here.

A: After enough noodling around I remembered that the function charsetEncode() might be of some use.
I tested this on both Windows and OSX to make sure that the windows fix didn't break functionality on OSX, and so far it works perfectly in both locations:
cfhttp( method=arguments.method, url=arguments.uri, result="result" ) {
    cfhttpparam( type="header", name="Content-Type", value="application/javascript; charset=UTF-8" );
    cfhttpparam( type="body", value="#charsetEncode(fileReadBinary( file ), 'utf-8')#" );
}


text:
Q: How to convert this timestamp to a more readable form in javascript? My mongo timestamp is this 2020-04-07T07:11:12.922+00:00.
I want the date to be like, 07 april, 2020 I also need to have time like 07:11:12.

A: Try using:
Let d=new Date(timestamp.getHighBits()*1000);

Hope this helps.

A: You can use https://momentjs.com/ . This is a great library to transform any date format to whatever you want.

  function convert() {
    $('#newDate').text(moment($('#date').val()).format('YYYY-MM-DD'));
    $('#newDate2').text(moment($('#date').val()).format('MMMM Do YYYY, h:mm:ss a'));
  }

$( document ).ready(function() {
  convert();
  $('#convert').click(function(){convert()})
});

<input type=text value="2020-04-07T07:11:12.922+00:00" id="date" /> <input type="button" id="convert" value="Convert" />

A: You could try using the library Momentjs
Basically your db response, say: res would be formatted like:
const date = moment(res).format('LLL');
console.log(date);

This would return something like moment(10 de abril de 2020 4:01 PM). This will depend on the locale you set to moment.js or your machine locale.

const date = document.getElementById('date');
date.value = moment().format('LLL');

<input type=text value="" id="date" />

A: For converting timestamps into date and time format you can use moment.js which is a JavaScript library.
You can install the package in your project and import the moment library in the file as required.
 //importing in react
   import moment from "moment";

//importing in node
   var moment = require('moment');

As per your mentioned format you can get the desired output by using the following  syntax:
 //for getting date from timestamp: Output: 07 April, 2020

  moment("2020-04-07T07:11:12.922+00:00").format("DD MMMM, YYYY")

 //for getting time from timestamp in desired format

  moment("2020-04-07T07:11:12.922+00:00").format("hh:mm:ss")

For exploring other syntax and formats you can read the official docs at : https://momentjs.com/docs/


text:
Q: Calculating upper and lower bound Suppose there is a function f(x)= 19n^2/5n +1-n
I want to calculate upper and lower bound. But I had this confusion that whether I have to calculate in terms of n^2? Because dominating term is n^2
or If I solve the above equation as f(x)= 19n/5 +1-n (canceling n in 1st term)
then what? Then I have to calculate c1 and c2 in terms of n? because that will be the dominating term .
So, Kindly tell me that in which term do I have to calculate c1 and c2 i.e n or n^2?? Can I cancel n in 19n^2/5n or not? What will be its asymptotic form? f(n)∈Θ(n^2) or f(n)∈Θ(n) ?

A: Well if you have
f(n) = 19n^2 / (5n) - n + 1

you can, for the purpose of finding asymptotic bounds, indeed cancel out the n's to obtain
f(n) = (19/5)n - n + 1 = (14/5)n + 1

The easy way to do this is observing that (14/5)n is a dominating term here so +1 can be ignored, and 14/5 is a (positive) constant which can therefore also be ignored.
Therefore, we have that f(n) ∈ Θ(n).
In terms of lower and upper bound coefficients c1 and c2, this can be motivated by the fact that you can find two such coefficients (greater than zero!) such that c1 * n is asymptotically smaller than f(n), whereas c2 * n is asymptotically larger than f(n). For instance, consider c1 = 1 and c2 = 3.


text:
Q: MYSQL concatenating large string I have a web crawler that saves information to a database as it crawls the web. While it does this, it also saves a log file of its actions, and any errors it encounters to a log field in a mysql database (field becomes anywhere from 64kb to 100kb. It accomplishes this by concatenating (using the mysql CONCAT function).
This seems to work fine, but I am concerned about the cpu useage / impact it has on the mysql database. I've noticed that the web crawling is performing slower than before I implemented saving the log to the database.
I view this log file from a management webpage, and the current implementation seems to work fine other than the slow loading. Any recommendations for speeding this up, or implementation recommendations?

A: Reading 100kb strings into memory numerous time then write them to disk via a db.  Of course your going to experience slowdown!  Every part of what you are doing is going to task memory, disk, and cpu (especially if memory usage hits the system max and you start swapping to disk). Let me count some of the ways your going to possibly decrease overall site performance:

*

*Sql connections max out and back up as the time to store 100kb records increases time a single process holds a connection

*Webserver processes eat up free process pool and max out and take longer to free up because they have to wait on db connections to free.

*Web server processes begin to bloat and take more memory each, possibly more than the system can handle without swapping.  This is compounded by using the max. Umber of processes due to #2

*... A book could be written on your situation.


text:
Q: Unable to close file, being used by another process I am trying to find a way to close the process that is holding the pdf file that I am creating. I have tried to dispose and close the stream after it is created but I get the message that The process cannot access the file '\server\PDFs\test.pdf' because it is being used by another process. Basically once test.pdf is created originally I then have a page where they can edit the data and it recreates a revised test.pdf. Any idea how I can close the process? I tried doing a while statement loop to keep trying but no luck?
'Create the original pdf
 Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(Doc1, New FileStream(path & myUniqueFileName, FileMode.Create))

    Doc1.Open()
    Dim test As String
    test = Session("PDF")
    Dim PDFHeader As String
    PDFHeader = Session("Header")
    Dim imagepath As String = Server.MapPath(".") & "/images/Header.png"
    Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagepath)
    image.ScalePercent(70.0F)
    Dim line1 As New iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)

    Doc1.Add(image)
    Doc1.Add(New Paragraph(PDFHeader))
    Doc1.Add(New Chunk(line1))
    Doc1.Add(New Paragraph(test))
    pdfWrite.Flush()
    Doc1.Close()
    Doc1.Dispose()
    pdfWrite.Dispose()
    pdfWrite.Close()

Re-create the pdf after editing the data:
 Dim _fileInUse As Boolean = True
    Do While _fileInUse
        _fileInUse = FileInUse(myUniqueFileName)
        If Not _fileInUse Then
            Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(Doc1, New FileStream(path & myUniqueFileName, FileMode.Create))

            Doc1.Open()
            Dim test As String
            test = Session("PDF")
            Dim PDFHeader As String
            PDFHeader = Session("Header")
            Dim imagepath As String = Server.MapPath(".") & "/images/Header.png"
            Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagepath)
            image.ScalePercent(70.0F)
            Dim line1 As New iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)

            Doc1.Add(image)
            Doc1.Add(New Paragraph(PDFHeader))
            Doc1.Add(New Chunk(line1))
            Doc1.Add(New Paragraph(test))
        End If
    Loop

    Doc1.Close()
    Doc1.Dispose()

Public Function FileInUse(ByVal sFile As String) As Boolean

    Dim thisFileInUse As Boolean = False
    Dim fs As FileStream

    If File.Exists(sFile) Then
        Try
            fs = File.Open(sFile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)

            fs.Close()
            fs.Dispose()
        Catch
            Try
                fs.Close()
                fs.Dispose()
            Catch

            End Try

            thisFileInUse = True
        End Try
    End If
    Return thisFileInUse
End Function

A: You've got a New FileStream in Dim pdfWrite As PdfWriter =... with no way to close it.
I suggest that you use the Using construct to take care of disposing of things for you, and also take advantage of the Finally clause in a Try..Catch, like this:
Sub X()
    'Create the original pdf
    Using doc1 As New Document
        Dim myFile As String = Path.Combine(myPath, myUniqueFileName)
        Using fs As New FileStream(myFile, FileMode.Create)
            Using pdfWrite As PdfWriter = PdfWriter.GetInstance(doc1, fs)

                doc1.Open()
                Dim test As String
                test = Session("PDF")
                Dim PDFHeader As String
                PDFHeader = Session("Header")
                Dim imagepath As String = Server.MapPath("./images/Header.png")
                Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagepath)
                image.ScalePercent(70.0F)
                Dim line1 As New iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)

                doc1.Add(image)
                doc1.Add(New Paragraph(PDFHeader))
                doc1.Add(New Chunk(line1))
                doc1.Add(New Paragraph(test))
                pdfWrite.Flush()

            End Using
        End Using
    End Using

End Sub

Public Function FileInUse(ByVal sFile As String) As Boolean

    Dim thisFileInUse As Boolean = False

    If File.Exists(sFile) Then
        Dim fs As FileStream = Nothing
        Try
            fs = File.Open(sFile, FileMode.Open, FileAccess.Write, FileShare.None)
        Catch
            thisFileInUse = True
        Finally
            If fs IsNot Nothing Then
                fs.Dispose()
            End If
        End Try
    End If

    Return thisFileInUse

End Function

The Finally part of a Try..Catch always runs.
Edit: You will of course have checked that the .Dispose() method on an instance of a Class will take care of any housework which needs to be done, for example I checked Stream.Dispose Method before not doing an explicit .Close(). I don't have documentation to hand for the methods of ITextSharp, so you'll have to check that for yourself.

A: Could you not just create another file with a unique name and update that. I haven't tried it but I don't like the idea of continually trying to open the file in a loop to check if you can write to it or not. Maybe that's causing issues in itself
Something like this?:
'Create the original pdf
Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(Doc1, New FileStream(path &          myUniqueFileName, FileMode.Create))
Dim rdm As New Random()
Dim newName As String
newName =  myUniqueFileName + rdm.Next(0, 100000).ToString("00000")

Dim pdfWrite As PdfWriter = PdfWriter.GetInstance(Doc1, New FileStream(path & newName , FileMode.Create))
Doc1.Open()
Dim test As String
test = Session("PDF")
Dim PDFHeader As String
PDFHeader = Session("Header")
Dim imagepath As String = Server.MapPath(".") & "/images/Header.png"
Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(imagepath)
        image.ScalePercent(70.0F)
Dim line1 As New iTextSharp.text.pdf.draw.LineSeparator(0.0F, 100.0F, BaseColor.BLACK, Element.ALIGN_LEFT, 1)

Doc1.Add(image)
Doc1.Add(New Paragraph(PDFHeader))
Doc1.Add(New Chunk(line1))
Doc1.Add(New Paragraph(test))

Doc1.Close()
Doc1.Dispose()


text:
Q: vba, soap webservice incomplete response i am trying to get a large data of stock market by soap 1.1 envelope request, the structure of webservice explained in this link:
http://service.tsetmc.com/WebService/TsePublicV2.asmx?op=BestLimitsAllIns
it is my code:
sub downloaddata()
Dim Url As String
Url = "http://service.tsetmc.com/WebService/TsePublicV2.asmx"
Dim fldr As String
fldr = "C:\Users\daily\"
'init variable values
Dim Response As String
'Build the HTTP Request object
Dim ObjHttp As New MSXML2.XmlHttp
'build soap envelope for fetching header
Dim sEnv As String
sEnv = "<?xml version=" & """" & "1.0" & """" & " encoding=" & """" & "utf-8" & """" & "?>"
sEnv = sEnv & "<soap:Envelope xmlns:xsi=" & """" & "http://www.w3.org/2001/XMLSchema-instance" & """" & " xmlns:xsd=" & """" & "http://www.w3.org/2001/XMLSchema" & """" & " xmlns:soap=" & """" & "http://schemas.xmlsoap.org/soap/envelope/" & """" & ">"
sEnv = sEnv & "<soap:Body>"
sEnv = sEnv & "<BestLimitsAllIns xmlns=" & """" & "http://tsetmc.com/" & """" & ">"
sEnv = sEnv & "<UserName>" & """" & "username" & """" & "</UserName>"
sEnv = sEnv & "<Password>" & """" & "password" & """" & "</Password>"
sEnv = sEnv & "<Flow>" & "0" & " </Flow>"
sEnv = sEnv & "</BestLimitsAllIns>"
sEnv = sEnv & "</soap:Body>"
sEnv = sEnv & "</soap:Envelope>"
'wrap the http request in a with statement
With ObjHttp
    .Open "post", Url, False
    .setRequestHeader "Host", "service.tsetmc.com"
    .setRequestHeader "Content-Type", "text/xml; charset=utf-8"
    .setRequestHeader "Content-Length", Len(sEnv)
    .setRequestHeader "SOAPAction", "http://tsetmc.com/BestLimitsAllIns"
    .send sEnv
    Response = ObjHttp.responseText
    Debug.Print "111111111111111111111111"
    Debug.Print .getAllResponseHeaders
    Debug.Print .responseText
    Debug.Print .Status
    Debug.Print .statusText
End With
Dim XDoc As MSXML2.DOMDocument
Dim xEmpDetails As MSXML2.IXMLDOMNode
Dim xParent As MSXML2.IXMLDOMNode
Dim xChild As MSXML2.IXMLDOMNode
Dim Col, Row As Integer
Set XDoc = New MSXML2.DOMDocument
XDoc.async = False
XDoc.validateOnParse = False
If Not XDoc.LoadXML(Response) Then  'strXML is the string with XML'
    Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
End If
XDoc.LoadXML (Response)
Set xEmpDetails = XDoc.DocumentElement
Set xParent = xEmpDetails.FirstChild
Row = 2
Col = 1
For Each xParent In xEmpDetails.ChildNodes
    For Each xChild In xParent.ChildNodes
        ThisWorkbook.Worksheets("a").Cells(Row, Col).Value = xChild.Text
        Col = Col + 1
    Next xChild
    Row = Row + 1
    Col = 1
Next xParent
End Sub

the response should be this:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
    <BestLimitsAllInsResponse xmlns="http://tsetmc.com/
    <BestLimitsAllInsResult>
        <xsd:schema>schema(real content will be replaced)
        </xsd:schema>xml(real content will be replaced
        </BestLimitsAllInsResult>
    </BestLimitsAllInsResponse>
</soap:Body>
</soap:Envelope>

but the real response i've given is just a part of sample and the main data have not shown:
Cache-Control: private, max-age=0
Content-Length: 301
Content-Type: text/xml; charset=utf-8
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Sat, 06 Oct 2018 05:23:47 GMT
Connection: keep-alive
<?xml version="1.0" encoding="utf-8"?><soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body
<BestLimitsAllInsResponse xmlns="http://tsetmc.com/" /></soap:Body>
</soap:Envelope>
200
OK

the response is incomplete, the main data in 4 line above is missing. i don't know why i can't debug the problem. please check it and help me. thank you


text:
Q: MySQL search for user and their roles I am re-writing the SQL which lets a user search for any other user on our site and also shows their roles.
An an example, roles can be "Writer", "Editor", "Publisher".
Each role links a User to a Publication.
Users can take multiple roles within multiple publications.
Example table setup:
"users" : user_id, firstname, lastname
"publications" : publication_id, name
"link_writers" : user_id, publication_id
"link_editors" : user_id, publication_id

Current psuedo SQL:
SELECT * FROM (
  (SELECT user_id FROM users WHERE firstname LIKE '%Jenkz%')
  UNION
  (SELECT user_id FROM users WHERE lastname LIKE '%Jenkz%')
) AS dt
JOIN (ROLES STATEMENT) AS roles ON roles.user_id = dt.user_id

At the moment my roles statement is:
SELECT  dt2.user_id, dt2.publication_id, dt.role FROM (
  (SELECT 'writer' AS role, link_writers.user_id, link_writers.publication_id
  FROM link_writers)
  UNION
  (SELECT 'editor' AS role, link_editors.user_id, link_editors.publication_id
  FROM link_editors)
) AS dt2

The reason for wrapping the roles statement in UNION clauses is that some roles are more complex and require a table join to find the publication_id and user_id.
As an example "publishers" might be linked accross two tables
"link_publishers": user_id, publisher_group_id
"link_publisher_groups": publisher_group_id, publication_id

So in that instance, the query forming part of my UNION would be:
SELECT 'publisher' AS role, link_publishers.user_id, link_publisher_groups.publication_id
FROM link_publishers
JOIN link_publisher_groups ON lpg.group_id = lp.group_id

I'm pretty confident that my table setup is good (I was warned off the one-table-for-all system when researching the layout). My problem is that there are now 100,000 rows in the users table and upto 70,000 rows in each of the link tables.
Initial lookup in the users table is fast, but the joining really slows things down.
How can I only join on the relevant roles?
-------------------------- EDIT ----------------------------------

Explain above (open in a new window to see full resolution).
The bottom bit in red, is the "WHERE firstname LIKE '%Jenkz%'" the third row searches WHERE CONCAT(firstname, ' ', lastname) LIKE '%Jenkz%'. Hence the large row count, but I think this is unavoidable, unless there is a way to put an index accross concatenated fields?
The green bit at the top just shows the total rows scanned from the ROLES STATEMENT.
You can then see each individual UNION clause (#6 - #12) which all show a large number of rows. Some of the indexes are normal, some are unique.
It seems that MySQL isn't optimizing to use the dt.user_id as a comparison for the internal of the UNION statements. Is there any way to force this behaviour?
Please note that my real setup is not publications and writers but "webmasters", "players", "teams" etc.

A: My initial idea was to create a temporary table to hold (and index) the user_id that match the name, and use that to join against each link table.  Unfortunately, in MySQL a temporary table can only be joined against ONCE in a query.
The nasty workaround is to create a permanent table, adding the connection_id to the primary key so separate sessions do not get confused.
create table tt ( connection_id int not null,
                  user_id int not null,
                  firstname varchar(10) not null,
                  lastname varchar(10) not null,
                  primary key( connection_id, user_id ) );

The following sequence would be repeated each time you need an answer:
delete from tt where connection_id = connection_id();

insert into tt
  SELECT connection_id(), user_id, firstname, lastname FROM users
  WHERE firstname LIKE '%Jenkz%'
  UNION
  SELECT connection_id(), user_id, firstname, lastname FROM users
  WHERE lastname LIKE '%Jenkz%';

Next, your existing UNION is extended so that only the relevant user_id is pulled out:
SELECT 'writer' AS role, link_writers.user_id, link_writers.publication_id
FROM link_writers
JOIN tt ON tt.connection_id = connection_id() and tt.user_id = link_writers.user_id

UNION

SELECT 'editor' AS role, link_editors.user_id, link_editors.publication_id
FROM link_editors
JOIN tt ON tt.connection_id = connection_id() and tt.user_id = link_editors.user_id

UNION

SELECT 'publisher' AS role, link_publishers.user_id, link_publisher_groups.publication_id
FROM link_publishers
JOIN link_publisher_groups
   ON link_publisher_groups.publisher_group_id = link_publishers.publisher_group_id
JOIN tt ON tt.connection_id = connection_id() and tt.user_id = link_publishers.user_id

Perhaps this will be an improvement because not every row of all the link tables is being pulled into the union.
The EXPLAIN is a bit peculiar in that only 4 bytes of the index on tt is being used - where I would have expected all 8 bytes.  Perhaps this is because I have so little data in tt.
*************************** 1. row ***************************
           id: 1
  select_type: PRIMARY
        table: tt
         type: ref
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 4
          ref: const
         rows: 1
        Extra: Using index
*************************** 2. row ***************************
           id: 1
  select_type: PRIMARY
        table: link_writers
         type: ref
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 4
          ref: test.tt.user_id
         rows: 1
        Extra: Using index
*************************** 3. row ***************************
           id: 2
  select_type: UNION
        table: tt
         type: ref
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 4
          ref: const
         rows: 1
        Extra: Using index
*************************** 4. row ***************************
           id: 2
  select_type: UNION
        table: link_editors
         type: ref
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 4
          ref: test.tt.user_id
         rows: 1
        Extra: Using index
*************************** 5. row ***************************
           id: 3
  select_type: UNION
        table: tt
         type: ref
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 4
          ref: const
         rows: 1
        Extra: Using index
*************************** 6. row ***************************
           id: 3
  select_type: UNION
        table: link_publishers
         type: ref
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 4
          ref: test.tt.user_id
         rows: 1
        Extra: Using index
*************************** 7. row ***************************
           id: 3
  select_type: UNION
        table: link_publisher_groups
         type: ref
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 4
          ref: test.link_publishers.publisher_group_id
         rows: 2
        Extra: Using index
*************************** 8. row ***************************
           id: NULL
  select_type: UNION RESULT
        table: <union1,2,3>
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: NULL
        Extra:
8 rows in set (0.00 sec)

A: Having checked out OMG Ponies' answer for SO - Use Of Correlated Subquery, I came up with this:
SELECT * FROM (
  (SELECT user_id FROM users WHERE firstname LIKE '%Jenkz%')
  UNION
  (SELECT user_id FROM users WHERE lastname LIKE '%Jenkz%')
) AS dt
JOIN ( SELECT 'writer' AS role, link_writers.user_id, link_writers.publication_id
       FROM link_writers
       UNION
       SELECT 'editor' AS role, link_editors.user_id, link_editors.publication_id
       FROM link_editors
       UNION
       SELECT 'publisher' AS role, lp.user_id, lpg.publication_id
       FROM link_publishers lp
       JOIN link_publisher_groups lpg ON lpg.publisher_group_id = lp.publisher_group_id
     ) roles on roles.user_id = dt.user_id

The explain looks reasonable on my tiny data set.  What does it look like on the real thing ?

A: Yet another approach is to slightly denormalise your design to better support your query.
To do this, create a new table "role":
create table role (
     user_id int not null,
     role enum ('writer', 'editor', 'publisher' ) not null,
     primary key (user_id, role )
);

This would be updated whenever a new row is added to one of your link tables that includes a user_id:
insert ignore into role values( $user_id, $role );

After a while, it is likely that the role entry will already exist, hence the "ignore" modifier.
The table could be boot-strapped from your existing tables:
insert ignore into role select distinct user_id, 'writer' from link_writers;
insert ignore into role select distinct user_id, 'editor' from link_editors;
insert ignore into role select distinct user_id, 'publisher' from link_publishers;

Your search query then becomes a set of simple JOINS which MySQL should have no problem optimising:
SELECT
   r.user_id,
   r.role,
   case r.role
        when 'writer' then w.publication_id
        when 'editor' then e.publication_id
        when 'publisher' then pg.publication_id
        end as publication_id
FROM (
  (SELECT user_id FROM users WHERE firstname LIKE '%Jenkz%')
  UNION
  (SELECT user_id FROM users WHERE lastname LIKE '%Jenkz%')
) AS dt
JOIN role r on r.user_id = dt.user_id
LEFT JOIN link_writers w on r.user_id = w.user_id and r.role = 'writer'
LEFT JOIN link_editors e on r.user_id = e.user_id and r.role = 'editor'
LEFT JOIN link_publishers p on r.user_id = p.user_id and r.role = 'publisher'
LEFT JOIN link_publisher_groups pg on p.publisher_group_id = pg.publisher_group_id;

This will give a very "wide" answer.


text:
Q: Textmate: Defining a class/module called "Feature" breaks my themes In textmate, in Ruby, when I define a class or module whose name contains Feature, my themes break! By "break", I mean I loose coloration and indentation, it's like it was basic text.
#works fine
class Featurable
end

#break
class Model::Feature
end

#break
module Featured
end

If you could test that or tell me what's wrong...

A: Do you also have the Cucumber bundle activated? I can see how that would interfere with Ruby highlighting.


text:
Q: Insert formula in plot with easy and pretty code Gnu R ships with a very odd way to note formulas and symbols. It is often discussed here and mentioned in the R helppage ?plotmath. For anyone who ever wrote LaTeX the code for a simple formula in R looks unreadable and is errorprone to write.
Is there a better way to annotate with formulas? Is there a function like tex2r("x_2") that will generate the strange code?
edit:
I am looking for a solution without TikZdevice, because TikZdevice is still very fragile and the printoout does not look exactly the same.

A: With the tikzDevice package (currently available only from the CRAN archive) you can use straight-up LaTeX markup to annotate your plots. (The package comes with a beautiful vignette that'll get you up and running).
The example below was lifted directly from this page, which also displays the figure it produces:
require(tikzDevice)

tikz('normal.tex', standAlone = TRUE, width=5, height=5)

# Normal distribution curve
x <- seq(-4.5,4.5,length.out=100)
y <- dnorm(x)

# Integration points
xi <- seq(-2,2,length.out=30)
yi <- dnorm(xi)

# plot the curve
plot(x,y,type='l',col='blue',ylab='$p(x)$',xlab='$x$')
# plot the panels
lines(xi,yi,type='s')
lines(range(xi),c(0,0))
lines(xi,yi,type='h')

#Add some equations as labels
title(main="$p(x)=\\frac{1}{\\sqrt{2\\pi}}e^{-\\frac{x^2}{2}}$")
int <- integrate(dnorm,min(xi),max(xi),subdivisions=length(xi))
text(2.8, 0.3, paste("\\small$\\displaystyle\\int_{", min(xi),
    "}^{", max(xi), "}p(x)dx\\approx", round(int[['value']],3),
    '$', sep=''))

#Close the device
dev.off()

# Compile the tex file
tools::texi2dvi('normal.tex',pdf=T)

A: I just found a package that does exactly what OP was asking for: latex2exp and in there the fuction TeX.
E.g.:
library(latex2exp)
library(berryFunctions)
set.seed(1)
milk <- data.frame(Datum = as.Date(rep(seq(17500, 18460, by = 30), each = 30), origin = "1970-01-01"),
                   Milch = abs(rnorm(990, mean = 20, sd = 8)))
X11(width = 12, height = 7)
par(mar = c(3,5.5,3,1))
with(milk, plot(Datum, Milch, pch = "-", cex=1.5, col = rgb(red = 0, green = 0.5, blue = 0.5, alpha = 0.7),
                xaxt = "n", xlab = "", ylab = "",
                main = "Milchleistung am Wolkenhof"))
title(ylab = TeX("Milchmenge $\\,$ $\\left[\\frac{\\mathrm{kg}}{\\mathrm{Kuh} \\cdot \\mathrm{Tag}}\\right]$"), line = 2.5)
monthAxis()

yields:

Edit: Now there is a space between "Milchmenge" and the left bracket "[", but I didn't want to upload a new picture therefore.


text:
Q: PHP / MySQL timetable comparison I have an idea for a project that I am currently working on, I am however struggling to find a way to implement this in PHP/MySQL.
I have a database with a list of activities that a tattoo parlour has, basically he works from 9 to 5 and when an event is added it is added to the database using date and time
| --- DATE----- |    TIME |
  2012-11-02     ---| 10:00:00
What I am trying to do is list all the times and dates within the tattooist timetable in the following week that does not already have events going on, this will also ensure the tattooist doesn't double book too!
any assistance will help guys, any assistance will help

A: The best way to create the application is to store each scheduled event into a database and "black out" dates that are already taken by the applications "events" table (per say)... You will probably want to do your event creation checks during the point that the event would be created or written to the mysql db.... You will probably want to have an events table with a start and end time for each event.... when you go to schedule an event (assuming user input dictates event time and date) just write a mysql query that selects the event where the DATE(a.lastevent) = DATE(NOW())... let me know if you have further questions
Edit:
I would build the front end of the application calendar style using a JavaScript interface. In the long run it will be much more user friendly and much easier to create, I've implemented them in a day.
The framework I suggest using is ExtJS, there are many tutorials and extensions for calendars, I know that ExtJS 3 has a calendar built into it and you can view a tutorial on that here: http://www.sencha.com/learn/using-calendar
Additionally, if you decide to use ExtJS4, you can use this plugin: https://github.com/bmoeskau/Extensible/downloads or this one http://www.sencha.com/forum/showthread.php?142488-Extjs-4-based-open-source-Calendar-application
The second link is open source, the demo looks to be Spanish (it does what you need and more), but if you use Chrome you'll get a bar at the top asking if you want the page translated, click yes, it does a great job. From there you can do find and replaces to get it to English.
The ExtJS 3 tutorial will show you how to interface the calendar with a PHP page so that you can update your MySQL database via AJAX. It is much simpler than you might think, and you'll save a ton of time trying to code it from scratch.

A: Sometimes it depends on how long each scheduled event might be. Are you adding these events with just a timestamp or are you also tracking how long of a block is being assigned?
you could have an appointment set using a start and stop time and some math..
I have a annoying tendency to use a epoch timestamp instead of a mysql date time. then you can make calculations to see if an appointment overlaps or find the gaps. just have to learn to count in seconds or provide math to adjust :).


text:
Q: Laravel won't reload .env file on MAMP I recently switched from using the built-in Apache2, and PHP installation on Mac, and changed to the newest version of MAMP (3.5) and moved all of my projects into the htdocs folder. Everything works fine except for my Laravel projects after I update to the new MySQL info. When trying to access anything that uses the MySQL, I get this error
PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'cumc'@'localhost' (using password: YES)
The new .env file looks like this in the database information.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cumc
DB_USERNAME=root
DB_PASSWORD=root

So by the error, it looks like something is getting cached, but I've run every cache:clear command I could find, restart MAMP, my Mac, and tried everything I can think of. Even changing the app/database.php with the new details, and changing the name of .env so it wouldn't load, and it still shows the error.
Here's the config/database.php file
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | PDO Fetch Style
    |--------------------------------------------------------------------------
    |
    | By default, database results will be returned as instances of the PHP
    | stdClass object; however, you may desire to retrieve records in an
    | array format for simplicity. Here you can tweak the fetch style.
    |
    */

    'fetch' => PDO::FETCH_CLASS,

    /*
    |--------------------------------------------------------------------------
    | Default Database Connection Name
    |--------------------------------------------------------------------------
    |
    | Here you may specify which of the database connections below you wish
    | to use as your default connection for all database work. Of course
    | you may use many connections at once using the Database library.
    |
    */

    'default' => env('DB_CONNECTION', 'mysql'),

    /*
    |--------------------------------------------------------------------------
    | Database Connections
    |--------------------------------------------------------------------------
    |
    | Here are each of the database connections setup for your application.
    | Of course, examples of configuring each database platform that is
    | supported by Laravel is shown below to make development simple.
    |
    |
    | All database work in Laravel is done through the PHP PDO facilities
    | so make sure you have the driver for your particular database of
    | choice installed on your machine before you begin development.
    |
    */

    'connections' => [

        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
        ],

        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', 'localhost'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'schema' => 'public',
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Migration Repository Table
    |--------------------------------------------------------------------------
    |
    | This table keeps track of all the migrations that have already run for
    | your application. Using this information, we can determine which of
    | the migrations on disk haven't actually been run in the database.
    |
    */

    'migrations' => 'migrations',

    /*
    |--------------------------------------------------------------------------
    | Redis Databases
    |--------------------------------------------------------------------------
    |
    | Redis is an open source, fast, and advanced key-value store that also
    | provides a richer set of commands than typical key-value systems
    | such as APC or Memcached. Laravel makes it easy to dig right in.
    |
    */

    'redis' => [

        'cluster' => false,

        'default' => [
            'host' => env('REDIS_HOST', 'localhost'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 0,
        ],

    ],

];

A: Run php artisan config:clear, it will clear cached configuration.

A: Same behavior with Mamp Pro in 2021.
In fact, config is stored in sessions.
Solve it by deleting content of storage/framework/sessions/ if sessions saved in files.
If saved in DB ( for instance, mysql ) just empty the right table.
and so on :)


text:
Q: Import error in django settings . How to remove the error? ImportError: Could not import settings 'file-patn/settings' (Is it on sys.path?): Import by filename is not supported.

My code has this
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

What changes need to be done in the code to remove the error ?

A: Just add this:
os.environ['DJANGO_SETTINGS_MODULE'] = 'application_path.settings'

A: Could it be that, you wanted to specify the Python import like:
file-patn.settings

instead?


text:
Q: php script files not running on server i have uploaded php files on my server but not executing when i run it on server.
but the images files are opening properly. I also checked zip, xml and other ones are working but .php extension files are not working.
do anyone know why this happens?

A: You must check if your host have the php module installed, if not, you'll see a download dialog when you try to access the php file.

A: The most likely causes are that either:

*

*Your web server is not configured to support PHP

*The permissions on your files do not give the server the right to execute the PHP programmes

The former is more likely if the files are downloaded by the browser. The latter is more likely if the server presents the user with a 500 error.

A: In php.ini look for this line
engine = On

in apache modules   php5_module This should be ticked(on).
also
if you have mime_module ticked in the Apache Modules
Check you have the mime types set correctly in httpd.conf
This line is required
AddType application/x-httpd-php .php


text:
Q: Prove that a topological space which satisfies the following conditions has base composed of clopen sets I'll start with the definition I know:

Let $X$ be a topological space. We say that $\text{dim}X\leq n$ if for every closed set $F\subseteq X$ with continuous function $f:F\to S^n$, there exists a continuous extension for $f$ over $X$, i.e $ \tilde{f}:X\to S^{n} $ continuous, such that $\tilde{f}\restriction_{F}=f$.

Now, let $X$ be a sperable metric space. How can I prove that $ \text{dim}X\leq0 $ $\iff $ $X$ has a base which composed of clopen sets (both open and closed)?
I'm not sure how to start any of the directions, so any hints/guidance would be very appreciated.
Thanks in advance.


text:
Q: how to update column values in sql when having " in the string I would like to set the value of query column with the following value:
call sp_customer('ABC', 'US', 'XYZ', '["1234"]');
SELECT ROUND(gross_profit) as current_gp,
FROM t_CUSTOMER

I have written the following update query for the same but it not working and I get an error

Incorrect syntax near '1234'

update TABLE_NAME
set Query = "call sp_customer('ABC', 'US', 'XYZ', '["1234"]');
SELECT ROUND(gross_profit) as current_gp,
FROM CUSTOMER" where TC_ID = 'TestCaseName' and SubIteration = '11';

Please help me with this query.


text:
Q: Installing Windows 8 to HDD while Windows 7 is running? Basically, I want to still use my PC while I install Windows 8.
The drive I want to install to is physically different from the one I am running Windows 7 on, and so, if I wanted to boot to Windows 8, I'd choose a different boot device from my BIOS.
Can I install Windows 8 to a separate hard drive (not external) whilst still using Windows 7, without touching the Windows 7 installation?

A: It wont "touch" your windows 7 install but you wont be able use the computer while you're installing an OS. You cant boot to the drive with windows 7 on and then somehow boot seperately to your windows 8 installation disk

A: I think what you are looking for is built into Windows, it's called imagex.
About
imagex /apply d:\imaging\data.wim 1 d:\New_Directory /verify
Here is actually another SuperUser answer about it.  I would summarize it, but it is complete with screenshots and somewhat lengthy.
Edit: As per the commenters below, this is not the fastest or easiest method, and it would be fastest to just boot the disc live and install directly.  However, if you really want to do it this way, that is the best resource I have seen.

A: Run the Windows 8 installer from Windows 7. Press Alt+Tab to switch back to your other applications. When it goes to restart, kill the process.
You can then finish installation by restarting your PC and choosing the Windows 8 drive from your BIOS boot menu.

A: Here is how I would do it. I would just create a virtual machine (your favorite vendor) and give it access to the windows 8 drive. I will boot it and install windows 8 inside, will add with bcdedit the entry for booting and then on the first boot entry into Windows 8 will just start it in safe mode to recognize the real hardware.


text:
Q: XSL sort by title I don't see the solution and hope someone can help me. I want to sort the result by title. But I don't know where and how to put the sort into the XSL file.
Can somebody help me?
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="TotalResults" />
  <xsl:template match="NumberOfResults" />

  <xsl:template name="DisplayString">
    <xsl:param name="str" />
    <xsl:if test='string-length($str) > 0'>
      <xsl:value-of select="$str" />
    </xsl:if>
  </xsl:template>

  <xsl:template name="HitHighlighting">
    <xsl:param name="hh" />
    <xsl:apply-templates select="$hh"/>
  </xsl:template>

  <xsl:template name="ResultPreviewToolTip">
    <xsl:param name="contentclass" />
    <xsl:param name="picturethumbnailurl" />
    <xsl:param name="url" />
    <xsl:param name="title" />
    <xsl:param name="hithighlightedsummary" />
    <xsl:param name="description" />
    <xsl:param name="version" />

    <xsl:choose>
      <xsl:when test="$contentclass[. = 'STS_ListItem_PictureLibrary'] and $picturethumbnailurl[. != '']">

      </xsl:when>
      <xsl:when test="contains( $url, 'jpg' ) or contains( $url, 'jpeg' ) or contains( $url, 'gif' ) or contains( $url, 'JPG' ) or contains( $url, 'JPEG' ) or contains( $url, 'GIF' )">

      </xsl:when>
      <xsl:otherwise>

          <xsl:choose>
            <xsl:when test="$hithighlightedsummary[. != '']">
              Preview:

              <xsl:call-template name="HitHighlighting">
                <xsl:with-param name="hh" select="$hithighlightedsummary" />
              </xsl:call-template>
            </xsl:when>
            <xsl:when test="$description[. != '']">
              Preview:

              <xsl:value-of select="$description"/>
            </xsl:when>
            <xsl:otherwise>
              No preview available
            </xsl:otherwise>
          </xsl:choose>
          <xsl:call-template name="DisplayString">
            <xsl:with-param name="str" select="$version" />
            <xsl:with-param name="text" select="'Version: '" />
            <xsl:with-param name="stringcolor" select="'#808080'" />
          </xsl:call-template>

      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="Result">
    <xsl:variable name="tdClass">
      <xsl:if test="(position() mod 2 = 0)">
        <xsl:value-of select="'even'" />
      </xsl:if>
      <xsl:if test="(position() mod 2 = 1)">
        <xsl:value-of select="'odd'" />
      </xsl:if>
    </xsl:variable>

            <xsl:attribute name="src">
              <xsl:value-of select="imageurl"/>
            </xsl:attribute>

            <xsl:call-template name="ResultPreviewToolTip">
              <xsl:with-param name="contentclass" select="contentclass" />
              <xsl:with-param name="description" select="description" />
              <xsl:with-param name="hithighlightedsummary" select="hithighlightedsummary" />
              <xsl:with-param name="picturethumbnailurl" select="picturethumbnailurl" />
              <xsl:with-param name="title" select="title" />
              <xsl:with-param name="url" select="url" />
              <xsl:with-param name="version" select="version" />
            </xsl:call-template>

          <xsl:attribute name="href">
            <xsl:value-of select="url" disable-output-escaping="yes" />
          </xsl:attribute>
          <xsl:value-of select="filename"/>

          <xsl:attribute name="href">
            <xsl:value-of select="url" disable-output-escaping="yes" />
          </xsl:attribute>
          <xsl:choose>
            <xsl:when test="doctitle != ''">
              <xsl:value-of select="doctitle"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="title"/>
            </xsl:otherwise>
          </xsl:choose>

        <xsl:choose>
          <xsl:when test="docauthor != ''">
            <xsl:value-of select="docauthor"/>
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select="author"/>
          </xsl:otherwise>
        </xsl:choose>

        <xsl:value-of select="revisiondate" />

        <xsl:value-of select="doclanguage"/>

          <xsl:attribute name="href">
            <xsl:value-of select="sitename" disable-output-escaping="yes" />
          </xsl:attribute>

        <xsl:call-template name="ShowVersionHistory" />

  </xsl:template>

  <xsl:template name="ShowVersionHistory">

    <xsl:variable name="EncodedUrl">
      <xsl:value-of disable-output-escaping="yes" select="ddwrt:UrlEncode(url)" />
    </xsl:variable>

    <xsl:if test="string-length(serverredirectedurl) > 0">

      <xsl:variable name="WebUrl">
        <xsl:value-of select="substring-before(serverredirectedurl, '_layouts')"/>
      </xsl:variable>

      <xsl:variable name="FinalLink">
        <xsl:value-of select="$WebUrl"/>
        <xsl:text>_layouts/Versions.aspx?FileName=</xsl:text>
        <xsl:value-of select="$EncodedUrl"/>
      </xsl:variable>

    </xsl:if>

  </xsl:template>

  <xsl:template match="/">

        Filename
        Title
        Author
        Revision Date
        Language
        Actions

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="TotalResults" />
  <xsl:template match="NumberOfResults" />

  <xsl:template name="DisplayString">
    <xsl:param name="str" />
    <xsl:if test='string-length($str) > 0'>
      <xsl:value-of select="$str" />
    </xsl:if>
  </xsl:template>

  <xsl:template name="HitHighlighting">
    <xsl:param name="hh" />
    <xsl:apply-templates select="$hh"/>
  </xsl:template>

  <xsl:template name="ResultPreviewToolTip">
    <xsl:param name="contentclass" />
    <xsl:param name="picturethumbnailurl" />
    <xsl:param name="url" />
    <xsl:param name="title" />
    <xsl:param name="hithighlightedsummary" />
    <xsl:param name="description" />
    <xsl:param name="version" />

    <xsl:choose>
      <xsl:when test="$contentclass[. = 'STS_ListItem_PictureLibrary'] and $picturethumbnailurl[. != '']">

      </xsl:when>
      <xsl:when test="contains( $url, 'jpg' ) or contains( $url, 'jpeg' ) or contains( $url, 'gif' ) or contains( $url, 'JPG' ) or contains( $url, 'JPEG' ) or contains( $url, 'GIF' )">

      </xsl:when>
      <xsl:otherwise>

          <xsl:choose>
            <xsl:when test="$hithighlightedsummary[. != '']">
              Preview:

              <xsl:call-template name="HitHighlighting">
                <xsl:with-param name="hh" select="$hithighlightedsummary" />
              </xsl:call-template>
            </xsl:when>
            <xsl:when test="$description[. != '']">
              Preview:

              <xsl:value-of select="$description"/>
            </xsl:when>
            <xsl:otherwise>
              No preview available
            </xsl:otherwise>
          </xsl:choose>
          <xsl:call-template name="DisplayString">
            <xsl:with-param name="str" select="$version" />
            <xsl:with-param name="text" select="'Version: '" />
            <xsl:with-param name="stringcolor" select="'#808080'" />
          </xsl:call-template>

      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="Result">
    <xsl:variable name="tdClass">
      <xsl:if test="(position() mod 2 = 0)">
        <xsl:value-of select="'even'" />
      </xsl:if>
      <xsl:if test="(position() mod 2 = 1)">
        <xsl:value-of select="'odd'" />
      </xsl:if>
    </xsl:variable>

            <xsl:attribute name="src">
              <xsl:value-of select="imageurl"/>
            </xsl:attribute>

            <xsl:call-template name="ResultPreviewToolTip">
              <xsl:with-param name="contentclass" select="contentclass" />
              <xsl:with-param name="description" select="description" />
              <xsl:with-param name="hithighlightedsummary" select="hithighlightedsummary" />
              <xsl:with-param name="picturethumbnailurl" select="picturethumbnailurl" />
              <xsl:with-param name="title" select="title" />
              <xsl:with-param name="url" select="url" />
              <xsl:with-param name="version" select="version" />
            </xsl:call-template>

          <xsl:attribute name="href">
            <xsl:value-of select="url" disable-output-escaping="yes" />
          </xsl:attribute>
          <xsl:value-of select="filename"/>

          <xsl:attribute name="href">
            <xsl:value-of select="url" disable-output-escaping="yes" />
          </xsl:attribute>
          <xsl:choose>
            <xsl:when test="doctitle != ''">
              <xsl:value-of select="doctitle"/>
            </xsl:when>
            <xsl:otherwise>
              <xsl:value-of select="title"/>
            </xsl:otherwise>
          </xsl:choose>

        <xsl:choose>
          <xsl:when test="docauthor != ''">
            <xsl:value-of select="docauthor"/>
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select="author"/>
          </xsl:otherwise>
        </xsl:choose>

        <xsl:value-of select="revisiondate" />

        <xsl:value-of select="doclanguage"/>

          <xsl:attribute name="href">
            <xsl:value-of select="sitename" disable-output-escaping="yes" />
          </xsl:attribute>

        <xsl:call-template name="ShowVersionHistory" />

  </xsl:template>

  <xsl:template name="ShowVersionHistory">

    <xsl:variable name="EncodedUrl">
      <xsl:value-of disable-output-escaping="yes" select="ddwrt:UrlEncode(url)" />
    </xsl:variable>

    <xsl:if test="string-length(serverredirectedurl) > 0">

      <xsl:variable name="WebUrl">
        <xsl:value-of select="substring-before(serverredirectedurl, '_layouts')"/>
      </xsl:variable>

      <xsl:variable name="FinalLink">
        <xsl:value-of select="$WebUrl"/>
        <xsl:text>_layouts/Versions.aspx?FileName=</xsl:text>
        <xsl:value-of select="$EncodedUrl"/>
      </xsl:variable>

    </xsl:if>

  </xsl:template>

  <xsl:template match="/">

        Filename
        Title
        Author
        Revision Date
        Language
        Actions

      <xsl:apply-templates />

  </xsl:template>
</xsl:stylesheet>

A: You have to add <xsl:sort> (see: w3schools: xsl:sort Element).
It should be added to your xsl:apply-templates element (or if you would use xsl:for-each, then there).


text:
Q: When Objects "Hit" Each Other - Javascript How can one keep track of when objects hit each other? Below is an example of a bullet (div) that flies around, hitting a triangle (svg polygon). How can one know when the bullet is within the green area of the triangle?

var left1 = parseInt(document.getElementById("bullet").style.left);
var left2 = 0;

setInterval(bounce, 10);
function bounce() {
  if ( left1 < (window.innerWidth - 35) ) {
    left1++;
    left2 = left1;
    document.getElementById("bullet").style.left = left1 + "px";

  }
  if ( left1 >= (window.innerWidth -35) ) {
    left2--;
    document.getElementById("bullet").style.left = left2 + "px";
  }
  if ( left2 <= 0 ) {
    left1 = 0;
  }
}

<svg height="200" width="200" style="position:absolute; top: 0px; left: 100px;">
  <polygon points="100,10 200,200 0,200" style="fill:#23ac6a;"/>
</svg>

A: The svg polygon element provides a property called points which returns the values specified in its points attribute as an array-like structure called an SVGPointList. Each element of the structure has an x and y property which is relative to the position and viewBox of the svg element. You can use those values to figure out the x and y coordinates of the bounds of the triangle in relation to your moving div and from there detect if any of the div's corners are inside the triangle.
So let's say your polygon has an id of triangle, you can get an array of those points with Array.prototype.slice.call(document.getElementById('triangle').points)


text:
Q: Dom Document - Scrape data I have a jQuery script embed into a webpage that I am scraping with Tampbermonkey and It works well but it is posting back to my server the entire body of the html.
Embed into an html page that I am scraping has this code:
jQuery(document.body).append("<iframe id='somenewtab' name='somenewtab' />");
jQuery(document.body).append("

<form action='https://example.com/test.php' target='somenewtab' id='form_submit_data' method='post'>
<input type='hidden' name='data' id='submit_data'><input type='submit' value=''></form>

");
jQuery("#submit_data").val( btoa(unescape(encodeURIComponent(document.body.innerHTML) )));
jQuery("#form_submit_data").submit();

The script grabs all the html and then posts it to php script where it parses the data.
test.php
$data = base64_decode($_POST['data']);
$dom = new DOMDocument();
$dom->loadHTML($data);
$select = $dom->getElementById('portfolio');

My question is, is there a way to only post the body of the html without all of there head information or better yet only post back whats inside the getElementById('portfolio') tag? The data in the id tag is the only data I need to parse.
Currently it posts everything in the html webpage and the server is getting bogged down with the POST limit size.

A: you can use wrapper based on "simplehtmldom" project available on Sourceforge and get the text/html of the dom element, and can post it.
https://github.com/sachinsinghshekhawat/simple-html-dom-parser-php


text:
Q: Searching for buttons using the button's text attribute I want to be able to search for a button's text and return any buttons which match that search.
E.g. I have three buttons, each with the button text: One, Two & Three.
When I search for "Two", I want the button which has the button test "Two" to display.
I've seen how this is done with SearchView but that is only for a string and I'm unsure of how to approach for button text
This is my MainActivity
public class MainActivity extends AppCompatActivity {

private static  ListView lv;
private static Button bt, bt2, bt3;

ArrayList<Button> items;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    items = new ArrayList<>();
    items.add(0, bt);
    items.add(1, bt2);
    items.add(2, bt3);

    lv = (ListView) findViewById(R.id.list);
    lv.setAdapter(new MyListAdapter(this, R.layout.item, items));
}

private class MyListAdapter extends ArrayAdapter<Button> {
    private int layout;

    public MyListAdapter(Context context, int resource, List<Button> objects) {
        super(context, resource, objects);
        layout = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder mainViewholder = null;
        if (convertView == null) {
            LayoutInflater inflater = LayoutInflater.from(getContext());
            convertView = inflater.inflate(layout, parent, false);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.bt = (Button) convertView.findViewById(R.id.button);
            viewHolder.bt2 = (Button) convertView.findViewById(R.id.buttonn);
            viewHolder.bt3 = (Button) convertView.findViewById(R.id.buttonnn);
            convertView.setTag(viewHolder);

        } else {
            mainViewholder = (ViewHolder) convertView.getTag();
        }
        return convertView;
    }
}

public class ViewHolder {
    Button bt;
    Button bt2;
    Button bt3;
}
}

A: I don't really understand what you want to do. But, there are a few things in the code we don't normally do with ListView.

*

*You should pass a collection of data models to the ArrayAdatper, not UI controls.

*Your MyListAdapter doesn't use the given items.

*You don't need to specify the position when adding data to ArrayList.

It seems, in your code, you have 3 buttons on each row. So, your data model should contain the text to be displayed on 3 buttons and 3 booleans to control their visibility. you search the button text in the models and change the boolean value, then call notifyDataSetChanged. GetView will be called for each row for you to update the UI.


text:
Q: Smallest possible sum $\sum_{i=0}^{\infty} \frac{a_i^2}{a_{i+1}}$ over non-increasing infinite sequences starting with 1 Let $a_n$ be a sequence of positive numbers such that $a_0=1$ and $\forall n : a_n \ge a_{n+1}$.
Find the infinum of $\sum_{i=0}^{\infty} \frac{a_i^2}{a_{i+1}}$ over all such sequences.
If $\{a_n\}$ is a geometric seriess $1, q, q^2, ...$, where $0<q<1$, then the sum equals $\frac{1}{q}+\frac{1}{1-q}$, which has minimum at $q=\frac{1}{2}$, so the infinum is no greater than $4$.
I suspect that the answer is indeed $4$, but I have no idea how to prove that.

A: The infimum is indeed $4$.
We have
$$
\begin{align}
\sum_{i=0}^{\infty} \frac{a_i^2}{a_{i+1}}&\geq \sum_{i=0}^n \frac{a_i^2}{a_{i+1}}+\sum_{i=n+1}^{\infty} a_i \ \ \ \ \textrm{( by $a_i\geq a_{i+1}$: replace denominator.)}\\
&>\sum_{i=0}^n \frac{a_i^2}{a_{i+1}} + a_{n+1} \ \ \ \ \textrm{(drop all terms with $i\geq n+2$.)}\\
&\geq \sum_{i=0}^{n-1} \frac{a_i^2}{a_{i+1}}+2a_n \ \ \ \ \textrm{(apply AM-GM to the last two terms)}\\
&\geq \sum_{i=0}^{n-2} \frac{a_i^2}{a_{i+1}}+2\sqrt 2 a_{n-1} \ \ \textrm{(apply AM-GM to the last two)}
\end{align}
$$
We repeat this process until we obtain
$$
\sum_{i=0}^{\infty} \frac{a_i^2}{a_{i+1}} > \frac1{a_1}+2^{1+\frac12+\cdots + \frac1{2^{n-1}}}a_{n-(n-1)}.
$$
Then applying AM-GM to this one, we obtain
$$
\sum_{i=0}^{\infty} \frac{a_i^2}{a_{i+1}} > 2^{1+\frac12+\cdots+\frac1{2^n}}
$$
This lower bound can be made arbitrary close to $4$. Hence, the claim is proved.


text:
Q: Is there any way to align jumbotron elements in center? In the below code snippet, I tried to align the div inside .jumbotron to the center but it didn't work. Is there any extra class needed because I already tried .justify-content-center and .mx-auto.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

Lorem.

Lorem, ipsum dolor.Lorem, ipsum.
Lorem ipsum dolor
      sitamet.

A: text-center class of bootstrap may help

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

Lorem.

Lorem, ipsum dolor.Lorem, ipsum.
Lorem ipsum dolor sitamet.

A: You can use the following solution:

*

*Set d-flex to the jumbotron to use flex classes (like justify-content-center) on the jumbotron.

*Set the justify-content-center to the jumbotron itself to center its content.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

Lorem.

Lorem, ipsum dolor.Lorem, ipsum.
Lorem ipsum dolor
      sitamet.

A:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

Lorem.

Lorem, ipsum dolor.Lorem, ipsum.
Lorem ipsum dolor
      sitamet.

A: Please try this code,To Is there any way to align jumbotron elements in center?
<!DOCTYPE html>

  <title>Bootstrap Centered Jumbotron</title>
  <meta charset="utf-8" />

  <link type="text/css" rel="stylesheet" href="http://getbootstrap.com/dist/css/bootstrap.css" />

The easiest and powerful way

Redirect
Visitors where they converts more.

Track
Views, Clicks and Conversions.

Check
Constantly the status of your links.

Collaborate
With Customers, Partners and Co-Workers.

            GET STARTED

FREE VERSION AVAILABLE!

I hope this code will be useful for you.
Thank you.


text:
Q: Custom Function class I'm working on a project that involves constructing functions from other functions. I had the idea of writing a class to simplify things but I haven't been able to get it to work without resorting to using __proto__.
Here's basically what my vision is.
function MyFunction () {
    // ...
}
var myFn = new MyFunction();
myFn(); // executes without error
myFn instanceof MyFunction; // returns true

The following code does just that using __proto__
function MyFunction () {
    var fn = function () { return 'hello'; };
    fn.__proto__ = this;
    return fn;
}
var myFn = new MyFunction();
alert( myFn() ); // hello
alert( myFn instanceof MyFunction ); // true

Here's something I've tried using valueOf
function MyFunction () {
    this.fn = function () { return 'hello'; };
    this.valueOf = function () { return this.fn; };
}
var myFn = new MyFunction();
alert( myFn instanceof MyFunction ); // true
alert( myFn.valueOf()() ); // hello
alert( myFn() ); // error

And here's something else extending the function to contain all the properties of MyFunction.
function MyFunction () {
    this.foo = 'hello'
    var fn = function () { return 'hello'; };
    for ( var i in this ) {
        fn[ i ] = this[ i ];
    }
    return fn;
}
var myFn = new MyFunction();
alert( myFn() ); // hello
alert( myFn.foo ); // hello
alert( myFn instanceof MyFunction ); // false

I don't want to use __proto__ because it's non-standard. Also, this was kind of a freak idea, I'd really like to get it to work, but if it's not possible I'll live. But I guess my question is, is what I'd like to do possible?

A: Fascinating idea. I don't believe you can do it with standard ECMAScript yet, not even using ES5.
ES5 gives us better access to and control over the prototype, including providing a means of setting the prototype when creating objects (without having to go through constructor functions) with Object.create, but you can't construct functions via that mechanism. And that's what you would have to do, because instanceof uses the abstract spec [[HasInstance]] method, which is currently only implemented by functions, and the function implementation of it works by seeing if the object's underyling prototype ([[Proto]]) is === to the function's prototype property. The only standard way to set the object's underlying prototype is to create it via new MyFunction or via Object.create, and neither mechanism creates a function object.
ES.next may make this possible. There's a proposal that's been promoted to "harmony" status (so, fairly advanced) for a "set prototype operator", <|, which is intended to solve many of the problems currently solved via __proto__. One of the things it's for is "Setting the prototype of a function to something other than Function.prototype". Using it (in its current form), your MyFunction would look something like this:
function MyFunction () {
  return MyFunction.prototype <| function () { return 'hello'; };
}
MyFunction.prototype = Object.create(Function.prototype);

That last bit is to make it that MyFunction.prototype is an object with the prototype Function.prototype, so that functions constructed via MyFunction have call, apply, bind, etc.


text:
Q: Print a web page from a webview I made an app that is just a webview showing a website, at a certain point in my website I have a button that prints a div via javascript, as it is it doesn't work, how can I make it possible?
my js code:
     function printDiv(divName) {
    var printContents = document.getElementById(divName).innerHTML;
    var originalContents = document.body.innerHTML;

    document.body.innerHTML = printContents;

    window.print();

    document.body.innerHTML = originalContents;
}


text:
Q: Foundation Button Groups plain html and ng-repeat different results I upgrades my Foundation version from 5.3.3 to 5.5.2. Everything works great, expect some elements like button groups. Here is an example.

        {{i}}

1

1

This two methods will create different results. The Angular ng-repeat directive will create an smaller result. How can this happen?
I created some reproduce able example. The first is the non working example.
Example 1: http://jsfiddle.net/kauzbzby/1/
Foundation 5.5.2
The second example works as expected, but with an older Foundation version.
Example 2: http://jsfiddle.net/h5kqb4yv/1/
Foundation 5.3.3
The Angular version has not changed. Have someone an idea how to fix this?
Even examples without the even-* class will create different results
Cheers.

A: See here for explanation: http://jsfiddle.net/13k/gTm9S/
This is due to ng-repeat adding lis without spaces between them, where the manually created ones have a space due to the carriage return and tabs for alignment.
See here for your example working: http://jsfiddle.net/mk490brw/

1

2

3

4

5

6

7

Mushing all of the lis together in one line makes them the same width and spacing... even if it is a little unsightly to read.
Styles in 5.3.3 for button-group lis were
.button-group>li {
  margin: 0;
  float: left;
}

Whereas 5.5.2 is:
.button-group.even-# li {
  display: inline-block;
  margin: 0 -2px;
  width: 14.28571%;
}

Again, the important part is the inline-block. Inline block makes any spaces between each element display as a space.
If you're curious as to why this was added, it appears that it was added to support button stacking. Here's the commit https://github.com/zurb/foundation/commit/d49b9a72b9d989f2c9c7156c6a30e510cc0c9df4


text:
Q: Generate merged array from a string by multiple positions of the string For example,
const text = "APPLE ORANGE";
const text_position = [0,4,4,7,9];
const inserted_value = ["yo","wo","go","lo","zo"];

For this example, I would like to create an array like this:
return ["yo","APPL","wo","go","E O","lo","RA","zo","NGE"];

My code:
I am trying to merge into an array from a given string by an array of string positions.
There are one string and two arrays given:
const content = "0123456789TEXT";
const footnote_position  = [0, 1, 2, 2, 6]; // string positions
const footnote_value = ["ZERO", "ONE", "TWO", "TWO", "SIX"]; // inserted values

But for my code and above given content, footnote_position, and footnote_value, the algorithm must output as follow:
["ZEROR","0","ONE","1","TWO","TWO","2345","SIX","67899TEXT"]

My complete code is:

const content = "0123456789TEXT";
const footnote_position = [0, 1, 2, 2, 6]; // must be sorted
const footnote_value = ["ZERO", "ONE", "TWO", "TWO", "SIX"];

const position_set = [...new Set(footnote_position)]; // must be sorted 1,2,6
const contentArray = [];

let textArray = [];
let prev = -1;
let count = footnote_position.length;

for (let index = 0; index < count + 1; index++) {

  switch (index) {

    case 0: // ok
      var item = footnote_position[index];
      if (item != 0) {
        textArray.push(content.substring(0, item));
      }
      footnote_position.forEach((value, position) => {
        if (value == item) {
          textArray.push(footnote_value[position]);

        }
      })
      prev = item;
      break;
    case length: // ok
      textArray.push(content.substring(prev)); // <Text>
      footnote_position.forEach((value, position) => {
        if (value == item) textArray.push(footnote_value[position]);
      })
      break;
    default: // not ok
      var item = footnote_position[index];
      textArray.push(content.substring(prev, item));
      footnote_position.forEach((value, position) => {
        if (value == item) textArray.push(footnote_value[position]);
      })
      prev = item;
      break;
  }
}

console.log(textArray);

Unfortunately, my output is different as follows:
["ZERO", "0", "ONE", "1", "TWO", "TWO", "", "TWO", "TWO", "2345", "SIX", "6789TEXT"]

What went wrong? Do you have any alternative different algorithm solution for this problem?
Plus, I really have no idea why case length: is working. There is no defined variable length in the code.

A: Use forEach, slice and maintain last
Update: Fixing the issue of last element. Great suggestion @mplungjan and Thank you.

const text = "APPLE ORANGE";
const text_position = [0, 4, 4, 7, 9];
const inserted_value = ["yo", "wo", "go", "lo", "zo"];

let last = 0;
const output = [];
text_position.forEach((index, i) => {
  const value = text.slice(last, index);
  if (value) {
    output.push(value);
  }

  output.push(inserted_value[i]);
  last = index;
});
if (last < text.length) output.push(text.slice(last));

console.log(output);

Alternate way using flatMap

const text = "APPLE ORANGE";
const text_position = [0, 4, 4, 7, 9];
const inserted_value = ["yo", "wo", "go", "lo", "zo"];

let last = 0;
const output = text_position.flatMap((index, i) => {
  const output = [];
  last < index && output.push(text.slice(last, index));
  output.push(inserted_value[i]);
  last = index;
  (i === (text_position.length - 1)) && (last < text.length) && output.push(text.slice(last));
  return output;
})

console.log(output);

A: I rewrote the code to handle your second example

const mergeIt = (content, posArr, valArr) => {
  const arr = content.split("");
  posArr.sort((a, b) => a - b); // must be sorted
  while (posArr.length) {
    const pos = posArr.pop(); // destructive - you may want to clone
    const val = valArr.pop(); // destructive - you may want to clone
    if (val !== null) arr.splice(pos, 0, `|${val}|`);
  }
  return arr.join("").split("|").filter(w => w)
};

let content = "0123456789TEXT";
let footnote_position = [2, 1, 0, 2, 6];
let footnote_value = ["ZERO", "ONE", "TWO", "TWO", "SIX"];
console.log(mergeIt(content, footnote_position, footnote_value))

const text = "APPLE ORANGE";
const text_position = [0, 4, 4, 7, 9];
const inserted_value = ["yo", "wo", "go", "lo", "zo"];
console.log(mergeIt(text, text_position, inserted_value))

// returns  ["yo","APPL","wo","go","E O","lo","RA","zo","NGE"]