text:
Q: Postgres cluster: password authentication failed for user "postgres" In my Postgres server have created a cluster using the command pg_createcluster listening on port 5433. To set the password for the user postgres I followed the following steps:

*

*Edit the file nano /etc/postgresql/9.3//pg_hba.conf

Changing the line
host all all 127.0.0.1/32 md5
By line
host all all 127.0.0.1/32 trust

*Change the password using the following commands

sudo -u postgres psql -h localhost -p 5433
postgres = # \ password postgres
Enter new password:
Enter it again:
postgres = # \ q

*Edit the file nano /etc/postgresql/9.3//pg_hba.conf

Changing the line
host all all 127.0.0.1/32 trust
By line
host all all 127.0.0.1/32 md5
Shows no errors but to connect both the console and from the pgadmin3 triggers an error: password authentication failed for user "postgres". With this same process in the instance by default (main) I can connect successfully.
I appreciate any help because I do not find much documentation to work with instances of Postgres.
Thanks in advance.

A: thanks for the reply. I've had in the pg_hba.conf with the configuration of your response:
# TYPE  DATABASE        USER            ADDRESS                 METHOD
# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5

Changing the password:
# nano /etc/postgresql/9.3/<instance_name>/pg_hba.conf
# /etc/init.d/postgresql restart
# su - postgres
$ psql -U postgres -p 5433 -h localhost
Password for user postgres:

The authentication server prompts me to enter psql. The following configuration is that it allows me to enter the psql without password:
# TYPE  DATABASE        USER            ADDRESS                 METHOD
# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

Changing the password:
# nano /etc/postgresql/9.3/<instance_name>/pg_hba.conf
# /etc/init.d/postgresql restart
# su - postgres
$ psql -U postgres -p 5433 -h localhost
postgres=# \password postgres
Enter new password:
Enter it again:
postgres=# \q
$ exit
# nano /etc/postgresql/9.3/<instance_name>/pg_hba.conf
# /etc/init.d/postgresql restart

Changing settings and entering again to psql:
# TYPE  DATABASE        USER            ADDRESS                 METHOD
# "local" is for Unix domain socket connections only
local   all             all                                     md5
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5

# su - postgres
$ psql -U postgres -p 5433 -h localhost
Password for user postgres:
psql: FATAL:  password authentication failed for user "postgres"
FATAL:  password authentication failed for user "postgres"

A: First of all, you need reload configuration, so all your changes can be applied. Connection port might not be opened and besides that you haven't clearly shared config for local connections. This should work fine:
# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            md5


text:
Q: Android Studio can't find device I am using Android Studio for Windows but it doesn't show any list of devices in the "choose a running device" option.  In a Command Tool, adb devices also shows nothing.
Things I have tried:

*

*I have tried this with 2 devices, an Xperia Sola as well as a Lenovo tablet, with the same results.

*I have enabled USB Debugging via Developer's Options on each device.

*I have tried adb kill-server followed by adb start-server, and adb devices still shows nothing. However, I can see the device in Windows File Explorer.

*I checked that the driver is up-to-date.

Can anyone help solve this problem?

A: I had the same problem. So here is what i did

*

*reinstalled the device driver

*changed the USB computer connection from MTP to Mass storage(UMS)

And it worked.
check out this thread Android Studio doesn't recognize my device

redpajama_set_name: RedPajamaStackExchange


text:
Q: Flair buttons suddenly broken? For the last year or so, I've been using this link to display my combined flair https://stackexchange.com/users/flair/1144664.png
As of yesterday (?) that image link is broken and redirects to https://stackexchange.com/error?aspxerrorpath=/users/flair/1144664.png.
My Stack Overflow flair still works - https://stackoverflow.com/users/flair/1127699.png
I can see that other people's Combined Flair still works e.g. https://stackexchange.com/users/flair/1.png
According to the Flair page, my link is correct - so what's going on?

A: As mentioned by Oded here:

The flair is cached individually on each server, so whether you hit the corrupted cache depends on the server you hit. This is why some people can repro and some can't. One way or another, the caches are cleared weekly, so this will resolve itself.


text:
Q: way to create summary table in R with two grouping factors I am trying to create a summary table in R with two grouping factors based on the following data
   species        plot   type  `mean(C)`
   <fct>        <fct> <fct>     <dbl>
 1 CA          MI  A         -35.7
 2 CA          MI  B         -35.6
 3 CA          MI  C         -35.9
 4 FO          MI  A         -35.7
 5 FO          MI  B         -34.9
 6 FO          MI  C         -35.3
 7 HE          MI  A         -35.4
 8 HE          MI  B         -35.6
 9 HE          MI  C         -35.6
10 LA          MI  A         -36.5

mean(C) is the response variable I am looking to show, and I'd like for it to be split up based on type and species; i.e. type as columns and species as rows
Every package I've tried to use (xtable, stargazer, gtsummary) doesn't seem to have the ability to do this. Of course, I can just plug and chug myself, but it'd be nice to know if there is a package. Anyone have any ideas?
Thanks so much

A: This is one solution using the tidyr:: package.
library(tidyr)
# define your data as dataframe df
df <- data.frame("species" = c("CA","CA","CA","FO","FO", "FO", "HE", "HE", "HE", "LA"),
                         "plot" = c("MI"),
                         "type" = c("A", "B", "C", "A", "B", "C", "A", "B", "C", "A"),
                         "mean" = c(-35.7, -35.6, -35.9, -35.7, -34.9, -35.3, -35.4, -35.6, -35.6, -36.5))
# pivot df around 'type', using 'mean'
df %>%
  pivot_wider(names_from = type, values_from = mean)

This returns:
> df %>%
+   pivot_wider(names_from = type, values_from = mean)
# A tibble: 4 x 5
species plot      A     B     C
<fct>   <fct> <dbl> <dbl> <dbl>
1 CA      MI    -35.7 -35.6 -35.9
2 FO      MI    -35.7 -34.9 -35.3
3 HE      MI    -35.4 -35.6 -35.6
4 LA      MI    -36.5  NA    NA

A: If you just want the data frame you presented with the type variable values as columns, you're just looking for the spread function from the tidyverse.
library(tidyr)

df <- data.frame(species = c("CA", "CA", "CA", "FO", "FO", "FO", "HE", "HE", "HE", "LA"),
                 plot = "MI",
                 type = c("A", "B", "C", "A", "B", "C", "A", "B", "C", "A"),
                 mean_C = c(-35.7,-35.6,-35.9, -35.7,-34.9,-35.3, -35.4,-35.6, -35.6,-36.5))

new_df <- df %>%
  spread(type, mean_C)

print(new_df)

A: You can add any number of stratifying variables with tbl_strata() in {gtsummary}. Example below!
library(gtsummary)
packageVersion("gtsummary")
#> [1] '1.5.0'

tbl <-
  trial %>%
  mutate(grade = paste("Grade", grade)) %>%
  tbl_strata(
    strata = grade,
    ~ .x %>%
      tbl_summary(
        by = trt,
        include = c(age, response),
        missing = "no"
      )
  )

Created on 2022-01-07 by the reprex package (v2.0.1)


text:
Q: Sidebar and navigation in Reactjs. routing inside rendered component I have a simple User dashboard app. From top of the navigation, it link to user dashboard. In user dashboard, there is side menu, and user content. I have rendered Userprofile from App.js. Now, in the userprofile, when I click Account settings or others, they should replace Overview Component. But, when I click sidebar links, it goes to right path, example: /dashboard/profile/accountsetting, butthere is nothing on page.
Userprofile.js

      <Sidebar/>
       <Switch>
           <Route exact path="/dashboard/profile" component={Overview} />
           <Route exact path="/dashboard/profile/settings "component={AccountSetting} />
           <Route exact path="/dashboard/profile/passwordchange" component={PasswordSetting} />
      </Switch>

Sidebar.js

   <Link to="/dashboard/profile" >Overview</Link>
   <Link to="/dashboard/profile/settings">Accounting Settings</Link>
   <Link to="/dashboard/profile/passwordchange">Password Settings</Link>
   <Link to="/dashboard/info" className="border-bottom-0">Info</Link>


text:
Q: Do I need to set the "Explicitly Shared" option? For a Facebook, Open Graph action type, what's the meaning of the "Explicitly Shared" property? How does it effect the story?
If there's a button in my app that publishes a story, does the action need to be "Explicitly Shared" or not?
Any clarifications are welcome,
Thank you!

A: Using Open Graph actions and explicit sharing is more powerful.
Is no need waiting to see FB dialog or confirm your action.
Stories should only be shared explicitly when people indicate that they want to share their in-app experience in the same way that they would post to Facebook themselves. Explicitly shared stories will always be posted to the Timeline of the person who shares them, and might appear in their friends' News Feeds.
Explicit sharing can happen through a variety of actions, like posting a photo or adding a message to an action they've taken. The important thing is that people clearly understand they are posting this action and must opt in to publishing this action to Facebook.
Learn more


text:
Q: Excel vba to mac I have an excel spreadsheet which works fine in the windows environment however when we try to run the same spreadsheets in MAC office 2011 the macros work but the buttons are not enabled?  They just show up as an image.  Any ideas.

A: Looks like you solved the button issue in the comments by converting the buttons from ActiveX to Forms.
Regarding the reference to the Microsoft XML library, I have done LOTS of looking around the web to find something to give this functionality on the Mac Office 2011 and have found nothing.
Here are some of the other places I saw people asking this same issue:
http://www.vbaexpress.com/forum/archive/index.php/t-12976.html
VBA for Mac: MSXML2.DOMDocument or System.PrivateProfileString doesn't work
If somebody else knows how to get DOMDOCUMENT to work on Mac Office 2011, please chime in!


text:
Q: SparkR drop multi-line header How to drop the first n lines (header) of a CSV file read in by SparkR. I know some things are possible in Scala like How do I convert csv file to rdd or http://qnalist.com/questions/4849107/skip-lines-in-spark but struggle to apply it to SparkR.

A: I will try to use something like this:
my_id <- createDataFrame(sqlContext, data.frame(my_id = 1:count(data)))
data.new <- merge(data, my_id)
data.filtered <- filter(data.new, data.new$my_id > 4)


