text:
Q: Looking for online space to collaborate but NOT open source I have an applicaion, that can best be described 'loosly' as a scripting application, primarly designed for part time developers, engineers and sciences types with a VB.NET background (can theoretically do C#).
This has been a long three year hobby and I am about 95% complete.  I am planning to make the applicaiton freely available for most (if not all) uses, but I do not want to open source it (at least right now).
I was looking for an online place to post and collaborate with some folks for feedback, to get some testing done and finalize the application (my wife wants me to be DONE with it).  My searches online have revealed many spaces, but all seem to be open-source spaces that require release of the source code, or just aplace to post 'free' completed software.  I am looking for the collaboration part.
Can anyone point me to a such a space that does not require providing the open source code (if it even exits)?

A: I think you can use most of the collaboration places without actually uploading any source to the repository.
I've seen a bunch of project on Google Code Hosting that have no source (usually its then on  GitHub) and just use the Google Hosting for bug-tracking and collaboration.

A: I created a BitBucket account. Looks like it might work. Many of the sites require you to choose an open source license before you even create a space. BitBucket does not.


text:
Q: Finding a vector for an orthonormal basis after using gram-schmidt. So I started with a basis for $P_3$ (polynomial of degree less than 3).
$$\{1,x,x^2\}$$
which has inner product define as
$$\langle p,q \rangle=p(-1)q(-1)+p(0)q(0)+p(1)q(1)$$
For this product I found an orthonormal basis, $U$ as follows:
$$u_1=\frac{1}{||1||}=\frac{1}{\sqrt{\langle1,1\rangle}}=\frac{1}{\sqrt{3}}$$
$$u_2=\frac{x-p_1}{||x-p_1||} \quad\quad p_1=\langle x,u_1 \rangle u_1$$
$$u_2=\frac{x}{\sqrt2}$$
$$u_3=\frac{x^2-p_2}{||x^2-p_2||} \quad\quad p_2=\langle x^2,u_1 \rangle u_1 + \langle x^2,u_2 \rangle u_2=\frac{2}{3}$$
$$u_3=\frac{x^2-\frac{2}{3}}{||x^2-\frac{2}{3}||}$$
$$u_3=\sqrt\frac{3}{2}x^2-\sqrt\frac{2}{3}$$
Therefore the orthonormal basis is
$$U=\left\{ \frac{1}{\sqrt3},\frac{x}{\sqrt2},\sqrt\frac{3}{2}x^2-\sqrt\frac{2}{3} \right\}$$
Now I need to fine the polynomial $1+x+x^2$ in this new basis and here is where I'm having trouble. I can easily get $\{\sqrt3, \sqrt2, \dots\}$ but how do I get the last vector?
Let the scalar to be multiplied with be $z$. Then presumably
$$z\left(\sqrt\frac{3}{2}x^2-\sqrt\frac{2}{3}\right)=x^2$$
But this means that $z$ is not a scalar but is a function of $x^2$ so I'm definitely doing something wrong but I don't know what.

A: To verify your result, I just calculated $\langle 1,1\rangle=3$, $\ \langle 1,x\rangle=0=\langle x^2,x\rangle\ $ and $\ \langle x^2,1\rangle=2$.
So that, the first two basis vectors are indeed multiples of $1$ and $x$ as they are already 'orthogonal' to each other, and $(x^2-2/3)$ is 'orthogonal' to both $1$ and $x$.
Now to answer your question, there are more ways to write $1+x+x^2$ in this new basis. Start it from the highest term: the coefficient of $x^2$ can only arrive from $u_3$, and hence it must be $\sqrt{2/3}$. Can you carry on from here?
Alternatively, as we are talking about orthonormal basis, the $i$th coordinate of any element $v$ will be exactly $\langle v,u_i\rangle$ w.r.t. basis $u_1,u_2,\dots$.
Use it for $v=1+x+x^2$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android "Screen overlay detected": block overlaying apps programmatically As many developers on Stackoverflow, I have got the problem that when a user grants a system dangerous permission, I have got the "Screen overlay detected" alert.
I have seen many answers:

*

*some recommend to display an alert to open the phone settings so that the user can block the overlaying apps by himself (I don't like this, I don't want to ask something confusing to the user)

*some other recommend to delete the apps which induce an overlay (it is just a non sense as I cannot ask this to my users...)

*some others explain to take care to potential overlaying toasts from my own app (I don't perform any operation when the user accept the permission => not the cause of my problem)

So, what I want is to block PROGRAMMATICALLY any third party app which would like to overlay something on my app. I want everything to be invisible by the user.
Any possibility to do this ?
Thanks


text:
Q: Yosemite upgrade process stuck for hours - Cmd-L not working Today I started the upgrade of my Mid 2011 iMac 27 from Mavericks to Yosemite. Initially it got stuck at the end of the first part of the installation. I could however pull up the installation log using Command-L and so I could tell it was still doing something. Eventually it completed and rebooted. It then got into the Completing Installation phase with a similar progress screen. It's been at "Less than a minute remaining" for the past 4 hours and no sign of activity. I also can't pull up the installation log by pressing Command-L. I just hear the familiar error sound when I try that.
I do use Homebrew so there's probably a lot of stuff in /usr/local causing the installation to take a long time, but I figured that's what caused part 1 of the installation to take so long, but it doesn't explain why part 2 is taking even longer.
Mavericks was installed on an external SSD (Lacie Rugged series) connected through thunderbolt. I now read that some people are experiencing problems with 3rd party SSD drives in Yosemite (yeah, I know I should have checked that before starting the upgrade, but who would have known?).
I'm not sure what to do now: just power off the computer and see if it continues finalizing the installation process after I restart it? Or just wait until tomorrow morning and see if it's still stuck? Even though I have a time machine backup on an external drive I don't want to risk losing my data forcing me to do a restore. Any advice?

A: Alright so I waited it out only to come back this morning to see that it was still stuck. I've waited several more hours until 10 am this morning which comes down to a total wait of 18 hours. I went ahead and manually rebooted and it looks like the upgrade was completed successfully after all.
Please note that this is not me suggesting you should reboot if the installation seems stuck. In general you should just be patient and wait. In the first phase of the installation press Command-L to show the installation log and you can verify it's actually doing something. Note that it can take a while for the installation log to show up after pressing Command-L.
In the second phase if it gets stuck you can't view what it's doing so it's pretty much a gamble if you decide to reboot it when it seems to be stuck.
I rebooted with my external backup hard drive disconnected to make sure my backup stays intact when things turn sour after all.
I verfied the disk and the permissions with Disk Utility and some permissions were off so I've repaired those. I'm now in the process of fixing Apache, but I'm guessing that's because of the differences between Apache 2.2 and 2.4.

A: UPDATE: I bit the bullet and just rebooted by holding down the power button and it seems to have rebooted as normal and I have Yosemite, hopefully with no issues!

A: Same thing happened with my dead standard 2011 Macbook Pro. Got stuck while booting after the upgrade. Hard rebooted after a few hours. Had to run disk checker but now everything appears to be fine.


text:
Q: from pandas import * -- Python issue I am trying to run the following code in python 3.3
    from pandas import *

and I receive the following error:
    Traceback (most recent call last):
    File "C:\Users\Tom\Desktop\ProgrammingStuff\Python\FXCointegrationBacktesting.py", line 9, in <module>
    cannot import name text_type
    from pandas import *
    File "C:\Python33\lib\site-packages\pandas\__init__.py", line 6, in <module>
    from . import hashtable, tslib, lib
    File "tslib.pyx", line 31, in init pandas.tslib (pandas\tslib.c:48782)
    File "C:\Python33\lib\site-packages\dateutil\parser.py", line 24, in <module>
    from six import text_type, binary_type, integer_types
    ImportError: cannot import name text_type

Not sure what the problem is, I am fairly new to python and I cannot currently find any solutions to this problem on stack overflow.
Thanks!

A: You're using a version of dateutil that depends on six.
In dateutil <= 1.5 you don't need six, but those versions are not compatible with Python >= 3.0. So, the solution is to install six. However you do that is up to you.
You could do
pip install six

If you choose not to use pip it will depend on your system's package manager how you go about installing it.


text:
Q: Filtering & Accordion I have developed a Website in Wordpress and there is training calendar in it, its working fine in Desktop Version. But for mobile version we are hiding some content and added accordion.
You can check the below link : (I have removed this link as my issue is resolved)
My issue is that, in mobile version, the accordion is working but the content is overlapping. :(
What is wrong or can be done for resolving this issue?? I have tired a lot of things :(

A: I have succeeded with this query, i have used Bootstrap Table expandable with MultiFilter.
Thanks you for your support
You can download MultiFilter here : Click Here


text:
Q: Foxpro form databinding and Next, Prev button I have form like below, and a .dbf (data table) which contains the same fields as the form, now I want to bind the first record to the form and implement Next and Prev... I know this seems very basic, but I can't find any page about this.

A: I'll give you the basics, then try to guide you elsewhere, and if you are interested in an email mentor, can help you along too.
First, I don't know how you put the text boxes on the form if it was from the data environment being dragged, or manual.  If your "Properties" window is not available, right-click on any control, then click "Properties..."  Look to the property "ControlSource" and set it to the alias.column you are trying to tie it to.  Do this with each of the fields.
Now, to the buttons.  It LOOKS like you grabbed the "Wizard" style controls, if so, let me know.. different answer will be applied...
If NOT, you can double-click on any "button", the system will bring up a snippet window associated with the "Click" event of buttons, but you could change it to any other available event in the future.  Now, the code.  Whatever you put in this snippet window will be executed when the button is clicked.  So, for each respective button, you may do something like..
*/ Code for the TOP button
select YourTable
GO TOP
Thisform.Refresh()

*/ Code for the BOTTOM button
select YourTable
GO BOTTOM
Thisform.Refresh()

*/ For the PREVIOUS button
select YourTable
if NOT BOF()  && BOF() is for Beginning of File
  skip -1
ENDIF
Thisform.Refresh()

*/ For the NEXT button
select YourTable
if NOT EOF()  && EOF() is for END of File
  skip +1
ENDIF
Thisform.Refresh()

*/ Delete button
IF MESSAGEBOX( "Confirm Delete Record?", 36, "Confirm" ) = 6
   */ Delete deletes whatever the CURRENT SINGLE record is,
   */ and is not a full SQL-Delete statement
   DELETE
ENDIF

Find, Print, Edit and Delete would be somewhat similar, but what condition to "FIND", you would need to build a report to print. Editing should just be directly available until you add in your own modes of add vs edit vs view mode to handle swapping.


text:
Q: Access onprem SAML / OAuth protected SAP API with Azure AD authentication (ADFS federated) Context:

*

*AD domain, AAD Connect, Office365 tenant

*ADFS deployed, federation between AD and AAD

*SAP GW on premise, with SAML and OAuth configured

*SAP GW does not support integration with AAD (only SAML SSO, and it's required to use it's own OAuth server)

Scope:
I'm trying to build an application in SharePoint online where the authenticated user can:

*

*fetch data from the SAP gateway (oh behalf of the user)

*fetch data from Microsoft Graph

Design (So far):

*

*The user access Office 365 and authenticate with ADFS

*With ADAL/MSAL I'm able to acquire an OAUTH token from AAD and get data from Graph (supported by the registration of an Enterprise application in AAD with permission for Graph)

Issue:

*

*The OAuth token generated by AAD is not validated by SAP OAuth Server onprem if I try to access the onprem SAP API.

What should I do?

*

*Should I get another SAML assertion directly from ADFS to get another OAuth token for SAP OAuth Server to access the onpremise SAP API? If so, how can I get a SAML assertion (to call the SAP OAuth server) from ADFS without passing to adfs user credential (like in this example: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-saml-bearer-assertion) and by using information available in the user session (already authenticated with AAD)?

*Is there a way to configure ADFS to accept SAML assertions / JWT tokens originating from AAD?

*Should I do something else?
Any idea on how could I support this scenario?
Thank you


text:
Q: cookie or session can not work on IIS Windows 7 Pro I developed an Asp.Net application and published it on IIS on a Windows 7 Professional.
Suddenly, people who view my web application from internet, started encountering with a problem which seem to prevent cookies or sessions being created. Basicly, cookies and sessions can not work or can not be created or destroyed immediately.
My application has been on classic application pool on iis.
What do you recommend me about this strange problem?

A: I have solved my problem on my own. The problem is very silly indeed. My web server was configured to use port 8080. So i had to write the address as localhost:8080 on my browser.
I did some searches and i realised that : is a special character which causes the problem.  I read some people who uses special characters (like _ etc.) in their address path faces the same issue on IIS on Windows 7 Professional


text:
Q: WebpackError: Reference Error with Firebase/app
*

*Summarize the problem:
When I merge a commit to Gitlab and run a pipeline, there is a script failure when trying to deploy. more specifically: WebpackError: ReferenceError: __WEBPACK_EXTERNAL_MODULE_firebase_app__ is not   defined
-The goal of this post is to hopefully get a better understanding of what I am doing wrong here, as I am trying to follow the errors to find the solution on my own, but have not been successful thus far.
-The expected result is that, because the pipeline had previously worked up until this point, that it would continue to do so. The strange part about this pipeline failure is that I did not actually install any packages on the merge that caused the failure. I went ahead and updated packages and some previous errors went away (for instance, there was a failure involving the sharp library that has now gone away) but now firebase app has become the focus.
The only actual error I saw in the output was WebpackError: ReferenceError: __WEBPACK_EXTERNAL_MODULE_firebase_app__ is not   defined followed by ERROR: Job failed: exit code 1

*Describe what you've tried: as stated before, I initially thought if I just updated all dependencies, this would help get me a better idea of what was going wrong. I thought I was on the right track when I noticed more progress along the pipeline than before, and there was this issue error (node:260) [DEP_WEBPACK_EXTERNALS_FUNCTION_PARAMETERS] DeprecationWarning: The externals-function should be defined like ({context, request}, cb) => { ... } (Use `node --trace-deprecation ...` to show where the warning was created) so I followed the error message's advice and added curly brackets around context, request in my gatsby-node.js file. That error went away on the next pipeline attempt, but WebpackError: ReferenceError: __WEBPACK_EXTERNAL_MODULE_firebase_app__ is not   defined remains

*Show some code:
I believe the gatsby-node.js file is what is relevant here, so here it is:
exports.onCreateWebpackConfig = ({ stage, actions, getConfig }) => {
  if (stage === 'build-html') {
    actions.setWebpackConfig({
      // Don't bundle modules that reference browser globals such as `window` and `IDBIndex` during SSR.
      // See: https://github.com/gatsbyjs/gatsby/issues/17725
      externals: getConfig().externals.concat(function ({ _context, request }, callback) {
        // Exclude bundling firebase* and react-firebase*
        // These are instead required at runtime.
        if (/^@?(react-)?firebase(.*)/.test(request)) {
          console.log('Excluding bundling of: ' + request);
          return callback(null, 'umd ' + request);
        }
        callback();
      }),
    });
  }
};

I can provide other details if needed, and would appreciate any advice that anyone has to offer. Thanks!

A: Downgraded Gatsby back to v2 (as well as all the relevant gatsby plugins) and the error went away


text:
Q: calling C++ from R I am using Visual Studio to create my C++ DLLS. A sample C++ function is
void _stdcall MyFunc(char ** strInput)
{
   MessageBox(NULL,"Hi from C++", L"C++ program", NULL);
}

I can then call this function from R by doing the following
dyn.load("Path\myDll.dll")
.C("MyFunc","Hello")

The above code works fine when called from R 64 bit. However, when I compile my DLL as 32 bit DLL and call it from R 32 bit, it crashes after briefly displaying the messagebox. I know that my DLL is working and is a valid 32 bit DLL since I can call its functions from other programs with no problem. Do you know why R 32 bit would be crashing when R 64 bit can handle the same call with no problem?

A: Reposted from comment:
Replace _stdcall with __cdecl – x64 has a single, universal calling convention, but x86 does not, and you're apparently using the wrong one.


text:
Q: SAS: Add Conditional Variable To Existing Data Source First time writing SAS code. Trying to add a new numeric variable that has a conditional value based on another existing variable. This is what I have so far:
data dataset;
    set dataset;
    newnum = .;
    If oldnum >= 2;
    newnum = 1;
run;

I'm getting an error when I try to run this SAS Code node that is attached to the relevant data source item.

A: There is no conditional statement in your code because you end your IF block with a semicolon. You need to move the newnum up to before the semicolon and add a THEN.
data dataset;
set dataset;
newnum = .;
If oldnum >= 2 then newnum = 1;
run;

As is, the line If oldnum >=2 will filter your dataset and keep only records that have oldnum>=2. Then it will assign newnum=1. So it does do what you want, but the resulting dataset will only be a subset of the original data set.


text:
Q: how to move json file from a directory into another( cache directory) I am trying to create a code that moves my json file( in assets directory) into cache directory, read the file and parse it. I already know how to parse it but I'm just not sure how to deal with cache directory. but I am not sure how to do it. I am new to android. any help would be appreciated. This is the code: In the middle of reading assets and parsing, I need to move the file into cache directory and read it there. How can I do that with code?
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    List<String> questions = new ArrayList();
    // Reading json file from assets folder
    StringBuffer sb = new StringBuffer();
    BufferedReader br = null;
    String temp="";
    try {
        br = new BufferedReader(new InputStreamReader(getAssets().open("animals.json")));

        while ((temp = br.readLine()) != null)
            sb.append(temp);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            br.close(); // stop reading
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    TextView output = (TextView) findViewById(R.id.textView1);
    String myjsonstring = sb.toString();
    String strJson="";
    String data = "";
    try {
        // Create the root JSONObject from the JSON string.
        JSONObject jsonRootObject = new JSONObject(myjsonstring);

        //Get the instance of JSONArray that contains JSONObjects
        JSONArray jsonArray = jsonRootObject.getJSONArray("Employee");

        //Iterate the jsonArray and print the info of JSONObjects
        for(int i=0; i < jsonArray.length(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            String text = jsonObject.optString("text").toString();
            String name = jsonObject.optString("name").toString();
            float salary = Float.parseFloat(jsonObject.optString("salary").toString());

            data += "Data"+i+" : \n text= "+ text +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
        }
       //String cacheDir = context.getCacheDir();
        readAllCachedText(getApplicationContext(),"animals.json");
        //FileInputStream fis = new FileInputStream(new File(getCacheDir(), "cachefile"));
        //String yourFilePath = context.getFilesDir() + "/" + "animals.json";
        //File yourFile = new File( yourFilePath );
        //FileInputStream fis = new FileInputStream(new File(getCacheDir(), "cachefile"));
        output.setText(data);
    } catch (JSONException e) {e.printStackTrace();}
}


text:
Q: Сортировка массивов на С++ Дана задача
На основе исходных массивов А[n] и B[m] (n и m — рабочие размеры массивов) сформировать массив С, который будет состоять из чисел, которые входят в массив В, но при этом не входят в массив А. Упорядочить массив С по возрастанию, используя метод
«пузырька». Вывести элементы массивов А, В и С на экран.
Массивы А, В и С являются целочисленными. Значения m и n вводятся пользователем с клавиатуры. Значения элементов массивов А и В генерируются при помощи датчика случайных чисел.
Так вот вопрос. Как сделать правильное заполнение массива С, не могу понять почему никак не хочет убирать повторяющиеся члены
Вот код, который есть на данный момент (Без пузырька)
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <iomanip>
using namespace std;
int main () {
    int n, m, i, d, b, k, s;
    int A[n], B[m], C[b];
    cout << "1 cikl - ";
    cin >> n;
    cout << "2 cikl - ";
    cin >> m;
    srand(time(0));
        for (i = 0; i <= n; i++)
            A[i] = -100 + rand()%200;
        for (i = 0; i <= m; i++)
            B[i] = -100 + rand()%200;
    if ( m >= n)
        d = m;
    else
        d = n;
    b=0;
    for (k = 0; k <= d; k++) {
        s = 0;
            for (i = 0; i <=n; i++){
                if ( B[k] == A[i] ) s++;
            }
        if ( s == 0) {
            C[b] = B[k];
            b++;
        }
    }
    for (i = 0; i <= d; i++) {
        cout << setw(4) << i;
        cout << setw (12) << A[i];
        cout << setw(18) << B[i];
        cout << setw (24) << C[i] << endl;
    }
}

A: Удивительно, что ваш код вообще собрался, особенно учитывая замечание @AR Hovsepyan. Пример рабочего кода:
#include <iostream>
#include <ctime>
void BubbleSorting(int arr[], int lenght)
{
    for (int i = 0; i < lenght - 1; i++)
    {
        for (int c = 0; c < lenght - 1; c++)
        {
            if (arr[c] > arr[c + 1])
            {
                arr[c] ^= arr[c + 1];
                arr[c + 1] ^= arr[c];
                arr[c] ^= arr[c + 1];
            }
        }
    }
}
void FillArray(int arr[], int lenght)
{
    for (int i = 0; i < lenght; i++)
        arr[i] = -100 + rand() % 200;
}
void ShowArrayContent(int arr[], int lenght)
{
    for (int i = 0; i < lenght; i++)
    {
        std::cout << arr[i] << std::endl;
    }
}
int main()
{
    int firstArrayLenght, secondArrayLenght;
    std::cout << "Enter first array lenght: ";
    std::cin >> firstArrayLenght;
    std::cout << "Enter first array lenght: ";
    std::cin >> secondArrayLenght;
    int *arrFirst = new int[firstArrayLenght];      //Массив А
    int *arrSecond = new int[secondArrayLenght];    //Массив B

    //Заполнение массивов
    srand(time(0));
    FillArray(arrFirst, firstArrayLenght);
    FillArray(arrSecond, secondArrayLenght);
    //Поиск элементов
    int  index = 0;
    //На случай если всех элементов массива B нет в массиве A,
    //создаем временный массив с размером массива B
    int *temp = new int[secondArrayLenght];
    for (int i = 0; i < secondArrayLenght; i++)
    {
        bool equal = false;
        for(int j = 0; j < firstArrayLenght; j++)
        {
            if (arrSecond[i] == arrFirst[j])
            {
                equal = true;
                break;
            }
        }
        if (!equal)
            temp[index++] = arrSecond[i];
    }
    //Создание результирующего массива и копирование в него найденных элементов
    int *arrResult = new int[index];
    for (int iter = 0; iter < index; iter++)
    { arrResult[iter] = temp[iter]; }
    //Удаление временного массива
    delete[] temp;
    //Сортировка
    BubbleSorting(arrResult, index);
    std::cout << "First array: " << std::endl;
    ShowArrayContent(arrFirst, firstArrayLenght);
    std::cout << "Second array: " << std::endl;
    ShowArrayContent(arrSecond, secondArrayLenght);
    std::cout << "Result array: " << std::endl;
    ShowArrayContent(arrResult, index);
    //Освобождение памяти
    delete[] arrFirst;
    delete[] arrSecond;
    delete[] arrResult;
    return 0;
}


text:
Q: No depurador do Google Crhome para JavaScript, tem como Pular alguns arquivos? Como o "Angular.js"
Tipo, preciso debugar com F10 ou F11, mas antes de uma função para outra, já chama esses arquivos, tipo o da imagem abaixo.
Tem que como marcar que quero pular eles?

A: No canto superior direito, próximo ao fechar existe um mais opções (3 pontinhos), ao clicar nele vai aparecer uma opção chamada settings, conforme imagem:

Em settings existe uma opção chamada Blackboxing, conforme imagem:

Clicando ali, vai existir uma opção chamada "Add patern", ai você coloca a url em questão que você quer ignorar, ou uma expressão regular.


text:
Q: Why does PHP consider it "unsafe" to use system time zone? PHP manual says:

Since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_WARNING message if using the system settings or the TZ environment variable.

What security concerns come from using default system time zone?
Why does PHP consider it unsafe?

A: I believe it is less of a worry of security issues (at least directly) using the local system timezone and more of issues reliably determining the system timezone at all. The solution, that gave you the message you are seeing, is based on the established coding convention that it's better to be explicit.
From my understanding, PHP devs have run into bugs in some underlying operating systems that had prevented reliable timezone detection in the past. The solution (after trying several) was to explicitly specify the timezone PHP should be working with.
As far as being unsafe, I believe there are a lot of scenarios where a faulty timezone could cause security issues for your application, even if not directly. Everything from transaction timestamps to session management in a multi-datacenter environment.


text:
Q: Reading from a TCPSocket in Ruby This code sends two HTTP requests to the www.example.com website:
require 'socket'

@host = 'www.example.com'
@port = 80
@path = "/"

# Build HTTP request
def request(close=false)
  "GET #{@path} HTTP/1.1\r\nHost: #{@host}#{"\r\nConnection: close" if close}\r\n\r\n"
end

# Build socket
socket = TCPSocket.open(@host,@port)  # Connect to server

# Send request twice via socket
2.times {socket.print request}

Here are various methods I have found for reading the response:
# Method 1: close_write and read
socket.close_write # Without this line, the next line hangs
response = socket.read
puts response.length

# Method 2: send another http request with 'Connection: close' header, then use 'read'
socket.print request(true) # Without this line, the next line hangs
response = socket.read
puts response.length

# Method 3: recv
# puts socket.eof?  # Method fails when I add this line
r1, r2 = socket.recv(1000000), socket.recv(1000000)
puts r1.length, r2.length

# Method 4: IO.select and read_nonblock
puts socket.eof?
# IO.select([socket])  # The code still works without this IO.select...
r1 = socket.read_nonblock(9999999)
IO.select([socket])  # ...but not without this one
r2 = socket.read_nonblock(9999999)
puts r1.length, r2.length
puts socket.eof? # Hangs for ages before returning 'true'

Questions:

*

*What exactly is 'socket.close_write' line doing in Method 1 and why is it necessary for the method to work?

*In Method 2, is the 'Connection: close' header somehow achieving the same result as the 'socket.close_write' line in Method 1?  If not, what is it doing, and why is it necessary for the rest of the method to work?

*Why, in Method 3, does the addition of the commented line, 'puts socket.eof?', cause the rest of the code to hang?

*In Method 3, how and why does the recv call stop at the end of an HTTP response (as opposed to picking up the next response as well)?

*Why is it that the second IO.select in Method 4 is necessary, but the first isn't?

*What does IO.select actually do?

*Why does the last line, 'puts socket.eof?', in Method 4 hang for ages before returning true?

*Is there a general way of checking how many responses a socket is currently expecting, and reading that number of responses from the socket, without closing the socket for writing?

Finally, if not possible in an answer here, is there a good resource somewhere where I can get some clarity on all of the above, and general clarity on reading from TCP sockets (or network sockets in general)?
Thanks.

A: socket.close_write is not necessary. I mean you can get what socket returns by socket.read, but you are gonna to wait some time. The reason why is because you are trying to read the whole stream in one with socket.read. It takes time. You can find out what socket returns by doing:
socket.each_line do |line|
  puts line
end

BTW, Nagle's algorithm makes it slow too.
Whatclose_write does is let the client side half-close the socket.When the server side notice this, it will also close its side. Then you can finish reading very quickly.
Or you can use IO::select.As the documentation said:

It monitors given arrays of IO objects, waits one or more of IO objects ready for reading, are ready for writing, and have pending exceptions respectively, and returns an array that contains arrays of those IO objects. It will return nil if optional timeout value is given and no IO object is ready in timeout seconds.

ready = IO.select([socket], nil, nil, 10)
if ready
  # do something
else
  # raise timeout
end

Here we pass the first parameter, which is the object ready for reading and the last is the timeout you want set. This means if the reading is not ready in 10 seconds it will return nil then raise timeout error.


text:
Q: Show part of the value returned by a Json with Javascript Clarify that I am making a request to a file that is locally, I am doing it with fetch, not if it is correct, I have tried the following (excuse my English):
Array = [
{
 0: "46140:ADEMUZ"
 1: "46729:ADOR"
 2: "46940:AEROPUERTO DE MANISES (VALENCIA)"
 3: "46890:AGULLENT"
 4: "46176:AHILLAS"}
]

I would like to show only, a part of the value:
Array = [
{
 0: "46140"
 1: "46729"
 2: "46940"
 3: "46890"
 4: "46176"}
]

I have tried with the following:
document.addEventListener("DOMContentLoaded", () => {

    mostrar()

});

function mostrar() {

    fetch('/46xcodpos.txt')
        .then(res => res.text())
        .then(content => {
            let lines = content.split(/\n/);
            console.log(lines);
            recorrer(lines)
        });
}

function recorrer(lines) {
    //Iterar
    const resultado = document.getElementById('resultado');

    lines.forEach(muestra => {

        resultado.innerHTML += `

                    ${muestra}

                `;
    }

    )
};

If you know of another method, do not hesitate to expose it, I am with relatively little javascript. Thanks a lot

A: You could Array.prototype.map() over the object values of your first array value and only take the first 5 chars using String.prototype.slice(). Then simply append your modified text to the DOM somehow. I chose a list here because it shows quite well what's going on in my opinion.

const list = document.getElementById("list");

const array = [{
  0: "46140:ADEMUZ",
  1: "46729:ADOR",
  2: "46940:AEROPUERTO DE MANISES (VALENCIA)",
  3: "46890:AGULLENT",
  4: "46176:AHILLAS"
}];

Object.values(array[0]).map((e) => {
  const li = document.createElement('li');
  li.appendChild(document.createTextNode(e.slice(0, 5)));
  list.appendChild(li);
});


text:
Q: A special graph coloring problem
Let $G$ be an undirected graph. We define:
An Orientation $D$ from $G$: A subgraph $D$ with $V(D) = V(G)$ such that for every edge $\{u, v\} \in E(G)$, we take either $(u, v)$ or $(v, u)$ in $D$.
We call a function $c: V(D) \rightarrow \{1, ..., k\}$ a $k$-In-Out-Coloring if for every vertex $v \in V(D)$ the following holds:
$$\{c(u) | (u, v) \in E(D) \} \cap \{c(w) | (v, w) \in E(D) \} = \phi$$
In other words, no vertex in a $k$-in-out-colored, directed graph has an in-neighbor $u$ and an out-neighbor $w$, so that $c(u) = c(w)$. In this graph for example, the vertices $0$, and $2$ have to colored in different colors, so $c(0) \neq c(2)$. Note that we didn't impose restrictions on vertex $1$, it is allowed to be colored in $c(0)$ or $c(2)$.
For a function $f: A \rightarrow B$ and a subset $C \subseteq A$ we define a restriction from $f$ onto $C$ as $f_{\restriction C}(x):= f(x)$ if $x \in C$. So the function $f_{\restriction C}$ has the type $f_{\restriction C}: C \rightarrow B.$
Let $k \in \mathbb{N}$ be fixed, $G$ an undirected Graph (with no parallel edges or self-loops) with countably infinite vertices and let $c:V(G) \rightarrow \{1, ..., k\}$ be an $k$-in-out coloring function.
Prove: If every finite subgraph $G'$ from $G$ has an orientation which is $k$-in-out-colored by $c_{\restriction V}(G')$, then there must exist an orientation of $G$, which is $k$-in-out-colored by $c$.

There are too many layers in this proof and I don't know where to begin. A proof by contradiction seems suitable but even then, I don't see what follows.
If every subgraph $G'$ has an orientation which is $k$-in-out-colorable by $c_{\restriction V}(G')$, then the subgraph $H$ with $V(H) = V(G)$ and $E(H) = E(G)$ is $k$-in-out-colorable by $c_{\restriction V}(G')$. If $H$ is $k$-in-out-colorable by this restriction function, then it must be colorable by $c$, and so must be $G$, which is exactly the same graph as $H$. So I'm not really sure what the question is looking for. Any help would be much appreciated.

A: As the vertex set is enumerable, so does the set of edges. Then let $\{e_{i}\}_{i \in \mathbb{N}}$ be an enumeration of $E(G)$. For each $i \in \mathbb{N}$, let $\{u_{i},v_{i}\} = \{e_{i}\} $ and define $G_{i} = (\bigcup_{j = 1}^i e_{i},  \{ e_{j} ~\colon j \in \{1,\ldots, i\}\})$. In other words, $G_{i}$ is the finite graph induced by the edges $\{e_{1},\ldots, e_{i}\}$. Let $G_{i}'$ be the orientation of $G_{i}$ respecting the property mentioned by OP.
We will define an orientation in $\{e_{i}\}_{i \in \mathbb{N}}$ by induction. First, we have two possibilities of orientation for $e_{1}$, $(u_{1},v_{1})$ or $(v_{1},u_{1})$. Moreover an orientation of the edge $e_{1}$ appears in an infinite number of graphs in the sequence $\{G_{i}'\}$(of course appears in all of them). Then, by the pigeonhole principle, at least one of theses orientations occurs in an infinite subsequence of $\{G_{i}'\}$. Then we define $\overrightarrow{e_{1}}$ to be the orientation of $e_{1}$ that occurs in all orientations of the subsequence $\{G_{i_{k}}\}_{k \in \mathbb{N}}$. Now notice that the edge $e_{2}$ occurs in an infinite number of orientations of $\{G_{i_{k}}\}$. Therefore, using the same argument one can find an infinite subsequence of $\{G_{i_{k}}\}$ where the orientation of $e_{2}$ is the same for all graph in this subsequence. And then define $\overrightarrow{e_{2}}$ to be this orientation. Notice that even in this news subsequence, all orientations of $e_{1}$ still are $\overrightarrow{e_{1}}$. By induction we can define the orientation of all edges like this. Than call by $A = \{\overrightarrow{e_{1}},\overrightarrow{e_{2}},\overrightarrow{e_{3}}, \ldots\}$.
Now we must prove that $A$ respects the property. Suppose otherwise and take two vertices $w_{1}$ and $w_{2}$ such that $c(w_{1}) = c(w_{2})$ and there is a vertex $z$ such that $(w_{1},z,w_{2})$ is a directed path in $(V(G),A)$. Let $i_{1}$ and $i_{2}$ be natural numbers such that $(w_{1}, z) = \overrightarrow{e_{i_1}}$ and $(z,w_{2}) = \overrightarrow{e_{i_{2}}}$. Without loss of generality suppose that $i_{2} > i_{1}$.
Let's remember the construction. When we are choosing the orientation of $e_{i_2}$, we are in a subsequence $\{G_{i_{k}}\}$ such that the graphs $\{G_{i_{k}}'\}$ contain all edges from $e_{1}$ to $e_{2} - 1$ and they are oriented in the same direction, in particular the direction of $e_{i_{1}}$ is the same as in $A$. Then we take a subsequence which by abuse of notation we will denote also by $\{G_{i_{k}}'\}$ where $e_{i_2}$ is oriented in the same direction as in $A$, $\overrightarrow{e_{2}}$. Let $G^*$ be an arbitrary graph in the  subsequence of orientations. As $(w_{1},z,w_{2})$ is a directed path in $G^*$ and the property holds by hypothesis for finite sets, we have that $c(w_{1}) \neq c(w_{2})$. An contradiction.
I know that it is far from being easy to understand this demonstration and maybe its because of my english mistakes, I am sorry in advance. If you don't understand feel free to ask.


text:
Q: Terraform.tfvars parsing lists for variables.tf file I've got a couple of variables set in my variables.tf files which are of type list and I am trying to find the correct syntax on my .tfvars file
variables.tf
variable "subnet_cidrs" {
  type        = list(string)
  description = "A list of Subnets CIDR's - Should consist of minimum 2"
}

variable "aws_region" {
  type        = string
  description = "Region where all AWS Resources will be created"
}

variable "az" {
  type        = list(string)
  description = "Availability-Zones - Should match numbers of CIDRs given and AWS Region"
}

terraform.tfvars
subnet_cidrs    = ["192.168.1.100", "192.168.4.100"]
aws_region      = "eu-central-1"
az              = ["eu-central-1a", "eu-central-1b"]

A typical output i'll receive is :
│ Error: Incorrect attribute value type
│
│   on ..\ec2\ec2.tf line 21, in resource "aws_subnet" "public":
│   21:   availability_zone       = var.az
│     ├────────────────
│     │ var.az is a list of dynamic
│
│ Inappropriate value for attribute "availability_zone": string required.

When brackets are removed for example : az = "eu-central-1a", "eu-central-1b"
It will return the following instead Argument definitions must be separated by newlines, not commas. An argument definition must end with a newline.
Edit
ec2.tf
I've made this as short as possible and included only the variables
# Main VPC
resource "aws_vpc" "main" {
  cidr_block = var.vpc_cidr

  tags = {
    Name = "vpc-${var.name_prefix}"
  }
}

# Two Subnets in different AZ - Public IP on launch
resource "aws_subnet" "public" {
  count = length(var.subnet_cidrs)

  cidr_block              = var.subnet_cidrs
  availability_zone       = var.az

  tags = {
    Name = "subnet-${var.name_prefix}-${count.index}"
  }
}

resource "aws_security_group" "ec2_sg" {
  name        = var.ec2_name
  ...
  tags = {
    Name = "EC2-SG-${var.name_prefix}"
  }
}

# VM Key pair
resource "aws_key_pair" "auth" {
  key_name   = var.key_pair_name
  public_key = file("~/.ssh/${var.ssh_file_name}.pub")
}

# EC2 Instance within 2 AZ's
resource "aws_instance" "ec2" {
  count = length(var.subnet_cidrs)

  tags = {
    Name = "ubuntu-${var.name_prefix}-${count.index}"
  }
}

A: Based on the variable definition and the way subnet resource is created, the following change is required:
resource "aws_subnet" "public" {
  count = length(var.subnet_cidrs)

  cidr_block              = var.subnet_cidrs
  availability_zone       = var.az[count.index] # <---- using count.index here

  tags = {
    Name = "subnet-${var.name_prefix}-${count.index}"
  }
}

This is needed because otherwise the problem will occur as availability_zone requires a single string value and passing only var.az will be an entire list. Using the count.index with the var.az will fetch a single value as is required.


text:
Q: How can I ensure that a React component is loaded only after some API call has been made? I have a App component as below and it has MyHeaderComponent as it's child.
On MyHeaderComponent load, I invoke a service call/endpoint. However, I want to ensure that MyHeaderComponent itself is invoked only after callSomeServiceEndpoint has finished. Not sure if that is possible, since the call to /myrefresh is an opaque response (just returning me a cookie)
function App() {
    const [url, setUrl] = useState({});
    const urls = useMyFetch('api/myApiURLs', {});
    const [isEntitled, setIsEntitled] = useState(false);

    useEffect(() => {
        if (Object.keys(urls).length > 0) {
            setUrl(urls);
            callSomeServiceEndpoint(urls);
        }
    }, [urls])

    return (
        <>
            <MyContextProvider>
                <MyHeaderComponent url={urls} />
            </MyContextProvider>
        </>
    );
}

export default App;

Below is callSomeServiceEndpoint
export default function callSomeServiceEndpoint(myURLs) {
    const int = 1 * 60 * 1000;
    function myrefresh(myURLs) {
        Object.values(myURLs).forEach((myURL) => {
            fetch(`${myURL}/myapi/myrefresh`, {
                mode: 'no-cors',
                credentials: 'include'
            });
        });
    }
    myrefresh(myURLs);
    const refInterval = setInterval(myrefresh, int, myURLs);
    window.addEventListener("beforeunload", function () {clearInterval(refInterval)});
}

Below is useMyFetch
import {useEffect, useState} from 'react';

export default function useMyFetch(url, data) {
    const [url] = useState(url);
    const [mydata, setMyData] = useState(data);
    useEffect(() => {
        fetch(url, {mode: 'no-cors', credentials: 'same-origin'})
            .then(response => {
                // Response handling and setMyData()
            })
            .catch(error => {
            });
    }, [url]);

    return data;
}

A: What do you think about a boolean in custom hook triggered in in fetch's then? Something like:
import {useEffect, useState} from 'react';

export default function useMyFetch(url, data) {
    const [url] = useState(url);
    const [mydata, setMyData] = useState(data);
    const [isDone, setIsDone] = useState(false); //<-- boolean here
    useEffect(() => {
        fetch(url, {mode: 'no-cors', credentials: 'same-origin'})
            .then(response => {
                // Response handling and setMyData()

                setIsDone(true); //<-- set to true
            })
            .catch(error => {
            });
    }, [url]);

    return [mydata, isDone];
}

And the App component:
function App() {
    const [url, setUrl] = useState({});
    const [urls, isDone] = useMyFetch('api/myApiURLs', {});
    const [isEntitled, setIsEntitled] = useState(false);

    useEffect(() => {
        if (Object.keys(urls).length > 0) {
            setUrl(urls);
            callSomeServiceEndpoint(urls);
        }
    }, [urls])

    return (
        <>
            <MyContextProvider>
                {isDone && <MyHeaderComponent url={urls} />}  //<-- conditional rendering
            </MyContextProvider>
        </>
    );
}

export default App;

A: You may create a state like const [endpointCalled, setEndpointCalled] = useState(false); in the App component.
Then change callSomeServiceEndpoint so that it returns a promise in order to rewrite it like
callSomeServiceEndpoint(urls).then(setEndpointCalled(true));

and finally
<>
 <MyContextProvider>
  {endpointCalled ? <MyHeaderComponent url={urls} /> : null}
 </MyContextProvider>
</>


text:
Q: Is there an easy way to find the runtime environment in Pyramid In pyramid, I need to render my templates according to different runtime environments -- enable google analytics, use minified code, etc. (when in production). Is there an easy way to find out the current environment -- perhaps an existing flag to find out which ini file was used?

A: I set this sort of thing as an environmental variable named something like PYRAMID_ENV which can be viewed via os.environ. For example in your code:
import os

pyramid_env = os.environ.get('PYRAMID_ENV', 'debug')

if pyramid_env == 'debug':
    # Setup debug things...
else:
    # Setup production things...

Then you can set the variable in the init script or when starting the server:
PYRAMID_ENV=production python server.py

Docs on access to environmental variables: http://docs.python.org/library/os.html#os.environ

A: Pyramid INI files can hold arbitrary configuration entries, so why not include a flag in your files that distinguishes between production and development deployments?
I'd do it like this; in your production .ini file:
[app:main]
production_deployment = True # Set to False in your development .ini file

Pass this value on to the Pyramid Configurator:
def main(global_config, **settings):
    # ...
    from pyramid.settings import asbool
    production_deployment = asbool(settings.get(
               'production_deployment', 'false'))
    settings['production_deployment'] = production_deployment
    config = Configurator(settings=settings)

You can now access the settings from just about anywhere in your Pyramid code. For example, in a request handler:
settings = request.registry.settings
if settings['production_deployment']:
    # Enable some production code here.

However, I'd also use more finegrained settings in this case; a flag for enabling Google Analytics, one for minifying resources, etc. That way you can test each individual setting in your development environment, write unit tests for these switches, etc.


text:
Q: How to create an object property function from a string in javascript? First, thought we already have overcome the evil eval, right? Plus, I am working in pure JavaScript.
So I have an object:
var MyObj = new Object();
MyObj.myFunction = function(a, b) { return a + b; }

But this function is stored in a string, and the Function constructor ask for the parameters first, and than the body after, and I don't know about the parameters, if exists. The point is to create the function by "interpreting" (not EVALuating) the content of the string. I wish this was possible:
var MyObj = new Object();
var myFuncStr = "function(a, b) { return a + b; }";
MyObj.myFunction = new Function(myFuncStr);

I found this discussion from 11 years ago: Given a string describing a Javascript function, convert it to a Javascript function
But this was a decade ago and the answer is for a specific case.
I am thinking in try to identify the parameters inside the string and try to pass to the Function constructor, something like a String.toFunction extension that will require some code (maybe I locate the first parentheses, get the slice, locate the brackets, get the content... voilá, seems a bit rust).
Is there an answer already for this situation? Any existing solutions?
EDIT: Since there is a lot of votes asking for a step back, I will post the code one level up (two will be about 3k lines)
Object.defineProperty(String.prototype, "toObject", {
enumerable: false,
configurable: false,
writable: false,
value: function(method, extended) {
    var string = this;
    if(!method) method = "typeof";
    let ini = string.indexOf('{');
    let fim = string.lastIndexOf('}');
    if(ini==-1 || fim==-1) {
        $monitor("Erro de parâmetro String.toObject","erro","O parâmetro passado a String.toObject ("+string+") não é um objeto literal.");
        return null;
    }
    var str = string.slice(ini+1, fim);
    console.log("String.toObject str...");
    console.log(str);
    var Elems = str.split(','), Terms, prop, value, isStr, val, type, dp = new DOMParser();
    var Obj = new Object();
    for(let i=0; i<Elems.length; i++) {
        Terms = Elems[i].split(':');
        prop = Terms.shift().filter('property');
        value = Terms.join(':').filter('value');
        console.log(" ...filter "+prop+" : "+value);
        isStr = (value.charAt(0)=='"' && value.charAt(value.length-1)=='"');
        switch(method) {
            case "typeof":
                val = (isStr)? value.slice(1,-1) : value ;
                type = (isStr)? "string" : val.typeof(extended) ;
                break;
            case "string":
                val = (isStr)? value.slice(1,-1) : value ;
                type = "string";
                break;
            default:
                $monitor("Erro de parâmetro String.toObject","erro","O parâmetro 'method' ("+method+") passado a String.toObject não é válido.");
                return null;
        }
        switch(type) {
            case "null":
                Obj[prop] = null;
                break;
            case "boolean":
                Obj[prop] = (val.toLowerCase()=="true");
                break;
            case "number":
                Obj[prop] = Number.parseFloat(val);
                break;
            case "string":
                Obj[prop] = val;
                break;
            case "function":
                Obj[prop] = "StackOverflowWillGiveMeTheAnswer";
                break;
            case "xml":
                Obj[prop] = dp.parseFromString(val, "text/xml");
                break;
            case "object":
                Obj[prop] = val.toObject(extended);
                break;
        }
    }
    return Obj;
}
});

But this function depends on typeof, so here is:
Object.defineProperty(String.prototype, "typeof", {
enumerable: false,
configurable: false,
writable: false,
value: function(extended) {
    var string = this;
    if(string.length==0 && extended) return "null";
    if(string.toLowerCase()=="true" || string.toLowerCase()=="false") return "boolean";
    if(string.isNumeric()) return "number";
    if(string.replaceAll(' ','').substring(0, 9)=='function(' || string.replaceAll(' ','').substring(0, 5)=='()=>{') return 'function';
    string = string.trim();
    if(extended) {
        try {
            var DOM = new DOMParser();
            var xml = DOM.parseFromString(string, "text/html");
            return "xml";
        } catch(e) {}
    } else {
        if(string.charAt(0)=='<' && string.charAt(string.length-1)=='>') return "xml";
    }
    //console.log("String.typeof chr 0 -1: "+string.charAt(0)+" "+string.charAt(string.length-1));
    if(string.charAt(0)=='{' && string.charAt(string.length-1)=='}') return "object";
    return "string";
}
});

Both are in development, not 100% functional yet. I was avoiding to post so much code because of the downvotes, will take my chances. Just give me an answer instead of just asking why... sometimes God only knows why!
By the way, "no you can't" is an answer.

A: Yes, you can do this without eval (whether you should is another discussion), using URL.createObjectURL to basically create a file that contains the JS code you want to execute...

// Object as string including function definition
const objectAsString = `{
    a: 1,
    b: 2,
    c: function(x) {
        return this.a + this.b + x;
    }
}`;

// Wrap in script to assign to global variable
const source = `
var objectFromStrWithFunc = ${objectAsString}`;
const script = document.createElement("script");

// Create a Blob from the source and create a file URL
script.src = URL.createObjectURL(new Blob([source], { type: 'text/javascript' }));

// When it loads call the function on the global variable
script.addEventListener(
    'load',
    () => alert(objectFromStrWithFunc.c(3)));

document.head.appendChild(script);

This will run with some content security policies that will block eval (specifically those that allow blob but not unsafe-eval) and will work slightly better with some debugging tools (as the browser sees it as a file).
However, from the comments it looks like you're using E4X, which hasn't been supported by any mainstream browsers for over a decade now, but is really easy to port to JSX (the syntax is extremely similar). You may be better off using any of the many JSX tools (it's the basis of React) to output the JS you want at build time or on the server.
Converting E4X to text that you deserialise to JS on the client is a fairly unique solution - you'll have to write everything yourself.
Converting JSX to JS that runs in the browser is what every React app is doing, and has massive support and probably already has solutions written for most problems.

A: I will share my own solution to the question. I have created a method for String instances:
Object.defineProperty(String.prototype, "toFunction", {
enumerable: false,
configurable: false,
writable: false,
value: function(useEval) {
    if(!$params(["String.toFunction",
        {nome:"useEval",valor:useEval,tipos:"boolean"}
        ])) {
        $monitor("Erro de parâmetro String.toFunction","erro","O parâmetro passado a String.toFunction ("+useEval+") não é válido.");
        return null;
    }
    var string = this, Func, params, body;
    if(useEval) {
        Func = eval(string);
        if(typeof(Func)!="function") {
            $monitor("Erro de parâmetro String.toFunction","erro","O parâmetro passado a String.toFunction ("+string+") não é interpretável como funcção por eval.");
            return null;
        }
    } else {
        if(string.split("=>").length==2) { // Arrow Function
            let Terms = string.split("=>");
            params = Terms[0].filter('value');
            body = Terms[1].filter('value');
        } else if(string.substring(0,8)=='function') {
            let Terms = string.split(')');
            params = Terms[0].split('(')[1];
            Terms.shift();
            body = Terms.join(')').filter('value');
        } else {
            $monitor("Erro de parâmetro String.toFunction","erro","String não reconhecida como função.");
            return null;
        }
        if(params.charAt(0)=='(') params = params.slice(1,-1);
        params = params.replaceAll(' ','');
        if(body.charAt(0)=="{") body = body.slice(1, -1);
        Func = new Function(params, body);
    }
    return Func;
}
});

I did some tests and the code seems promising. I didn't test the eval option, but will leave it available, who knows. The 'filter' method is a function that returns the string filtered. In the 'value' option, it strips spaces and text marks (tab, enter, etc) before and after the content.
This is the testing code:
var MyObj = new Object();
var Funcs = ["function (a, b) { return a + b; }",
    "(a, b) => { return a + b; }"];
MyObj.myFunc = Funcs[0].toFunction();
console.log("String.toFunction test: "+MyObj.myFunc(1, 2).toString());
MyObj.arrFunc = Funcs[1].toFunction();
console.log("String.toFunction test: "+MyObj.arrFunc(1, 2).toString());

Should log 3 and 3.


text:
Q: Relative invariants of prehomogeneous vector space Let $(G,\rho,V)$ be a prehomogeneous vector spaces with $f_1,\dots,f_N$ the basic irreducible relative invariants. Suppose that $(G',\rho',V')$ is a second prehomogeneous that is in the same castling class of the previous one. Is there a way to compute the basic irreducible relative invariants of the second one starting from $f_1,\dots,f_N$? and if they are just castling transforms of each other?

A: Yes, this is discussed on pp.67-68 of Sato-Kimura, "A classification of irreducible prehomogeneous vector spaces".


text:
Q: Multiple Applescript lines from terminal osascript call So I'm trying to run multiple Applescript commands from the command line in one go. However, no matter how I try it, it won't work:
$ osascript -e "set x to 0; display dialog x"
$ osascript -e "set x to 0 \n display dialog x"
$ osascript -e "set x to 0 then display dialog x"

Is there a way to do this without saving to file?

A: This works for me:
osascript -e "set x to 0" -e "display dialog x"

Have a look at the -e option in the manual page for osascript in Terminal: man osascript

−e statement
Enter one line of a script. If −e is given, osascript will not look for a filename in the argument list. Multiple −e options may be given to build up a multi-line script. Because most scripts use char- acters that are special to many shell programs (for example, AppleScript uses single and double quote marks, "(", ")", and "∗"), the statement will have to be correctly quoted and escaped to get it past the shell intact.

You can also do e.g.:
osascript <<END
set x to 0
display dialog x
END

Or:
osascript -e '
set x to 0
display dialog x'

A: Your second attempt was very close to proper:
osascript -e "set x to 0
PRESS ENTER
display dialog x"
PRESS ENTER


text:
Q: Write file A to file B in python In Python, have a file A, and I want to copy it to file B.  What's the most efficient way to do that? I will also be appending further text to file B after the initial copy. Thanks.

A: Use shutil
from shutil import copyfile
copyfile(A,B)

Then use B as a regular file.

A: If you'd like use file.write()...
with open('A', 'r') as f:
    text = f.read()

with open('B', 'w') as f:
    f.write(text)

About append, use append mode(a) when you write text:
with open('A', 'r') as f:
    text = f.read()

with open('B', 'a') as f:
    f.write(text)


text:
Q: Zend 2, Doctrine 2 Entity validator Single field validaton
Is it possible to check if a value already exists in another entity? So when a username already exists, a new user can't get that username. In doctrine 2, there are some validators which checks for object existence or unique objects (don't know if a ZF2 validator can use this?). How can I put that in my inputFilter so usernames can't be duplicated? I have the following inputFilter for my username right now:
$inputFilter->add($factory->createInput(array(
                'name' => 'username',
                'required' => true,
                'filters' => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array( array(
                        'name' => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min' => 3,
                            'max' => 50,
                ),
            ),
        ),
 )));

Is it possible to extend this validator with a doctrine-validator, so I can check if there are duplicated usernames?
Multiple field validation
Currently I'm catching the DBAlException, to see if something went wrong, but in this case I would like to have a message returned of what went wrong, like duplicated key or unique constraints being invalid. So a message at the field which went wrong.
try {
$this->getEntityManager()->flush();
            } catch (\Doctrine\DBAL\DBALException $e) {
                $this->flashMessenger()->addMessage('Duplicate key, please set another name for user.');
return array(
  'form' => $form,
'flashMessages' => $this->flashMessenger()->getCurrentMessages()
                );
}

By catching a DBAlException you can't see which unique key(s) are invalid. For example: I've got a Category Entity with the following Unique Constraint -> uq_ParentId_Name. How can I check if this constraint is valid for a new (Category) Entity?

A: Check Zend\Validator\Db\NoRecordExists. For example, you want a company name to be unique:
new NoRecordExists( array(
    'adapter' => $serviceManager->get( 'Zend\Db\Adapter\Adapter' ),
    'table' => 'COMPANY',
    'field' => 'NAME',
    'message' => 'The company name already exists'
);

You have to attach it to the desired input, and the message will be related to it.


text:
Q: Unable to pull image from amazon ECS private repository on container instances running in ECS cluster I have created a NON default cluster on AWS ECS and I am able to pull docker images from docker public repository and run it too for testing.
I then created a ECS private repo and built and pushed an image to this repository and it succeeds. But when I try to pull it manually using docker pull, it complains with following error:

Error response from daemon: Get
  https://532193077341.dkr.ecr.ap-south-1.amazonaws.com/v2/12r/manifests/latest: no basic auth credentials

It seems to be an issue with IAM roles and permissions but I am not sure which role/policy to change.

A: In your ECS container (task) definition
If you are using a private ECR repository:
Do not check Private repository authentication option, as ECR doesn't use username-password authentication, it will use the IAM role/user permissions. Then, just make sure that the ECS IAM role (called ecsTaskExecutionRole by default) have permissions to pull images from ECR, which if it doesn't add these lines yourself:
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",

If you are using a non-ECR private repository:
Check Private repository authentication option and give your username-password using Secrets Manager

A: You need to authenticate against ECR first.  Local AWS credentials on their own aren't enough to allow you to pull from a private ECR repository.  Try something like this beforehand:
$(aws ecr get-login --registry-ids <YOUR-ID> --region <YOUR-REGION>)

Which will perform a docker login for you against ECR, allowing you to pull private images (assuming your local AWS credentials have the required permission).
For more information, see "Step 1: Authenticate Docker to your Default Registry" within the Amazon ECR Documentation.


text:
Q: Error when building fluent_ui on flutter 3.8.0 I am new to flutter and have been trying to use the fluent_ui package without success. My packages are added correctly and my main.dart file picks the fluent package but I get a weird long error when building the project.

../../../AppData/Local/Pub/Cache/hosted/pub.dev/fluent_ui-3.9.1/lib/src/controls/form/selection_controls.dart(26,29): error G4906CC7E: The parameter 'clipboardStatus' of the method '_FluentTextSelectionControls.buildToolbar' has type 'ClipboardStatusNotifier', which does not match the corresponding type, 'ClipboardStatusNotifier?', in the overridden method, 'TextSelectionControls.buildToolbar'. [C:\Users\juanb\Desktop\proyectos flutter\fluent_test\build\windows\flutter\flutter_assemble.vcxproj]
../../../AppData/Local/Pub/Cache/hosted/pub.dev/fluent_ui-3.9.1/lib/src/controls/form/text_box.dart(31,35): error G4906CC7E: The parameter 'details' of the method '_TextBoxSelectionGestureDetectorBuilder.onSingleTapUp' has type 'TapUpDetails', which does not match the corresponding type, 'TapDragUpDetails', in the overridden method, 'TextSelectionGestureDetectorBuilder.onSingleTapUp'. [C:\Users\user\Desktop\proyectos flutter\fluent_test\build\windows\flutter\flutter_assemble.vcxproj]
../../../AppData/Local/Pub/Cache/hosted/pub.dev/fluent_ui-3.9.1/lib/src/controls/form/text_box.dart(47,42): error G4906CC7E: The parameter 'details' of the method '_TextBoxSelectionGestureDetectorBuilder.onDragSelectionEnd' has type 'DragEndDetails', which does not match the corresponding type, 'TapDragEndDetails', in the overridden method, 'TextSelectionGestureDetectorBuilder.onDragSelectionEnd'. [C:\Users\user\Desktop\proyectos flutter\fluent_test\build\windows\flutter\flutter_assemble.vcxproj]
../../../AppData/Local/Pub/Cache/hosted/pub.dev/fluent_ui-3.9.1/lib/src/controls/form/text_box.dart(41,25): error GC2F972A8: The argument type 'TapUpDetails' can't be assigned to the parameter type 'TapDragUpDetails'. [C:\Users\user\Desktop\proyectos flutter\fluent_test\build\windows\flutter\flutter_assemble.vcxproj]
C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Microsoft\VC\v170\Microsoft.CppCommon.targets(247,5): error MSB8066: Compilaci�n personalizada de "C:\Users\user\Desktop\proyectos flutter\fluent_test\build\windows\CMakeFiles\39bb34ccd2a2d63cfc27b36bad2cfc61\flutter_windows.dll.rule;C:\Users\user\Desktop\proyectos flutter\fluent_test\build\windows\CMakeFiles\be203ab2df29ff02ede16a6967f51054\flutter_assemble.rule" terminada con el c�digo 1. [C:\Users\user\Desktop\proyectos flutter\fluent_test\build\windows\flutter\flutter_assemble.vcxproj]
Exception: Build process failed.

I will show my flutter version, my dependencies "pubspec.yaml" file and the "main.dart" file.
My flutter version

Flutter 3.8.0-17.0.pre.4 • channel main • https://github.com/flutter/flutter.git
Framework • revision 5ce4f80eeb (5 days ago) • 2023-02-25 04:23:38 -0500
Engine • revision ddfd3dce13
Tools • Dart 3.0.0 (build 3.0.0-272.0.dev) • DevTools 2.22.1

My pubspec.yaml file
name: fluent_test
description: A new Flutter project.

publish_to: 'none'
version: 1.0.0+1

environment:
  sdk: '>=3.0.0-272.0.dev <4.0.0'
dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  fluent_ui: ^3.9.1

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^2.0.0
flutter:
  uses-material-design: true

My main.dart file
import 'package:fluent_ui/fluent_ui.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const FluentApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}


text:
Q: Global sections of a tangent sheaf of a blown-up surface. Let $V$ be a smooth projective algebraic surface and let $\pi\colon V'\to V$ be a blowup of a point $p\in V$. I would like to ask if the following is true:
$h^{0}(V,\Theta_{V})=h^{0}(V', \Theta_{V'})$,
where $\Theta_{X}$ denotes the tangent sheaf to $X$. I am particularly interested in the case of rational surfaces.
As far as I know, we have $\pi_{*}\Theta_{V'}=\mathfrak{m}_{p}\cdot \Theta_{V}$ and $\pi^{*}\Theta_{V}=\Theta_{V'}\langle E \rangle (E)$, where $E$ is the exceptional curve of $\pi$ and $\Theta_{X}\langle D \rangle$ denotes the subsheaf of $\Theta_{X}$ consisting of vector fields tangent to a divisor $D$. However, I have no intuition on what the functors $\pi^{*}$ and $\pi_{*}$ do with the sheaf cohomology (and how to apply it to my original question). If someone knows a comprehensive guide I can learn such things, I would be very grateful for a reference.
Thank you for any help.

A: This is not true. For an example with rational surfaces, one can check that if $X_0=\mathbb P^2$ and $X_i$ is the blowup of $X_0$ at $i$ points in general position, then
$H^0(T_{X_0})=8$,
$H^0(T_{X_1})=6$,
$H^0(T_{X_2})=4$,
$H^0(T_{X_3})=2$, and $H^0(T_{X_i})=0$ for $i>3$.
One way to see why this is not true is as follows: Let $f: X\to Y$ be the blowup of $Y$ at a point. The cotangent sequence for the blowup is
$$
0\to f^* \Omega_Y \to \Omega_X \to \Omega_{X/Y}\to 0,
$$
with $\Omega_{X/Y}$ supported on the exceptional divisor $E$.
Dualizing and using that $\mathcal H\mathrm{om}(\Omega_{X/Y},\mathcal O_X)=0$ we get
$$
0\to T_X\to f^* T_Y\to \mathcal E\mathrm{xt}(\Omega_{X/Y},\mathcal O_X)\to 0.
$$
One can then check
$\mathcal E\mathrm{xt}(\Omega_{X/Y},\mathcal O_X) = \mathcal O_{E}(-E)=\mathcal O_{\mathbb P^1}(1)$.
Applying $H^0(-)$ and using that $H^0(f^* T_Y)=H^0(T_Y\otimes f_* \mathcal O_X)=H^0(T_Y)$ (since $f_* \mathcal O_X=\mathcal O_Y$), we get
$$
0\to H^0(T_X)\to  H^0(T_Y)\to H^0(\mathbb P^1)\to H^1(T_X)\to\cdots.
$$
Thus $H^0(T_X)=H^0(T_Y)$ if and only if $H^0(T_Y)\to H^0(\mathbb P^1)$ is the zero map, and you can check by a local calculation that for $Y=\mathbb P^2$ this is not the case.


text:
Q: Graphing and Analyzing Probit Regression I am currently analyzing a data set having to do with oak tree mortality. I am trying to understand the correlation between dead crowns (dead = 0, live = 1) and the distance to (1) nearest dead crown and (2) distance to nearest bay tree. (See Below).
I have run a probit regression model:
Living<-sample(0:1,10,replace=T)
    Dead_Dist<-c(158.68,99.62,64.42,64.42,86.92,117.77,41.81,41.81,54.73,64.35)
    Bay_Dist<-c(92.47,179.92,317.73,365.23,58.70,193.23,330.36,123.14,88.65,72.34)
    mydata<-cbind(Living,Dead_Dist,Bay_Dist)
    mydata1<-data.frame(mydata)
    myprobit <- glm(Living ~ Bay_Dist + Dead_Dist, family = binomial(link = "probit"),data = mydata1)
    myprobit

But I am at a loss for how to plot and interpret the results, as I am fairly new to R and regressions.
If anyone has suggestions with how to proceed with this analysis, I would appreciate it!

A: First, here are some fake results to consider using set.seed(8) before sampling Living:
Call:
glm(formula = Living ~ Bay_Dist + Dead_Dist, family = binomial(link = "probit"),
data = mydata)

Deviance Residuals:
Min       1Q   Median       3Q      Max
-1.7826  -1.0012   0.7055   0.8691   1.4256

Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept)  1.5650207  1.5138702   1.034    0.301
Bay_Dist    -0.0002185  0.0040025  -0.055    0.956
Dead_Dist   -0.0159294  0.0133800  -1.191    0.234

(Dispersion parameter for binomial family taken to be 1)

Null deviance: 13.460  on 9  degrees of freedom
Residual deviance: 11.793  on 7  degrees of freedom
AIC: 17.793

In this sample it would seem the effects are pretty weak (small estimates, similar in size to their standard errors), but we can't say with any certainty that the effects really are weak without more data. Nothing is crossing any conventional significance thresholds (for whatever those are worth), but this is to be expected with such a small sample. Distance to the nearest dead crown is doing more for the model than distance to the nearest bay tree though (larger z).
One thing you could do is check product terms (squared/cubed predictors and interactions), but this will cost precious degrees of freedom in a small sample. As for plotting, I'd recommend ggplot2. I'm somewhat new to that package myself, so I'll offer a very simple plot:
require(ggplot2);ggplot(mydata,aes(x=Dead_Dist,y=Living))+
geom_point(position=position_jitter(width=0,height=.04))+    #Jittering helps reduce overlap
stat_smooth(method='glm',family=binomial(link='probit'))+
scale_y_continuous('Probability of dead crown')+
scale_x_continuous('Distance to nearest dead crown')

The blue line is just the model of Living~Dead_Dist; this version doesn't control Bay_Dist. The black dots are the observations. I've only jittered them vertically (they're all 0 or 1, and it's not hard to tell which) because their horizontal position is meaningful. The dark area is the 95% confidence band.

A: First how to interpret the results. In the Probit model, you model the probability of success $\pi=\Phi(x'\beta)$, where $\Phi$ is the cumulative normal distribution. In other words $\Phi^{-1}(\pi)=x'\beta$. So the interpretation of the regression coefficients are a little bit weird! For example let's look at the summary of your model
> summary(myprobit)

Call:
glm(formula = Living ~ Bay_Dist + Dead_Dist, family = binomial(link = "probit"),
    data = mydata1)

Deviance Residuals:
    Min       1Q   Median       3Q      Max
-1.5314  -0.8864  -0.4853   0.9984   1.6558

Coefficients:
             Estimate Std. Error z value Pr(>|z|)
(Intercept)  1.557554   1.509486   1.032    0.302
Bay_Dist    -0.002704   0.003895  -0.694    0.488
Dead_Dist   -0.017399   0.014683  -1.185    0.236

(Dispersion parameter for binomial family taken to be 1)

    Null deviance: 13.460  on 9  degrees of freedom
Residual deviance: 11.707  on 7  degrees of freedom
AIC: 17.707

Number of Fisher Scoring iterations: 5

Here the estimated coefficient for Dead_Dist is -0.017399. What does that means? Well based on what I wrote above (i.e. $\Phi^{-1}(\pi)=x'\beta$) it means that if you increase the nearest dead crown by one unit (while keeping Bay_Dist variable unchanged) then $\Phi^{-1}$ of the probability that we observe a dead crown deceases by 0.017399. This is as I said a little bit weird but we need to live with it!
Now lets find the estimated probabilities and try to plot them in 3D.
> p=predict(myprobit, type = "response" )
> library(scatterplot3d)
> scatterplot3d(Bay_Dist,Dead_Dist,p,pch=19)


text:
Q: Swift - How to check if two users are present in JSQMessagesViewController? We are developing an iOS application which has a chat through JSQMessagesViewController and Firebase. When a message is sent by one user, the other user will receive a notification for the message. However, we desire a functionality where if the other user is in the chat, he should not receive the notification as he can already see all the chat-messages.
What is the best logic / way to implement this desired functionality?
Xcode 8.1, Swift 3, Firebase, JSQMessagesViewController

A: According to me there are two things that you can do:
1)You can use observers, like typing , for mapping two users when they are in private chat. Just make a status key on firebase and set it to true if two users are on chat page. In this case just don't send push as probably you are sending it from client end.
2)Or you can just ignore notifications when application is active when you see that payload has same user with which you are chatting.

A: You would probably need to add a presence management system. I did something similar on my app while using Firebase and JSQMessagesViewController, you could probably customize the system to your liking.
Depending on what you use database wise for incoming and outgoing messages with the JSQMessagesViewController library, you could probably set it up there as well.
Firebase has worked best for me for what you're looking to do:
https://firebase.google.com/docs/database/ios/offline-capabilities


text:
Q: Stackoverflow authentication data storage Maybe this question has been asked, but I couldn't find it with google and stackoverflow.
I have deleted all my cookies and yet after entering stackoverflow.com I'm asked to refresh the page, because I have been logged in.
How does stackoverflow.com authentication data storage works?


text:
Q: Sender's Sendmail says "stat=Sent" but recipent doesn't receive the message I am trying to figure out why sendmail is saying that it sends out an email but I actually never get it.
This is from the logs when the email is being sent out:  I have replaced the email address with some fake address and I have also replaced the name of the server with a fake hostname.
The most significant point of this information from the logs is that it shows that the "Message was accepted for delivery".
Do you guys have any suggestions as to why it seems like the message goes out but I never get the actual email?
Jun  2 14:34:40 server sendmail[9668]: o52IYeSi009668: --- 250 2.0.0 o52IYeSi009668 Message accepted for delivery
Jun  2 14:34:40 server sendmail[9667]: o52IYe9I009667: to=someone@someone.com, ctladdr=rick (500/500), delay=00:00:00, xdelay=00:00:00, mailer=relay, pri=30058, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (o52IYeSi009668 Message accepted for delivery)
Jun  2 14:34:40 server sendmail[9668]: o52IYeSj009668: <-- QUIT
Jun  2 14:34:40 server sendmail[9668]: o52IYeSj009668: --- 221 2.0.0 server.server.com closing connection
Jun  2 14:34:41 server sendmail[9670]: o52IYeSi009668: SMTP outgoing connect on [192.168.1.9]
Jun  2 14:34:41 server sendmail[9670]: o52IYeSi009668: to=<someone@someone.com>, ctladdr=<someone@server.server.com> (500/500), delay=00:00:01, xdelay=00:00:01, mailer=relay, pri=120368, relay=mailhost.worldnet.att.net. [207.115.11.17], dsn=5.1.1, stat=User unknown
Jun  2 14:34:42 server sendmail[9670]: o52IYeSi009668: o52IYgSi009670: DSN: User unknown
Jun  2 14:34:42 server sendmail[9670]: o52IYgSi009670: to=<rick@server.rickrodriguezjr.com>, **delay=00:00:00, xdelay=00:00:00, mailer=local, pri=31625, dsn=2.0.0,** ***stat=Sent*****

A: mailhost.worldnet.att.net informs you that the recipient is unknown. What you see as mail sent is the DSN sent to inform you of this fact.


text:
Q: Thread in my code does not work Here is the code, Results Activity should start if button is clicked:
 public class Tab19 extends Activity {

ImageButton button1;
SoundPool mSoundPool;
AssetManager assets;
int catSound;
int countLoadedSound;
Context mContext;
ProgressDialog dialog;
int count = 0;
TextView t;
boolean has_been_clicked = false;

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

    count = getIntent().getIntExtra("CountNum", 0);
    mContext = this;
    mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
    assets = getAssets();
    catSound = loadSound("catSound.mp3");

    button1 = (ImageButton)findViewById(R.id.button2);
    button1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            playSound(catSound);
            Intent firstIntent = new Intent(Tab19.this, Results.class);
            TextView t = (TextView)findViewById(R.id.t);
            t.setText("score: " + ++count +"/18");
            firstIntent.putExtra("CountNum", count);
            has_been_clicked = true;
            startActivity(firstIntent);
            finish();
        }
    });

    new Thread(
              new Runnable() {
                public void run() {
                  while (!has_been_clicked) {

                      try {
                            // Thread will sleep for 10 seconds
                            sleep(10*1000);

                      } catch (Exception e) {

                        }

                  }
                  Intent i=new Intent(getBaseContext(),Results.class);
                    i.putExtra("CountNum", count);
                  startActivity(i);
                  finish();
                  return;

                }

                private void sleep(int i) {
                    // TODO Auto-generated method stub

                }
              }
            ).start();   }

    @Override
    protected void onDestroy() {

        super.onDestroy(); }

        protected void playSound(int sound) {
            if (sound > 0)
                mSoundPool.play(sound, 1, 1, 1, 0, 1);
        }

        private int loadSound(String fileName) {
            AssetFileDescriptor afd = null;
            try {
                afd = assets.openFd(fileName);
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "Не могу загрузить файл " + fileName,
                        Toast.LENGTH_SHORT).show();
                return -1;
            }

            return mSoundPool.load(afd, 1);

} }

