text:
Q: Correct way to setup linux company share folder with usable permissions I've just started working for a small company that has a globally shared folder run from an Ubuntu file server (Raid 5, etc) shared by Samba.
The workstations (Centos) are all fstab setup to mount this samba share in their root file system -> /Data/.
The client fstab configs :
//10.1.1.3/DATA01 /DATA01 cifs  username=username,password=password 0 0

The samba configuration for the share :
[DATA01]
path = /DATA01
writeable = yes

Before I started the boss had decided he'd had enough of unix permissions and user mismatch "problems", so every workstation and server has the same user and group name (the current project name) - we'll call this project.  He'd also made sure that the User UID on every machine was identical - i'm not sure how important this is at a practical level.
So in short, a ls -l /Data results in items that are chowned by project : project.
This is what I've just walked into. My job here is to administer all of this, but i'll add i'm a windows programmer by experience so my Linux sysadmin knowledge is more theoretical than practical (I took the job to learn their industry as i'm attempting a career pivot).
So the setup works to an extent, as Bob and Mary can add/edit files etc under /Data and no "you do not have permission" errors happen, which I believe was the Boss' main boggle.  So it seems weird to me as security is totally out the window, but it practically works.
But this makes me terrified of when project finishes and project2 starts.  This is 3 months away and i'm not sure how to handle this.  I know he'll say "just  chown -R project2:project2 /Data, reimage all machines to have that user, and move on", but i'm sure there's a better solution.
So i'm wondering from this setup how can I have unique users manage /Data without causing "you do not have permission" errors?
Additionally I'm wondering is there a kind of linux equivalent of "Active Directory" that can be setup to administrate users and groups (for projects) in the company?  I've no idea how this problem is usually managed in the linux world.
And anything else I should consider?
Sorry if this is Linux 101 stuff but i'm not sure how it's typically managed and practically pulled off.

A: As it happens, the latest release of Samba can indeed provide a full Active Directory domain controller service, however it seems to me that your boss just doesn't want to deal with any account type restrictions, so this probably isn't going to work well.
It would be useful to see the stanza in the current Samba config that defines the /Data share, and the mount options on the client systems, to understand how it's working for you now.
EDIT: From the info provided, it looks like all the remote users get mapped to the  user on the server, It means that anyone can trash all the data there (accidentally or otherwise), and it most certainly isn't the best approach -- but it has the virtue of being brutally simple.
In terms of "best practice", first of all put the credentials for the mount in a file that's only readable by root, then specify it in the mount as credentials=filename.
Also, if you can arrange to have the server and the clients having the same uid and gids for the users, using the setuid option will ensure that files show up properly owned by their creators on the share, and you can apply standard unix group permissions to who can modify what file.


text:
Q: how to upload different file on the same form i try to upload different file on the same form. I want to add my file in my directory and name of file into my database. I can upload file in directory but into database it doesn't work.
this my controller
function tambahdata()
{
    $this->load->view('vtambah_mastersub');
    if ($this->input->post('submit')) {
        if (!empty($_FILES['picture']['name'])) {
            $config['upload_path'] = './assets/uploads';
            $config['allowed_types'] = 'gif|jpg|jpeg|png';
            $config['max_size'] = '40000';
            $config['max_width'] = '1288';
            $config['max_height'] = '1288';
            $config['file_name'] = "file_" . time();
            $this->load->library('upload');
            $this->upload->initialize($config);
            // if there was an error, return and display it
            if (!$this->upload->do_upload('picture')) {
                echo "errornya : ";
                echo $this->upload->display_errors();
            } else {
                echo "sukses";
                $gbr = $this->upload->data();
                $data = array(
                    'nm_gbr' => $gbr['file_name'],
                    'tipe_gbr'=>$gbr['file_type'],
                ) ;
            }
        }
        if (!empty($_FILES['pdf']['name'])) {
            $config['upload_path'] = './assets/uploads';
            $config['allowed_types'] = 'pdf';
            $config['max_size'] = '40000';
            $config['max_width'] = '1288';
            $config['max_height'] = '1288';
            $config['file_name'] = "file_" . time();
            $this->load->library('upload');
            $this->upload->initialize($config);
            // if there was an error, return and display it
            if (!$this->upload->do_upload('pdf')) {
                echo "errornya : ";
                echo $this->upload->display_errors();
            } else {
                echo "sukses";
                $pdf = $this->upload->data();
                $dataa = array(
                    'nm_pdf' => $pdf['file_name'],
                    'tipe_pdf' => $pdf['file_type'],
                );
            }
        }
        $this->m_mastersub->tambah($data,$dataa);
        redirect('mastersub');
    }
}

this my model
function tambah($gambar,$pdf){
    $kd_mastersub = $this->input->post('kd_mastersub');
    $nama = $this->input->post('nama');
    $picture = $gambar['nm_gbr'];
    $deskripsi = $this->input->post('deskripsi');
    $pdf = $pdf('nm_pdf');
    $video = $gambar('nm_video');
    $drive = $gambar('nm_drive');

    $data = array(
        'kd_mastersub' =>$kd_mastersub,
        'name_cate' =>$nama,
        'picture' => $picture,
        'description' =>$deskripsi,
        'pdf' => $pdf,
        'video' => $video,
        'drive' => $drive

    );
    $this->db->insert('tbl_mastersub',$data);
}

this my form

                        Picture

                        <input type="file" name="picture"  />

                        PDF

                        <input type="file" name="pdf"  />

this my error

any one can help me to solve this problem please, thanks

A: it looks like there are some typos in your code
try this instead
function tambah($gambar,$pdf){
    $kd_mastersub = $this->input->post('kd_mastersub');
    $nama = $this->input->post('nama');
    $picture = $gambar['nm_gbr'];
    $deskripsi = $this->input->post('deskripsi');
    $pdf = $pdf['nm_pdf'];
    $video = $gambar['nm_video'];
    $drive = $gambar['nm_drive'];

    $data = array(
        'kd_mastersub' =>$kd_mastersub,
        'name_cate' =>$nama,
        'picture' => $picture,
        'description' =>$deskripsi,
        'pdf' => $pdf,
        'video' => $video,
        'drive' => $drive

    );
    $this->db->insert('tbl_mastersub',$data);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting "Bye Bye Big Sur" error on installing Big Sur My current macOS version is 10.14.6 (18G103). I have downloaded Big Sur from App Store but when I am trying to install, I am getting error "Bye Bye Big Sur" when I click on installer.

A: That is not a macOS prompt. The icon is from Jamf, a mobile device management solution used by organisations to control devices. Your IT department has most likely blocked Big Sur. They control the dialog and text content. Contact your company or device administrator.


text:
Q: AS400 RPGLE Defining a display file in a module I have been reading on creating modules and service programs in ILE, but I can't find much on defining a display window (prompt screen) inside a module.  I have tried the following, but keep getting an error that the RECNO parameter (RRN here) is not defined (*RNF7004).
Any idea what I am doing wrong....or where I can get more info...
    H NOMAIN
    FWDWFACV   CF   E             WORKSTN
    F                                     SFILE(FACSFL:RRN)
    FZMFL01    IF   E           K DISK
    D/COPY CUSSRCV6/QCPYSRC,TOOLS
    P WDWFAC          B                   EXPORT
    DWDWFAC           PI
    DWFAC                            2A
    DWFDESC                         20A   options(*nopass)
    D RRN             S              3S 0 inz(0)
    D WKFLAG          S              1S 0
    /free

A: The RRN variable, which is attached to the display file, probably needs to be global (defined outside the module).


text:
Q: How to link a SunriseDD C library with a C++ app? I was looking for a lock-free hash table implementation in C or C++ and found one: SunriseDD. That was the good news :) For a few days I am trying to get this up and running but with no luck. I can compile downloaded sources as a static library using GCC C compiler. And I get libSunriseDD.a archive.
So far so good :D
I have created a simple C++ application to wrap the SunriseDD C implementation of the hash table. Here is the main.cpp:
#include <iostream>
#include <dd_data_dictionary.h>

using namespace std;

struct Node{
    int oid;
    int x, y;
};
struct HashTableEntry{
    Node *node;
    int idx;
};
void copyFunction(void * source, void * target){
    target = source;
}

template<typename T>class HashTableDD{
private:
    dd_dictionary objects;
public:
    HashTableDD() {
        objects = dd_new_dictionary(); // creating dictionary
        dd_set_object_copy_function_for_dictionary(objects, copyFunction); // setting copy function
    }
    ~HashTableDD() {
        dd_dispose_dictionary(objects);
    }
    bool insert(T obj, long key){
        return dd_add_object_for_key(objects, (char *)key, (void*)obj);
    }
    bool remove(long key){
        return dd_remove_object_for_key(objects, (char *)key);
    }
    T find(long key) {
        return (T)dd_object_for_key(objects, (char *)key, false);
    }
};

int main(int argc, char ** argv){
    HashTableDD<HashTableEntry*> *ht = new HashTableDD<HashTableEntry*>();
    HashTableEntry* hte = new HashTableEntry;
    hte->idx = 1;
    hte->node = NULL;
    ht->insert(hte, 1);
    HashTableEntry* hte2 = new HashTableEntry;
    hte2->idx = 2;
    Node n;
    n.oid = 10; n.x = 10; n.y = 10;
    hte2->node = &n;
    ht->insert(hte2, 2);

    HashTableEntry* ret = ht->find(1);
    if(ret != NULL){
        cout << "hte. idx: " << ret->idx << " node: " << ret->node << endl;
    }
    ht->remove(1);
    ht->remove(2);
    delete hte; delete hte2; delete ht;
    return 0;
}

But the linker is not happy about that:
:~/Desktop/HashTable$ make
Building file: main.cpp
Invoking: GCC C++ Compiler
g++ -ISunriseDD/build/../ -O0 -g3 -m64 -c -o"build/main.o" "main.cpp"
Finished building: main.cpp