text:
Q: Performance issue with AWS Fargate We have an old Java application running in Jboss As 7.1.1. Currently, this application is running on AWS EC2 instance type t3.medium, which is 2 CPU cores and 4GB memory.
We are trying to modernize our applications with CI/CD and AWS Fargate. We succeed to achieve modernization but not with performance.
The task definition of the Fargate has the same CPU and memory as the EC2 instance(2048 CPU and 4096 Memory). The Fargate is in the same subnet and linked to the same security group as the EC2 instance. We couldn't understand the reason for the slow performance.
The application normally searches for music works detail (creators, publishers, artists, and so on). If we take a music work with a large list of interested parties, in the EC2 instance it takes less than 20 seconds but in the Fargate it takes around 30 minutes.
I created the docker image from the same Jboss running on the EC2 instance and the same Java version.
One more piece of information, the database is in a different(non-AWS) data center.
Could you please guide me on how to achieve the same performance as the older setup by using AWS Fargate? What Am I missing in the Fargate?
Task definition

{
    "containerDefinitions": [
      {
        "name": "CONTAINER_NAME",
        "image": "<IMAGE1_NAME>",
        "memory": 4096,
        "essential": true,
        "logConfiguration": {
            "logDriver": "awslogs",
            "secretOptions": null,
            "options": {
              "awslogs-group": "/ecs/TaskDefinitionName",
              "awslogs-region": "eu-central-1",
              "awslogs-stream-prefix": "ecs"
            }
        },

        "portMappings": [
          {
             "hostPort": 8080,
             "containerPort": 8080,
             "protocol": "tcp"
          }
        ]
      }
    ],
    "compatibilities": [
        "EC2",
        "FARGATE"
    ],
    "requiresCompatibilities": [
        "FARGATE"
    ],
    "networkMode": "awsvpc",
    "cpu": "2048",
    "memory": "4096",
    "family": "TaskDefinitionName",
    "taskRoleArn": "arn:aws:iam::accountId:role/ecsTaskExecutionRole",
    "executionRoleArn": "arn:aws:iam::accountId:role/ecsTaskExecutionRole"
}

A: The answer I get from AWS support is as follows.
"ECS Fargate tasks may be placed on any underlying host that is available, and meets the CPU and Memory specified in the task definition and as such may have varying performance. EC2 instances are better suited in situations where control of the application performance is required."
My recommendation for developers, if network throughput and IO performance are important for your application better to use EC2.

A: The only way to monitor the performance lag is by using Container insights.
Only then you can monitor the metrics like CPU and memory utilization, network bandwidth, performance logs. Perhaps then increasing CPU limit and memory may help, in case needed. However Fargate has been reported multiple times to be slower as compared to AWS EC2 being validated by performance tools. So far no concrete solutions has been provided by AWS.
References -

*

*https://discuss.newrelic.com/t/php-agent-on-aws-fargate-performance-issue/124367

*https://filia-aleks.medium.com/ec2-versus-fargate-performance-comparison-34b1002fbbaa

*https://community.cloudonaut.io/t/spring-boot-on-fargate-slow/318

*https://www.reddit.com/r/aws/comments/921szi/migrating_java_applications_from_ec2_to_fargate/

*https://www.reddit.com/r/aws/comments/hqjyqd/ecs_performance_10x_slower_than_ec2_instances/

A: While you could expect a small variance in performance between EC2 and Fargate the delta you see is pretty "ridiculous" and there is definitely something going on here. Is the setup 100% identical (with the only difference being where the task runs)? Also, have you tried, for purpose of troubleshooting to start a Fargate task on a larger set of resources (e.g. 4 vCPU / 30GB) to see if that makes any difference? Again just for the sake of figuring out if "capacity" is the issue or the issue lies somewhere else.


text:
Q: Как удалить(убрать) QLayout из другого QLayuot Есть Layout, который содержит другой под-Layout. В некий момент мне нужно этот под-Layout удалить, а новый добавить.
QVBoxLayout* mainLayout = new QVBoxLayout; //layout
QHBoxLayout* subLayout = new QHBoxLayout; //под-layout
for(int i = 0; i < 3; i++)
   subLayout->addWidget(new QPushButton(this)); //содержимое под-layout'a
mainLayout->addLayout(subLayout);
setLayout(mainLayout);

После этого необходимо subLayout и его содержимое убрать, а какой-то новый с другим содержимым добавить.
Как? QLayout предоставляет только removeWidget, и совсем никакого removeLayout, а просто delete subLayout; никакого здравого эффекта не дает.

A: Используйте removeItem, это как раз то, что Вам нужно.

A: Следует всегда назначать родителя для виджета и лэйаутов:
QVBoxLayout* mainLayout = new QVBoxLayout(this); //layout
QHBoxLayout* subLayout = new QHBoxLayout(this); //под-layout

В этом случае delete должен работать.


text:
Q: Any elegant way to generate numeric value of the same type based on input numeric type? I have a function which takes as input a numeric value (Long/Integer/Byte/Double/BigDouble ...) and set the output value to 1 if it's larger than some threshold value, otherwise 0. The function may look like this,
static Number foo(Number input) {
    if (input > threshold) { return 1;}
    else { return 0;}
}

But I've to keep the output the same type as input. One thing I can do is to enumerate all Number types and do casts and repeat the same logic like:
static Number foo(Number input) {
    if (input instanceof Double) {
        if (input > threshold) { return new Double(1.0);}
        else { return new Double(0);}
    } else if (input instanceof Integer) {
        // ...
    }
    // ...
}

So, I don't know if there's some more simple and elegant way to do this?
Thanks!!

A: Well... since comments are limited in length, I decided to formulate my comment as an answer.
I inferred from your question that the Atomic... classes are not relevant. I further assume that the six primitive number types (byte, short, int, long, float and double) are the ones of interest. We can use a combination of overloading and clever use of automatic type widening:
public static final double THRESHOLD = ...;

public static byte foo(final byte input) {
    return internalFoo(input);
}

public static short foo(final short input) {
    return internalFoo(input);
}

public static int foo(final int input) {
    return internalFoo(input);
}

public static long foo(final long input) {
    return internalFoo(input);
}

public static float foo(final float input) {
    return internalFoo((double) input);
}

public static double foo(final double input) {
    return internalFoo(input);
}

private static byte internalFoo(final double input) {
    return (byte) (input > TRESHOLD ? 1 : 0);
}

Ideone example
This works since every primitive number type can be automatically widened to be double. Following this argumentation, one could also do away with all the overloads an just use internalFoo:
public static byte foo(final double input) {
    return (byte) (input > THRESHOLD ? 1 : 0);
}


text:
Q: Flipping animation behaving very differently in other browsers I am currently working on making a flipping animation on some divs.
However, I have found that it works incorrectly and differently in every browser that I have tried. Only Edge works the way that I want.
I want clicking the "flip" text to flip over in order to show the .flipping-view-back div, and hide the .flipping-view-front div. Additionally, the toolbar with position:fixed on the back div should be fixed at the top of the page even when scrolling.
In reality, this is only working in some browsers.
On Edge:  This is working exactly how I want it to. Video
On Chrome: The front div flips over, but there is no back div visible behind it. The back div only pops in once the rotation transition has fully completed. Strangely, scrolling at any time during the flip will also trigger the back div to pop in. Also, scrolling down moves the fixed div out of sight. Video
On iOS Safari: This flips correctly, but scrolling down moves the fixed div out of sight. Video
In all these videos, I clicked on the flip text and waited for the animation to finish. Then I scrolled down.
How can I make the flip animation correct and keep the fixed div at the top in all browsers?

var currView = 0;
const rotatingViewElem = document.querySelector(".main");
const VIEW_FEED = 0;
const VIEW_FLIPPING_SEND = 1;

var viewFeedElem = document.querySelector(".view-positioner.feed");
var viewCreateElem = document.querySelector(".view-positioner.create");
var viewSelectRecipientsElem = document.querySelector(".view-positioner.select-recipients");
var viewFlippingSendElem = document.querySelector(".view-positioner.flipping-send");
var viewsList = [viewFlippingSendElem];

function flipView(isGoForward) {
    var flippingElem = viewsList[currView];
    var globalRotate;

    if (isGoForward) {
        globalRotate = "rotateY(180deg)";//flip around
    } else {
        globalRotate = "rotateY(0deg)";
    }
    flippingElem.style.transform = globalRotate;

}

document.querySelector(".create-send-button").addEventListener("click", function (e) { flipView(true) })
body, html{
    width:100%;
    height:100%;
    margin:0px;
    overflow:hidden;
}
.main{
    perspective: 2000px;
    height:100%;
}
.flipping-view-wrapper{

    transform: rotateY(0);
    transform-style: preserve-3d;
    transition: transform 5.5s;
}
body{
    height: 100%;
}
.view{
    transform-style: preserve-3d;
    position: relative;
    padding-top:1px;
    overflow-y:auto;
    height: calc(100% - 1px);
    width:100%;
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
}

.view-positioner{

    position: absolute;
    left:0px;
    top:0px;
    width:100%;
    height:100%;
}

.flipping-view-front{
    background-color: pink;
    transform: rotateY(0deg);
}
.flipping-view-back{
    background-color: green;
    transform:rotateY(180deg);
}
.create-send-button{
    cursor: pointer;
}

/* begin top toolbar */
.top-toolbar{
    position:fixed;

    top:0px;
    left:0px;
    width:100%;
    height:55px;
    background:#FFFB00;
}
<!DOCTYPE html>

     flip to the backside this is long so you can see

    fixed

Long text a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a
    a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a

A: Could have something to do with the browsers itself, maybe look into -webkit. There are webkits for different browser so you might need to use multiple webkits for different browsers
What is WebKit and how is it related to CSS?
That post might give you some more info


text:
Q: .Find not working in Word from Excel vba I'm trying to get information from a table in Word and pull it into Excel, since the number of tables is variable and I have no other way to reference the table I wanted to find the table directly after the text before it in the document. I've used the .Find method before but for some reason I can't get it to work this time and from everything I've read and used before, this should work:
Sub Process_NIM()
    Dim WordPullFile As Object
    Dim PullFolder As String
    Dim PullDate As Date
    Dim AppWord As Word.Application
    Dim wd As Word.Document
    Dim Table1 As Word.Table
    Dim wb As Workbook
    Dim ws1, ws2 As Worksheet
    Dim Text1 As Word.Range

    PullDate = DateAdd("d", 1, Now())
    PullFolder = "M:\Production Case Files\" & Format(PullDate, "YYYY") & _
        " Production Case Files\" & UCase(Format(PullDate, "MMM")) & _
        "\" & UCase(Format(PullDate, "MMM DD")) & "\"
    On Error GoTo OpenFileError
    Set WordPullFile = Application.FileDialog(msoFileDialogOpen)
    With WordPullFile
        .AllowMultiSelect = False
        .Filters.clear
        .Filters.Add "DOC Files (*.doc)", "*.doc"
        .InitialFileName = PullFolder
        .Show
    End With
    On Error GoTo 0
    If WordPullFile.SelectedItems.Count > 0 Then
        PullFolder = WordPullFile.SelectedItems(1)
    End If

    Set AppWord = CreateObject("Word.Application")
    Set wd = AppWord.Documents.Open(PullFolder)
    wd.Application.Visible = True

    Set wb = ThisWorkbook
    Set ws1 = wb.Worksheets(1)
    Set ws2 = wb.Worksheets(2)

    If Text1.wd.Selection.Find.Execute(findtext:="Generator Outages for Today - Greater than 25MW") = True Then
        'do stuff
    End If