If button is not clicked Thread should start next Activity within 10 seconds, but it does  not happen, please help me find a mistake. Thanks in advance

A: Into your thread change the while loop into an if statement:
 if (!has_been_clicked) {
     try {
          // Thread will sleep for 10 seconds
          sleep(10*1000);
     } catch (Exception e) {
     }
}

A: I think you should change your code to
              boolean has_been_clicked = true;
              ...
              while (has_been_clicked) {
                  has_been_clicked = false;
                  try {
                        // Thread will sleep for 10 seconds
                        sleep(10*1000);

                  } catch (Exception e) {

                    }
              }
              Intent i=new Intent(getBaseContext(),Results.class);
                i.putExtra("CountNum", count);
              startActivity(i);
              finish();
              return;


text:
Q: Where to store Facebook access token in ASP.NET MVC? In my ASP.NET MVC app, when I authenticate the user with OAuthWebSecurity, Facebook sends back an ExtraData which contains the access token. Initially I thought of storing this in the database, but it says in the FB docs:

You should also remove the stored access token.

...when logging the user out.
So the token should be handled as a session variable, but in ASP.NET MVC I don't have session variables (or there are ways, but it's not a good pattern). What is the best way to store the FB user acess token for the session duration?
Thanks

A: What's wrong with using the session, and what do you mean by not having a session and "there are ways"?  Controller has a Session property.  Should be easy to store & retrieve your token in there.