Building target: build/HashTableDD
Invoking: GCC C++ Linker
g++ -LSunriseDD/build/ -lSunriseDD -o build/HashTableDD build/main.o
build/main.o: In function `HashTableDD':
/home/robertas/Desktop/HashTable/main.cpp:32: undefined reference to `dd_new_dictionary()'
/home/robertas/Desktop/HashTable/main.cpp:33: undefined reference to `dd_set_object_copy_function_for_dictionary(void*, void (*)(void*, void*))'
build/main.o: In function `HashTableDD<HashTableEntry*>::insert(HashTableEntry*, long)':
/home/robertas/Desktop/HashTable/main.cpp:40: undefined reference to `dd_add_object_for_key(void*, char const*, void*)'
build/main.o: In function `HashTableDD<HashTableEntry*>::find(long)':
/home/robertas/Desktop/HashTable/main.cpp:47: undefined reference to `dd_object_for_key(void*, char const*, bool)'
build/main.o: In function `HashTableDD<HashTableEntry*>::remove(long)':
/home/robertas/Desktop/HashTable/main.cpp:44: undefined reference to `dd_remove_object_for_key(void*, char const*)'
build/main.o: In function `~HashTableDD':
/home/robertas/Desktop/HashTable/main.cpp:36: undefined reference to `dd_dispose_dictionary(void*)'
collect2: ld returned 1 exit status
make: *** [build/HashTableDD] Error 1

Any ideas what am I doing wrong here? Do I link the SunriseDD library incorrectly?
BTW I have the following directory listing where my main.cpp resides:
+HashTable
|--+build
|   |--main.o
|---main.cpp
|--+SunriseDD
   |--+build
   |  |--libSunriseDD.a
   |  |--other object files
   |--headers and source files of SunriseDD

Thanks for the help!

A: Put -lSunriseDD last on the linker line. The linker processes arguments left to right, and searches libraries for currently undefined symbols when it processes a static library.
Also, unless the library is C++-aware, wrap includes in extern "C".
extern "C" {
  #include <dd_data_dictionary.h>
}


text:
Q: Method that determines if a number is 'insipid' So I have been tasked with writing a program that determines if a number is insipid or not. Meaning, if you take a number:
57 for example, and you add the square of each digit, 5*5 + 7*7, that is now the new number:74. And you keep doing that until you either get 58 which means the number is NOT insipid, or you get 1, meaning the number is. 58 will just repeat a sequence that always ends back on 58.
So I wanted to attempt it with some basic recursion but perhaps I misunderstand the use of recursion here.
Here are the two relevant methods I wrote:
public static boolean insipid(int num){

    int dig1 = 0, dig2 = 0, dig3 = 0; // num = 159 for example, dig1 would be 1. Default is 0 in case of a 2 digit number, dig1*dig1 = 0
    if(num == 58){ //The number is not insipid
        return false;
    }
    if(num == 1){ // the number is insipid
        return true;
    }

    if (num < 10){
        insipid(num * num);
    }
    if(num>99){
        dig1 = (int)(num / 100);
        dig2 = (int)((num - 100)/10);
        dig3 = num - (((int)(num / 10))*10);
        insipid(squaresum(dig1,dig2,dig3));
    }
    else{
        dig2 = (int)(num/10); //the 10s place
        dig3 = num - (((int)(num/10)) * 10); // the 1's place
        insipid(squaresum(dig1, dig2,dig3)); //dig1 = 0 so I just pass it along with it.
    }
}

public static int squaresum(int dig1, int dig2, int dig3){
    //Returns the sum of three digits squared.
    return (dig1 * dig1) + (dig2 * dig2) + (dig3 + dig3);
}

It gives me an error saying that Insipid() must return a boolean whenever I supply it a number. But I know for any number given it will always either eventually resolve to 58 or 1. So shouldn't true or false always eventually be returned so a boolean is returned and the error is invalid? Obviously this is not the case, but how I see it. Is it the use of the recursion here that is invalid?
Also, if you have any suggestions on how I might clean this up I wouldn't mind harsh criticism, my java is not very good.

A: If you went with your solution, the only thing missing is the return statements from the recursive calls to incipid.

A: Update you insipid as below. A method declared with return must return values in all cases. Your method doesn't return any value if it reach second else i.e. if number is anything other than 1 & 58.
public static boolean insipid(int num){
  boolean returnValue = false;
  if(num == 58){ //The number is not insipid
   //do nothing
  } if(num == 1){ // the number is insipid
    returnValue = true;
  }else{
    int dig1 = 0, dig2 = 0, dig3 = 0; // num = 159 for example, dig1 would be 1. Default is 0 in case of a 2   digit number, dig1*dig1 = 0
    if (num < 10){
        returnValue = insipid(num * num);
    }
    else if(num>99){
        dig1 = (int)(num / 100);
        dig2 = (int)((num - 100)/10);
        dig3 = num - (((int)(num / 10))*10);
        returnValue = insipid(squaresum(dig1,dig2,dig3));
    }
    else{
        dig2 = (int)(num/10); //The 10s place
        dig3 = num - (((int)(num/10)) * 10); //the 1s place
        returnValue = insipid(squaresum(dig1, dig2,dig3)); //dig1 = 0 so I just pass it along with it.
    }
  }
  return returnValue ;
}

Please Note: I just tried to answer your issue regarding return issue ONLY.

A: In addition to Yogendra Singh's answer, you're calculating digits incorrectly: e.g. with
dig2 = (int)((num -100)/10);

you're assuming that the hundreds digit is 1.  Try
dig2 = (int)((num - dig1 * 100)/10);

and similarly for dig3.


text:
Q: R function is well and functioning but I'm not getting the exact results Ok, first let me define the project I'm working on and what I need as results. I have this data of 332 comma separated value files which is actually the US department of health's statistical data on pollution parameters for nitrate and sulphate pollutants. There are 332 IDs for a list of 332 entities that monitored pollution across all cities and I have to conduct some analysis on it.
So the data table looks something like this:
Date (yyyy-mm-dd)    sulphate      nitrate     ID
xxxx-xx-01           some value    some value  5
xxxx-xx-02           some value    some value  5

So theres daily data for monitor number 5. Similar is with the rest of the 332 IDs.
Now my job requires me to write a function that displays the number of non-NA values according to each ID. Ok? Which means that if I specify ID 1, then the function will process the data table and provide me with a simple data frame with the ID number and the number of non-NA values for that ID.
Now, my current function performs the fact manner as it should if I specify only one ID. but when I specify a combination of IDs, the function provides me the sum of all IDs specified, that is not what i  want actually.
This is the full function:
complete <- function(directory, id = 1:332){
file.list <- list.files(directory, full.names = TRUE) ## list of files need to be read
pollutant.data <- data.frame() ## forming an empty data frame
for (i in 1:332){
     pollutant.data <- rbind(pollutant.data, read.csv(files))} ## final data frame
ID <- pollutant.data[which(pollutant.data[,'ID'] %in% id),] ## for the id vector that needs to be specified in the function
good <- complete.cases(pollutant.data)
nobs <- sum(complete.cases(ID)) ## sum of complete data according to ID
return(data.frame(id, nobs = nobs))
}

Now when I specify say, id = 1, the function give me the correct result. But when I specify more than 1 ID, like so, c(3,6,4), it provides me with the addition of all the three IDs with each row for individual ID, and that is where I'm unable to resolve.
Now, I believe that I need to work on the for loop to specify that sum needs to be found for each ID, I tried inserting the for loop between the good and nobs vector but still I get the wrong values.

A: This line is the culprit:
ID <- pollutant.data[which(pollutant.data[,'ID'] %in% id),]

You are asking for all of the IDs that match the vector you pass, so you are in no way separating by ID.
A leaner way to do it is:
# Generate a mock dataset
test.data <- data.frame(ID = rep(1:5, each = 10), value = rnorm(50))
# Every 5th element is NA
test.data$value[seq(1, 50, 5)] <- NA

countComplete <- function(data.frame, id)
  {
  # Get only the subset of data we need (only requested id)
  tmp <- subset(data.frame, ID %in% id)

  # Split it by ID
  tmp.split <- split(tmp, tmp$ID)

  # Use sapply to count complete cases for the different IDs
  res <- sapply(tmp.split, function(x){
    sum(complete.cases(x))
    })

  # Return the result
  res
  }

For instance:
countComplete(test.data, c(1,3))

Returns
1  3
8  8


text:
Q: How to validate read and secure documents in CouchDB? In 10 Common Misconceptions about CouchDB, Joan Touzet is asked (30:16) if CouchDB will have a way to secure/validate reads on specific documents and/or specific fields of a document.
Joan says that if someone has access to the database, he/she can access all documents in that database.
So she says that there are a few ways to accomplish that:

*

*(30:55) Cloudant was working on field level security access. Have they implemented it yet? Is it open-sourced?

*(32:10) You should create separate document in a separate database.

*(32:20) Filtered replications. She mentions that it slows 'things' down. She means that the filter slows the replication, correct?

Also, according to rcouch wiki (https://github.com/rcouch/rcouch/wiki/Validate-documents-on-read), it implements a validate_doc_read function (I haven't tested it, though). Does CouchDB has anything like it?
As far as I can see, the best approach is to model the database according to my problem (one database for this, another for that, one for this person, another for that person) and do filtered replications when necessary. Any suggestions?


text:
Q: How to fix an error in SQL query in a Winforms application I'm trying to insert data to a table called ansat (vagtplan). I'm currently writing a WinForms application which uses a SQL Server database, but I still get an error and I can't really see in the code where the error is.
I think, that it must be an error with the SQL query, because when I try to insert data to a table pressing a button, then I get following error message:

Incorrect syntax near 'ansatID, Navn, Efternavn, Adresse, Email, Mobilnr'.

Desired result is a message box with 'Saved', which will confirm, that data are inserted to the table ansat(vagtplan). I have gone through the query many times, but I can't really see where the error is located, so my question is: where is the error located? Maybe should the query be formulated in another way? Here is the code:
private void button1_Click(object sender, EventArgs e)
{
   try
    {
        String ConnectionString = @"Data Source=.\SQLEXPRESS01;Initial Catalog=Vagtplan;Integrated Security=True";
        SqlConnection myconnection = new SqlConnection(ConnectionString);
        myconnection.Open();

        SqlCommand AddCommand = myconnection.CreateCommand();
        AddCommand.CommandText = "INSERT INTO ansat(vagtplan) ([ansatID, Navn, Efternavn, Adresse, Email, Mobilnr]) VALUES (@ansatID, @Navn, @Efternavn, @Adresse, @Email, @Mobilnr)";

        AddCommand.Parameters.AddWithValue("@ansatID", textBox8.Text);
        AddCommand.Parameters.AddWithValue("@Navn", textBox1.Text);
        AddCommand.Parameters.AddWithValue("@Efternavn", textBox2.Text);
        AddCommand.Parameters.AddWithValue("@Adresse", textBox3.Text);
        AddCommand.Parameters.AddWithValue("@Email", textBox6.Text);
        AddCommand.Parameters.AddWithValue("@Mobilnr", textBox7.Text);

        AddCommand.ExecuteNonQuery();

        myconnection.Close();
        MessageBox.Show("Saved");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

A: The insert statement is wrong. It should be something like this:
INSERT INTO ansat(ansatID, Navn, Efternavn, Adresse, Email, Mobilnr)
VALUES(@ansatID, @Navn, @Efternavn, @Adresse, @Email, @Mobilnr)

No need to specify the database as its already mentioned in the connection string.

A: You may try the following query:
INSERT INTO vagtplan.dbo.ansat ([ansatID], [Navn], [Efternavn], [Adresse], [Email], [Mobilnr]) values (@ansatID, @Navn, @Efternavn, @Adresse, @Email, @Mobilnr)

A: The issue is with your command text "INSERT INTOansat(vagtplan) ([ansatID, Navn, Efternavn, Adresse, Email, Mobilnr]) values (@ansatID, @Navn, @Efternavn, @Adresse, @Email, @Mobilnr)";
INSERT statement syntax is: Insert into <tableName>(<column1>,<column2>) Values(<column1Value>,<column2Value>);

*

*Your INSERT statement's table name seems wrong. It seems ansat is schema name and vagtplan is table name, it should be like ansat.vagtplan or [ansat].[vagtplan]

*Column names should be like [column1],[column2]. You have added all columns in a single []; that's wrong.

A: Right click the table in SQL Server Management studio and then script, then INSERT into script. This will give you a SQL insert script for inserting into your table.  You can use this script as a basis to create your code.

A: Thanks for all responses :) I havde figured it out and it works now, but another problem has occured. Now I'm trying to insert data to two tables related to each other through Foreign Key. Table dbo.Ansatte has a primary key called ansatID and table dbo.Login_data has a primary key called brugerID and foreign key AnsatID, which reference to primary key ansatID in table dbo.Ansatte. The primary key in both tables are inserted incrementally when the query s running. I have tried to set IDENTITY_INSERT to ON (in ms sql server management studio), but it doesn't help as I still get error message that IDENTITY_INSERT is set to OFF. The problem is, that after running the query, foreign key AnsatID in table dbo.Login_data is still NULL despite the fact that foreign key AnsatID reference to primary key called ansatID in table dbo.Ansatte. Desired result is that foreign key AnsatID in table dbo.Login_data has the same value as primary key ansatID in table dbo.Ansatte. This also shown on the picture below:
enter image description here
So, how to value from primary key into the foreign key?
Here is my code:
private void button1_Click(object sender, EventArgs e)
    {
        {
            try
            {
                String ConnectionString = @"Data Source=.\SQLEXPRESS01;Initial Catalog=Vagtplan;Integrated Security=True";
                SqlConnection myconnection = new SqlConnection(ConnectionString);
                myconnection.Open();

                SqlCommand AddWorkerCommand = myconnection.CreateCommand();
                AddWorkerCommand.CommandText = "INSERT INTO dbo.Ansatte ([Navn], [Efternavn], [Adresse], [Postnummer], [Bynavn], [Email], [Mobilnr]) VALUES ( @Navn, @Efternavn, @Adresse, @Postnummer, @Bynavn, @Email, @Mobilnr)";

                AddWorkerCommand.Parameters.AddWithValue("@Navn", textBox1.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Efternavn", textBox2.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Adresse", textBox3.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Postnummer", textBox4.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Bynavn", textBox5.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Email", textBox6.Text);
                AddWorkerCommand.Parameters.AddWithValue("@Mobilnr", textBox7.Text);
                AddWorkerCommand.ExecuteNonQuery();

                SqlCommand AddUserCommand = myconnection.CreateCommand();
                AddUserCommand.CommandText = "INSERT INTO dbo.Login_data ([Brugernavn], [Adgangskode], [Brugertype]) VALUES ( @Brugernavn, @Adgangskode, @Brugertype)";

                AddUserCommand.Parameters.AddWithValue("@Brugernavn", textBox10.Text);
                AddUserCommand.Parameters.AddWithValue("@Adgangskode", textBox9.Text);
                AddUserCommand.Parameters.AddWithValue("@Brugertype", textBox8.Text);
                AddUserCommand.ExecuteNonQuery();

                myconnection.Close();
                MessageBox.Show("Saved");
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
    }


text:
Q: Spring MappingJackson2HttpMessageConverter not getting triggered? I have a fairly old Java 8 / Spring app which provides a REST API. The response is sent in either JSON or XML depending on the Accept Header.
So for example

*

*application/json-v1 converts the response to JSON of version 1 of the
response object

*application/json-v2 - converts the response to JSON
of version 1 of the response object

*application/xml-v1 - converts the
response to XML of version 1 of the response object

The app is in Spring 5 now but was initially in Spring3 and this aspect has never been converted to use code config.
So the core config XML is has this
<!-- Enables the Spring MVC @Controller programming model, and set converters in use -->
    <mvc:annotation-driven>
        <message-converters>
            <beans:bean class="com.packagpath.AppJaxb2RootElementHttpMessageConverter">
                <beans:property name="supportedMediaTypes">
                    <beans:list>
                        <beans:bean class="org.springframework.http.MediaType">
                            <beans:constructor-arg index="0" value="application"/>
                            <beans:constructor-arg index="1" value="xml"/>
                        </beans:bean>
                        <beans:bean class="org.springframework.http.MediaType">
                            <beans:constructor-arg index="0" value="application"/>
                            <beans:constructor-arg index="1" value="xml-v1"/>
                        </beans:bean>
                        <beans:bean class="org.springframework.http.MediaType">
                            <beans:constructor-arg index="0" value="application"/>
                            <beans:constructor-arg index="1" value="xml-v2"/>
                        </beans:bean>
                    </beans:list>
                </beans:property>
            </beans:bean>

            <beans:bean class="com.packagpath.AppMappingJackson2HttpMessageConverter">
                <beans:property name="supportedMediaTypes">
                    <beans:list>
                        <beans:bean class="org.springframework.http.MediaType">
                            <beans:constructor-arg index="0" value="application"/>
                            <beans:constructor-arg index="1" value="json"/>
                        </beans:bean>
                        <beans:bean class="org.springframework.http.MediaType">
                            <beans:constructor-arg index="0" value="application"/>
                            <beans:constructor-arg index="1" value="json-v1"/>
                        </beans:bean>
                        <beans:bean class="org.springframework.http.MediaType">
                            <beans:constructor-arg index="0" value="application"/>
                            <beans:constructor-arg index="1" value="json-v2"/>
                        </beans:bean>
                    </beans:list>
                </beans:property>
            </beans:bean>
            <beans:bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
        </message-converters>
    </mvc:annotation-driven>

    <beans:bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    </beans:bean>

The controllers have the produces attribute set along these lines
@RequestMapping(method = RequestMethod.GET, value = AppController.RESOURCE_NAME + "/{id}", produces = {
            XML_MIME_TYPE_DEFAULT, JSON_MIME_TYPE_DEFAULT, XML_MIME_TYPE_V1, JSON_MIME_TYPE_V1,
            XML_MIME_TYPE_V2, JSON_MIME_TYPE_V2 })
    @ResponseBody
    public Person getAccount(@PathVariable(value = "id") String id, HttpServletRequest request) { ...

The main override class for the JSON handler is along these lines...
public class AppMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
    private Utils utils = new Utils();

    /**
     * Init method must be called to ensure the object mapper used by this converter ignores null fields.
     */
    @PostConstruct
    public void init() {
        System.out.println("init 1");
        getObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
        System.out.println("init 2");

    }
//
    @Override
    protected void writeInternal(Object responseObject,  HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        System.out.println("VersionConversion versionConversion");
    ...

So having set the scene. The XML version works well.
    public class AppJaxb2RootElementHttpMessageConverter extends Jaxb2RootElementHttpMessageConverter {
        private Utils utils = new Utils();

        @Override
        protected void writeToResult(Object responseObject, HttpHeaders headers, Result result) throws IOException {
            VersionConversion versionConversion = AnnotationUtils.findAnnotation(responseObject.getClass(), VersionConversion.class);
...

The basic config seems to work for the JSON message handler as if I put a configured Mime type in the header it returns a JSON document but if I put a non existent version it throws an error.
However the writeInternal method never gets called and so any version change code is never reached. I've looked at this from a few angles and I can't work out why. The clumsy Init 1, init2 print statements get output to the console. I'm sure it used to work but I can't see what is different now and as it is all wired in Spring I'm not sure how to investigate any further than looking at the code for errors!
If anyone knows what the issue might be that would be fantastic, at the moment though I'm not sure how & where to investigate as a) the code definitely used to work and b) I can't see anything wrong in the config that has changed.  I'm wondering if it is a change in the dependencies that I didn't notice at the time ?


text:
Q: Twitter OAuth with Android - Still getting a 401 but no glue where the mistake is located I'm experiencing some problems regarding Twitter OAuth within an android activity. I read a lot of tutorials and example code, but I'm still not able to receive the access token.
Everytime I try to authorize I'm getting this OAuthNotAuthorizedException:
oauth.signpost.exception.OAuthNotAuthorizedException: Authorization failed (server replied with a 401). This can happen if the consumer key was not correct or the signatures did not match.

I googled a lot and it felt like I read thousands of solutions, but none of them worked out for me. Hope you can help me with this one (and I'm not bothering your with the same old newbie question! ;) )
Here is my complete activity code:
package de.ownor.moremote;

import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MakeTweet extends Activity {
    public static final String CONSUMER_KEY = "Y0iYMkUgNX8kKgvDjzFgg";
    public static final String CONSUMER_SECRET = "nuBZd8UGml5cjbm94Hf6dWOwIByrisZWpSnqODaUB5Q";
    public static final String CALLBACK_URL = "de.ownor.moremote://twitter";
    private static final String REQUEST_URL = "https://api.twitter.com/oauth/request_token";
    private static final String ACCESS_TOKEN_URL = "https://api.twitter.com/oauth/access_token";
    private static final String AUTH_URL = "https://api.twitter.com/oauth/authorize";
    public static final String PREFS_NAME = "TwitterLogin";
    public static final String TAG = "moremote - MakeTweet";

    private Twitter twitter;
    private CommonsHttpOAuthProvider provider;
    private CommonsHttpOAuthConsumer consumer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        System.setProperty("http.keepAlive", "false");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.make_tweet);

        twitter = null;
        if (!checkForSavedLogin()) {
            askOAuth();
        }

        getConsumerProvider();
    }

    @Override
    protected void onResume() {
        super.onResume();
        System.out.println("RESUMING!!");
        if (this.getIntent() != null && this.getIntent().getData() != null) {
            Uri uri = this.getIntent().getData();
            if (uri != null && uri.toString().startsWith(CALLBACK_URL)) {
                String verifier = uri
                        .getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
                try {
                    // this will populate token and token_secret in consumer

                    // /////////////////////////////
                    // exception is thrown here! //
                    // /////////////////////////////
                    provider.retrieveAccessToken(consumer, verifier);

                    // Get Access Token and persist it
                    AccessToken a = new AccessToken(consumer.getToken(),
                            consumer.getTokenSecret());
                    storeAccessToken(a);

                    // initialize Twitter4J
                    twitter = new TwitterFactory().getInstance();
                    twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
                    twitter.setOAuthAccessToken(a);
                    ((ApplicationEx) getApplication()).twitter = twitter;

                } catch (Exception e) {
                    // Log.e(APP, e.getMessage());
                    e.printStackTrace();
                    Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG)
                            .show();
                }
            }
        }
    }

    private void askOAuth() {
        try {
            consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY,
                    CONSUMER_SECRET);
            provider = new CommonsHttpOAuthProvider(REQUEST_URL,
                    ACCESS_TOKEN_URL, AUTH_URL);
            provider.setOAuth10a(true);
            String authUrl = provider.retrieveRequestToken(consumer,
                    CALLBACK_URL);
            Toast.makeText(this, "Please authorize this app!",
                    Toast.LENGTH_LONG).show();
            setConsumerProvider();
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
        } catch (Exception e) {
            Log.e(TAG, "Error in askOAuth");
            e.printStackTrace();
            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private Boolean checkForSavedLogin() {
        // Get Access Token and persist it
        AccessToken a = getAccessToken();
        if (a == null) {
            Log.d(TAG, "No saved Login found");
            return false;
        }

        // initialize Twitter4J
        twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(a);
        ((ApplicationEx) getApplication()).twitter = twitter;

        return true;
    }

    private AccessToken getAccessToken() {
        SharedPreferences settings = getSharedPreferences(PREFS_NAME,
                MODE_PRIVATE);
        String token = settings.getString("accessTokenToken", "");
        String tokenSecret = settings.getString("accessTokenSecret", "");
        if (token != null && tokenSecret != null && !"".equals(tokenSecret)
                && !"".equals(token)) {
            return new AccessToken(token, tokenSecret);
        }
        return null;
    }

    private void storeAccessToken(AccessToken a) {
        SharedPreferences settings = Preferences.getPreferences(this);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("accessTokenToken", a.getToken());
        editor.putString("accessTokenSecret", a.getTokenSecret());
        editor.commit();
    }

    private void getConsumerProvider() {
        CommonsHttpOAuthProvider p = ((ApplicationEx) getApplication()).provider;
        if (p != null) {
            provider = p;
        }
        CommonsHttpOAuthConsumer c = ((ApplicationEx) getApplication()).consumer;
        if (c != null) {
            consumer = c;
        }
    }

    private void setConsumerProvider() {
        if (provider != null) {
            ((ApplicationEx) getApplication()).provider = provider;
        }
        if (consumer != null) {
            ((ApplicationEx) getApplication()).consumer = consumer;
        }
    }
}

The exception is thrown in the onResume()-Method. I marked the exact line. I really hope anyone can help me here. If you need further information just scream!
Thanks!
Simon.

A: I finally managed to get the OAuth running. Unless I don't know the exact error. I guess it was some issue with the consumer.
Here is my running code:
onCreate:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.twitter);

    pref = Preferences.getPreferences(this);
    consumer = new CommonsHttpOAuthConsumer(Key.TW_CONSUMER_KEY,
            Key.TW_CONSUMER_SECRET);
    provider = new CommonsHttpOAuthProvider(Key.TW_REQUEST_TOKEN_URL,
            Key.TW_ACCESS_TOKEN_URL, Key.TW_AUTHORIZE_URL);
    provider.setOAuth10a(true);

    [...]

    if (getIntent().getData() == null) {
        checkForSavedLogin();
    }
}

onResume:
protected void onResume() {
    super.onResume();

    Uri uri = getIntent().getData();
    if (uri != null
            && Key.TW_CALLBACK_URI.getScheme().equals(uri.getScheme())) {
        String token = pref.getString(Key.TW_REQUEST_TOKEN, null);
        String secret = pref.getString(Key.TW_REQUEST_SECRET, null);
        try {
            if (!(token == null || secret == null)) {
                consumer.setTokenWithSecret(token, secret);
            }
            String otoken = uri.getQueryParameter(OAuth.OAUTH_TOKEN);
            String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);

            Assert.assertEquals(otoken, consumer.getToken());

            provider.retrieveAccessToken(consumer, verifier);
            token = consumer.getToken();
            secret = consumer.getTokenSecret();
            saveAuthInformation(token, secret);
            // Delete request information
            saveRequestInformation(null, null);

            if (!(token == null || secret == null)) {
                Log.d(TAG, "Twitter login found!");
                consumer.setTokenWithSecret(token, secret);
                twitter = new TwitterFactory().getInstance();
                twitter.setOAuthConsumer(Key.TW_CONSUMER_KEY,
                        Key.TW_CONSUMER_SECRET);
                twitter.setOAuthAccessToken(new AccessToken(token, secret));
            }
        } catch (Exception e) {
            Log.d(TAG, "Couldn't receive token" + e.getMessage());
            e.printStackTrace();
        }
    }

    [...]
}

other methods:
private void checkForSavedLogin() {
    if (pref.contains(Key.TW_USER_TOKEN)
            && pref.contains(Key.TW_USER_SECRET)) {
        token = pref.getString(Key.TW_USER_TOKEN, null);
        secret = pref.getString(Key.TW_USER_SECRET, null);
        if (!(token == null || secret == null)) {
            Log.d(TAG, "Twitter login found!");
            consumer.setTokenWithSecret(token, secret);
            twitter = new TwitterFactory().getInstance();
            twitter.setOAuthConsumer(Key.TW_CONSUMER_KEY,
                    Key.TW_CONSUMER_SECRET);
            twitter.setOAuthAccessToken(new AccessToken(token, secret));
        }
    } else {
        Log.d(TAG, "No Twitter login saved - asking for OAuth");
        askOAuth();
    }
}

private void askOAuth() {
    try {
        String authUrl = provider.retrieveRequestToken(consumer,
                Key.TW_CALLBACK_URI.toString());
        saveRequestInformation(consumer.getToken(),
                consumer.getTokenSecret());
        Toast.makeText(this, "Please authorize this app!",
                Toast.LENGTH_LONG).show();
        this.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                .parse(authUrl)));
    } catch (OAuthException e) {
        e.printStackTrace();
    }
}

private void saveRequestInformation(String token, String secret) {
    // null means to clear the old values
    SharedPreferences.Editor editor = pref.edit();
    if (token == null) {
        editor.remove(Key.TW_REQUEST_TOKEN);
    } else {
        editor.putString(Key.TW_REQUEST_TOKEN, token);
    }

    if (secret == null) {
        editor.remove(Key.TW_REQUEST_SECRET);
    } else {
        editor.putString(Key.TW_REQUEST_SECRET, secret);
    }

    editor.commit();
}

private void saveAuthInformation(String token, String secret) {
    pref = Preferences.getPreferences(this);
    Editor editor = pref.edit();
    editor.putString(Key.TW_USER_TOKEN, token);
    editor.putString(Key.TW_USER_SECRET, secret);
    editor.commit();
}

Feel free to use this code... :)

A: ¿Are you using
mHttpOauthprovider = new DefaultOAuthProvider("https://api.twitter.com/oauth/request_token",
            "https://api.twitter.com/oauth/access_token",
            "https://api.twitter.com/oauth/authorize");
with HTTPS protocol?


text:
Q: How to send js string from chrome extension content script to php I am trying to make a chrome extension which will scrap text data from certain websites(when i visit the page) and save it in a SQL database. The js for data scrapping is working fine and it can save all data I need in a string. Now I want to send that js string to a localhost php file I have using XAMPP, but looks like the php can't receive the string I send.
My js code snippet for sending data
$.post("http://localhost:8080/naukri/index.php",            //link to localhost php
    {variable: finalVal},                               //finalVal contains the string I want to send
    function(data) {if (data != "") {
    alert('We sent Jquery string to PHP : ' + data);                //alert shows the string I am sending
    window.open("http://localhost:8080/naukri/index.php");  //open php page to confirm if data received or not
    console.log(data);    //SOLVED use this instead of window.open()
    }
});

My php code
$test;
$test = $_POST['variable'];
echo $test;  //just checking if string received or not, I will worry about inserting into SQL later.

Now the alert shows the correct string that I am trying to send but the php page shows this error
" Notice: Undefined index: variable in C:\xampp\htdocs\naukri\index.php on line 4"

I think which means that the php file haven't received the string I am sending.
Please tell me how to successfully send string from js to php.

A: Your issue here is that your opening your calling your php file twice.

*

*The first thing your doing is sending a post request to your php file.

*Then your trying to check whether it was received or not by opening your php page in another window (via a get request).

These two calls to your file are completely separate, and therefore the data passed in the first request is not available in your second as php is stateless.
If you want to check whether your web-extention is working properly with your php, you'll have to check what the ajax request actually returned, rather than calling the page a second time. Open up your browsers developer tool's network tab to check.


text:
Q: Reconocimiento facial para el control de datos     if result[1] < 70:
        cv2.putText(frame,'{}'.format(imagePaths[result[0 ]]),(x,y-25),2,1.1,(0,255,0),1,cv2.LINE_AA)
        cv2.rectangle(frame, (x,y),(x+w,y+h),(0,255,0),2)

        cara= format(imagePaths[result[0 ]])
        nombrecara=str(cara)
        cararesult=(result[1] < 70)
        contador= 1

        if cararesult is True:
          print(nombrecara+  "   DETECTADO")

    else:
        cv2.putText(frame,'Desconocido',(x,y-20),2,0.8,(0,0,255),1,cv2.LINE_AA)
        cv2.rectangle(frame, (x,y),(x+w,y+h),(0,0,255),2)

        return frame

Como se puede apreciar en el codigo en la parte de if cararesult is True me imprime a quien esta detectando en la consola, pero el problema es que se imprimi sin fin de veces debido a los fotogramas que va leyendo en el video stream, quisiera saber alguna manera para hacer que me envie el nombre de (persona x) cada determinado tiempo y solo una vez, igual cuando detecte a mas personas haga lo mismo , solo la muestre una vez, intente con time.sleep pero detiene el codigo y yo quisiera que siguiera corriendo el programa mientras hace lo anterior.
Quisiera alguna ayuda o alguna forma para que se puediera realizar cierta accion


text:
Q: Bootstrap col-sm-offset-2 does not align button in form Why doesn't the col-sm-offset-2 line up button 'two' with the col-sm-2 labels above it in this form?

I have a lame fix for it using the empty label (see button 'one'), but I want to understand how to use cleaner code and make this right so all my forms don't have the kludge label in them for buttons.
<form class="form-horizontal" role="form" action="/company/create" method="post">

     <%= label_tag(:name, 'Company name:', :class => 'control-label col-sm-2') %>

        <%= text_field_tag(:name, @company.name, :class => 'form-control') %>

     <%= label_tag(:category, 'Category:', :class => 'control-label col-sm-2') %>

        <%= collection_select(nil, :category_id, Category.all, :id, :description, :include_blank => 'select') %>

    <%= label_tag(:x, '', :class => 'col-sm-2') %>

        <button type="submit" class="btn btn-primary">one</button>

     <button type="submit" class="btn btn-primary col-sm-offset-2">two</button>

</form>

A: Step 1: build a DIV around your button.
Step 2: give that DIV the class of "col-sm-2 col-sm-offset-2".
Step 3: place your BUTTON inside that DIV
Step 4: give me feedback if that solved your issue.

   <button type="submit" class="btn btn-primary">two</button>

A: Try this one:

         <button type="submit" class="btn btn-primary">two</button>


text:
Q: Grant "full disk access" to sandboxed applications permanently I'm using Microsoft Office 2016 (not 365) on macOS High Sierra. There's an annoying issue where I can open files normally but when I select a file from the "recently opened" menu it opens a dialog where I need to choose the file and grant permission. But I have already gave permission, not once, not twice, but multiple times. It seems likes Office just "forgets" about its permission to open files that it has already opened each restart.
I tried to disabled the sandbox by first changing com.apple.security.app-sandbox from true to false in the binary, and by signing it manually with the same entitlements but com.apple.security.app-sandbox disabled, both of which did not crash the application but did not solve the issue: now there is no files in the "recently opened" menu, which defeats the whole purpose. I'm sure that it can now open any file it wants, but that's useless without a "recently opened" menu.
Is there a way to grant full disk access to a sandboxed application permanently?


text:
Q: How to assign values to IEnumerable I have the following code:
var db = Database.Open("Text");
var headers = db.Query("SELECT * FROM Headers");

//headers is now an IEnumerable<dynamic>

string s = headers[0].Text; // Works correctly

headers[0].Text = "Some string";

If I try to assign "Some string" to the Text property of the headers I get the following error:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: WebMatrix.Data.DynamicRecord contains no definition for Text.
How can I convert the headers object to a List/Array so that I am able to assign new values to it?

A: The problem is that the DynamicRecord class being returned from WebMatrix is effectively 'read-only'.  The DynamicObject does not allow setting of Text.
You would need to map this data onto your own classes if you want to make changes to the values, and not leave them within the original dynamic type.


text:
Q: Differences in behavior after passing arguments to function in Python For this code below:
def add_minor(person):
    person.append('math')
def switch_majors(person):
    person=['physics']
    person.append('economics')
John=['computer_science']
Tim=John
add_minor(Tim)
switch_majors(John)
print(John, Tim)

Can someone explain why the output is:
['computer_science', 'math'] ['computer_science', 'math']
How come "John" did not change major?
In addition, for the two pieces of code below:
a=[3,4]
b=[6,7]
def do_stuff(a,b):
    a+=[5]
    b+=[8]
    return a,b
do_stuff(a,b)

and
a=3
b=5
def do_stuff(a,b):
    a+=1
    b+=2
    return a,b
do_stuff(a,b)

How come the values for a and b changed in the do_stuff function when they are lists but not when they are numbers?
Lastly, why does the follwing code return None values?
a=[3,4]
b=[6,7]
def do_stuff(a,b):
    return(a.append(6), b.append(8))
do_stuff(a,b)

Thanks

A: def add_minor(person):
    person.append('math')

here person is not mutated, you call append on the object that was passed as argument, explaining why Tim is modified
def switch_majors(person):
    person=['physics']
    person.append('economics')

after first line, person refer to a totally new object ( ['physics'] ).
when you append economics to the array, it is the new object that is modified, the initial value John that was passed as argument remains untouched.
More globally, modifying the value of an argument (like a += 6) does not modify it outside the function scope explaining why append works in function : it does not modify the variable but rather the internal state of the object (i.e. the list elements)
Lastly :
a=[3,4]
b=[6,7]
def do_stuff(a,b):
    return(a.append(6), b.append(8))
do_stuff(a,b)

do_stuff return (None,None) because a.append(6) and b.append(8) both returns None, that is normal behaviour since the append method does not return anything

A: 1st question:
You changed it in line person=['physics']
The same is with this easier example
person=[1,2,3]
person.append(4)
print(person) # prints [1,2,3,4]
person=[1] # assigning to [1] again
print(person) # prints [1]

2nd question:
Lists are mutable
Numbers don't change because int is immutable
https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747
Also this is useful:
There are 2 ways to add to list, lets say you have this line example=[1,2]:
example+=[3]
print(example) # [1,2,3]

example.append(3)
print(example) # gives the same output [1,2,3]

3rd:
You need to change it to this becase append() doesn't return a value
a=[3,4]
b=[6,7]
def do_stuff(a,b):
    a.append(6)
    b.append(8)
    return(a, b)
print(do_stuff(a,b))


text:
Q: Formatting emails from crontab with ssmtp I've seen a number of examples on how to setup ssmtp but can't seem to find clear answers how to configure crontab to send data to an email.
What I want to accomplish is a crontab config that will send emails with system stats

*

*every 12 hours

*at each boot. (@reboot)

I've installed and configured ssmtp correctly since I can send emails by doing for example
printf "Subject:Test\n\rthis is a test\n\r" |ssmtp mail@domain.com"
and it works exactly as intended. However doing the exact same thing from cron results in command being treated as a string to mail. All backquotes are ignored.
Here I set it to every minute:
MAILTO="mail_user@domain.com"
* * * * * bash -c 'printf "Subject:Test\n\rthis is (`date`) a test\n\r" | ssmtp mail_user@domain.com'

And Receive:

SUBJECT:
Cron <user@host> printf "Subject:Test\n\rthis is (`date`) a test\n\r" |/usr/bin/ssmtp mail_user@domain.com`
CONTENT:
bash: ssmtp: command not found