OpenFileError:
    MsgBox ("There was an error opening the word file. Try closing any other instances of word and re-run.")
    Exit Sub

End Sub

I use this from Word currently, but I can't get it to work from Excel:
If Text1.Find.Execute(findtext:="RC South Regional Review for") Then
    Text1.InsertAfter (" " & Format(FileDate, "MMMM DD, YYYY"))
End If

A: the good news is, the text you say you use in word that doesn't work in excel, actually does work.  The issue is with the value you are trying to put in, I used your code and for a while I was stumped because it appeared to not be working, but when I substituted some plain text instead of your date, it worked fine, whihc told me the find was working.  It turns out it simply wasn't resolving Filedate as a date and so wasn't inserting anything.  Here is a version of your code, modified to work on my PC that does insert a date after the found string, did you mean to add Pulldate instead of Filedate as the variable to append maybe?
Sub Process_NIM()
    Dim WordPullFile As Object
    Dim PullFolder As String
    Dim PullDate As Date
    Dim AppWord As Word.Application
    Dim wd As Word.Document
    Dim Table1 As Word.Table
    Dim wb As Workbook
    Dim ws1, ws2 As Worksheet
    Dim Text1 As Word.Range

    PullDate = DateAdd("d", 1, Now())
    PullFolder = "D:\Users\Mark\Documents\"
    On Error GoTo OpenFileError
    Set WordPullFile = Application.FileDialog(msoFileDialogOpen)
    With WordPullFile
        .AllowMultiSelect = False
        .Filters.Clear
        .Filters.Add "DOC Files (*.doc)", "*.doc"
        .InitialFileName = PullFolder
        .Show
    End With
    On Error GoTo 0
    If WordPullFile.SelectedItems.Count > 0 Then
        PullFolder = WordPullFile.SelectedItems(1)
    End If

    Set AppWord = CreateObject("Word.Application")
    Set wd = AppWord.Documents.Open(PullFolder)
    wd.Application.Visible = True

    Set wb = ThisWorkbook
    Set ws1 = wb.Worksheets(1)
    Set ws2 = wb.Worksheets(2)

    Set Text1 = wd.Range
If Text1.Find.Execute(findtext:="RC South Regional Review for") Then
    Text1.InsertAfter (" " & Format(Date, "MMMM DD, YYYY"))
Else
    MsgBox "could not find text"
End If
wd.Save
wd.Close
AppWord.Quit
Set AppWord = Nothing

Exit Sub
OpenFileError:
    MsgBox ("There was an error opening the word file. Try closing any other instances of word and re-run.")
    Exit Sub

End Sub


text:
Q: Upload file error message not appearing. CodeIgniter I hope someone can help me with this. Whenever I upload a file with the wrong format and submit the form, an error is supposed to appear. However after passing multiple variables back to the view from my controller, none of the errors seem to be appearing. Thank you.
Controller Code :
function upload()
{
    $this->load->library('pagination');
    //the name on the view must be userfile
    $username = $this->session->userdata('username');
    $company = $this->session->userdata('company');
    $title = $this->input->post('title');
    $description =$this->input->post('description');
    $path = './assets/files/'.$company.'/announcements';
    $config['upload_path'] = $path;
    $config['allowed_types'] = 'pdf';
    $config['max_size']    = '10000';
    $this->load->library('upload',$config);

    $this->load->model('announcement');
    $this->load->library('pagination');
    $config['per_page']=5;
    if(!$this->upload->do_upload())
    {

        //$error = array('error'=>$this->upload->display_errors());
        $data = array(
        'announcement' => $this->announcement->fetch_announcement($username,$company,$config['per_page'],$this->uri->segment(3)),
        'links' => $this->pagination->create_links(),
        'error' => $this->upload->display_errors()
        );
        print_r($this->upload->display_errors());
        $this->load->view('includes/admin_header');
        $this->load->view('announcements',$data);
        $this->load->view('includes/admin_footer');
        //redirect('announcements/index');
    }
    else
    {
        $data = array(
        'announcement' => $this->announcement->fetch_announcement($username,$company,$config['per_page'],$this->uri->segment(3)),
        'links' => $this->pagination->create_links(),
        'error' => $this->upload->display_errors()
        );
        $file_data = array('upload_data' => $this->upload->data());
        $result = $this->announcement->create($insert);
        //$this->load->view('includes/admin_header');
        //$this->load->view('announcements',$data);
        //$this->load->view('includes/admin_footer');
        redirect('announcements/index');
    }

}

View Code :

    No.
    Title
    Description
    Added By
    Company
    Date Added
    Publish

<?php $offset = $this->uri->segment(3,0)+1; ?>
<?php foreach($announcement as $row): ?>

<?php echo $offset++; ?>
<?php echo $row->title; ?>
<?php echo $row->description; ?>
<?php echo $row->addedby; ?>
<?php echo $row->company; ?>
<?php echo $row->dateadded; ?>
<?php echo $row->published; ?>
<?php endforeach; ?>

<?php echo $links; ?>

<?php $error = ''; ?>

Add an announcement

<?php echo form_open_multipart('announcements/upload'); ?>

Title : <input type="text" name="title"/>

Description :
<textarea style="resize:none;" maxlength="200" row="20" cols="20"     name="description"></textarea>

Upload file :<input type="file" name="userfile">

<input type="submit" name="submit" value="Upload">

</form>
<?php echo $error; ?>

A: Kindly refer below code :-
if ( ! $this->upload->do_upload())
        {
            $error = array('error' => $this->upload->display_errors());

            $this->load->view('upload_form', $error);
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());

            $this->load->view('upload_success', $data);
        }

Ref From : https://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
Let me know, if this does not work.

A: Remove the below starting of coding
<?php $error = ''; ?>

in announcements view file


text:
Q: Is there a way to search the answers of a Question?
Possible Duplicate:
Seaching Questions with n-Pages of Answers

Is there a way?
I first thought about this with those 'best X' questions as I'd rather up-vote an answer that was already given rather than add another of the same answer.
It might also be useful for more 'regular' questions, if I had a very specific case and the top answers didn't address it. It might be nice to search the answers of a question instead of paging through.


text:
Q: Zooming in datagridview reacts weird I have two forms: F1 and F2, both containing datagridview controls.
F1 has a datagridview control to display some entries. Double clicking on a row opens F2 to display the selected entry infos.
On F1, i have a "Datagridview Zoom In/Zoom Out" fonction w:
Private Sub btnZoomOut_Click(sender As Object, e As EventArgs) Handles btnZoomOut.Click
Dim strMsgboxNoMoreZoomOut As String = "Cant zoom out more"
Dim intActualFontSizeCell As Int16 = CShort(dtgHashtagSrchResults.DefaultCellStyle.Font.Size)
Dim intActualFontSizeHEader As Int16 = CShort(dtgHashtagSrchResults.DefaultCellStyle.Font.Size)
With Me.dtgHashtagSrchResults
   If intActualFontSizeCell < 8 Then
      MsgBox(strMsgboxNoMoreZoomOut, MsgBoxStyle.Information, strMsgBoxHashtagTitle)
   Else
     .DefaultCellStyle.Font = New Font("Lato", intActualFontSizeCell - 1)
     .ColumnHeadersDefaultCellStyle.Font = New Font("Lato", intActualFontSizeHEader - 1)
   End If
End With
End Sub

Private Sub btnZoomIn_Click(sender As Object, e As EventArgs) Handles btnZoomIn.Click
Dim strMsgboxNoMoreZoomIn As String = "Cant zoom in more"
Dim intActualFontSizeCell As Int16 = CShort(dtgHashtagSrchResults.DefaultCellStyle.Font.Size)
Dim intActualFontSizeHEader As Int16 = CShort(dtgHashtagSrchResults.DefaultCellStyle.Font.Size)
With Me.dtgHashtagSrchResults
     If intActualFontSizeCell = 50 Then
        MsgBox(strMsgboxNoMoreZoomIn, MsgBoxStyle.Information, strMsgBoxHashtagTitle)
     Else
       .DefaultCellStyle.Font = New Font("Lato", intActualFontSizeCell + 1)
       .ColumnHeadersDefaultCellStyle.Font = New Font("Lato", intActualFontSizeHEader + 1)
     End If
End With
End Sub

When I used this zoom in/out in F1,

*

*if F1 is the only form opened, the zoom In/out fonction is applied on F1

*if F1 and F2 are opened, zoom in/out fonction applied only on F2. If i close F1 and F2, reopened F1 (F1 is opened through a button on the main form of the application) then the zoom is applied to F1 and to any datagridview used in the application!

Video: https://www.youtube.com/watch?v=y6ll-tiTQL8


text:
Q: Unexpected Keyword argument using formset_factory I'm working on a project in which a teacher can add marks to his students, I want to use formset_factory so the teacher can add many marks at the same time, but I want a teacher to see only his students, and not the students who are not in his class.
I got it when using a single form, but when I try to use the formset_factory, I get this error:
init() got an unexpected keyword argument 'request'
This is my working code
in views:
  class AddNotaBlock(FormView):

template_name='notas/insertar_nota.html'

form_class= NotaCreateFormTeacher
success_url= reverse_lazy('home')

def get_form_kwargs(self):
    """ Passes the request object to the form class.
     This is necessary to only display members that belong to a given user"""

    kwargs = super(AddNotaBlock, self).get_form_kwargs()
    kwargs['request'] = self.request
    return kwargs

in forms:
  class NotaCreateFormTeacher(ModelForm):

def __init__(self, *args, **kwargs):

    self.request = kwargs.pop('request')
    super(NotaCreateFormTeacher, self).__init__(*args, **kwargs)
    usuario=self.request.user
    profe=Teacher_profile.objects.get(profesor=usuario)
    colegio=profe.colegio
    self.fields['Username'].queryset = Student_profile.objects.filter(
        colegio=colegio)

class Meta:
    model = Nota
    fields = ('Username', 'nota', 'colegio')
    widgets= {'colegio':HiddenInput()}

  formset=formset_factory(NotaCreateFormTeacher, extra=2)

when I use:
  form_class= NotaCreateFormTeacher

Everything works (but only a form is displayed)
If I use:
  form_class=formset