text:
Q: Alert dialog EditText make the text/strings inputted masked with asterisk My current situation is when one of my item in recycler is deleted, it will prompt an alert dialog and it should be ask for a pin to open the item but then i can't mask all the strings being inputted in my alert dialog edittext.
Here is my current code and all the things that i have tried:
  final EditText passwordSales = new EditText(SalesHistoryActivity.this);
        passwordSales.setText("");
        passwordSales.setTransformationMethod(PasswordTransformationMethod.getInstance());
        passwordSales.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        AlertDialog alertDialog = new AlertDialog.Builder(SalesHistoryActivity.this).create();
        alertDialog.setTitle("Delete this sale?");
        alertDialog.setView(passwordSales);
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "CANCEL",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();

when i'm typing the password, it still show the text/string while typing.

A: Set the transformation after the input type :
// setting a type may change the transformation method
passwordSales.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
// override the transformation
passwordSales.setTransformationMethod(PasswordTransformationMethod.getInstance());
AlertDialog alertDialog = new AlertDialog.Builder(SalesHistoryActivity.this).create();

By the way in your case TYPE_NUMBER_VARIATION_PASSWORD is probably better than TYPE_TEXT_VARIATION_PASSWORD


text:
Q: RegEx: Capture character only if previous groups matching I'm implementing a regular expression to match an absolute URI as defined in RFC 3986.