where user@host is my local user and pc host and mail_user@domain.com is the actual email that should be used to send data.
I tried providing full path /user/bin/ssmtp instead of just ssmtp to no avail
Disclaimer:
This is a reduced example, there's more data that I want to mail to my monitoring email (A gmail account)
UPDATE
I had to change form /usr/bin/ssmtp to /usr/sbin/sftmp which shows my problem is somewhat different than I initially thought. The emails are sent correctly, but at the same time crontab is sending the old "email" with command as string in subject. I removed all MAILTO= sections from my crontab, but while I can still send my correct emails, I still have CRON commands (not sure how to better phrase it) written out into my e-mail.
So to sum up - I'm getting two emails per crontab task, one being an actual email, and the other being delivery failure with atempt to mail username@hostname from email_user@gmail.com


text:
Q: Get lazy children set by Criteria I have a Parent class and a Child class with the current setup
@Entity
public class Parent {
   @OneToMany(mappedBy = "parent")
   private Set<Child> children;

   @Column
   private int type;
}

@Entity
public class Child {
   @ManyToOne
   @JoinColumn(name = "parent_id")
   private Parent parent;
}

For some functions, I want to when querying the parent based on its type, the child is automatically retrieved and filled into the set.
This is what I have tried so far
res = getSession().createCriteria(
   Parent.class, "parent"
).createAlias(
   "parent.children", "children"
).add(
   Restrictions.eq("parent.type", type)
).setFetchMode(
   "children", FetchMode.JOIN // FetchMode.SELECT
).list();