I get the unexpected keyword argument error:
init() got an unexpected keyword argument 'request'
What I'm I doing wrong?
Thanks for helping.

A: You pass this as form_kwargs=… parameter [Django-doc], so:
class AddNotaBlock(FormView):
    template_name = 'notas/insertar_nota.html'
    form_class = formset
    success_url = reverse_lazy('home')

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs.setdefault('form_kwargs', {})['request'] = self.request
        return kwargs


text:
Q: Unable to connect to ChromeCast I recently moved home and upgraded my router. It's a ZTE router and the model number is ZXHN H298A.
Since I have installed this router, I am unable to connect to Chromecast.
I did a factory reset couple of times on Chromecast and reconnected through the Google Home app. It finds and connects but then eventually says it is unable to connect. I cannot find my device when I try to cast from my phone/tablet. It just says no device found. When I go to my Google Home app, this device is listed but when I click on it, it says cannot connect.
I have looked around for this issue. A lot of suggestions are to disable Access Point Isolation. I have gone through all options on my router portal but I am unable to find it.
Has anyone come across this problem or does anyone know how to disable AP isolation on ZTE ZXHN H298A.
Many thanks.

A: If you're trying to turn off the wifi isolation (aka WIRELESS, AP OR CLIENT ISOLATION) to fix this issue.
According to the ZTE manual (Manual Source: https://hyperoptic.com/wp-content/uploads/2017/10/ZTE-H298A-admin-manual.pdf) you can:

*

*log in your router

*navigate to Local Network > WLAN > WLAN Basic > WLAN SSID Configuration

*under this page, there is "WLAN SSID configuration" section, If you have more than one ssid setup, then make sure you choose the right one that your Chromecast has been connected.

*You will find the wifi isolation on/off option, inside that "WLAN SSID configuration" section

Hope this helps.


text:
Q: How to match a pattern that repeats n times in a string using findall()? I'm trying to parse a repetitive string and find multiple matches from it that match the pattern in my findall() function.
Essentially what I want to do is extract the names of the players from the string. They're separated by commas and the last name of the player is preceded by an "and". I tried to get the comma part down but for some reason findall() doesn't seem to repeat the matching pattern even though I added a *.
x = re.findall('Players(?:\s([A-Z]+[a-z]+)),*', 'Players Jeremiah, Lou, Martha and Kay,')

I haven't gotten the and part down yet since I'm stuck on the commas but from the above code, I feel like, x should capture Jeremiah, Lou and Martha at the very least. My code only manages to capture Jeremiah.

A: Your pattern starts with Players... hence it will only match once, because your string has only one Players in it.
This would be the correct pattern which also handles the and part:

*

*a player name is any character that is non-white space or comma,

*it must be followed either by a comma or white space + and
import re

x = re.findall(r'([^\s,]+)(?:,|\s+and)',
               'Players Jeremiah, Lou, Martha and Kay,')

print(x)

Test run:
$ python3 dummy.py
['Jeremiah', 'Lou', 'Martha', 'Kay']

Update to match further sample sentences given by OP a single regex is no longer enough:

*

*match a mandatory prefix Players and extract the rest

*match an optional postfix, e.g. are ..., and strip that

*detect player names in the remaining sentence

*

*starts at a word boundary

*starts with an uppercase letter

*followed by one-or-more lowercase letters

*ends at a word boundary

import re;

for input in (
        'Jeremiah, Lou, Martha and Kay,',
        'Players Jeremiah, Lou, Martha and Kay,',
        'The Players are Martha, Joe, Toby and Kay.',
        'The Players Martha, Joe and Toby are German.',
        'The Players Martha, Joe and Toby are German,',
    ):

    # strip mandatory prefix
    match = re.search('Players(.*)', input)
    if not match:
        continue
    #print(match[1])

    # strip optional postfix
    postfix = re.search('(.*)(?:\s+(?:are)\s+\S+[,.])$', match[1])
    if postfix:
        match = postfix
    #print(match[1])

    result = re.findall(r'(\b[A-Z][a-z]+\b)', match[1])
    print(input, '->', result)

Test run:
$ python3 dummy.py
Players Jeremiah, Lou, Martha and Kay, -> ['Jeremiah', 'Lou', 'Martha', 'Kay']
The Players are Martha, Joe, Toby and Kay. -> ['Martha', 'Joe', 'Toby', 'Kay']
The Players Martha, Joe and Toby are German. -> ['Martha', 'Joe', 'Toby']
The Players Martha, Joe and Toby are German, -> ['Martha', 'Joe', 'Toby']

A: I guess you're basically looking for a pattern for proper nouns. In the pattern you're using, it only captures "Jeremiah" because your pattern 'Players(?:\s([A-Z]+[a-z]+)),*' specifically looks for a proper noun after the word "Players".
Please try this pattern instead:
(?!^[A-Z]\w+)(?<![.]\s)([A-Z]\w+)
It looks for proper nouns but exclude capitalized words at the beginning of the sentence.

([A-Z]\w+) matches a capitalized word
(?<![.]\s) ensures that we don't pick anything that follows a full-stop and a space
(?!^[A-Z]\w+) leaves out capitalized words at the beginning of the string (in a new line for example)

Warning
A generalized pattern may not be ideal if you require 100% precision in your results. This pattern could potentially understate the number of names if your sentence begins with a name.
Test it out here


text:
Q: Java Generic (List list1) VS (List super SuperClass> list2) Q. why first one is not working, but second is working fine.?
1
public List<? extends Animal> doAdd(List<? extends Animal> list) {
    //here unable to add, compilation error
    list.add(new Cat());
    return list;
}

2
private static <T> List<T> doAdd(List<T> list){
    //working fine.
    ls.add((T) new Cat());
    return ls;
}
List<Animal> list = new ArrayList<Aninal>();
doAdd(list);

A: ? extends Sometype doesn't allow you to add anything other than null.? extends Sometype is to allow us to refer to subtype.
Let's take an example
List<? extends Animal> list = new ArrayList<Dog>(); // this assignment works because of ? extends Animal and Dog is a subtype of Animal

list.add(new Cat()); // this will give a compiler error

but assume if add() worked, you would be able add Cat to a list of Dog which would defeat the idea of compile time checks that generics provide.That's why ? extends Sometype prevents you from adding anything other than null
In the second case, you need a cast because the method itself doesn't know what T would be , so ls.add((T) new Cat());  would fail without a cast.
you can update the second method definition to allow add() to work without cast.
private static  List<? super Animal> doAdd(List<? super Animal> list){

        list.add(new Cat());
        return list;
    }


text:
Q: How to Limit Google Map Zoom Is it possible to limit how far the user can zoom out in a Google Map in Android? I don't want the user to be able to zoom out far enough to see more than one Earth. Thanks.

A: you can disable the built in zoom and add you own bottons and changing your zoon on click. you will be able to disable zoom out for a certain level.
Important I think the user may always be able to scroll horizontally.


text:
Q: Route53, A record with alias and ip at the same time? I have a Route53 A record alias to my ELB for example.com (https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-elb-load-balancer.html)
and I'm trying to connect domain example.com to firebase hosting.
(to use example.com as dynamic link domain)
And firebase setup tool asks me to create two A record example.com for two ip addresses.
Route 53 doesn't seem to allow me to have an alias A record and non-alias A record.
How to proceed from here?

A: The supported options are to point the domain only to Firebase (not any other service, like an ELB), or to use a subdomain or a different domain altogether.

To use a custom domain for Dynamic Links, the domain must point to Firebase Hosting. If you have a domain you want to use with Dynamic Links and the domain points to a different host, you can either move to Firebase Hosting or create a subdomain hosted by Firebase, which you can use for Dynamic Links.
https://firebase.google.com/docs/dynamic-links/custom-domains


text:
Q: resValue under buildTypes produces No resource found that matches the given name This is my build.gradle
buildTypes {
        debug {
           resValue "string", "facebook_app_id", "\"XXXXXXXXX\""
        }
        live{
           resValue "string", "facebook_app_id", "\"XXXXXXXXX\""
        }
}

and this my manifest file where I use facebook_app_id
<meta-data
     android:name="com.facebook.sdk.ApplicationId"
     android:value="@string/facebook_app_id"/>

this works fine while debugging but when generating a signed apk this error produced
No resource found that matches the given name (at 'value ' with value '@string/facebook_app_id').

A: goto -> res->values->string.xml open that file and write
<string name="facebook_app_id">Facebook</string>


text:
Q: How to Click a ImageButton using Robotium please refer the image.
In the image (which is blue color is selected one). I want to click on the imageView.
I am not sure how to select a imageView, when multiple linear layout is there.
-Relative Layout:
     -(0)Linear Layout
       -(0)TabWidget
          -(0) LinearLayout
                (0)imageView
          -(1) LinearLayout
                (0)imageView
          -(2) LinearLayout
                (0)imageView (I want Click this image View).

A: If there are no ids and the Relative Layout is root layout, you can click on image view with index 2.
solo.clickOnImage(2);


text:
Q: Odoo 11: Cant update module because new template was added to the module I am fairly new to Odoo and I wanted to toy around on a test module for which I have created a few views (templates) for the web pages. At first, when there was only one template, everything was working fine, but when I tried adding another, the updates suddenly wouldn't work anymore. You'll find below the code of the first and the second template plus the error message as-well as my manifest file
First template
<?xml version="1.0" encoding="utf-8"?>
<odoo>

    <template id="template_test_hello_world" name="Test Hello World"><!DOCTYPE html>

Url text: <t t-esc="val"/>

                    <t t-foreach="models" t-as="model">

<t t-esc="model.id"/><t t-esc="model.preview_name"/>

                    </t>

    </template>

</odoo>

Second Template
<?xml version="1.0" encoding="utf-8"?>
<odoo>

    <template id="template_random" name="Test Random"><!DOCTYPE html>

BlaBlaBla

    </template>

</odoo>

The manifest
{
    'name': "Tests",
    'summary': """
        Testing stuff
    """,
    'description': """
        Yes.
    """,
    'author': "",
    'website': "",
    'category': 'Uncategorized',
    'version': '0.1',
    'depends': [],
    'data': [
        'views/test_hello_world_template.xml',
        'data/test_models.xml',
        'security/ir.model.access.csv',
        'views/random_template.xml',
    ],
    "installable": True,
}

The Error message
2020-02-07 11:21:47,945 27164 ERROR smthg odoo.sql_db: bad query: b'INSERT INTO "ir_ui_view" ("id", "key", "priority", "active", "type", "name", "mode", "create_uid", "write_uid", "create_date", "write_date") VALUES(nextval(\'ir_ui_view_id_seq\'), \'my_module.template_test_hello_world\', 16, true, \'qweb\', \'Test Hello World\', \'primary\', 1, 1, (now() at time zone \'UTC\'), (now() at time zone \'UTC\')) RETURNING id'
ERROR: null value in column "projection" violates not-null constraint
DETAIL:  Failing row contains (2531, 2020-02-07 11:21:47.854173, 1, 2020-02-07 11:21:47.854173, t, null, null, null, Test Hello World, null, 16, primary, null, qweb, 1, null, null, null, null, null, null, my_module.template_test_hello_world, null, null, null, null, null).

2020-02-07 11:21:47,946 27164 WARNING smthg odoo.modules.loading: Transient module states were reset
2020-02-07 11:21:48,044 27164 ERROR smthg odoo.modules.registry: Failed to load registry
Traceback (most recent call last):
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 745, in parse
    self._tags[rec.tag](rec, de, mode=mode)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 723, in _tag_template
    return self._tag_record(record, data_node)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 655, in _tag_record
    id = self.env(context=rec_context)['ir.model.data']._update(rec_model, self.module, res, rec_id or False, not self.isnoupdate(data_node), noupdate=self.isnoupdate(data_node), mode=self.mode)
  File "/etc/odoo/odoo-server/odoo/odoo/addons/base/ir/ir_model.py", line 1504, in _update
    record = record.create(values)
  File "/etc/odoo/odoo-server/odoo/odoo/addons/base/ir/ir_ui_view.py", line 408, in create
    return super(View, self).create(self._compute_defaults(values))
  File "/etc/odoo/odoo-server/odoo/odoo/models.py", line 3409, in create
    record = self.browse(self._create(old_vals))
  File "/etc/odoo/odoo-server/odoo/odoo/models.py", line 3502, in _create
    cr.execute(query, tuple(u[2] for u in updates if len(u) > 2))
  File "/etc/odoo/odoo-server/odoo/odoo/sql_db.py", line 155, in wrapper
    return f(self, *args, **kwargs)
  File "/etc/odoo/odoo-server/odoo/odoo/sql_db.py", line 232, in execute
    res = self._obj.execute(query, params)
psycopg2.IntegrityError: null value in column "projection" violates not-null constraint
DETAIL:  Failing row contains (2531, 2020-02-07 11:21:47.854173, 1, 2020-02-07 11:21:47.854173, t, null, null, null, Test Hello World, null, 16, primary, null, qweb, 1, null, null, null, null, null, null, my_module.template_test_hello_world, null, null, null, null, null).

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/etc/odoo/odoo-server/odoo/odoo/modules/registry.py", line 85, in new
    odoo.modules.load_modules(registry._db, force_demo, status, update_module)
  File "/etc/odoo/odoo-server/odoo/odoo/modules/loading.py", line 376, in load_modules
    force, status, report, loaded_modules, update_module, models_to_check)
  File "/etc/odoo/odoo-server/odoo/odoo/modules/loading.py", line 274, in load_marked_modules
    perform_checks=perform_checks, models_to_check=models_to_check
  File "/etc/odoo/odoo-server/odoo/odoo/modules/loading.py", line 181, in load_module_graph
    _load_data(cr, module_name, idref, mode, kind='data')
  File "/etc/odoo/odoo-server/odoo/odoo/modules/loading.py", line 95, in _load_data
    tools.convert_file(cr, module_name, filename, idref, mode, noupdate, kind, report)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 792, in convert_file
    convert_xml_import(cr, module, fp, idref, mode, noupdate, report)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 853, in convert_xml_import
    obj.parse(doc.getroot(), mode=mode)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 752, in parse
    exc_info[2]
  File "/etc/odoo/odoo-server/odoo/odoo/tools/pycompat.py", line 86, in reraise
    raise value.with_traceback(tb)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 745, in parse
    self._tags[rec.tag](rec, de, mode=mode)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 723, in _tag_template
    return self._tag_record(record, data_node)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 655, in _tag_record
    id = self.env(context=rec_context)['ir.model.data']._update(rec_model, self.module, res, rec_id or False, not self.isnoupdate(data_node), noupdate=self.isnoupdate(data_node), mode=self.mode)
  File "/etc/odoo/odoo-server/odoo/odoo/addons/base/ir/ir_model.py", line 1504, in _update
    record = record.create(values)
  File "/etc/odoo/odoo-server/odoo/odoo/addons/base/ir/ir_ui_view.py", line 408, in create
    return super(View, self).create(self._compute_defaults(values))
  File "/etc/odoo/odoo-server/odoo/odoo/models.py", line 3409, in create
    record = self.browse(self._create(old_vals))
  File "/etc/odoo/odoo-server/odoo/odoo/models.py", line 3502, in _create
    cr.execute(query, tuple(u[2] for u in updates if len(u) > 2))
  File "/etc/odoo/odoo-server/odoo/odoo/sql_db.py", line 155, in wrapper
    return f(self, *args, **kwargs)
  File "/etc/odoo/odoo-server/odoo/odoo/sql_db.py", line 232, in execute
    res = self._obj.execute(query, params)