*

*in the current state there is no capturing of path, query and fragment

*additionaly to the specified authority there are groups capturing user, password and the authless authority
Actually I'm able to capture the following URIs.
https://regex101.com/r/aXYPbl/2
RegEx

~^(?<scheme>.+?):(?://(?<authority>(?:(?<user>.+?)(?::(?<password>.+?))?@)+(?<authlessAuthority>.+)?))?$~

---
Examples

https://example.com
https://@example.com
https://user@example.com
https://user:password@example.com

My current problem URI is the second one. This URI is invalid and should not be matched while the @ character should not be captured within the authority while there is no authentication provided in the URI.
So my question is:
How can I exclude the @ character from the authority group if there is no authentication provided?
I'm sure it's pretty simple. But I currently lost my focus.

A: You may require the "authlessAuthority" group to start with any char but @:
^(?<scheme>.+?):(?://(?<authority>(?:(?<user>.+?)(?::(?<password>.+?))?@)?(?<authlessAuthority>[^@].*)?))?$
                                                                                ^^^^

Here, [^@] is a negated character class that matches any char but @.
See the regex demo
Also, you might be interested in an Email Address Regular Expression That 99.99% Works.


text:
Q: SQL Server: Group by First Character (i.e. Letter) How do I a query in SQL Server using T-SQL to return the counts of the first letter/character in a column's values?

A: SELECT SUBSTRING(FileName, 1, 1) as first_letter, COUNT(FileId)
FROM Files
GROUP BY SUBSTRING(FileName,1,1)
ORDER BY first_letter

I modified an example for Oracle that can be found here:
group by first character


text:
Q: If$ -log(f)$ is convex, is $f $automatically convex? Say I want to know if $f(x)$ is convex. Can I apply any convex function, strictly increasing function to it and preserve convexity?
Say $f(x),g(x)$ are convex and strictly positive and I want to know if $f(x)g(x)$ is convex, then can I say
$-log(f(x)g(x)) = -log(f)-log(g)$
Which would mean ANY product of strictly positive convex functions are also convex. This seems a bit too simple so I guess I'm missing something.

A: As already noted in the comments, if $f$ is convex and increasing and $g$ is convex, then $f \circ g$ is convex. If both $f$ and $g$ are $\mathcal{C}^2$, you can easily show this via derivatives:
$$
{(f \circ g)}'' = {((f' \circ g)g')}' = (f'' \circ g) {(g')}^2 + f'(g) g'' \geq 0
$$
if $f'', f', g'' \geq 0$. The proof can be given also for functions which are just continuous.
However the converse is not true at all, so from the convexity of $f \circ g$ you cannot deduce anything on the convexity of $g$. For instance, take $f(x) = x^3$ and $g(x) = \sqrt{x}$ as functions of $\mathbb{R}^+$. $g$ is not convex, but $f$ is convex and increasing and $f \circ g(x) = x^{\frac{3}{2}}$ is strictly convex. This test can help you only if $f$ is linear: then convexity is preserved in both directions (or, if $f$ is decreasing, is swapped with concavity).
Moreover, in general there is no hope that the product $fg$ is convex if $f$ and $g$ are convex. Take for example $f(x) = x^2$ and $g(x) = {(x-1)}^2$. You need additional conditions, for example it is sufficient that $f$ and $g$ are both positive and the derivatives $f'$ and $g'$ have pointwise the same sign. Again, it is useful to think to the differentiable case and noting the identity
$$
{(fg)}'' = f''g + g''f + 2f'g'.
$$


text:
Q: Create Event Trigger Based on Date Let's say currently I'm having a table which consists a column named as 'next_update' in date format, I can calculate the time left (in day) by simply subtract the value in 'next_update' with the current date using sql command, however, how could I able to create an event trigger that automatically update some data in this table to another table when the time left for example is equal to 2. I'm using postgresql as my database.
Appreciate and thank you for any help.

A: You can make a function in your database that when called: check date/time difference and update another table if necessary. You can achieve this by doing a simple batch script, which is called regularly by a cron job (Depends on OS) or pgAgent.


text:
Q: Facebook login breaks when Facebook app is installed I'm building an Android app that allows the user to log in with his facebook account. I followed the official tutorial and got it working perfectly.
That is untill I installed the facebook app on my phone.
When I try to log in and I press "log in with facebook" button I get a screen switch for half a second and then I get back to my login screen where I was before.
If I uninstall the app everythings works again. I believe the app is interfearing but I don't know how to handle it, I have found no one with my same problem.
I follow the official tutorial step by step, I have a main activity with a fragment containing a button.
Usually if you click the button the facebook login screen pops up and you're able to enter your credential.
Anyone know how to handle this?

A: Do you add you application package and hash to Android facebook app on developers.facebook.com ?
If you login using SDK UI, not installed Facebook app - key does not checked.


text:
Q: Table doesn't contain the foreign key column I am trying to make a table named of Reminder that while consist of username as a foreign key from table named as User. but I am getting table Reminder has no column named Username error on runtime.
Add user code.
package com.example.champ.remindme;
import android.app.AlertDialog;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SignUp extends AppCompatActivity {
EditText editUsername,editPassword,editEmail,editMobileNumber;
Button btnSignUpButton;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_up);
    editUsername = (EditText)findViewById(R.id.editUsername);
    editPassword = (EditText)findViewById(R.id.editPassword);
    editEmail = (EditText)findViewById(R.id.editEmail);
    editMobileNumber = (EditText)findViewById(R.id.editMobileNumber);
    btnSignUpButton = (Button)findViewById(R.id.btnSiginUpButton);
    db=openOrCreateDatabase("RemindMe", Context.MODE_PRIVATE, null);
    db.execSQL("create table IF NOT EXISTS User (Username TEXT PRIMARY KEY ,Password TEXT, Email TEXT, Contact_No INTEGER)");
}
public  void AddUser(View v){
    if(editUsername.length()==0||
            editPassword.length()==0||
            editEmail.length()==0||
            editMobileNumber.length()==0)
    {
        showMessage("Error", "Please enter all values");
        return;
    }
    db.execSQL("INSERT INTO User VALUES('"+editUsername.getText().toString()+"'," +
            "'"+editPassword.getText().toString()+ "'," +
            "'"+editEmail.getText().toString()+"',"+
            "'"+Integer.parseInt(editMobileNumber.getText().toString())+"');");

    showMessage("Success", "Record added");
}