When I run the unit test, the getter is always equals to Null (I do have data and relationship in database)
Parent parent = new Parent();
parent.setType(ParentType.WEEK);
parentDao.save(parent);

Child child = new Child();
child.setParent(parent);
childDao.save(child);

List<Parent> res = parentDao.findByType(0, 10, ParentType.WEEK, true);

assertNotNull(res.get(0).getChildren());
assertEquals(1, res.get(0).getChildren().size());

How can I fix this ?

A: You're creating a parent, wil a null children list, and persisting it. The Parent instance is thus stored in the first-level cache.
Then you're creating a child and persist it.
Then you're executing a query that retrieves the parent you've just created. Hibernate thus gets the ID from the database, sees that the ID is one of a Parent entity that is already in the cache, and thus returns that Parent instance. And since you' have not set its children list, it's still null.
It's your responsibility to maintain the coherence of the entity graph in memory. Hibernate only cares about the owning side of the association. By setting a child's parent, but not adding the child to the parent's children, you have introduced an incoherence in the graph of entities. Everything will be fine in database because the owning side of the association is correctly initialized.
If you start a new transaction and execute the query, the children list will be correctly populated. Similarly if you clear the session before executing the query. But inside the same transaction, Hibernate doesn't automagically initialize one side of the association when you initialize the other.