odoo.tools.convert.ParseError: "null value in column "projection" violates not-null constraint
DETAIL:  Failing row contains (2531, 2020-02-07 11:21:47.854173, 1, 2020-02-07 11:21:47.854173, t, null, null, null, Test Hello World, null, 16, primary, null, qweb, 1, null, null, null, null, null, null, my_module.template_test_hello_world, null, null, null, null, null).
" while parsing None:4, near
<t name="Test Hello World" t-name="my_module.template_test_hello_world"><!DOCTYPE html>

Url text: <t t-esc="val"/>

                        <t t-foreach="models" t-as="model">

<t t-esc="model.id"/><t t-esc="model.preview_name"/>

                        </t>

        </t>
2020-02-07 11:21:48,048 27164 CRITICAL smthg odoo.service.server: Failed to initialize database `smthg`.
Traceback (most recent call last):
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 745, in parse
    self._tags[rec.tag](rec, de, mode=mode)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 723, in _tag_template
    return self._tag_record(record, data_node)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 655, in _tag_record
    id = self.env(context=rec_context)['ir.model.data']._update(rec_model, self.module, res, rec_id or False, not self.isnoupdate(data_node), noupdate=self.isnoupdate(data_node), mode=self.mode)
  File "/etc/odoo/odoo-server/odoo/odoo/addons/base/ir/ir_model.py", line 1504, in _update
    record = record.create(values)
  File "/etc/odoo/odoo-server/odoo/odoo/addons/base/ir/ir_ui_view.py", line 408, in create
    return super(View, self).create(self._compute_defaults(values))
  File "/etc/odoo/odoo-server/odoo/odoo/models.py", line 3409, in create
    record = self.browse(self._create(old_vals))
  File "/etc/odoo/odoo-server/odoo/odoo/models.py", line 3502, in _create
    cr.execute(query, tuple(u[2] for u in updates if len(u) > 2))
  File "/etc/odoo/odoo-server/odoo/odoo/sql_db.py", line 155, in wrapper
    return f(self, *args, **kwargs)
  File "/etc/odoo/odoo-server/odoo/odoo/sql_db.py", line 232, in execute
    res = self._obj.execute(query, params)
psycopg2.IntegrityError: null value in column "projection" violates not-null constraint
DETAIL:  Failing row contains (2531, 2020-02-07 11:21:47.854173, 1, 2020-02-07 11:21:47.854173, t, null, null, null, Test Hello World, null, 16, primary, null, qweb, 1, null, null, null, null, null, null, my_module.template_test_hello_world, null, null, null, null, null).

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/etc/odoo/odoo-server/odoo/odoo/service/server.py", line 1006, in preload_registries
    registry = Registry.new(dbname, update_module=update_module)
  File "/etc/odoo/odoo-server/odoo/odoo/modules/registry.py", line 85, in new
    odoo.modules.load_modules(registry._db, force_demo, status, update_module)
  File "/etc/odoo/odoo-server/odoo/odoo/modules/loading.py", line 376, in load_modules
    force, status, report, loaded_modules, update_module, models_to_check)
  File "/etc/odoo/odoo-server/odoo/odoo/modules/loading.py", line 274, in load_marked_modules
    perform_checks=perform_checks, models_to_check=models_to_check
  File "/etc/odoo/odoo-server/odoo/odoo/modules/loading.py", line 181, in load_module_graph
    _load_data(cr, module_name, idref, mode, kind='data')
  File "/etc/odoo/odoo-server/odoo/odoo/modules/loading.py", line 95, in _load_data
    tools.convert_file(cr, module_name, filename, idref, mode, noupdate, kind, report)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 792, in convert_file
    convert_xml_import(cr, module, fp, idref, mode, noupdate, report)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 853, in convert_xml_import
    obj.parse(doc.getroot(), mode=mode)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 752, in parse
    exc_info[2]
  File "/etc/odoo/odoo-server/odoo/odoo/tools/pycompat.py", line 86, in reraise
    raise value.with_traceback(tb)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 745, in parse
    self._tags[rec.tag](rec, de, mode=mode)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 723, in _tag_template
    return self._tag_record(record, data_node)
  File "/etc/odoo/odoo-server/odoo/odoo/tools/convert.py", line 655, in _tag_record
    id = self.env(context=rec_context)['ir.model.data']._update(rec_model, self.module, res, rec_id or False, not self.isnoupdate(data_node), noupdate=self.isnoupdate(data_node), mode=self.mode)
  File "/etc/odoo/odoo-server/odoo/odoo/addons/base/ir/ir_model.py", line 1504, in _update
    record = record.create(values)
  File "/etc/odoo/odoo-server/odoo/odoo/addons/base/ir/ir_ui_view.py", line 408, in create
    return super(View, self).create(self._compute_defaults(values))
  File "/etc/odoo/odoo-server/odoo/odoo/models.py", line 3409, in create
    record = self.browse(self._create(old_vals))
  File "/etc/odoo/odoo-server/odoo/odoo/models.py", line 3502, in _create
    cr.execute(query, tuple(u[2] for u in updates if len(u) > 2))
  File "/etc/odoo/odoo-server/odoo/odoo/sql_db.py", line 155, in wrapper
    return f(self, *args, **kwargs)
  File "/etc/odoo/odoo-server/odoo/odoo/sql_db.py", line 232, in execute
    res = self._obj.execute(query, params)
odoo.tools.convert.ParseError: "null value in column "projection" violates not-null constraint
DETAIL:  Failing row contains (2531, 2020-02-07 11:21:47.854173, 1, 2020-02-07 11:21:47.854173, t, null, null, null, Test Hello World, null, 16, primary, null, qweb, 1, null, null, null, null, null, null, my_module.template_test_hello_world, null, null, null, null, null).
" while parsing None:4, near
<t name="Test Hello World" t-name="my_module.template_test_hello_world"><!DOCTYPE html>