public void showMessage(String title,String message)
{
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();
}
}

Add reminder code.
 package com.example.champ.remindme;
 import android.Manifest;
 import android.app.AlertDialog.Builder;
 import android.content.Context;
 import android.content.pm.PackageManager;
 import android.database.sqlite.SQLiteDatabase;
 import android.location.Address;
 import android.location.Geocoder;
 import android.os.Bundle;
 import android.support.v4.app.ActivityCompat;
 import android.support.v4.app.FragmentActivity;
 import android.view.View;
 import android.widget.EditText;
 import com.google.android.gms.maps.CameraUpdateFactory;
 import com.google.android.gms.maps.GoogleMap;
 import com.google.android.gms.maps.OnMapReadyCallback;
 import com.google.android.gms.maps.SupportMapFragment;
 import com.google.android.gms.maps.model.LatLng;
 import com.google.android.gms.maps.model.MarkerOptions;
 import java.io.IOException;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.List;

 public class AddEventPlace extends FragmentActivity implements  OnMapReadyCallback {

private GoogleMap mMap;
Double Latitude=0.0;
Double Longitude=0.0;
EditText edtAddress;
String username,item;
SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_event_place);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    edtAddress=(EditText)findViewById(R.id.Address);
    db=openOrCreateDatabase("RemindMe", Context.MODE_PRIVATE, null);
    db.execSQL("create table IF NOT EXISTS Reminder (" +
            "ID INTEGER PRIMARY KEY   AUTOINCREMENT," +
            "item TEXT not NULL," +
            "Time TIMESTAMP DEFAULT CURRENT_TIMESTAMP not NULL," +
            "Date DATETIME DEFAULT CURRENT_TIMESTAMP not NULL," +
            "x_coordinates REAL," +
            "y_coordinates  REAL," +
            "Username  TEXT," +
            "FOREIGN KEY(Username) REFERENCES User(Username));");
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    mMap.setMyLocationEnabled(true);
}