text:
Q: Sharing large mmaped data file across machines in Linux Cluster Say I have a 1 TB data file mmapped read/write from the localy mounted hdd filesystem of a "master" linux system into the virtual address space of a process running on this same "master" system.
I have 20 dedicated "slave" linux servers connected across a gigabit switch to the "master" system.  I want to give random read access to this 1 TB on these "slave" servers by mmaping it read-only into their process address spaces.
My question is what is the most efficient way of synchronizing (perhaps lazily) the dataset from the master system to the slave systems?  (for example is it possible to mount the file over NFS and then mmap it from there?  if yes, is this the best solution?  if no, what is a solution?)

A: I have been playing around with an idea like this at work recently (Granted this was with significantly smaller file sizes). I believe NFS would be fine for reads but you might hit problems with concurrent writes. Providing you have only one "writer" then your idea should work reasonably well. If the data file is structured, I'd recommend going for a distributed cache of some description and allowing multiple copies of the data spread across the cluster (for redundancy).
In the end we went for a SAN and clustered file system solution (in our case Symantec VCS, but any generic clustered filesystem would do). The reason we did this is because we couldn't get the performance we required from using pure NFS. The clustered file system you choose would need to support mmap properly and a distributed cache.


text:
Q: Automatically update a field on one model after saving another [Django 1.11][Python3.x] I am learning how to use the post_save signal on Django. Though I am not getting any errors, what I want to do will not work.
I have a model (Model) that is supposed to aggregate and average the ratings from the Review model and saves that number in a field called "average_rating."
I want the averaging to be done once a user provides a rating on the "Review" model and for the average rating to automatically be calculated and updated on the "Model" model.
I know that I can do this with a post_save signal. But I am not sure how.
How can I do what I am trying to do?
Thanks in advance.
models.py
from django.db import models
from django.db.models import Func, Avg
from django.urls import reverse
from django.template.defaultfilters import slugify
from django.db.models.signals import post_save
from django.dispatch import receiver