Url text: <t t-esc="val"/>

                        <t t-foreach="models" t-as="model">

<t t-esc="model.id"/><t t-esc="model.preview_name"/>

                        </t>

        </t>

The most interesting tho me probably is the first line:
bad query: b'INSERT INTO "ir_ui_view" ("id", "key", "priority", "active", "type", "name", "mode", "create_uid", "write_uid", "create_date", "write_date") VALUES(nextval(\'ir_ui_view_id_seq\'), \'my_module.template_test_hello_world\', 16, true, \'qweb\', \'Test Hello World\', \'primary\', 1, 1, (now() at time zone \'UTC\'), (now() at time zone \'UTC\')) RETURNING id'
ERROR: null value in column "projection" violates not-null constraint
DETAIL:  Failing row contains (2531, 2020-02-07 11:21:47.854173, 1, 2020-02-07 11:21:47.854173, t, null, null, null, Test Hello World, null, 16, primary, null, qweb, 1, null, null, null, null, null, null, my_module.template_test_hello_world, null, null, null, null, null).

But I don't know much about SQL or Odoo yet and I have found very little on the web although I spent almost an entire day on this, also, as you can see at the bottom of the error there seems to be a problem with the first template maybe it'll be useful for you to know that at some point it was the second template that was being displayed there.
I guess in the end my question is, does anyone know what is happening and how I can solve this?

A: For anyone facing the same issue, the problem seems to be caused by a corrupted view. A complete update of the system forces Odoo to recreate every view so that works. That means update all your packages by specifying all as the package name in the update command:
odoo-bin -d db -c config -u all


text:
Q: How to create a zip file of multiple image files I am trying to create a zip file of multiple image files. I have succeeded in creating the zip file of all the images but somehow all the images have been  hanged to 950 bytes. I don't know whats going wrong here and now I can't open the images were compressed into that zip file.
Here is my code. Can anyone let me know what's going here?
String path="c:\\windows\\twain32";
File f=new File(path);
f.mkdir();
File x=new File("e:\\test");
x.mkdir();
byte []b;
String zipFile="e:\\test\\test.zip";
FileOutputStream fout=new FileOutputStream(zipFile);
ZipOutputStream zout=new ZipOutputStream(new BufferedOutputStream(fout));

File []s=f.listFiles();
for(int i=0;i<s.length;i++)
{
    b=new byte[(int)s[i].length()];
    FileInputStream fin=new FileInputStream(s[i]);
    zout.putNextEntry(new ZipEntry(s[i].getName()));
    int length;
    while((length=fin.read())>0)
    {
        zout.write(b,0,length);
    }
    zout.closeEntry();
    fin.close();
}
zout.close();