public void onSearch(View view)
{
    EditText location_tf = (EditText)findViewById(R.id.Address);
    String location = location_tf.getText().toString();
    List<Address> addressList = null;
    if(location != null || !location.equals(""))
    {
        Geocoder geocoder = new Geocoder(this);
        try {
            addressList = geocoder.getFromLocationName(location , 1);

        } catch (IOException e) {
            e.printStackTrace();
        }

        Address address = addressList.get(0);
        LatLng latLng = new LatLng(address.getLatitude() , address.getLongitude());
        Latitude=address.getLatitude();
        Longitude=address.getLongitude();
        //Latitude=0.0;
        //Longitude=0.0;
        mMap.addMarker(new MarkerOptions().position(latLng).title("Marker"));
        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

    }
}

 public  void Done(View view){
     username = getIntent().getStringExtra("Username");
     item = getIntent().getStringExtra("item");

     DateFormat timeFormat = new SimpleDateFormat("h:mm a");
     String time = timeFormat.format(Calendar.getInstance().getTime());
     DateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yy");
     String date = dateFormat.format(Calendar.getInstance().getTime());
     if(item.trim().length()==0||
             date.trim().length()==0||
             Longitude ==0.0||
             Latitude==0.0||
             username.trim().length()==0)
     {
         showMessage("Error", "Please enter all values");
         return;
     }
     db.execSQL("INSERT INTO Reminder (item, Time, Date, x_coordinates, y_coordinates, Username) VALUES(" +
             "'"+item+"'," +
             "'"+time+"'," +
             "'"+date+"',"+
             "'"+Longitude+"',"+
             "'"+Latitude+"',"+
             "'"+username+"'"+
             ");");

     showMessage("Success", "Record added");
 }