class Model(models.Model):
    name = models.CharField(max_length=55, default='')
    slug = models.SlugField(unique=True)
    average_rating = models.DecimalField(decimal_places=1,
                                            max_digits=2,
                                            default=0.0,
                                            blank=True,
                                            null=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.average_rating = self.review_set.aggregate(
                    rounded_avg_rating=Round(Avg('rating')))['rounded_avg_rating']
        self.slug = (slugify(self.name))
        super(Model, self).save(*args, **kwargs)

class Review(models.Model):
    RATING_CHOICES = [
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
        (5, '5'),
    ]
    model = models.ForeignKey(Model,
                                null=True)
    rating = models.IntegerField(choices=RATING_CHOICES,
                                    default=1)
    review_date = models.DateField(auto_now_add=True)
    reviewer = models.ForeignKey(User,
                                    null=True,
                                    related_name = 'review_user')
    comment = models.TextField(default='')

    class Meta:
        verbose_name_plural = 'Reviews'
        verbose_name = 'Review'

    def __str__(self):
        return self.model.name

@receiver(post_save, sender=Review)
def update_average_rating(sender, instance, **kwargs):
    instance.average_rating = Review.objects.aggregate(
                rounded_avg_rating=Round(Avg('rating')))['rounded_avg_rating']

Update:
Using the solution provided by RajKris, I got this:
class Review(models.Model):
    ....

    def save(self, *args, **kwargs):
        Model.save(avg_rating_flag=True)
        super(Review, self).save(*args, **kwargs)

Now I am getting this error: TypeError: save() missing 1 required positional argument: 'self'
RajKris's updated answer fixed my problem. Works like a charm.
def save(self, *args, **kwargs):
    super(Review, self).save(*args, **kwargs)
    model_obj = self.model
    model_obj.average_rating = model_ob.review_set.aggregate(
                rounded_avg_rating=Round(Avg('rating')))['rounded_avg_rating']
    model_obj.save()

A: In your Review save function:
def save(self, *args, **kwargs):
    super(Review, self).save(*args, **kwargs)
    model_obj = self.model
    model_obj.average_rating = model_obj.review_set.aggregate(
                rounded_avg_rating=Round(Avg('rating')))['rounded_avg_rating']
    model_obj.save()

What happens here is that,  each time a review object is created the corresponding Model object get updated with the new average rating.


text:
Q: FindAndModify missing in mongodb C# driver I am using Mongodb shell 3.2.4 and C# driver 2.2.3. I have even installed legacy driver 2.2.3 but still facing following problem.
I want to use AutoIncremented value for one of my field i.e eventID so I am trying to use FindAndModify but I cannot seem to find it.
_client = new MongoClient();
_database = _client.GetDatabase("users");
var counters = _database.GetCollection<BsonDocument>("counters");
var counterQuery = Query.EQ("_id", "eventId");

var findAndModifyResult = counters.FindAndModify(
      new FindAndModifyArgs()
      {
          Query = counterQuery,
          Update = Update.Set("web", "testweb")
     });

But I get following error:
Error   2   'MongoDB.Driver.IMongoCollection<MongoDB.Bson.BsonDocument>' does not contain a definition for 'FindAndModify' and no extension method 'FindAndModify' accepting a first argument of type 'MongoDB.Driver.IMongoCollection<MongoDB.Bson.BsonDocument>' could be found (are you missing a using directive or an assembly reference?)

Attaching screenshot

A: In the new 2.0 driver, this is now called FindOneAndUpdate.
You have a mix of the old legacy, and new format in your question - Query.EQ is also from the legacy driver - so I suggest removing that legacy driver as the first step.
Then you should be able to get what you need by using the Builders, for example:
var _client = new MongoClient();
var _database = _client.GetDatabase("users");
var counters = _database.GetCollection<BsonDocument>("counters");
var counterQuery = Builders<BsonDocument>.Filter.Eq("_id", "eventId");

var findAndModifyResult = counters.FindOneAndUpdate(counterQuery,
              Builders<BsonDocument>.Update.Set("web", "testweb"));


text:
Q: why is "read" through each line of a file much faster than "xargs" I have a large input file which contains 30M lines, new lines in \r\n. I decided to do something silly and compare the speed of counting all lines via read -r compared to xargs (stripping the \r first, because xargs does not seem to be able to split on multiple characters). Here are my two commands:
time tr -d '\r' < input.txt | xargs -P 1 -d '\n' -I {} echo "{}" | wc -l

time while read -r p || [ -n "$p" ]; do echo "$p"; done < input.txt | wc -l

Here, the second solution is much faster. Why is that?
Please note that I know that this is not a proper way to count lines of a file. This question is merely out of interest of my observation.

A: Yes, as you suspected, xargs -P 1 -d '\n' -I {} echo "{}", which is actually the same as xargs -rd '\n' -n1 as echo is the default command, will fork a process and execute the standalone echo in the child process while waiting for its termination in the parent for each line of input.
So that's a lot more work than even using the inefficient read builtin and the echo builtin all in the same shell process.
If instead of GNU xargs, you use busybox xargs which (at least in some configurations and recent versions) will call the busybox echo internally without forking a process, you'll notice it will be significantly faster than the bash loop.
For a more relevant comparison, you should compare:
tr -d '\r' | xargs -rd'\n' -n1

with
tr -d '\r' |
  while IFS= read -r line || [ -n "$line" ]; do
   /bin/echo "$line"
  done

Which are likely to give you similar outcomes as the bulk of the time will be spent forking processes and executing  the standalone echo.
Here, on the output of seq 3e7 and measuring with pv -al > /dev/null (to measure throughput in average number of lines per second), I get around:

*

*1.12M/s for busybox xargs

*70k/s for bash loop with builtin echo

*860/s for GNU xargs

*850/s for bash loop with /bin/echo


text:
Q: reverse geocode a set of co-ordinates I have sets of co-ordinates in the following format

(-33.9,18.6)

How do I go about getting the name of the nearest town or Country for those co-ords? I'm guessing it will involve Javascript, but am happy to also use PHP if appropriate?
EDIT: Am trying the Google Reverse Geocoder but having trouble with it. The following code is pretty identical to one of their examples but doesn't seem to be running at all... any ideas why?
<script type="text/javascript" charset="utf-8">
            function reverseGeocode(lat,lon){

                var geocoder = new GClientGeocoder();
                var latlng = new GLatLng(lat, lon);
                geocoder.getLocations(latlng, function(addresses) {
                    alert(addresses);
                });

            }
        </script>

A: google has a webservice you can call to do (reverse) geocoding, which is much more lightweight then using the full javascript api.
an example with v2: http://maps.google.com/maps/geo?q=51,4&sensor=false&output=json&key=insert_your_api_key_here&callback=parseme
and with v3:
http://maps.google.com/maps/api/geocode/json?latlng=51,4&sensor=false&callback=parseme
in both cases you get a json response (javascript object), the difference being that in the now deprecated v2 you need to provide you api key and you can use a callback (for cross site ajax goodness) which for crying out loud isn't supported in v3 any more (but you don't need an api key any more).