A: This is my zip function I always use for any file structures:
public static File zip(List<File> files, String filename) {
    File zipfile = new File(filename);
    // Create a buffer for reading the files
    byte[] buf = new byte[1024];
    try {
        // create the ZIP file
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
        // compress the files
        for(int i=0; i<files.size(); i++) {
            FileInputStream in = new FileInputStream(files.get(i).getCanonicalName());
            // add ZIP entry to output stream
            out.putNextEntry(new ZipEntry(files.get(i).getName()));
            // transfer bytes from the file to the ZIP file
            int len;
            while((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            // complete the entry
            out.closeEntry();
            in.close();
        }
        // complete the ZIP file
        out.close();
        return zipfile;
    } catch (IOException ex) {
        System.err.println(ex.getMessage());
    }
    return null;
}

A: Change this:
while((length=fin.read())>0)

to this:
while((length=fin.read(b, 0, 1024))>0)

And set buffer size to 1024 bytes:
b=new byte[1024];


text:
Q: Read specific Word(Line 2, Word 3) from a text file by batch script I need to read specific words from a text file through batch script. Say I want Line 2 word 3 to be read.
Here is the code::
   @ECHO OFF
    cls
    SET /P line=Please enter Line number:
    ECHO Line number entered is : %line%

    SET /P word=Please enter Word number:
    ECHO Word number entered is : %word%

    FOR /F "tokens=%word% skip=%line% delims=," %%G IN (E_dir.txt) DO echo Chosen word is: %%G

The problem is, this gives me all the 3rd words starting from line 2. (say, user input is line 1, Word 3). There is a problem with the line count, But I can handle that. My problem is it is giving me all the words when I need only the single word of Line 2 and word 3.
Input file: E_Dir.txt
January,Snowy,02
February,Rainy,15
March,Sunny,25
April,Test,20

Output:
Please enter Line number: 1
Line number entered is : 1
Please enter Word number: 3
Word number entered is : 3
Chosen word is: 15
Chosen word is: 25
Chosen word is: 20

Expected Output:
Please enter Line number: 1
Line number entered is : 1
Please enter Word number: 3
Word number entered is : 3
Chosen word is: 15

A: Way the first
...
FOR /F "tokens=%word% skip=%line% delims=," %%G IN (E_dir.txt) DO echo Chosen word is: %%G&goto nextline
:nextline

Way the second
...
set showme=Y
FOR /F "tokens=%word% skip=%line% delims=," %%G IN (E_dir.txt) DO if defined showme set showme=&echo Chosen word is: %%G

Amendment
SET /a showme=line-1
SET showme=skip=%showme%
IF %line% equ 1 set "showme= "
FOR /F "tokens=%word% %showme% delims=," %%G IN (E_dir.txt) DO if defined showme set showme=&echo Chosen word is: %%G

Note that where %line% is 1, showme is deliberately set to a SPACE. This ensures that showme has a value initially.
I have no idea where your stray "2" is coming from. The procedure worked for me. Perhaps you may want to check the sourcefile with a hex editor. It may have a line without a LF. Possibly also check your batch. If you've used NOTEPAD, try an editor like EDITPLUS or NOTEPAD++. Notepad does some strange things.


text:
Q: Force horizontal expansion For a sort of thumbnail horizontal sliding viewer
How can I make the divs inside the horizontal scrolling divs force the scrolling div horizontally, instead of reaching the end and starting a new line?
I am already using float: left and display: inline-block but they reach the end of their container and make a new line instead of forcing the container to expand horizontally to fit them and thus forcing the horizontal scrollbar to be needed
so the div boxes are force to do this:
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
      <---->scroll

instead of:
[ ][ ][ ][ ]
[ ][ ][ ][ ]

code:

.box{
    width: 100px;
    height: 100px;
    border: solid 1px black;
    float:left;
    display: inline-block;
}

A: You don't need float and display:inline-block, and floats won't do it.. so you have to remove the float rule, (add a workaround for IE7 and below *) -  When float is present browsers ignore the display property
.box{
    width: 100px;
    height: 100px;
    border: solid 1px black;
    display: inline-block;
}

.box {display: inline !ie7;} /* to make it work in IE7 and below */

with white-space: nowrap on the inner div

etc..

A: Try this:

    FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO
    FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO
    BAR!
    FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO FOO

scroll to bar (HTML anchor)
<input type="button" value="scroll to bar (JS scrollIntoView)" />
<input type="button" value="scroll to bar (JS scrollLeft)" />

link


text:
Q: Repository and Data Mapper pattern After a lots of read about Repository and Data Mapper I decided to implement those patterns in a test project. Since I'm new to these I'd like to get your views about how did I implement those in a simple project.
Jeremy Miller says :

Do some sort of nontrivial, personal coding project where you can freely experiment with design patterns.

But I don't know I did all this things right or not.
Here is my project structure :

As you can see there are many folders which I'm going to describe them in detail in below.

*

*Domain : Project Domain Entities go here I've a simple Personnel class which is inherited from EntityBase class, EntityBase class has a single property named Id.
public int Id { get; set; }

*Infrustructure : Here is a simple Data Access Layer with two classes. SqlDataLayer is a simple class which is inherited from an abstract class named DataLayer. Here I provide some functionality like following code :
public SQLDataLayer() {
    const string connString = "ConnectionString goes here";
    _connection = new SqlConnection(connString);
    _command = _connection.CreateCommand();
}

adding parameter to commands parameter collection :
    public override void AddParameter(string key, string value) {
        var parameter = _command.CreateParameter();
        parameter.Value = value;
        parameter.ParameterName = key;

        _command.Parameters.Add(parameter);
    }

executing DataReader :
    public override IDataReader ExecuteReader() {
        if (_connection.State == ConnectionState.Closed)
            _connection.Open();

        return _command.ExecuteReader();
    }

and so on.

*

*Repository : Here I tried to implement repository pattern. IRepository is a generic interface

IRepository.cs :
public interface IRepository<TEntity> where TEntity : EntityBase
{
    DataLayer Context { get; }

    TEntity FindOne(int id);
    ICollection<TEntity> FindAll();

    void Delete(TEntity entity);
    void Insert(TEntity entity);
    void Update(TEntity entity);
}

Repository.cs :
public class Repository<TEntity> : IRepository<TEntity> where TEntity : EntityBase, new() {
    private readonly DataLayer _domainContext;
    private readonly DataMapper<TEntity> _dataMapper;
    public Repository(DataLayer domainContext, DataMapper<TEntity> dataMapper) {
        _domainContext = domainContext;
        _dataMapper = dataMapper;
    }
    public DataLayer Context {
        get { return _domainContext; }
    }
    public TEntity FindOne(int id)
    {
        var commandText = AutoCommand.CommandTextBuilder<TEntity>(CommandType.StoredProcedure, MethodType.FindOne);

        // Initialize parameter and their types
        Context.AddParameter("Id", id.ToString(CultureInfo.InvariantCulture));
        Context.SetCommandType(CommandType.StoredProcedure);
        Context.SetCommandText(commandText);

        var dbReader = Context.ExecuteReader();
        return dbReader.Read() ? _dataMapper.Map(dbReader) : null;
    }

I didn't expose not implemented methods from IRepository.
Here in Generic Repository class I expect two parameters in constructor first is a reference to my SqlDataLayer class and second is a reference to Entity DataMapper.
Those parameters sent by each Entities Repository class which inherited from Repository class. for example :
public class PersonnelRepository : Repository<Personnel>, IPersonnelRepository {
    public PersonnelRepository(DataLayer domainContext, PersonnelDataMapper dataMapper)
        : base(domainContext, dataMapper) {

    }
}

As you can see here in the FindOne method I tried to automate some operation such as creating CommandText, then I took the advantage of my DataLayer class to configure command and finally execute command to get IDataReader. I pass IDataReader to my DataMapper class to map to the Entity.

*

*DomainMapper : Finally here I map result of IDataReader to Entities, bellow is a sample of how I map Personnel entity :
public class PersonnelDataMapper : DataMapper<Personnel> {
public override Personnel Map(IDataRecord record) {
    return new Personnel {
        FirstName = record["FirstName"].ToString(),
        LastName = record["LastName"].ToString(),
        Address = record["Address"].ToString(),
        Id = Convert.ToInt32(record["Id"])
    };
}}

Usage :
    using (var context = new SQLDataLayer()) {
        _personnelRepository = new PersonnelRepository(context, new PersonnelDataMapper());
            var personnel  = _personnelRepository.FindOne(1);
    }

I know I did many mistake here, that's why I'm here. I need your advice to know what I did wrong or what are the good points in this simple test project.
Thanks in advance.

A: A few points:

*

*It strikes me that overall, you have a good design.  That's evidenced, in part, by the fact that you can make changes in it with little impact on any classes outside of the ones that are changed (low coupling).  That said, it's very close to what Entity Framework does, so while it's a good personal project, I'd consider using EF first before implementing it in a production project.

*Your DataMapper class could be made generic (say, GenericDataMapper<T>) using reflection.  Iterate over the properties of type T using reflection, and get them from the data row dynamically.

*Assuming you do make a Generic DataMapper, you could consider making a CreateRepository<T>() method on DataLayer, so that users don't need to worry about the details of which type of Mapper to pick.

*A minor critique- you assume that all entities will have a single integer ID named "Id", and that a stored procedures will be set up to retrieve them by such.  You may be able to improve your design here by allowing for primary keys of differing types, again maybe by using generics.

*You probably don't want to re-use Connection and Command objects the way you do.  That isn't thread safe, and even if it was, you'd end up with some surprising and hard-to-debug race conditions around DB Transactions.  You either should create new Connection and Command objects for each function call (making sure to dispose of them after you are done), or implement some synchronization around the methods that access the database.
For instance, I'd suggest this alternate version of ExecuteReader:
public override IDataReader ExecuteReader(Command command) {
    var connection = new SqlConnection(connString);
    command.Connection = connection;
    return command.ExecuteReader();
}

Your old one re-used the command object, which could lead to race conditions between multithreaded callers.  You also want to create a new connection, because the old connection might be engaged in a transaction started by a different caller.  If you want to re-use transactions, you should create a connection, begin a transaction, and re-use that transaction until you have executed all of the commands that you want to associate with the transaction.  As an example, you could create overloads of your ExecuteXXX methods like this:
public override IDataReader ExecuteReader(Command command, ref SqlTransaction transaction) {
    SqlConnection connection = null;
    if (transaction == null) {
        connection = new SqlConnection(connString);
        transaction = connection.BeginTransaction();
    } else {
        connection = transaction.Connection;
    }
    command.Connection = connection;
    return command.ExecuteReader();
}

// When you call this, you can pass along a transaction by reference.  If it is null, a new one will be created for you, and returned via the ref parameter for re-use in your next call:

SqlTransaction transaction = null;

// This line sets up the transaction and executes the first command
var myFirstReader = mySqlDataLayer.ExecuteReader(someCommandObject, ref transaction);

// This next line gets executed on the same transaction as the previous one.
var myOtherReader = mySqlDataLayer.ExecuteReader(someOtherCommandObject, ref transaction);

// Be sure to commit the transaction afterward!
transaction.Commit();

// Be a good kid and clean up after yourself
transaction.Connection.Dispose();
transaction.Dispose();

*Last but not least, having worked with Jeremy I'm sure he'd say that you should have unit tests for all of these classes!


text:
Q: Primeflex + PrimeNG tab + PrimeNG tree - unable to make tabPanel grow Could someone help me with the layout of those PrimeNG components?
I would like to have a tree taking the whole vertical space (minus buttonset at the bottom), scrolling if needed. Tree is being places inside a tab panel.
Thanks in advance
https://stackblitz.com/edit/angular-np8of7?file=src/app/app.component.html

A: Either you can add this kind of CSS
.p-tree {
  height: calc(100vh - 300px);
  overflow: auto;
}

but in order to apply it, you have to declare encapsulation: ViewEncapsulation.None in your component definition. See StackBlitz.
Either you just add in your CSS:
:host ::ng-deep .p-tree {
  height: calc(100vh - 300px);
  overflow: auto;
}


text:
Q: action support returning empty value when i click on the column action event working when i open the log coming with null value... values are not displaying in the table.
<apex:page controller="actionSupportController">
<apex:form >
            Household Name: <apex:inputText value="{!ID_c}" />
    <apex:commandButton value="Search" action="{!doSearch}" rerender="pblck"/>

   <apex:pageBlock id="pblck" >
    <apex:pageblockTable value="{!lstQuery}" var="eachRecord" >
        <apex:column ><apex:actionSupport event="onclick" action="{!incrementCounter}" rerender="out">
        <apex:param value="{!eachRecord.ID}" assignTo="{!test}"/>
        </apex:actionSupport></apex:column>
        <apex:column value="{!eachRecord.ID}"/>
        <apex:column value="{!eachRecord.Household__c}"/>
        <apex:column value="{!eachRecord.Name}"/>
        <apex:column value="{!eachRecord.Phone__c}"/>
        <apex:column value="{!eachRecord.of_Childrens__c}"/>
        <apex:column value="{!eachRecord.of_Exiting_Pets__c}"/>
        <apex:column value="{!eachRecord.Address__c}"/>
        <apex:column value="{!eachRecord.Previous_Dog__c}"/>
    </apex:pageblockTable>
   </apex:pageBlock>

    <apex:pageBlock id="out">
    <apex:pageBlockTable value="{!OnlstQuery}" var="eachReco">
        <apex:column value="{!eachReco.ID}"/>
        <apex:column value="{!eachReco.Household__c}"/>
        <apex:column value="{!eachReco.Name}"/>
        <apex:column value="{!eachReco.Phone__c}"/>
        <apex:column value="{!eachReco.of_Childrens__c}"/>
        <apex:column value="{!eachReco.of_Exiting_Pets__c}"/>
        <apex:column value="{!eachReco.Address__c}"/>
        <apex:column value="{!eachReco.Previous_Dog__c}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>

         <!--<apex:outputpanel id="panel1" >
                <apex:outputText value="Click here to increment!"/>
                <apex:actionSupport event="onclick" action="{!incrementCounter}" rerender="out"/>
            </apex:outputpanel>

             <apex:outputpanel id="panel2">
                <apex:outputText value="Click here to decrement!"/>
                <apex:actionSupport event="onclick" action="{!decrementCounter}" rerender="out"/>
            </apex:outputpanel>

            <apex:outputText value="{!Query}" id="out" label="Count Is:"/>-->
  </apex:form>
</apex:page>

Controller
public class actionSupportController {
public List<PCS_Household__c> lstQuery{get;set;}
public List<PCS_Household__c> OnlstQuery{get;set;}
public string ID_c{get;set;}
public string test{get;set;}

public PageReference incrementCounter() {
   string Query='';
    Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where ID=:test' ;
    system.debug('==Query=='+Query);
    OnlstQuery=Database.query(Query);
    system.debug('==lstQuery=='+OnlstQuery);
    return null;
}

 public Void doSearch(){
    string Query='';
    Query='SELECT ID,Name,Household__c,Phone__c,of_Childrens__c,of_Exiting_Pets__c,Address__c,Previous_Dog__c FROM PCS_Household__c where Household__c LIKE \'%'+ID_c+'%\'';
    system.debug('==Query=='+Query);
    lstQuery=Database.query(Query);
    system.debug('==lstQuery=='+lstQuery);
 }

}

A: Issue with apex:param you need to give any name to your param
<apex:param name="recordId" value="{!eachRecord.ID}" assignTo="{!test}"/>

This should work now. without name it will not work..
Let me know if this resolved your issue or not.


text:
Q: How to better display elements inside card? i have a task where i should have information inside "card", it should be displayed like on my example(picture)
so here is my html

        <el-card shadow="always">
            Dashboard
        </el-card>

    <el-card class="box-card">

Card name

Challenge

    </el-card>

can you help me to place those "approved posts", "influences", "likes", "comments" like on picture?
let's say i don't have such big experience bud i think that i should use grid or table display...
can you show me some example or to show how could it be in my example?
Thank you!
i am using Vue.js and Element UI libruary

A: Basicaly you need to follow col's, if you're familiar with bootstrap. so 2 equal col does the job
ex:

            Posts
            545454

            Influencer
            56656

            Likes
            label>545454

            Comments
            56656


text:
Q: Wordpress - Check if jquery plugin has already been registered I'm creating a wordpress plugin that uses Select2. What is the correct way of checking if Select2 has been loaded already before registering the script?
If I don't check it the plugin will be loaded twice.

A: You can use wp_script_is, which determines if script has been registered, enqueued, etc.
if( ! wp_script_is( 'custom-script', 'enqueued' ) ) {
    // the plugin is not enqueued
}

Update: wp_enqueue_script will check if specific plugin is loaded and will not load it twice, so in most cases you don't have to worry about this. Well, it should works if you doing things the right way, e.g. use built-in functions for dealing with custom scripts, like wp_register_script, etc.


text:
Q: Delete record on database with cron scheduler does not update if I wont save server I am using NodeJS cron-schedule to delete a record from the database.
I created a separate module that is executed in app.js file. The Module take all the users (silencedUsers) from the database and map trough them to get the time when the specific user should be deleted from the silenced table.
However, I face some challenges. If I input a record on the database and do not save the server with control + s, the function is not execute.
const {getAllSilencedUsers, deleteSilencedUser} = require('../dataAccessLayer/usersLayers.js');
let cron = require('node-schedule');

module.exports = async () => {
    try
    {
        const silencedList = await getAllSilencedUsers();

        if (silencedList) {
            silencedList.map(user => {

                let time = {
                    year:       user.end_date.getFullYear(),
                    month:      user.end_date.getUTCMonth() + 1,
                    day:        user.end_date.getUTCDate(),
                    hour:       user.end_date.getHours(),
                    minutes:    user.end_date.getMinutes()
                };

                let deadline = `${time.year}-${time.month}-${time.day} ${time.hour}:${time.minutes}:00`;
                cron.scheduleJob(deadline, function(){
                    deleteSilencedUser(user.userID)
                    console.log('Deleted');
                  });
            })
        }
        else return;
    }

    // Catch block
    catch (error)
    {
        if (error) console.log(error);
    }
}

Above is the function that create me problems. I exported it and import it into app.js
/* Node Cronjobs */
require('./services/automaticUnsilence.js')();

The main problem is: When I am input a record in the database and don't save the server, the function does not execute.
Please, how can I fix this?


text:
Q: Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in PHP mysql_connect("localhost","root","");
mysql_select_db("hitnrunf_db");

$result=mysql_query("select * from jos_users INTO OUTFILE 'users.csv' FIELDS ESCAPED BY '""' TERMINATED BY ',' ENCLOSED BY '"'
 LINES TERMINATED BY '\n' ");

header("Content-type:  text/plain");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

in the above code  in query string i.e string in side mysql_quey
we are getting following error
Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in C:\wamp\www\samples\mysql_excel\exel_outfile.php on line 8

in query string '\n' charter is not identifying as string thats why above error getting

A: You need to escape the double quote as: \" instead of ""
$result=mysql_query("select * from jos_users INTO OUTFILE 'users.csv' FIELDS ESCAPED BY '\"' TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' ");

An un-escaped " will prematurely terminate the string.
Example:
This is incorrect: "A " is a double quote"
This is correct: "A \" is a double quote"


text:
Q: Custom folder for custom codes We're having a restructuring on our application and currently the idea is to break the codes into Core library codes + customized codes for our developer.
I'm thinking of the possibility to have a folder (i.e. 'custom') that is empty by default, and when the developer need to customize any codes either from existing asp pages or new pages, they just need to put them into the folder and it will work. Example:
Lets say core folder store the default asp pages.
core\customer\createCustomer.asp <-- the default page

And when the developer want to overwrite that page, he needs to copy that asp page to the custom folder, like
custom\customer\createCustomer.asp <-- modified asp page

The application will automatically load the one in the custom folder rather the one in the core folder.
Is this doable in C#?

A: You can use a VirtualPathProvider to load a different file than the "actual requested one". This works well with IIS and caching for instance as well.
Basically you inherit the VirtualPathProvider and override the FileExists, GetFile, and DirectoryExists, GetDirectory methods (there's an example in the linked page). Then, in your AppInitialize, register the provider with
HostingEnvironment.RegisterVirtualPathProvider(sampleProvider);

By the way, don't forget to have a different (non-editable) page so the user can revert any changes that was made, in order to restore a potential misedit so to speak. I would probably have a simple version control system and use commit whenever the user made changes, and allow the user to revert to a previous changeset.

A: This MSDN article explains how to use an IHttpModule implementation to intercept HTTP requests and perform custom actions (they point out logging, but since you're intercepting the request you might as well fetch some different content, such as your 'customized' code).


text:
Q: Grails Local Plugin Render I'm trying to access methods from controllers in a local plugin. I included the plugin like so:
grails.plugin.location.'helloworld' = "../helloworld"

I want to invoke the hello() method and pass in some params to it. I tried the following from the index page of my app:
<g:include plugin="helloworld" action="index" controller="hello" model="['name':'John Doe']"></g:include>

Here is the controller method in the plugin:
package helloworld

class HelloController {

    def index() {
        println "working"
    }
}

I'm trying to keep it simple and get it to work before I worry about rendering views and processing parameters. I'm sure my approach is not the right way, I just need someone to point me in the right direction please.

A: Try:
package helloworld

class HelloController {

    def index() {
        render "working"
    }
}


text:
Q: Simple Magento question I have a website in Magento, it's still very simple and unfinished.
Since I'm a beginner in this field, I'd like someone to point me to a solution:
How do I change the Checkout link text?
Is it done inside the phtml/XML structure or inside admin panel?
this is my website: [notice the Checkout link]
http://gale.dev4.webenabled.net/

A: you can find locale files under app/locale/language_CODE and change the translation from there . To find the translations either use file search or grep for the string you are looking for
grep '"Checkout"' app/locale/en_US/ -rsn

this will show you filename, line number and the searched string:
app/locale/en_US/Mage_Checkout.csv:40:"Checkout","Checkout"

remember that locale files are utf-8 encoded and cache must be cleared after changing localizations

A: You should be able to change the text in the the following template
\app\design\frontend\enterprise\default\template\checkout\cart\cartheader.phtml
Kindly note that this is a directory path from an enterprise installation. Yours might be different but the filename of the template should be the same.
Another option is to use the locale files to actually change by Specifying a translation in the appropriate locale file.
HTH :)


text:
Q: Tag found but class not visible Python Selenium I've spent over 4 hours and counting trying to get an element that's visible on the web page but won't pull when I try using Selenium to scrape it. I even tried to copy direct xpath to element but still does not work. Inspecting the page on my browser shows the structure to be like this.

...

        <svg class="margin-center">
          <rect class="form-in-shape"></rect>
          <text class="form-win-text">TEXT</text>
        </svg>

...

...

...

...

...

TEXT is what I'm scraping for, I was able to locate upto all the 5 div tags with class="form-box flex-xs-no-grow cursor-pointer ", but it won't find the svg tag or the text tag, when I try using the direct xpath, it finds up to the text tag but returns empty string with I try to get the text within the tag.
Here is my code as I am currently out of ideas on how to approach this.
z = driver.find_element_by_xpath("//div[@class='sub-container head-to-head']/div[3]/div/div[@class='panel margin-bottom ']/div/div[@class='row']")

        z1 = z.find_element_by_xpath(".//div[@class='col-xs-6']/div[@class='row']/div[@class='col-xs-12 col-sm-5 col-md-7 flex-deprecated flex-items-xs-middle flex-items-xs-center']/div/div[@class='visible-md-up hidden-xs-up']/div/div[@class='row']/div/div/div[2]/div[@class='row flex-xs-nowrap no-margin form-left form-box-container ']")
        z2 = z1.find_elements_by_xpath(".//div[@class='form-box flex-xs-no-grow cursor-pointer ']")

        try:
            for i_ in range(0, 5):
                ztemp1 = z2[i_].find_element_by_class_name("margin-center")
                wait.until(EC.presence_of_element_located((By.CLASS_NAME, "form-with-text")))
                #ztemp = ztemp1.find_elements_by_class_name("form-with-text")
                ztemp =ztemp1.find_element_by_tag_name("text")
                #print("TESTIN>>> {}".format(len(ztemp)))
                print("SKKKKKK>>>>> {}".format(ztemp.text))
                z3 = z2[i_].find_elements_by_xpath(".//*")

                print('good here {}'.format(len(z3)))

        except(NoSuchElementException):
            print('Tag or Class not found')

When I try to find the text tag by class name, it does not find it, but it finds it when I search by tag name but it's an empty string. Here's the link to the site I'm using [Source Site][1]
Any help and tip will be highly appreciated.
[1]: https://s5.sir.sportradar.com/betking/en/1/season/83706/headtohead/17/42/match/27751100

A: That is a svg element. You can locate like this :
//*[name()='svg' and @class='margin-center']//*[name()='text']

this is giving me 66 web elements.
you can loop through it like below :
driver = webdriver.Chrome(driver_path)
driver.maximize_window()
driver.implicitly_wait(50)
driver.get("https://s5.sir.sportradar.com/betking/en/1/season/83706/headtohead/17/42/match/27751100")

for txt in driver.find_elements(By.XPATH, "//*[name()='svg' and @class='margin-center']//*[name()='text']"):
  print(txt.text)

A: You can also try this:
driver.implicitly_wait(10)
driver.get("https://s5.sir.sportradar.com/betking/en/1/season/83706/headtohead/17/42/match/27751100")
time.sleep(5)
elements = driver.find_elements_by_xpath("//div[contains(@class,'col-sm-5')]//div[contains(@class,'hidden-md-up')]")
for ele in elements:
    datalist = []
    data = ele.find_elements_by_xpath(".//div[contains(@class,'cursor-pointer')]")
    for d in data:
        datalist.append(d.get_attribute("innerText"))
    print(datalist)

Output:
['W', 'L', 'L', 'W', 'W']
['L', 'L', 'L', 'L', 'D']


text:
Q: Room Peristance get all records list size from embedded list I want to make a query which will get all the sizes from all the records of the list 'times'
example: i have these records
1) "20/3/2010" [1,2,3] "reason"
2) "21/3/2010" [1,4,6,7] "reason"

the result is
1)times.size +
2)times.size = 7

Entity
@Entity(tableName = "absence_table")
@TypeConverters(AbsenceTypeConverters::class)
class Absence (
  @PrimaryKey
  var date:String,

  var times:List<String>,
  var reason:String
)


text:
Q: How to transfer excel files to MacBook Air I have a new MacBook Air computer and would like to transfer my Excel spreadsheets from my Windows 7 to it.  How can I do this transfer without using a disk?

A: You could 1)install iCloud on the Windows machine and copy them to the iCloud folder, or 2)do the same thing with another cloud program such as Google drive or Microsoft OneDrive.