public void showMessage(String title,String message)
{
    Builder builder=new Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();
}
}

A: Let me make a guess, first you didn't have the Username column in Reminder, and you are trying to add that to the table?
The problem might be a table without Username column is already created because of previous version of the code and it is not able to re-create the table because it already exist.
You should create a DBHelper by extending SQLiteOpenHelper and then override onUpgrade method
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
        onCreate(db);

    }

More code to help you out -
public class DBHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "dpname.db";
    public static final String TABLE_NAME = "table1";
    public static final String COL1 = "col1";
    // More columns and tables ....
    private static final int DATABASE_VERSION = 2;
    //You should update database_version everytime you are trying to update the database, Note - data saved will be lost
    private static DBHelper mDbHelper;
    public void onCreate(SQLiteDatabase db) {
        String CREATE_FIRST_TABLE = "CREATE TABLE " + TABLE_NAME +
                "(" +
                COL1 + " INTEGER PRIMARY KEY ," +
                COL2 + " TEXT," +
                //... More columns
                ")";
        db.execSQL(CREATE_FIRST_TABLE);
        //.. Create More tables
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);

    }
    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    private DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // More functions to select, insert, delete, update records
    // Example a function to insert Post given below
    // Better make a class to hold your data structure for different tables

    public void insertDetail(String s1, String s2, Integer i1...){
         SQLiteDatabase db = this.getWritableDatabase();
         db.beginTransaction();
         try {
               ContentValues values = new ContentValues();
               values.put(COL1,i1);
               values.put(COL2,s1);
               //....
               db.insertOrThrow(TABLE_NAME, null, values);
               db.setTransactionSuccessful();
         } catch(SQLException e){
               //....
         } finally{
               db.endTransaction();
         }
    }

    public static synchronized DBHelper getInstance(Context context) {
       // Use the application context, which will ensure that you
       // don't accidentally leak an Activity's context.

       if (mDbHelper == null) {
           mDbHelper = new DBHelper(context.getApplicationContext());
       }
       return mDbHelper;
    }

}

Use this like this in your activity -
db = DBHelper.getInstance(getApplicationContext());
db.insertDetail(String1,String2,Integer1);

You should take a quick look at the android SQL Database documentation