A: Google maps API has a javascript example.
http://code.google.com/apis/maps/documentation/services.html#ReverseGeocoding

A: Have you registered for their API key?
Also are there any specific error messages?

A: Ok managed to get it working, so here's what I did:
<script src="http://maps.google.com/maps?file=api&v=2&key=INSERTAPIKEYHERE" type="text/javascript"></script>
function reverseGeocode(latitude,longitude){

            var geocoder = new GClientGeocoder();
            var latlng = new GLatLng(latitude, longitude);

            geocoder.getLocations(latlng, function(addresses) {
                var address = addresses.Placemark[0].address;
                var country = addresses.Placemark[0].AddressDetails.Country.CountryName;
                var locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;

                alert(address);
            });
        }


text:
Q: GnuPG homedir read/write permission I am trying to decrypt a tar file with GnuPG through a Python script on Win7.
filename_e_archive = askopenfilename()
current_directory = os.path.abspath('.')
folder_d_archive = filename_e_archive.split('.elog')[0]
filename_d_archive = folder_d_archive + ".tar.gz"
path_to_e_archive = os.path.dirname(filename_e_archive)
path_to_d_archive = os.path.join(path_to_e_archive,'/',folder_d_archive)
os.makedirs(path_to_d_archive)
os.chdir(path_to_d_archive)

gpg = gnupg.GPG()

with open(filename_e_archive, 'rb') as f:
    status = gpg.decrypt_file(f, passphrase='mypassword',output=filename_d_archive)

When run I got the following error:

C:\LA>python test.py Traceback (most recent call last):   File
  "test.py", line 30, in
      gpg = gnupg.GPG()   File "C:\Python27\lib\site-packages\gnupg\gnupg.py", line 125, in init
      ignore_homedir_permissions=ignore_homedir_permissions,   File "C:\Python27\lib\site-packages\gnupg_meta.py", line 183, in init
      self.homedir = os.path.expanduser(home) if home else _util._conf   File "C:\Python27\lib\site-packages\gnupg_util.py", line 765, in
  set
      getattr(obj, self.fset.name)(value)   File "C:\Python27\lib\site-packages\gnupg_meta.py", line 440, in
  _homedir_set ter
      raise RuntimeError(str(ae)) RuntimeError: Homedir ''C:\LA\gnupghome.config\python-gnupg'' needs read/write permissions
C:\LA>

A: I was able to solve the issue by removing the gnupg library:

pip uninstall gnupg

and installing the phyton-gnupg one

pip install python-gnupg

Docs: python-gnupg - A Python wrapper for GnuPG

A: This issue was also present with the latest version. Removing the gnupg and installing the python-gnupg solved the matter on win11/pycharm 2022.3


text:
Q: Interacting With Contract Web3.js I have been trying to interact with a contract on the AVAX chain using web3js and it keeps throwing the error, "TypeError: Cannot read properties of undefined (reading 'send')". I cannot figure out why this is happening, as it should be a valid statement. If anyone can help that would be awesome.
  const contract = new Contract(*abi*, '0x82194f7d4Ded53A546ec4e3A7a57f81C5a54E194');
  console.log("transaction sent");
  await contract.methods.transfer(address, amount).send({to: "0xxxxxx"});
  console.log("transaction sent really");
}

Also, is it acceptable to paste the abi directly into the constructor in between [] brackets, like so? const contract = new Contract(*abi*, '0x82194f7d4Ded53A546ec4e3A7a57f81C5a54E194');
Here is the Contract ABI
    "status": "1",
    "message": "OK",
    "result": "[{\"inputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"burn\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"burnFrom\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"mint\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"
  }]