text:
Q: Converting HashMap Error Message content to JSON So I'm struggling to find a solution to this issue, I've currently got a function on the front end which relies on an error message in the back end. This error section is summarised to this:
HashMap<Long, Integer> serviceListResponse = new HashMap<>();
...
if (!serviceListResponse.isEmpty()) {
                throw new IllegalArgumentException(String.valueOf(serviceListResponse));
}

So I thought this should be straight forward to parse:
$log.info(JSON.stringify(errorResponse.data.message))
log message = "{16=2140002475, 17=2140002724, 18=2140002116, 8=2140034827}"
$scope.listOfIds = JSON.parse(errorResponse.data.message);

However it doesn't seem to be passing the JSON.parse and therefore ending at that particular line. I've used JSON.parse before for ArrayLists and had no issues, so what am I doing wrong for this? Thanks.

A: There are 2 problems with your code. First you are not using ObjectMapper which basically take care of converting response to JSON in Java. Second since a raw string is coming in response it has characters that won't let you parse the response.
Like "{16=2140002475,..}", response is already a string so JSON.stringify won't work, it'll just prefix and suffix double quotes ""{16=2140002475, ..}"". Second even if you somehow manage to remove quotes, Your key is Number & delimiter is = both are not identified by JSON.parse, it need Key as String & delimiter as :.
Since you do not want to change code in Java (still highly recommended), I gave a try to parse your response in JS. What you need is a custom parser which will convert your response string to JS dictionary and then you can directly use it without JSON.parse.

function customParse(message) {
  var msgArray = message.replace(/[{}]/g, '').split(',');
  var dict = {};
  for (var data of msgArray) {
    var obj = data.split('=');
    dict[obj[0].trim()] = obj[1];
  }
  return dict;
}

var message = "{16=2140002475, 17=2140002724, 18=2140002116, 8=2140034827}";
console.log(customParse(message));

Note: This will not work if you introduce any nested HashMap in your original Java map.