A: The ABI needs to contain just the function and event definitions that are stored in your result property. Without the wrapper object containing status and other properties.
So in your case
const abi = [{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"burnFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"mint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"}];


text:
Q: How can i secure my wamp/www/Folder-name so that no one can play with the contents of my website I have created a local server in my computer lab and hosted a website on it so that people on same network can use it.I am using wamp and php for my website. The computer which is made server is also used by some students so I want to secure my website from being stolen or any changes in the code by students. How can I do it?
My website is stored at the location wamp/www/my-website


text:
Q: VC++ projects keep being out of date I have a solution which contains both C# and C++/CLI projects. My problem is that the C++ projects are always out of date, and the IDE keeps asking if I want to build them.
There are some custom build steps, which copy some files here and there, and I suspect that might cause the issue (?). I'd be fine with disabling up-to-date check for these projects (if there's no other way), because they are not going to be modified for now. How can I do that?
Please note, this question is very similar, but not a duplicate.

A: Check whether during build (or post build) tasks, you change a dependency, which determines (of course) a new, fresh build.
Another possibility is that you mentioned as part of the custom build task, a dependency that doesn't really exist (e.g. an external file with the wrong name or path).


text:
Q: cordova-plugin-ms-adal issues with chrome version 83+ I encountered some issues with cordova-plugin-ms-adal after the latest google chrome update (83), i assume the issues comes from the OOR-CORS update which they made on the chrome webview.
When i call app.authContext.acquireTokenAsync(resourceUrl, appId, redirectUrl), the promise is never resolved and i think that the response from Azure AAD is blocked somewhere.
I don't see any errors related to CORS and i also can't find how to update my app in order to be OOR-CORS compliant. Anyone is experiencing the same issue? (any chrome under 83 works as expected).
Updated:

The thing that is refreshing is the create context method which will be called twice, one time when i enter the page and second time when i'm refreshing the same page. (This fixes the adal blocked response)
When i'm calling the app.authContext.acquireTokenAsync it will never receive any response from AD until i do the first page reload, after that it will always work as expected.

A: In order to identify the issue, I would suggest you to look at the networks calls made with a chrome browser under 83 and compare it with chrome browser 83. The aim is to look for any difference in the response returned due to CORS headers etc. This might help you identify what has changed due to which promise is not resolved.
Since there is no CORS error being shown in console, I expect the response of the api is affected due to CORS implementation.
Another suggestion is to use adal-for-js (link) instead of adal-for-cordava (link) as the later is depcreated and not maintained any more. Any bug fixes which could affect newer browser would require you to patch it directly which could be cumbersome effort, IMO.


text:
Q: How to see GraphViz output from Julia REPL? I'm trying to follow this tutorial which uses GraphViz to display a diagram. When running the first piece of code:
using Decapodes, Decapodes.Diagrams
using Catlab.Present, Catlab.Graphics

Variable = @decapode Decapodes2D begin
  C::Form0{X}
end;

draw_equation(decapode) = to_graphviz(decapode, node_labels=true, prog="neato",
  node_attrs=Dict(:shape=>"oval"),
  graph_attrs=Dict(:nodesep=>"4.0"))

draw_equation(Variable)

I get the following output in the Julia REPL:
Catlab.Graphics.Graphviz.Graph("G", true, "neato", Catlab.Graphics.Graphviz.Statement[Catlab.Graphics.Graphviz.Node("n1", OrderedCollections.OrderedDict{Symbol, Union{String, Catlab.Graphics.Graphviz.Html}}(:label => "C:Ω₀"))], OrderedCollections.OrderedDict{Symbol, Union{String, Catlab.Graphics.Graphviz.Html}}(:nodesep => "4.0", :rankdir => "LR"), OrderedCollections.OrderedDict{Symbol, Union{String, Catlab.Graphics.Graphviz.Html}}(:height => "0.05", :margin => "0", :shape => "oval", :width => "0.05"), OrderedCollections.OrderedDict{Symbol, Union{String, Catlab.Graphics.Graphviz.Html}}(:arrowsize => "0.5"))

I expect the diagram to show up in another window, but no such window is created.
I'm running MacOS Monterey 12.4, Julia 1.7, and have GraphViz installed via Home-brew as well as the GraphViz.jl package. How can I view the diagram?

A: You need to use Graphviz to generate the image.
Assuming graphviz is in your system path you can do:
using Catlab
open("out.pdf","w") do f
         write(f, Catlab.Graphics.Graphviz.run_graphviz(draw_equation(Variable);format="pdf"))
       end


text:
Q: Order Alphabetically inside SharedPreferences Is there any way to order the lines inside of SharedPreferences?
I'm trying to add keys with a number, but they are shown without order.
<string name="Score_3">96</string>
<string name="Score_1">256</string>
<string name="Score_4">26</string>
<string name="Score_2">0</string>

I would like to be shown like this. Is this possible?
<string name="Score_1">256</string>
<string name="Score_2">0</string>
<string name="Score_3">96</string>
<string name="Score_4">26</string>```
Thanks.


text:
Q: Link Azure devops repos and boards Hi am new to Azure devops and try to understand Repos and Boards.
Is there a way to link both (i.e Azure Repos and Azure Boards)
Any pointers would be useful.
Basically, I want to understand whether code commits can be connected to link Boards tasks or User story.
Thanks.

A: Yes, you can link work items with user stories. You can find useful information here: Linking Work Items to Git Branches, Commits, and Pull Requests

A: You can link a work item to a pull request.

And you can link a lot of items to a work item.


text:
Q: Need help to implement PhoneGap/Cordova ContentSync Plugin Have a question regarding contentsync phonegap plugin (https://www.npmjs.com/package/phonegap-plugin-contentsync).
Will be very appreciated if someone could help.
The core of the problem is that my REST server allowing me to download .epub files (witch are same as .zip)  only by sending GET request similar to:
https://test-api.books.com/api/getPublishedEpub?session_hash=1235&publication_id=abv1243'

Providing this link to the plugin '.sync' call I get a 'Invalid request method' response from the server...
While trying to download ordinary .zip everything works just fine.
var pub_id = $scope.currentBook.publication_id, epubUrl = 'https://test-api.books.com/api/getEpub?session_hash='
 + $rootScope.sessionHash+ '&publication_id=' + pub_id;

                        var downloadBtn = document.getElementById("downloadBtn");
                        console.log('Download cliked');
                        var sync = ContentSync.sync({ src: epubUrl, id: 'book'+ pub_id});

                        sync.on('progress', function (data) {
                                downloadBtn.innerHTML = "Downloading: " + data.progress + "%";
                        });

                        sync.on('complete', function (data) {
                                console.log(data.localPath);
                                for (var x = 1; x <= 17; x++) {
                                        var fileUrl = "file://" + data.localPath;
                                        console.log(fileUrl);
                                }

                                downloadBtn.innerHTML = 'Download';
                        });


text: Q: How do I document that a function allows an arbitrary amount of arguments in JSDoc? I have a few functions that accept an arbitrary amount of arguments. I've checked out the JSDoc @Param wiki but it doesn't mention the issue. How would you, for instance, document a function like console.log?


text:
Q: How does on enable Laptop task on Debian I am fresh installing Debian on my laptop and I am having a little bit of trouble with the installer, from reading this link about "What packages are installed by default in Debian?", I understand that the laptop task may contain features I may need.
But on my Debian installer (Both netinst and DVD.ISO) there is no option for this task and was wondering how can I get this to appear, Do I need a different iso e.g CD.ISO?
Thanks

A: Netinstall. Choose Laptop and Standard system.

A: In most cases you wouldn't need to worry about installing task-laptop in the installer.
All you need is a root login / sudo access on the installed system.  Then you can run the tasksel command to install selected tasks, from available package sources (as configured in the installer).  Most of the tasks are relatively small, apart from Desktop and perhaps Web Server.
New in recent versions of Debian (I think coinciding with the use of metapackages like task-laptop): you can also remove tasks if you decide you didn't need them, and it will more-or-less work.  (Previously it ended up removing too many packages).


text:
Q: Sybase Split Data on Delimeter I have a column which stores data as
"George|Michael|15-06-1984|New York"

Expected Output is
FIRST_NAME LAST_NAME DOB        CITY
George     Michael   15-06-1984 NEW YORK

How to split this data on delimiter - | while calling a select query in Sybase ?

A: You can make a procedure:
Here is a good solution:

sa_split_list system procedure replacement

Or you can use function called ParseName:

ParseName

Of course, you have to change your delimeter in select statement from , to |.


text:
Q: How to select unicode text from SQL in codeigniter active record? I have a very basic, yet important question that I have been struggling with for over 2 hours now.
Question
How to force (N) prefix when selecting from MS-SQL using CodeIgniter active record?
This is my code:
Controller:
$result = $this->users->login($uname, $password);

Model
function login($username = NULL, $password = NULL)
{
    if( !$username || !$password){
        return FALSE;
    }

    $this->db->select('CustomerID');
    $query = $this->db->get_where('UsersTbl',array('Username' => $username, 'Password' => $password));

    return $query->row_object();
}

Now, I have tried putting "N" before the $username in the model function call like:
array('Username' => 'N\''.$username, 'Password' => $password)), which constructs the SQL query as: WHERE Username = 'N'arabicText'
and tried putting the (N) after the field name, like the '<' or '>' trick in the form:
array('Username=N' => $username, 'Password' => $password))which constructs the SQL query as: WHERE Username =N 'arabicText' --> And for this to work, the (N) must be directly attached to the text, in the form: N'arabicText'
It all seems to fail...any ideas??

A: Ok, I found the answer.
First:
Change the call in the model to: $query = $this->db->get_where('UsersTbl',array('Username = N' => $username, 'Password' => $password));
Second:
In codeigniter *System/database/DB_active_rec.php* I've changed the way SQL is contructed in line 427 they add space to the value of "where": $v = ' '.$this->escape($v), Now I had to remove this space so that it becomes: $v = ''.$this->escape($v) or just $v = $this->escape($v)
Now when I check the $sql it self, it's just how I need it to be: SELECT CustomerID
FROM UsersTbl
WHERE Username = N'جاد'
AND Password = '123'
As you can see, the Password field is not affected by the change, because it only applies to the fields with operators =D


text:
Q: Infopath doesn't show buttons in view mode I made a custom view with infopath and i'm trying to make something that looks like a tabbed view. So you would be able to switch views using tabs like navigation. But my buttons doesn't show up once in view mode. I checked on google it says that buttons doesn't show in read-only view. But i checked in properties of my infopath view in my infopath designer and the read-only checkbox is unchecked. When I try to run it inside the InfoPath Designer Buttons show up and they work. But once published to my site they don't show on the item view page. Everything else shows up but the buttons doesn't.
Is this normal behavior or i did something wrong?

A: If you can change the buttons to picture buttons you can opt to not hide in read mode.

*

*Right click on button and change control to picture button

*Open the picture button properties

*General tab-> in picture section-> uncheck the "hide picture button in read only views"


text:
Q: Affine space endomorphism and fixed point
Let $K$ be a field and $\mathcal E$ be a finite dimensional affine space over $K$. Let $f:\mathcal E \rightarrow \mathcal E$ be an affine endomorphism. Assume that there is some point $A\in \mathcal E$ whose orbit under the action of $f$ has finite cardinality $k\in \mathbb N$, where $k$ is not a multiple of the characteristic of the field $K$. Prove that $f$ admits a fixed point.

I have been struggling trying to solve this exercise. Here is what I have found so far.
Let us assume that $k\geq 2$, otherwise there is nothing to do. The vector $v:= \overrightarrow{Af(A)}$ is not zero. We may express our hypothesis in terms of $v$ and of the linear part $\overrightarrow f$ of $f$. We have
$$f(A) = A + v$$
$$f^2(A) = f(A+v) = f(A) + \overrightarrow f(v) = A + v + \overrightarrow f(v)$$
Proceeding in a similar fashion and using induction, one may show that for every $i\in \mathbb N$,
$$f^i(A) = A + v+ \overrightarrow f(v) + \ldots + \overrightarrow f^{i-1}(v)$$
Using this identity and the fact that $f^k(A)=A$ lies the following
$$v+ \overrightarrow f(v) + \ldots + \overrightarrow f^{i-1}(v)=0$$
Now, any point of $\mathcal E$ can be written under the form $A+w$ for a unique vector $w$. Such a point is fixed by $f$ if and only if $v+\overrightarrow f(w) = w$. Thus, we must show that $-v$ lies in the image of $\overrightarrow f - Id$.
I can't progress any further though. I did notice that if $P$ denotes the polynomial $1 + X + \ldots + X^{k-1}$, then $1$ is not a root of $P$ as the characteristic of $K$ does not divide $k$. If we could prove that this polynomial is the minimal polynomial of $\overrightarrow f$ (or at least that all eingenvalues are roots of $P$), then we may conclude that $\overrightarrow f - id$ is an isomorphism and we would be done.

A: Let $B=\mathrm{Bar}(A,A^2,\dots,A^k)$ be the barycenter of $A,A^2=f(A),\dots,A^k=f^{k-1}(A)$, where $k$ is chosen such that $A^{k+1}=f^k(A)=A$ and such that none of the $A^i$ with $i\leq k$ are equal to $A$. Then
\begin{align*}
f(B)&=f(\mathrm{Bar}(A,A^2,\dots,A^k))=\mathrm{Bar}(f(A),f(A^2),\dots,f(A^k))\\
&=\mathrm{Bar}(A^2,A^3,\dots,A^{k+1})\\
&=\mathrm{Bar}(A^2,\dots,A^k,A)\\
&=\mathrm{Bar}(A,A^2,\dots,A^k)\\
&=B
\end{align*}
is a fixed point.


text:
Q: Java Threads - Start() Doing some studying about threads and I'm confused about what the start() method in Java threads actually do.
My current understanding is that the start method doesn't immediately start the thread's execution, but instead moves it to a pool of threads waiting for it be picked for execution by the thread scheduler.
Is this correct? I can't seem to find any good resources about what the methods actually do.

A: Exactly, when a call to start() is performed, it just schedules the call to run().  You cannot determinate when the thread will effectively be launched, nor when it will effectively be stopped.
You can find more information in the Java Doc on oracle's website.

A:
start
public void start() Causes this thread to begin execution; the Java
  Virtual Machine calls the run method of this thread. The result is
  that two threads are running concurrently: the current thread (which
  returns from the call to the start method) and the other thread (which
  executes its run method).
Throws: IllegalThreadStateException - if the thread was already
  started. See Also: run(), stop()

Source

A: You are confusing Threads with ThreadPools
A thread is an "unit of execution", code executed on a separate thread runs in parallel with your main programs when you call start()
ThreadPools is a mechanism built on top of threads, it allows you to create a group of threads which will take care to execute tasks you submit to the ThreadPool queue.

A: Yes, this is correct. You don't know when this thread will be executed but for sure it is scheduled for running.
Have a look at the following picture. It explains the lifecycle of a thread: http://cs.fit.edu/~ryan/java/language/thread.gif

A: start immediately starts the new thread, but by the very nature of threads, there is no guarantee as to when any line of code in that thread will actually execute. It is not appropriate to use the term "thread pool" in this context because the concept of a pool involves resources that are reused between user-requested tasks. A Thread instance is hardwired to a single invocation of the run method, after which the thread dies.
The thread scheduler is a native OS-level component and is not under the direct control of the JVM.

A: When you call Thread.start it makes a special instarcution to JVM for starting a thread and JVM will taken care of its life cycle.