text:
Q: How we can send corresponding email verification link admin, vendor and user auth in laravel, How we can send corresponding email verification link admin, vendor and user auth in laravel,
as
admin: admin.verification.email (http://139.59.75.219/welwel/public/admin/email/verify/1?expires=1552402747&signature=b3768d97b4d98bb226171e880a95802e68540aae9f5f21f78a9782fce895c960)
vendor: vendor.verification.email (http://139.59.75.219/welwel/public/vendor/email/verify/1?expires=1552402747&signature=b3768d97b4d98bb226171e880a95802e68540aae9f5f21f78a9782fce895c960)
user already have verification.email (http://139.59.75.219/welwel/public/email/verify/1?expires=1552402747&signature=b3768d97b4d98bb226171e880a95802e68540aae9f5f21f78a9782fce895c960)
Even I have use:
Vendor\Auth\VerificationController.php
<?php
namespace App\Http\Controllers\Vendor\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;
class VerificationController extends Controller{
use VerifiesEmails;
public function __construct()
{
    $this->middleware('vendor');
    $this->middleware('signed')->only('verify');
    $this->middleware('throttle:6,1')->only('verify', 'resend');
}
public function verify(Request $request)
{
    if ($request->route('id') != $request->user('vendor')->getKey()) {
        throw new AuthorizationException;
    }

    if ($request->user('vendor')->markEmailAsVerified()) {
        event(new Verified($request->user('vendor')));
    }

    return redirect($this->redirectPath())->with('verified', true);
}
public function resend(Request $request)
{
    if ($request->user('vendor')->hasVerifiedEmail()) {
        return redirect($this->redirectPath());
    }

    $request->user('vendor')->sendEmailVerificationNotification();

    return back()->with('resent', true);
}
}

middleware: VendorEnsureEmailIsVerified.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Contracts\Auth\MustVerifyEmail;
class VendorEnsureEmailIsVerified
{
    public function handle($request, Closure $next)
    {
        if (! $request->user('vendor') ||
            ($request->user('vendor') instanceof MustVerifyEmail &&
            ! $request->user('vendor')->hasVerifiedEmail())) {
            return $request->expectsJson()
                    ? abort(403, 'Your email address is not verified.')
                    : Redirect::route('vendor.verification.notice');
        }

        return $next($request);
    }
}

other thing working fine, only link generating only for user, not seoreate for admin, vendor and user


text:
Q: Syslog start logging in the morning! why? Hello I've a Ubuntu server 18.04 running. But the problem is syslog start logging at every morning not at 00:00 midnight!
Jan  5 06:25:03 localhost snmpd[810]: truncating integer value > 32 bits
Jan  5 06:29:04 localhost snmpd[810]: message repeated 14 times: [ truncating integer value > 32 bits]
Jan  5 06:30:01 localhost CRON[10230]: (root) CMD (   PATH="$PATH:/usr/sbin:/usr/local/bin/" pihole updatechecker local)
Jan  5 06:30:04 localhost snmpd[810]: truncating integer value > 32 bits
Jan  5 06:35:04 localhost snmpd[810]: message repeated 17 times: [ truncating integer value > 32 bits]
Jan  5 06:36:03 localhost snmpd[810]: truncating integer value > 32 bits
Jan  5 06:38:04 localhost snmpd[810]: message repeated 8 times: [ truncating integer value > 32 bits]
Jan  5 06:39:01 localhost CRON[10288]: (root) CMD (  [ -x /usr/lib/php/sessionclean ] && if [ ! -d /run/systemd/system ]; then /usr/lib/php/sessionclean; fi)
Jan  5 06:39:04 localhost snmpd[810]: truncating integer value > 32 bits
Jan  5 06:39:04 localhost snmpd[810]: message repeated 2 times: [ truncating integer value > 32 bits]```

A: If you would like to have your logs rotate at midnight every day, you'll need to make some changes to your /etc/crontab file. This is the basic structure that you'll find as part of a default installation:
...
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

The daily actions happen at 6:25am, the weekly actions happen at 6:47am every Sunday, the monthly actions happen on the 1st at 6:52am. So, to modify the daily log rotation time, you will want to change:
25 6    * * *   root    test -x /usr/sbin/anacron ...

To:
 0 0    * * *   root    test -x /usr/sbin/anacron ...

Be sure to change just the numbers. Nothing else should be modified. Once this is complete, a reboot may be necessary just to ensure that the crontab is properly loaded.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Clr Button, state pressed is there an easy way to change the style of a button? so it looks pressed? I'm using clr-button from clarity project, I have several buttons on the page and my boss wants that the non pressed button to take the style of a secondary button, and the pressed one should look like a primary-button.
These are the buttons:

<clr-button-group>
    <clr-button (click)="externalFilterChanged('Upcoming', 'Stipulations')">Upcoming</clr-button>
    <clr-button (click)="externalFilterChanged('Overdue', 'Stipulations')">Overdue</clr-button>
    <clr-button (click)="externalFilterChanged()">All</clr-button>
</clr-button-group>
<clr-button-group>
    <clr-button (click)="externalFilterChanged('PA', 'Type')">PA</clr-button>
    <clr-button (click)="externalFilterChanged('MOA', 'Type')">MOA</clr-button>
    <clr-button (click)="externalFilterChanged('MOU', 'Type')">MOU</clr-button>
    <clr-button (click)="externalFilterChanged('Covenant', 'Type')">Cov</clr-button>
    <clr-button (click)="externalFilterChanged('BSC', 'Type')">BSC</clr-button>
    <clr-button (click)="externalFilterChanged()">All</clr-button>
</clr-button-group>
<clr-button-group>
    <clr-button (click)="externalFilterChanged('Opened', 'Status')">Opended</clr-button>
    <clr-button (click)="externalFilterChanged('Approval', 'Status')">Approval</clr-button>
    <clr-button (click)="externalFilterChanged('Monitoring', 'Status')">Monitoring</clr-button>
    <clr-button (click)="externalFilterChanged('Closed', 'Status')">Closed</clr-button>
    <clr-button (click)="externalFilterChanged()">All</clr-button>
</clr-button-group>

if they were only two I thought perhaps in a boolean to toggle between the class="btn" and class="btn btn-primary" but since they are several I'm kind of lost.
Here is the link for the buttons from clarity, or if there's another way to make it look pressed please tell me, maybe it could work too.

A: Something like below should do the tick:

    <button class="btn" [class.btn-primary]="true">
       one
    </button>
    <button class="btn" [class.btn-primary]="false">
        two
    </button>
    <button class="btn" [class.btn-primary]="false">
       three
    </button>


text:
Q: Add space between specific facets in ggplot2 (facet_grid) I've been able to add vertical space between all facets (Alter just horizontal spacing between facets (ggplot2)) but haven't been able to add just one space between specified facets?
Here's an example based on my real data (in the real plot I have stacked bars):
mydf<-data.frame(year = rep(c(2016,2016,2016,2016,2016,2016,2017,2017,2017,2017,2017,2017),times = 2),
             Area = rep(c('here','there'),times = 12),
             yearArea = rep(c('here.2016','here.2017', 'there.2016','there.2017'), times = 12),
             treatment = rep(c('control','control','control','treat', 'treat','treat'), times = 4),
             response = rep(c('a','b','c','d'), times = 6),
             count = rep(c(23,15,30,20), times = 6))
mycolour<-c("#999999", "#0072B2", "#009E73","#000000")

Returns plot:
#default facet spacing
example<-ggplot(data=mydf, aes(x=treatment, y=count, fill=response)) +
  geom_bar(stat="identity", width = 0.5) +
  scale_fill_manual(values = mycolour, name = "Response") +
  labs (y = "Count") +
  facet_grid(~yearArea) +
  theme_bw()
example

#spacing between each facet
spacedex<-example + theme(panel.spacing.x=unit(2, "lines"))

spacedex

How can I limit the addition of space to only between the second and third facet? (between here.2017 and there.2016)

A: library(grid)
gt = ggplot_gtable(ggplot_build(example))
gt$widths[7] = 4*gt$widths[7]
grid.draw(gt)


text:
Q: Multiple ActiveX buttons visible/hidden I have a Worksheet in excel 2013, with 25 activex buttons on it. depending on a cell value for each button, i would like it to be visible or hidden. In my case the value of cell U6 makes my commandbutton1 visible, U7 would make commandButton2 visible.... Only my CommandButton1 works properly. I have tried different combinations of code without succes.
    Private Sub CommandButton1_Click()
    End Sub
    Private Sub Worksheet_Change(ByVal Target As Range)
    'ActiveX button1
       If Range("U6") = 1 Then
        Sheets("Feuil1").CommandButton1.Visible = True
    Else
        Sheets("Feuil1").CommandButton1.Visible = False
      End If

   End Sub

A:
If Range("U6") = 1 Then

Shouldn't that check if the Target (i.e. the modified cell) is in column U?

Sheets("Feuil1").CommandButton1.Visible = True

That road leads to pastaland, you don't want to go there: extract a method. You'll want to query the OLEObjects collections to get the ActiveX control by name, rather than hard-coding the button names 25+ times.
Private Sub SetControlVisibility(ByVal controlName As String, ByVal isVisible As Boolean)
    Dim axControl As OLEObject
    On Error Resume Next 'next statement may throw error #9
        Set axControl = Me.OLEObjects(controlName)
        If axControl Is Nothing Then Exit Sub
    On Error GoTo 0 'restore error handling
    axControl.Object.Visible = isVisible
End Sub

Now you have a method that can toggle the visibility of any ActiveX control on the sheet, given its name.
So in the Worksheet_Change handler, you now just need to work out the name of the ActiveX control, and whether or not you want it visible:
Private Sub Worksheet_Change(ByVal Target As Range)
    'bail out if the modified cell isn't interesting, or if it's more than 1 cell:
    If Intersect(Target, Me.Range("U6:U31") Is Nothing  Or Target.Count <> 1 Then Exit Sub

    Dim buttonName As String
    buttonName = "CommandButton" & Target.Row - 5

    Dim isVisible As Boolean
    isVisible = Target.Value = 1

    SetControlVisibility buttonName, isVisible
End Sub

Or something like it. Note: code written in the answer box, untested & for illustrative purposes only. Copy-pasta at your own risk.


text:
Q: [Qt]Customising QTreeWidgetItem I want to customise QTreeWidgetItem. I wish to add to it, two Toolbuttons and a string.  Also I wish to add these to only one column in the treewidget.
I tried to subclass QTreeWidgetItem but realised I coult not "paint" on it as it is not derived from QWidget.
I then tried using QTreeWidget::setItemWidget(QTreeWidgetItem *item, int column, QWidget widget);However, the button overlaps over the text written to the item. If I add widgets to different columns, using the above call, I'm not able to acheive the look and feel the way I want to.
How do I acheive this?
Also, I want to change my "+/-"(expand collapse) buttons to triangular buttons as in Vista.
I saw an example where they do it using stylesheets, but is there another way to do it through code?
Thanks

A: For such an extensive modification, I would recommend changing from a tree widget to a model and tree view, and using a delegate to change how it is painted.  There are a number of examples on their web site.


text:
Q: error message indicates a conflict in the dependencies of the packages in my vproject PS E:\aub\stackoverflow-clone-mern\frontend> npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: react-html-parser@2.0.2
npm ERR! Found: react@17.0.2
npm ERR! node_modules/react
npm ERR!   react@"^17.0.2" from the root project
npm ERR!   peer react@"^16.8.0 || ^17.0.0" from @material-ui/core@4.12.3
npm ERR!   node_modules/@material-ui/core
npm ERR!     @material-ui/core@"^4.12.3" from the root project
npm ERR!     peer @material-ui/core@"^4.0.0" from @material-ui/icons@4.11.2
npm ERR!     node_modules/@material-ui/icons
npm ERR!       @material-ui/icons@"^4.11.2" from the root project
npm ERR!   20 more (@material-ui/icons, @material-ui/styles, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^0.14.0 || ^15.0.0 || ^16.0.0-0" from react-html-parser@2.0.2
npm ERR! node_modules/react-html-parser
npm ERR!   react-html-parser@"^2.0.2" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: react@16.14.0
npm ERR! node_modules/react
npm ERR!   peer react@"^0.14.0 || ^15.0.0 || ^16.0.0-0" from react-html-parser@2.0.2
npm ERR!   node_modules/react-html-parser
npm ERR!     react-html-parser@"^2.0.2" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! node_modules/react
npm ERR!   peer react@"^0.14.0 || ^15.0.0 || ^16.0.0-0" from react-html-parser@2.0.2
npm ERR!   node_modules/react-html-parser
npm ERR!     react-html-parser@"^2.0.2" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Ayoub\AppData\Local\npm-cache\eresolve-report.txt for a full report.
npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Ayoub\AppData\Local\npm-cache_logs\2023-02-03T22_54_33_973Z-debug-0.log
package.json
"dependencies": {
"axios": "^0.21.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^6.0.2",
"nodemon": "^2.0.12"
}


text:
Q: Uncaught Error: Minified React error #321 after deployment react js I'm trying to deployed a simple web app with react js.
My server is working fine and all my app is working fine on a dev mode.
But when i make a build , i put my build folder on my public folder , my web app appeared 1sec then i have white screen . When i opened my consol i have this error
Uncaught Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
When i delete my static folder from my public folder i have the web app ok on my dev environnement. So i think the problem is comming from the static folder but i don't know what :(
Evrytime the error bring me to this part
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById("root")
);

react 17.0.2
React dom 17.0.2


text:
Q: How do I pass current date range from Fullcalendar to the JSON function I use fullcalendar eventsources function, to get events data from db:
eventSources: getSources()

where getSources is
getSources(){
 var mysources = {
   mysourceone:{
                url: YOUR URL TO GET JSON,
                type: 'POST',
                data:{
                    st:'2016-08-19',et:'2016-08-24'
                 },
                 cache: false,
                 color: '#C1272D',
                 textColor: 'white'
                 }
              }
  return [mysources.mysourceone];
}

My question is, how do I replace fixed dates in this function with currently selected date range in fullcalendar?
                data:{
                    st:'2016-08-19',et:'2016-08-24'
                 },

A: FullCalendar should pass the start and end dates automatically, so just leave them out of your call, and on the page where FullCalendar checks for events you can just access $_GET['start'] and $_GET['end'] and query your database based on those dates. You can also go to your browser inspector and view the network tab while switching months, weeks or views on your calendar and see the calls it makes. You can also append your own variables like user id's, time zones and so on.


text:
Q: Discard runaway values from Distance measurement I am trying to get better readings from my HC-SR04 Ultra Sound Sensor:
I am using the New.ping library so sonar.ping_cm()gets me the measured distance in cm.
My idea is to measure Xtimes and calculate the mean value (Mean_Value_1).
The next step is to get all readings that are +/- 20% off Mean_Value_1 --> kick them --> calculate the new mean value and return it --> (return x_distance / new_count;)
I am uploading the value to thing speak but with the following code I always end up with 'NAN' uploaded :-(
Here's the code:
float getAverage(int X) {
float x_distance = 0,temporary,Mean_Value_1;
int i = 0, first_count = 0, new_count=0, values[]={};

for (i = 0; i < X; i++) {
    x_distance += sonar.ping_cm();
    values[first_count++] = x_distance;
    delay(100);
}
Mean_Value_1 = x_distance / X;
x_distance = 0;
for (i=0; i<first_count; i++){
  temporary = (Mean_Value_1 - values[i])*100/Mean_Value_1;
  if (temporary < 20 && temporary > -20){
    x_distance += values[i];
    new_count++;
  }
}
return x_distance / new_count;
}

thanks for the comments so far.
can I change values[]={}to `values[X]?
Edit for clarification:
I tried just the following code and it worked
double getAverage(int X) {
double x_distance = 0;
int i = 0;

for (i = 0; i < X; i++) {
    x_distance += sonar.ping_cm();
    delay(100);
}
return x_distance / X;

}

so if I call in the loop double distance = getAverage(1000);i get a decent measurement.
everything after that doesn't work

A: Check the value of new_count. I suspect you're dividing by zero
return new_count ? x_distance / new_count : -1; /* distance cannot be negative! */


text:
Q: time series prediction model with minute data I m trying to apply prediction at my data that is taken from the sensor after 15
min
2020-01-09 12:00:00 90.82098
2020-01-09 12:15:00 90.61686
2020-01-09 12:30:00 86.22828
2020-01-09 12:45:00 82.04382
2020-01-09 13:00:00 79.90056

I saw some methods. Stated from ARIMAX (but I understood that I can't apply because my data have multi-season )
So I looked the TBATS but something goes wrong
from tbats import TBATS, BATS
# Fit the model
estimator = TBATS(seasonal_periods=(96, 35.064))
model = estimator.fit(train_X)
# Forecast 365 days ahead
y_forecast = model.forecast(steps=35.064)

but the first value is different and others remain the same in fact the output of y_forecast is this :
array([89.39551833, 89.90889142, 90.04436999, 89.97717499, 89.97717499,
       89.97717499, 89.97717499, 89.97717499, 89.97717499, 89.97717499,
       89.97717499, 89.97717499, 89.97717499, 89.97717499, 89.97717499,
       89.97717499, 89.97717499, 89.97717499, 89.97717499, 89.97717499....

as I can see is various for the first 4 value..and for other is constant
I think I m wronging the seasonal period.
Any suggestions?


text:
Q: Response from a server, how to loop through each element I have an response formatted like this:
[{"url" : "www.link.com"}, ..., {"url" : "www.link.com"}]

How do I access each link and do something with it.

A: Use a regular for loop and access the properties with dot notation

var urls = [{
  "url": "www.link.com"
}, {
  "url": "www.link.com"
}];

for (var i = 0; i < urls.length; i++) {
  console.log(urls[i].url);
}


text:
Q: One user - 2 reports - 2 behaviours I have a user, whom is trying to edit reports.
The settings for the user profile is ok

*

*When looking at the 2 reports in issue, both reports were created by the user.

*Both reports show different buttons when looking at them

report 1:

report 2:

The only difference I see is that the report without the Save button, is in a public dashboard folder.

However, this folder is read/write enabled to all internal users

The main problem is that when the user created a report, he can't customize it. Weird

A: The user's profile must also have the Manage Public Reports permission checked.
Also, you should take a look at the new report and dashboard folder permissions available in Summer '13. It gives you much granular control over who can work with reports per folder.


text:
Q: SPI- Full duplex and Half duplex Could anyone tell what is the advantages/disadavantages of using half duplex SPI over full duplex SPI communication. I know using half duplex, we can save one pin. But is this the only advantage of using half duplex? Is the rate at which master reads the data from the slave same for both mode of communication?
Please reply
Regards

A: Half duplex unidirectional or write only mode could be used when master don't need data from slave. For example when working with most LCD it is usually OK to do writes only (although by reading status, framebuffer etc master can detect misbehavior and reset the slave, but LCD is usually not critical component and scheduled blind resets might be enough). The advantage is, as you mentioned, saving 1 pin.
Read/write clock rates are always same, since it is done simultaneously. MCUs SPI read and write buffers are shift registers with same clock, so when master is writing it is also reading (even if slave is not sending, in that case HIGH bits are received).

A: Mostly its a method for allowing a simpler design that has fewer pins on the CPU and allows for lower signal count on cables.  Effectively you're trading speed and complexity for cost and simplicity.


text:
Q: Working with data in java I've been using a formula for some time to try to find value in spreads for sports betting and done this by basically creating my own spread and comparing to what bookies offer and would like to automate the process.
I've written some code in java which will do the maths on the data I give it and I'm looking for a way to populate the input data either from a database or from an xml file I create but i'm quite new to programming.
Say for example if I pick two teams to compare. For each team I need a list of the teams they played, how many points each team scored in total, how many points each team conceded in total and how many games each team played so I can run the maths on those figures and I have no idea where to start. Could anyone help me or point me in the right direction?

A: It sounds like you've defined your problem (how to start), and also listed the information you need to get started (compare two teams, points, previous games, conceded points, etc). Are you sure you don't know how to start?
For a point in the right direction - I recommend creating a test case where you select two teams, give them some sample data for their previous games, points scored and conceded, and start working on the structure of your program.
This question lends itself too much to personal opinion and personal experience, and that makes it difficult to give you definitive answers without looking at any code or a program layout.
Give it your best effort and reply back with what you come up with, that will be much easier to critique and offer suggestions to.


text:
Q: Why google cloud function runs more that 2 minutes? I have a function, sometimes execution (even not after "cold start") takes 2 minutes.
The local copy of the same function works in milliseconds.
Am I missing smth in google cloud configuration?
latency stats from GCP dashboard

A: With Cloud Functions you have CPU Ghz compute power according to the memory that you allow to your Cloud Functions.
Note: in this table, with 4Gb, you have 2vCPU @2.4Ghz, not 1vCPU at 4.8Ghz.
By default the memory is set to 256Mb. Try to deploy with 2Gb and you will increase your performances.
Note2: Your workstation has often 4, 8 or 16CPU @3+Ghz. Here it's only 1 @2.4Ghz max!


text:
Q: Why can't I set my custom Listview item's background dynamically? I have a custom listview and I am using a custom listadapter to display that list. In my custom listadapter I am trying to set the colour of each item dynamically depending on a value within the object. However whenever I try to do this the items become faded rather than getting the colour they were set to. I am applying a few styles to the project but when I remove their effect it still doesn't work. This is my code to change the background colour of each item:
    private class stationAdapter extends ArrayAdapter<Station>{
    private ArrayList<Station> stations;

    public stationAdapter(Context context, int textViewResourceId, ArrayList<Station> stations) {
        super(context, textViewResourceId, stations);
        this.stations = stations;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
        }
        Station temp = stations.get(position);
        if (temp != null) {
            TextView stationName = (TextView) v.findViewById(R.id.stationname);
            TextView serviced = (TextView) v.findViewById(R.id.inservice);

            try{
                if(temp.getLine().equals("red")){
                    v.setBackgroundColor(R.color.red);

                }
                else{
                    v.setBackgroundColor(R.color.green);
                }
            }catch(Exception e){
                Log.d(TAG, "Null pointer");
            }
            if (stationName != null) {
                stationName.setText("Station: "+temp.getName());                            }
            if(serviced != null){
                serviced.setText("In Service: "+ temp.getInServive());
            }
        }
        return v;
    }

}

If anyone could point out what I am doing wrong I would really appreciate it.

A: You cant use setBackgroundColor and then reference a resource. if you want to use setBackgroundColor() you need to use the Color class like:
setBackgroundColor(Color.BLACK);

Instead if you want to set a resource (R.drawable, R.color etc...) you need to do it like
v.setBackgroundResource(R.color.black);

EDIT:
The cache color hint is what is needed if the items start becoming gray while scrolling the list. You need to set it to a transparent color if you are adding custom backgrounds to items and lists.

A: Like Darko mentioned, you're trying to set a color but using a resource ID instead. With that said, using a solid color for a list item background is a big no-no, you definitely want to use a selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_focused="false" android:state_pressed="false" android:state_selected="false"
        android:state_checked="false" android:state_enabled="true" android:state_checkable="false"
        android:drawable="@color/red" />
</selector>

Put that in a list_red_background.xml in your drawables folder and use setBackgroundResource() instead.

A: Have you switched fading off?
http://developer.android.com/resources/articles/listview-backgrounds.html
Add this to the ListView layout file:
android:cacheColorHint="#00000000"


text:
Q: Link google sheet to html page I need to link an editable google sheet to my html website so that any change in the sheet will automatically appears in my site.

A: You can make use of publish option on Google Drive docs files such as Sheets,Slides,Docs and embed them to your Webpages. You can find more information on how to do that here: https://support.google.com/docs/answer/183965
Of course keep in mind that depending on what publishing option you select, you may have to change the access permission of your document/sheets.
Quick Edit:
If you're planning to just embed the sheet, make sure to select the embed option on the same publish to the web section that can be found by going to File > Publish to the web.


text:
Q: Sharing a file system, or how to horizontally scale access to files My API mostly serves up stuff from the database, but a big part of the product is generating images by combining SVG files with large pattern fills (~50MB tiff files).
The API can scale horizontally, but each instance would need access to the file system somehow. Is there a solid way to share/mount the file system between multiple API nodes, or do I need to make a separate file service that provides them over HTTP or something?

A: I'd recommend you look at an NFS solution. It does exactly what you're saying you need done.


text:
Q: How to Convert JSON into Customize Array in PHP? Hi everyone I have a JSON something like this
{
"100": "Testing",
"200": "Usman",
"700": "User Test"
}

I need to convert it into like this in PHP.
[
["100", "Testing"],
["200", "Usman"],
["700", "User Test"],
]

A: Use json_decode for decoding the json. Then loop through the decoded json and make a new array.
$json = '{
"100": "Testing",
"200": "Usman",
"700": "User Test"
}';

$decoded = json_decode($json, true);

$newArray = [];

foreach($decoded as $key => $value){
    $newArray[] = [$key, $value];
}

echo '<pre>';
var_dump($newArray);
echo '</pre>';

Result:
array(3) {
  [0]=>
  array(2) {
    [0]=>
    int(100)
    [1]=>
    string(7) "Testing"
  }
  [1]=>
  array(2) {
    [0]=>
    int(200)
    [1]=>
    string(5) "Usman"
  }
  [2]=>
  array(2) {
    [0]=>
    int(700)
    [1]=>
    string(9) "User Test"
  }
}


text:
Q: How to specify alternate datasource when doing raw SQL queries in Grails 2.3.x? We have a reporting read only database clone set up as an alternate datasource in our Grails application named 'reporting'.  This works great when using dynamic finders or criteria as per the grails MyDomain.reporting.findByXXXX(..etc..)
However there are some nasty queries that have to be done in raw SQL.  Our current way of doing this (in a service) is
def sessionFactory;

public static List getSomeBigNastyData(...)
{
   sessionFactory.currentSession.createSQLQuery(
   """
   Big Ugly Query
   """
   ).list();
}

But this does not go to the reporting database and there doesn't seem to be a way of specifying 'reporting' - is there a way to specify the datasource to execute raw SQL against?

A: It's possible to use the dataSource as an injected bean and groovy.sql.Sql to run your queries. Below is a simple example of a service that will use your data source and allow you to run a query against it.
package com.example

import groovy.sql.GroovyRowResult
import groovy.sql.Sql

class ExampleSqlService {
  def dataSource_reporting // your named data source

  List<GroovyRowResult> query(String sql) {
    def db = new Sql(dataSource_reporting)
    return db.rows(sql)
  }
}

Using a service (like the above example) allows you to access it from basically anywhere (Controller, Service, TagLib, Domain, etc.)


text:
Q: Using Processing: A JSONArray text must start with '[' I am trying to parse a JSON Array from a .txt file with processing. However I keep on getting this error:
java.lang.RuntimeException: A JSONArray text must start with '['
    at processing.data.JSONArray.<init>(JSONArray.java:140)
    at processing.data.JSONArray.<init>(JSONArray.java:126)
    at processing.core.PApplet.parseJSONArray(PApplet.java:5494)
    at sketch_230108a.fileSelected(sketch_230108a.java:31)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at processing.core.PApplet.selectCallback(PApplet.java:5966)
    at processing.awt.ShimAWT.selectImpl(ShimAWT.java:835)
    at processing.awt.ShimAWT.lambda$selectInput$0(ShimAWT.java:742)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:318)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:771)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:722)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:716)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:741)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

I tried this code:
PrintWriter output;
  String data = "[ \"Capra hircus\", \"Panthera pardus\", \""+"90"+"\" ]";

void setup() {
  output = createWriter("positions.txt");
  output.print(data);
  output.flush();
  output.close();
  selectInput("Select a file to process:", "fileSelected");
}

void fileSelected(File selection) {

   JSONArray json = parseJSONArray(selection.toString());
  if (json == null) {
    println("JSONArray could not be parsed");
  } else {
    String species = json.getString(0);
    println(species);
  }
}

I am trying to get an output of Capra hircus, however I just get a JSONArray could not be parsed, and the error.

A: Use loadStrings or loadBytes
void fileSelected(File selection) {
   String[] lines = loadStrings(selection);
   for (int i =0; i< lines.length; i++) {
    println(lines[i]);
   }
}


text:
Q: Spark: explode 1 row into many rows? for example:
mydataframe has 2 columns and 1 row
val df = Seq(("1,2,3", "tom")).toDF("id", "name")

ids(String)           name(String)

1,2,3         tom

after transform =>
I want the df to be equal to
Seq(("1", "tom"), ("2", "tom"), ("3", "tom")).toDF("id", "name")

ids  name

1     tom

2     tom

3     tom

I saw there is an explode() function with the following signiture:
public <A extends scala.Product> DataFrame explode(scala.collection.Seq<Column> input,
                                      scala.Function1<Row,scala.collection.TraversableOnce<A>> f,
                                      scala.reflect.api.TypeTags.TypeTag<A> evidence$1)

*

*I want to use scala API

A: Try
from pyspark.sql.functions import explode
df.select(explode(df.ids).alias('ids'), name).collect()


text:
Q: Why is this reversing sentence algorithm not working? There are some comments in the code for human-readable code:
#include <stdio.h>
#include <string.h>

#define SIZE 100   //size of the input array and output array
#define ACCUM_CHAR_SIZE 25  //size of the temp array
int main(){
   char i[SIZE];
   char acc[ACCUM_CHAR_SIZE];
   char o[SIZE];
   int it_l = 0, it_a = 0, it_r = 0;
   //it_l is the iterator to the input sentence,
   //it_a is the iterator to the temp array
   //it_r is the iterator to the output sentence
   printf("Enter a sentence:");
   gets(i);
   int len = strlen(i) - 1;
   while(it_l <= len){
        if(i[len - it_l] != ' '){
            acc[it_a] = i[len - it_l];  //add letters to acc until space
            it_a++;
        }
        else{
            it_a -= 1;
//acc is reversed, I reversed it again to the output sentence
            while(it_a >= 0){
                o[it_r] = acc[it_a];
                it_r++;
                it_a--;
            }
            it_r += 1;
            o[it_r] = 32;   //put a space
            it_a = 0;  //reset the temp array
            strcpy(acc, ""); //clear the acc
        }
        it_l++;
   }
   printf("%s", o);
}

The program theoretically looks fine, but when it is executed, it sometimes print garbage values, only some words, or sentence which has only reversed half with garbage value instead of spaces.
The program above is to save each word to the temp, and reverse temp (temp is reversed when storing the word) back to the output. However, it fails.
Thank you for your help.

A: There are at least three problems.
The first problem is that you never terminate the string o To do that change:
   printf("%s", o);

into
   o[it_r] = '\0';
   printf("%s", o);

The second problem is that you increment it_r incorrectly. Change
        it_r += 1;
        o[it_r] = 32;   //put a space

into
        o[it_r] = ' ';  // Use ' ' instead of 32
        it_r += 1;

The third problem is that you don't handle the first word of the input (because there is no space in front). I'll leave that problem to you as an exercise.
BTW: Don't use gets for reading input. Use fgets instead.

A: #include <stdio.h>
#include <string.h>

#define SIZE 100   //The size of input array is prefered to be equal to ouput array.
int main(){
   char input[SIZE];
   char output[SIZE];
   int i = 0, j = 0;
   //i is the iterator to the input sentence,
   //j is the iterator to the output sentence
   printf("Enter a sentence:");
   gets(input);
   int len = strlen(input) - 1; //Total length.
   j = len;
   while(input[i]!= NULL){
            output[j] = input[i];
            i++;
            j--;
   }
    output[len+1]= NULL;
    printf("%s", output);
    printf("Finished");
 }

A: Try the modified code given below, the changed sections has been commented(all other comments were removed for readability)
#include <stdio.h>
#include <string.h>

#define SIZE 100
#define ACCUM_CHAR_SIZE 25
int main(){
   char i[SIZE];
   char acc[ACCUM_CHAR_SIZE];
   char o[SIZE];
   int it_l = 0, it_a = 0, it_r = 0;

   printf("Enter a sentence:");
   gets(i);
   int len = strlen(i) - 1;
   while(it_l <= len){
        if(i[len - it_l] != ' '){
            acc[it_a] = i[len - it_l];
            it_a++;
        }
        else{
            it_a -= 1;
            while(it_a >= 0){
                o[it_r] = acc[it_a];
                it_r++;
                it_a--;
            }
            /*it_r += 1; There is no need to increment it_r here as
              it is already incremented in the above loop*/
            o[it_r] = 32;
            it_r += 1;  /* The above increment statement was moved here(only
            incremented when a new value is loaded in to output array) */
            it_a = 0;
            strcpy(acc, "");
        }
        it_l++;
   }
  /* The below section reverses and stores the first word of the
   input which was not getting operated in the above loop */
   it_a -= 1;
    while(it_a >= 0){
        o[it_r] = acc[it_a];
        it_r++;
        it_a--;
    }
   o[it_r] = '\0'; // Terminating output array
   printf("%s", o);
}

The above code will work as expected but has some small issues(given below)

*

*Using gets():- gets is not recommended for inputting strings. See this link for more info.

*The Size of temporary array acc :- If a word greater than 25 characters is inputted the program may output garbage value.

A: Version without temporary storage.

*

*read the input string from start (0)

*copy any word from input into output, starting from the end of output - words are not reversed

*copy any space in output, from position in output, starting from the end

Code
#define SIZE 100   //size of the input array and output array

int main(){
    char i[SIZE];
    char o[SIZE];

    printf("Enter a sentence: ");
    fgets(i, SIZE, stdin);     // fgets instead of gets

    int j,len = strlen(i) - 1; // assuming you eat the EOL character
    o[len] = '\0';             // start by marking end of output string

    for(j=0 ; j<len ; j++) {   // navigating the input string
        if (i[j] == ' ') {
            o[len-j-1] = i[j]; // if space, copy (from end) in output
        }
        else {
            int k=j;
            do {
                k++;           // count(+1) the word, non-space, characters
            } while (k<len && i[k] != ' ');
            strncpy(&o[len-k], &i[j], k-j); // copy the word
            j = k-1;
        }
    }

   printf("%s\n", o);
}


text:
Q: Does spring injects dependencies of a class created manually I have an class's similar to this:
 @Controller
 class A{
   @Autowired
   private B b;
    ....
 }

class B:
 @Service
 class B{
 ....
 }

i am woring in a spring project. If i initialize class A manually like this:
A a= new A();

Will spring be able to inject B to my class. This aren't my real classes, but i have similar scenario, and am trying to run a unit test with spring test. I initialize the object manually as the above. But spring is complaining for NullPointerException. I am not used spring for long time and I am little bit confused. Can any body confirm's me if spring will still inject the dependency if i initialize the class?

A: Spring won't inject dependencies if you initialize the class. It only inject if the class is initialized by its container.
This may help you: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/overview.html


text:
Q: Do non-constant maps specialize to non-constant maps? Let $R$ be a dvr with fraction field $K$ and residue field $k$. Let $\mathcal{X}\to \mathcal{Y}$ be a morphism of $R$-schemes such that $\mathcal{X}_K\to \mathcal{Y}_K$ is non-constant.
Is the morphism on special fibres $\mathcal{X}_k\to \mathcal{Y}_k$ non-constant?
The answer should be "no", because one can take a morphism $\mathbb{A}^1_R\to \mathbb{A}^1_R$ of the form $x\mapsto \pi x$ with $\pi$ the uniformiser of $R$.
My question is really:

Under what additional conditions on $\mathcal{X}$ and $\mathcal{Y}$ is the morphism $\mathcal{X}_k\to \mathcal{Y}_k$ non-constant? What if $\mathcal{X}$ and $\mathcal{Y}$ are projective over $R$?


text:
Q: Variance of log return Suppose $C_i$ is i-day's closed price, when drift is small,
we have the close to close variance
$$\sigma^2 =\dfrac{1}{n}\sum\limits^n_{i = 1}\left(\log\left(\dfrac{C_i}{C_{i-1}}\right)\right)^2.$$
If we adjust this for the drift,
$$\sigma^2 =\dfrac{1}{n-1}\sum\limits^n_{i = 1}\left(\left(\log\left(\dfrac{C_i}{C_{i-1}}\right)\right)^2 - \dfrac{\log\left(\left(\dfrac{C_n}{C_0}\right)\right)^2}{n(n-1)}\right).$$
I don't know how to obtain the later one in the bracket? I know the original one should be
$$\left(\log\left(\dfrac{C_i}{C_{i-1}}\right) - \dfrac{\log\left(\dfrac{C_n}{C_0}\right)}{n}\right)^2$$


text:
Q: Creating an endless recurring task in rxjs I have a long running task that I want to loop forever in TypeScript.
It should only run the next task when the previous task has completed.
I want to use rxjs for this as it seems the most succinct way to do it.
So far I've used a combination of interval, queue scheduler, defer, exhaust and exhaust map but not had much luck.
This is what I have so far:
function longTask () : void {
    // some long running task
}

interval(1000)
.pipe(
     exhaustMap((x) =>
         defer(()=> longTask())
     )
.subscribe();

Thanks in advance.

A: Use zip, zip will fire the interval and then wait for your observable to fire.
zip(interval(1000), longTask()).subscribe(([_, longTaskResult]) => {
});

Or if your longTask only emits once and completes you could make a recursive call

const { of } = rxjs;
const { delay } = rxjs.operators;

const longTask = () => of(Math.random() * 10).pipe(delay(Math.floor(Math.random() * 5000)));

const runLongTask = () => {
  longTask().subscribe(result => {
    console.log(result);
    runLongTask();
  });
}

runLongTask();
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.3/rxjs.umd.min.js"></script>


text:
Q: how to import apache log into elasticsearcha and create an index pattern in Kibana I have an apache log file which i want to import in elasticsearch and create index pattern in kibana. i have installed ELK stack in my centos-7 machine and the services are running.I configured the /etc/logstash/conf.d/apachelog.conf file but its not showing in kibana. Please suggest what is missing in this or any other configurations required. The elasticsearch.yml amd kibana.yml has also been configured. The /etc/logstash/conf.d/apachelog.conf file is as follows:

input {
  file {
    path => "/home/vagrant/apache.log"
    start_position => "beginning"
  }
}

filter {

    grok {
      match => { "message" => "%{COMBINEDAPACHELOG}" }
    }
  date {
    match => [ "timestamp" , "dd/MMM/yyyy:HH:mm:ss Z" ]
  }
   geoip {
    source => "clientip"
  }
  }

output {
  elasticsearch {
    hosts => ["localhost:9200"]
    index => "project"
  }
  }


text:
Q: XmlSerializer one Class that has multiple classes properties Objective: Serialize all the public properties of the ClassMain:
public class ClassMain
{
    ClassA classA = new ClassA();
    public ClassMain()
    {
        classA.Prop1 = "Prop1";
        classA.Prop2 = "Prop2";
    }

    public string Prop1 { get; set; }
    public string Prop2 { get; set; }

    public ClassA ClassA
    {
        get
        {
            return classA;
        }
    }
}

ClassA:
public class ClassA
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

This is how i´m serializing:
    private void button1_Click(object sender, EventArgs e)
    {
        ClassMain classMain = new ClassMain();
        classMain.Prop1 = "Prop1";
        classMain.Prop2 = "Prop2";

        XmlSerializer mySerializer = new XmlSerializer(typeof(ClassMain));
        StreamWriter myWriter = new StreamWriter("xml1.xml");
        mySerializer.Serialize(myWriter, classMain);
        myWriter.Close();
    }

In this case, the xml output is:
<?xml version="1.0" encoding="utf-8"?>

<ClassMain xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Prop1>Prop1</Prop1>

  <Prop2>Prop2</Prop2>

</ClassMain>

As you see, is lacking the ClassA properties.
Can anyone help me out?
Regards

A: Properties will only be included in Xml serialization if they have both a getter and a setter, presumably as this rule ensures that serialization can round-trip i.e. if there is no setter, you would not be able to deserialize the Xml back into the target object.
Your ClassA property has no setter.


text:
Q: Eclipse: all main menus empty I use Eclipse Kepler on Ubuntu, which I downloaded and installed separately in /usr/local/eclipse
Last night I upgraded from Ubuntu 13.04 to 13.10, and today all menus (File, ..., Help) are empty. I don't know whether this is a coincidence or has to do with the upgrade. It should not, because I hadn't used the version from Ubuntu's repositories.
$ java -version
java version "1.7.0_25"
OpenJDK Runtime Environment (IcedTea 2.3.12) (7u25-2.3.12-4ubuntu3)
OpenJDK 64-Bit Server VM (build 23.7-b01, mixed mode)
I already tried using a different (empty) workspace and deleting the $HOME/.eclipse directory, but this doesn't help.
Is there any hope I can get the menus back without purging and re-installing the whole thing?

A: http://tpbapp.com/android-development/fix-the-ubuntu-13-10-update-eclipse-menu-problem/
answers the question. It seems to be a common problem, which actually should be solved automatically.

A: I tried this solution but it didn't work for me. I found another solution in this post.
It was posted by Robert (the last post).
I added:

*

*Exec=env UBUNTU_MENUPROXY=0 /home/user/Development/eclipse/eclipse

*Terminal=false

into the file eclipse.desktop located in:

*

*/home/user/.local/share/applications/eclipse.desktop


text:
Q: Atomic if not exist then insert in Mongodb .Net driver Let us say I have the following model:
public class Person
{
    [BsonId]
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public DateTime ReceivedAt { get; set; }
}

And I have N threads that perform "if not exists then insert", how can I ensure that only one thread inserts a document in DB.
What I tried is:
 void test(DBContext context)
    {

        var person = new Person() { Id = Guid.NewGuid(), Name = "name", Title = "title", ReceivedAt = DateTime.Now };
        Console.WriteLine(DateTime.Now);
        var update = Builders<Person>.Update.Combine(
              Builders<Person>.Update.SetOnInsert(y => y.Name, person.Name)
            , Builders<Person>.Update.SetOnInsert(y => y.Title, person.Title)
            , Builders<Person>.Update.SetOnInsert(y => y.ReceivedAt, person.ReceivedAt)
            , Builders<Person>.Update.SetOnInsert(y => y.Id, person.Id));
        var result = context.People.FindOneAndUpdateAsync<Person>(
            x => x.Title == person.Title && x.Name == person.Name && x.ReceivedAt > person.ReceivedAt - TimeSpan.FromSeconds(10),
            update,
            new FindOneAndUpdateOptions<Person>() { IsUpsert = true,ReturnDocument = ReturnDocument.Before}).GetAwaiter().GetResult();
        if (result?.Id != null)
        {
            Console.WriteLine("duplicate");
        }
        else
        {
            Console.WriteLine("first time");
        }
    }

And tested it using:
DBContext context = new DBContext ();
for (int i = 0; i < 10; i++)
  {
   Task.Run(() => test(context));
  }

But the above code inserts more than one document to collection, seems like FindOneAndUpdateAsync is not atomic.
Is there a way to achieve that only one thread inserts a document into collection in Mongodb?

A: You need a unique index.  What is your model's purpose?  Do you want one record for a person and ReceivedAt is the last time they were "received" or is this more like an event each time they were "received" should be here once?
Create a unique index on either (Name,Title) or (Name,Title,ReceivedAt).
Since DateTime.Now is going to increment while running, you are going to see multiple "first time" in the second case.  In the first case, you should change the ReceivedAt from SetOnInsert to just Set.


text:
Q: Kotlin code hard copy dirty BuildConfig Java members An Android application developed basically using Kotlin references the members in the intermediate generated BuildConfig.java in the code.
import com.dirtyinfo.BuildConfig;

private fun checkVersionInfo(): Int {
        val verCode = BuildConfig.VERSION_NAME
        Log.d(TAG, "version {verName}")
    }

If not compiled in full, there may be a case where verName is the last dirty data. Checking the decompiled code, I found that the compiler does not reference BuildConfig.VERSION_NAME or BuildConfig.VERSION_CODE, but uses the hard copied value: 1.0.0.
And during the incremental compilation, this file was not recompiled correctly, so the old dirty value provided.
My question is.

*

*If I want to reference BuildConfig.java fetch in Kotlin, do I need additional processing?

*If the compiler is hard copying the constants in BuildConfig, how can I let Gradle know the correct dependencies?


text:
Q: Scalability Azure Function/AWS Lambda I'm considering to use Azure Function/AWS Lambda/Serverless for backend. How does it scale to million of requests, that the code has to open database. I understand it does not reuse the connection?
For example the call is something like this.
using (var db = new Database(..,))
{
  // db calls
}

How does it scale out, and is it efficent?

A: Your question is somewhat imprecise. I don't know much about Azure, but for AWS Lambda it scales well. If you have 1 million concurrent requests Lambda would create an instance for each of those requests. Be aware that there is a default limit of 1000 concurrent executions per region, but these can be increased with a support request.
After a first request has been made a container may be reused. There is a blog post explaining how it works. While it's not recommended you can try buffer your connection within the container. Depending on database and driver your connection may stale during the freeze or it may still work. For one of the Lambdas I use buffering works quite well. You should be aware when you don't close the connection properly this may lead to leaks on your database server and of course you should validate the connection before using it again.
Using Java I put the connection into the scope of the class and check within my handler if the connection is already initialized e.g.:
public class LambdaHandler implements RequestStreamHandler {
  private Connection con = null;

  public void handleRequest(InputStream inputStream,
      OutputStream outputStream, Context context) {
    if (con == null) {
      con = getConnection(context);
    } else {
      con = validateConnection(context, con);
    }
  }

You can probably do the same using the language you use. I wouldn't be surprised if Azure Functions work quite similar to AWS Lambda, but you better check the documentation for verification.

A: When it comes to using DB connection in lambda in AWS, you should read about container execution model of lambda. When a lambda is invoked, AWS spins up a container to run the code inside the handler function. So if you define the Database connection outside the handler function it will be shared among the invocations of Lambda functions. You can find that in the above link.

Any declarations in your Lambda function code (outside the handler code, see Programming Model) remains initialized, providing additional optimization when the function is invoked again. For example, if your Lambda function establishes a database connection, instead of reestablishing the connection, the original connection is used in subsequent invocations. You can add logic in your code to check if a connection already exists before creating one.

const pg = require('pg');
const client = new pg.Client(<connection_string>);

exports.handler = (event, context, cb) => {
  client.query('SELECT * FROM users WHERE ', (err, users) => {
    // Do stuff with users
    cb(null); // Finish the function cleanly
});
};

Refer this blog post.
But there is a caveat.

When you write your Lambda function code, do not assume that AWS Lambda always reuses the container because AWS Lambda may choose not to reuse the container. Depending on various other factors, AWS Lambda may simply create a new container instead of reusing an existing container.

Additionally you can create a scheduled job to warm up lambda function. (runs in every 5mins)


text:
Q: Java backend returns a String but Angular frontend doesn't accept it What I want to do: Frontend sends username and password to the backend. Backend checks it, generates a random string, and sends back that string to the frontend. Frontend saves that string to localStorage.
In the backend:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String login(String credentials){
    return this.service.login(credentials);

}

this.service.login returns a string if username and password in credentials is OK or returns null if not.
In the frontend:
public login(username: string, password: string ){
return this.http.post<string>(this.authUrl, JSON.stringify({username: username, password: password}), this.getHeaders())
.pipe(
  tap(
    (token:string) => {
      if(token){
        localStorage.setItem('accessToken',token);
        console.log(`Successful login for username =${username} with password=${password} and token=${token}` );
      } else {
        console.log(`Login failed for username =${username} with password=${password} and token=${token}`);
      }
    }
  )
);

}
getHeaders(): {headers: HttpHeaders } {
const httpOptions = {
  headers: new HttpHeaders(
    {
      'Content-type': 'application/json',
      'responseType': 'text'
    }
  )
};
return httpOptions;

}
If I try to login with wrong username and password, this gets logged: Login failed for username =something with password=something and token=null So the returning null part works, But if I send the correct username and password, I get this error:
ERROR
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/login", ok: false, …}
error: {error: SyntaxError: Unexpected token M in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "MTMyOTUz"}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:8080/login"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:8080/login"
__proto__: HttpResponseBase

So it has some JSON.parse problem? Does it expect a JSON so doesn't know what to do with a string? What's a solution to this?

A: Alright I didn't know how to get this work with string, so I ended up using json instead. So in this.service.login:
JsonObject tokenJson = new JsonObject();
tokenJson.addProperty("token", token);
return tokenJson;

then:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public JsonObject login(String json){
    return this.service.login(json);
}

In the frontend changed return type from string to objectand get my token like this:
var tokenObject = JSON.parse(JSON.stringify(token));
localStorage.setItem('accessToken',tokenObject.token);

A: By default httpclient parses json. For telling it that in return text will come as response you need to use the syntax below.
this.httpClient.request('GET', 'url, {responseType:'text'});


text:
Q: Java sub-module error creating shaded jar I just created a new module in my Dropwizard Project and when I run
mvn install

I receive the following Exception:
Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:1.6:shade (default) on project justfortest: Error creating shaded jar: null: NullPointerException -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:1.6:shade (default) on project justfortest: Error creating shaded jar: null

I did not find anything relevant about it on the internet. Can someone tell me something about it?

A: You should not use the shade plugin on your parent project, but create a separate aggregator subproject for this. List all the other subproject you wish to include and add your shading configuration here.


text:
Q: Unable to paginate releases in GitHub V3 API I'm trying to list all of the releases of a public repository on GitHub using their V3 API. Here's the request I'm making:
curl -is -H 'Accept: application/vnd.github.v3+json' \
    https://api.github.com/repos/ffmpeg/ffmpeg/releases

The response headers I receive back are here:
HTTP/1.1 200 OK
Server: GitHub.com
Date: Fri, 29 Jan 2016 20:23:15 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 29612
Status: 200 OK
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 19
X-RateLimit-Reset: 1454099558
Cache-Control: public, max-age=60, s-maxage=60
ETag: "947039722a1073c5279a9fd39d00c0bf"
Vary: Accept
X-GitHub-Media-Type: github.v3; format=json
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: ETag, Link, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-
Access-Control-Allow-Origin: *
Content-Security-Policy: default-src 'none'
Strict-Transport-Security: max-age=31536000; includeSubdomains; preload
X-Content-Type-Options: nosniff
X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
Vary: Accept-Encoding
X-Served-By: b0ef53392caa42315c6206737946d931
X-GitHub-Request-Id: XXXXXXXXXXXXXXXXXXXXXXXXXXXX

Notice the lack of the Link response header? In the response body, I only get back around 7 releases and I can't seem to paginate forward or backward by manually specifying the ?page=N query parameter.
For some background, FFmpeg has about 226 releases present in its GitHub repository, and I'm only getting around 7 of those, unable to paginate through them.
Is there something I'm doing wrong here that would limit my responses back from the GitHub v3 API?

A: GitHub conflates its proprietary Releases feature with regular Git tags. Many of the "releases" that you see for ffmpeg are actually just tags.
Here is an example of a real release. Note how it contains much more information than a tag does. Despite their web UI showing tags mixed in with releases, GitHub's release API endpoint doesn't include regular tags:

This returns a list of releases, which does not include regular Git tags that have not been associated with a release. To get a list of Git tags, use the Repository Tags API.

Using the tags endpoint as GitHub suggests gives more results, and includes a Link header as you expect:
curl -is -H 'Accept: application/vnd.github.v3+json' \
    https://api.github.com/repos/ffmpeg/ffmpeg/tags


text:
Q: how to make animation with for loops? how to make animation with foor loops?
The animation does not work, if run start -> graphs are overlaped...
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import time
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation

df = pd.read_excel('D:\\python\\221027_phdiagram.xlsx', sheet_name=3)
df_sat = pd.read_excel('D:\\python\\221027_phdiagram.xlsx', sheet_name=2)

st=0
fig, ax=plt.subplots()
x=[]
y=[]
ims1=[]
ims2=[]
ims3=[]
ims4=[]
ims5=[]
for st in range(0,3600,600):

    x1=df.loc[st,'h1']    y1=df.loc[st,'P1']    z1=df.loc[st,'시간']    x2=df.loc[st,'h2']
    y2=df.loc[st,'P2']    z2=df.loc[st,'시간']    x3=df.loc[st,'h3']    y3=df.loc[st,'P3']
    z3=df.loc[st,'시간']    x6=df.loc[st,'h6']    y6=df.loc[st,'P6']    z6=df.loc[st,'시간']
    x7=df.loc[st,'h7']    y7=df.loc[st,'P7']    z7=df.loc[st,'시간']    x8=df.loc[st,'h8']
    y8=df.loc[st,'P8']    z8=df.loc[st,'시간']

    sat_y=df_sat.loc[3:1203,'pbar']
    sat_liq_x=df_sat.loc[3:1203,'hliquid']
    sat_vap_x=df_sat.loc[3:1203,'hvapor']
    plt.yscale('log',base=10)

    sat_curve1=plt.plot(sat_liq_x,sat_y,color='b')
    sat_curve2=plt.plot(sat_vap_x,sat_y,color='b')

    x=[x1,x2,x3,x6,x7,x8]
    y=[y1,y2,y3,y6,y7,y8]

    curveline=plt.plot(x,y,marker='o',color='r')
    curvex=plt.xlabel('Enthalpy')
    curvey=plt.ylabel('Pressure')
    plt.xticks([140,200,260,320,380,440,500,560])
    plt.yticks([0.5,0.6,0.7,0.8,0.9,1,2,3,4,5,6,7,8,9,10,20,30,40,50])
    #ims1.append([sat_curve1])
    #ims2.append([sat_curve2])
    #ims3.append([curveline])
    #ims4.append([curvex])
    #ims5.append([curvey])

#rint(st)
ani = FuncAnimation(fig,sat_curve1,frames=200,interval=50)
plt.show()

If want get graph at special point, i can .......
but i want to make animation
If want get graph at special point, i can .......
but i want to make animation
If want get graph at special point, i can .......
but i want to make animation
If want get graph at special point, i can .......
but i want to make animation
If want get graph at special point, i can .......
but i want to make animation
If want get graph at special point, i can .......
but i want to make animation
If want get graph at special point, i can .......
but i want to make animation
If want get graph at special point, i can .......
but i want to make animation

thank you


text:
Q: What to do if HttpServletResponse.getWriter() throws an IOException? The function HttpServletResponse.getWriter() actually throws an IOException, when that happens, the ideal thing to do is send an 500 status in the response, is there a way to do that without a viable PrintWriter?

A: Yes you can,
You can do that via HttpServletResponse using sendError() function.
You can do something like this:
response.sendError(SC_INTERNAL_SERVER_ERROR, "your error message");


text:
Q: Delphi 2007 drag from app this is a general question that I was asked to investigate.
What would we need, generally speaking, to be able to drag an image file (tif) from our Delphi 2007 application to some other application?
Thank you.

A: The easy way would be to use this component: http://melander.dk/delphi/dragdrop/ , which exists since a long time. You have all the components variants for drag and drop: source/target, various source/target kind.

A: Here is a good sample:
Drag and Drop files from your application to Windows Explorer


text:
Q: Making some parts of the window transparent in WinAPI I want to make only certain(rectangular) parts of the window transparent.
I have set the window as WS_EX_LAYERED and the WM_PAINT function is as follows:
    case WM_PAINT:;
        RECT rect;
        GetWindowRect(hwnd, &rect);
        HDC hdc = GetDC(hwnd);
        HDC hdc1 = CreateCompatibleDC(hdc);
        HBITMAP hBitmap = CreateCompatibleBitmap(hdc, rect.right - rect.left, rect.bottom - rect.top);
        SelectObject(hdc, hBitmap);
        SIZE size = {rect.right - rect.left, rect.bottom - rect.top};
        BLENDFUNCTION blendFunc = {AC_SRC_OVER, 0, 0, AC_SRC_ALPHA};
        UpdateLayeredWindow(hwnd, hdc1, NULL, &size, hdc, NULL, RGB(0, 0, 0), &blendFunc, ULW_ALPHA);
        DeleteObject(hBitmap);
        DeleteDC(hdc);
        ReleaseDC(hwnd, hdc1);
        break;

I tried creating a child window, but that doesn't seem to work if I change it's opacity through SetLayeredWindowAttributes, possibly because it mimics the parent windows opacity. I am currently trying to use UpdateLayeredWindow to make certain parts transparent, but I can't even make the entire part transparent using UpdateLayeredWindow.
What is the general way to make certain parts of the window transparent?

A: I suggest you could refer to the Doc:Using Layered Windows

To have a dialog box come up as a translucent window, first create the
dialog as usual. Then, on WM_INITDIALOG, set the layered bit of the
window's extended style and call SetLayeredWindowAttributes with the
desired alpha value.

The third parameter of SetLayeredWindowAttributes is a value that ranges from 0 to 255, with 0 making the window completely transparent and 255 making it completely opaque.
In order to use layered child windows, the application has to declare itself Windows 8-aware in the manifest. Refer to the thread: How to use WS_EX_LAYERED on child controls


text:
Q: Enable/Disable Html.ActionLink based on a ViewBag value I have more ActionLinks on a view, MVC project
I need to enable/disable these buttons based on a ViewBag value.
I have added this code in the view
@{
   if (ViewBag.ModifyOS)
   {
      @Html.ActionLink(@Resources.Common.ModifyOSTerms, "ModifyOSTerms", "Document", new { lotId = LotId }, new { @class = "btn btn-success disabled" })
    }
     else
     {
       @Html.ActionLink(@Resources.Common.ModifyOSTerms, "ModifyOSTerms", "Document", new { lotId = LotId }, new { @class = "btn btn-success" })
      }
}

This way it is working correct, but I would like a more elegant way to achieve this.
I have tried this way:
@{
   string Disabled = "";
   if (ViewBag.ModifyOS)
   {
    Disabled = "disable";
   }
  }

and I have set this Disabled to ActionLink
 @Html.ActionLink(@Resources.Common.ModifyOSTerms, "ModifyOSTerms", "Document", new { lotId = LotId }, new { @class = "btn btn-success" , disabled = "@Disabled" })

I have tried this way:
@Html.ActionLink(@Resources.Common.ModifyOSTerms, "ModifyOSTerms", "Document", new { lotId = LotId }, new { @class = "btn btn-success" , disabled = "@(ViewBag.ModifyOS)" })

But in both cases the button is always disabled.

A: Looks like you can handle disabling by adding disable class. Why not go with it?
string cssClass = "btn btn-success";
if (ViewBag.ModifyOS)
{
    cssClass += " disabled";
}

@Html.ActionLink(@Resources.Common.ModifyOSTerms, "ModifyOSTerms", "Document", new { lotId = LotId }, new { @class = @cssClass })


text:
Q: Finding inverses to solve a system of congruences
Solve this system using the chinese remainder theorem. Find $x\in [-900,0]$.
$x\equiv3\bmod{4}$
$x\equiv7\bmod{9}$
$x\equiv4\bmod{25}$

How do I go about this?
I've found $m=4*9*25=900$, and $M_1=225$ and $M_2=100$, $M_3=36$.
How do I find the inverses,$y_1,y_2,y_3$, so that $M_1y_1=1\mod4$ etc...?

A: Solution
Since $M_1=225\equiv 1\mod 4$, we get $y_1\equiv 1\mod 4$ for free. Similarly, $M_2=100\equiv 1\mod 9$ so $y_2\equiv 1\mod 9$. Finally, we have $M_3=36\equiv11\mod25$. This one is a little harder. We have $11\times 9=99\equiv -1\mod 25$, and thus $11\times(11\times 81)=(11\times9)^2\equiv1\mod 25$. Hence $$y_3\equiv 11\times 81\equiv 11\times 6=66\equiv 16\mod 25.$$
Alternate Solution
The first congruence says that $x=3+4n$ for some integer $a$. Substituting this into the second congruence, we have $$3 + 4a \equiv 7\mod 9\iff 4a \equiv 4\mod 9\iff a\equiv 1\mod 9.$$
Therefore $a=1+9b$ for some integer $b$, and thus $x= 3+4(1+9b)=7+36b$. Substituting this into the last congruence, we have
$$7+11b\equiv 7+36b \equiv  4\mod 25\iff 11b\equiv-3\equiv22\mod 25\iff b\equiv 2\mod 25.$$
So $b=2+25c$ for some integer $c$, and thus $x=7+36(2+25c)=79+900c$. Taking $c=-1$ yields $x=-821$, which is in the required range.
Comments
Instead of finding the inverse of $11$ mod $25$, say, it was easier to simply use the properties of modular arithmetic until we were able to find $b$ by inspection.


text:
Q: Difference between null == x and x == null?
Possible Duplicate:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)?

I have seen comparisons done both ways.  Is there a performance difference or is it just personal preference?
I saw it being used in this answer:
What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

A: Using null == x  prevents accidentally mistyping and missing out one equals symbol and therefore assigning rather than testing for a value.  You would end up with null = x which would not compile.
In any case, using Object.ReferenceEquals(x, null) is probably better anyway, as it would prevent cases where == has been overloaded.

A: In this case, its personal preference in C#.

Yoda Conditionals

A: It's a rudiment from C++ days, where you could accidentally assign variable by using = instead of == and it would still pass the compiler cause you could pass almost anything into comparisons in C++.
Do not use it in C#, cause it will not allow you to do so.
Valid C++:
if (p = NULL) // p gets assigned NULL and result is compared to 0
Invalid C#:
if (p = null) // can only use booleans in test

A: Absolutely identical in all aspects. Just a reversed way of doing the same thing.

A:
Is there a performance difference or is it just personal preference?

No, absolutely no performance difference. It's only a matter of personal preference.


text:
Q: MS Access Sequential number Calculation and record generation Ok, this one is new to me...  I have a table where the user enters the number of records to be entered (X).  I would like MS Access to calculate the number X down to and including 0, and enter those numbers as records in another table.
[User Entry Table].[Number] = 10
The following numbers are then added to table Y in Field Record Number
10
9
8
7
6
5
4
3
2
1
0

A: Public Sub Insert(nBase As Integer)
    Dim nIndex As Integer
    Dim db As Database
    Set db = CurrentDb
    For nIndex = nBase To 0 Step -1
        db.Execute "INSERT INTO [User Entry Table] ([Number]) VALUES (" & nIndex & ")"
    Next
End Sub


text:
Q: GWT FileUpload doesn't work on Chrome and Opera Hi
I have some appliacation written in GWT 2.2 (tested also on previuos versions) with file upload. Basicly there is FileUpload component with Struts servlet on server side. The problem is that it works fine on IE and FF, but does not work on Chrome and Opera.
I found some tip to use gwtupload library ( i build the simplest case ) and the problem still occurs... With gwtupload I get alert with:
"Error, your browser has not sent any information. Please try again or try it using another browser"
Simple code for gwtupload version:
   defaultUploader = new SingleUploader();
        verticalPanel.add(defaultUploader);
        defaultUploader.addOnFinishUploadHandler(onFinishUploaderHandler);

    // Load the image in the document and in the case of success attach it to the viewer
private IUploader.OnFinishUploaderHandler onFinishUploaderHandler = new IUploader.OnFinishUploaderHandler() {
    public void onFinish(IUploader uploader) {
      if (uploader.getStatus() == IUploadStatus.Status.SUCCESS) {

        //new PreloadedImage(uploader.fileUrl(), showImage);

        // The server can send information to the client.
        // You can parse this information using XML or JSON libraries
        //            Document doc = XMLParser.parse(uploader.getServerResponse());
        //            String size = IUploader.Utils.getXmlNodeValue(doc, "file-1-size");
        //            String type = IUploader.Utils.getXmlNodeValue(doc, "file-1-type");
        Window.alert("Upload work");
      }
    }
};

Deafult servlet on the serves side.
Again, it works only on FF and IE. I hope somebody faced similar problem. :)

A: It could be some nasty WebKit bug. I think to remember something about a problem uploading files with WebKit-based browsers on OS X. You may want to check the WebKit bug database.


text:
Q: MySQL Date Format From Fri Jan 10 00:00:00 UTC 1992 to YYYY-MM-DD I have a data "Fri Jan 10 00:00:00 UTC 1992" And I want to convert it to 1992-10-01.
I know how to do it with Javascript, but I have no idea how to do it with MySQL
I tried :
DATE_FORMAT(column, '%d/%m/%Y')
But it's return null

A: select date_format(str_to_date("Fri Jan 10 00:00:00 UTC 1992","%a %b %d %H:%i:%s UTC %Y"),"%Y-%m-%d");

First you need str_to_date, using "%a %b %d %H:%i:%s UTC %Y" to get a date, after that you can format the date using date_format in the desired format.
These specifiers shown in the following table may be used in the format string.


text:
Q: Binding asp:Label text to an appSetting I've taken over maintenance on an ASP.NET WebForms project and I'm lost as to how the previous developer implemented some of the features. Basically he has an empty Label control in a master page:
<asp:Label ID="MyLabelControl" runat="server"></asp:Label>

And this as an applicationSetting in Web.Config:
<setting name="MyLabelControl" serializeAs="String">
    <value>Test</value>
</setting>

And somehow the label is populated with the value of the application setting. I've searched everywhere and can't find where he is binding the setting's value to the label. If it was me, I would do it in the Page_Load method for the master page, but this is empty. Is there some special binding thing that I don't know about?
I've done some basic WebForms work before, but prior to this most of my ASP.NET work has been in MVC with Razor. Yes, I'm learning things backwards :). Any help you can give me in understanding how he is doing this would be great. Thanks!

A: You can search this code
NameValueCollection appSettings = ConfigurationManager.AppSettings;
MyLabelControl.Text = appSettings[MyLabelControl];

A: If Aghilas' advice doesn't give you anything, I'd start by looking at this answer: Get value from web.config applicationSettings into ASP.NET markup
You'll probably have to do some system-wide searching, as if this site is older, it may still be using deprecated means to read the config file, as well. In that case, you might want to search for something looking like:
ConfigurationSettings.AppSettings.Get("MySetting")
And upgrade that puppy to use ConfigurationManager ASAP!
(Though, I did see an interesting article on CodeProject that warns against using that in a class ... didn't get to read it all the way through, but might be one to read as a "friendly warning" kind of thing: http://www.codeproject.com/Articles/196563/Don-t-use-ConfigurationManager)

A: Maybe change the label's name and see what crashes? You know, introduce an error and see what pops up as no longer working...


text:
Q: Why class name is same as class used in import statement Below snippet of code is from ITDIAgentException.java file
Can some one help me understand "why class name is same as class used in import statement"(ITDIAgentException)
import com.ibm.di.entry.Entry;
import com.ibm.di.exception.ITDIAgentException;

public class ITDIAgentException extends Exception {
  private Entry entry = null;

  public ITDIAgentException(String paramString) { super(paramString); }

  public Entry getEntry() { return this.entry; }

  public void setEntry(Entry paramEntry) { this.entry = paramEntry; }
}

EDIT

A: You have ITDIAgentException twice: Once in the import statement, and once in the class definition. You are not allowed to have both (would create a namespace clash in the code), but you can access com.ibm.di.exception.ITDIAgentException (assuming that it is different from the class you are creating) by using the full package and class name.
import com.ibm.di.exception.ITDIAgentException;

public class ITDIAgentException extends Exception {


text:
Q: How do I replace the line breaks in a textarea by a  I formed a textarea and a button that replaces the line breaks of this textarea with
 tags.
Code:

var gtcontbtnafterTA = document.getElementById("contbtnafterTA");
var gtRequesttextarea = document.getElementById("Requesttextarea");

gtcontbtnafterTA.onclick = function(event) {
  "use strict";
  Requesttextarea.replace(new RegExp('\r?\n', 'g'), '
');
}
#Requesttextarea {
  font-family: Traditional Arabic;
  font-size: 14pt;
  color: #000099;
  font-weight: bold;
  text-align: center;
  direction: rtl;
  width: 80%;
  height: 100px;
  border: 3px double #FF0000
}

#contbtnafterTA {
  font-family: Traditional Arabic;
  font-size: 14pt;
  color: #0000FF;
  font-weight: bold;
  width: 450
}

<textarea rows="50" name="Requesttextarea" cols="50" dir="rtl" id="Requesttextarea"></textarea>

<input type="button" value="الخطوات التالية" name="contbtnafterTA" dir="rtl" id="contbtnafterTA" class="buttonstyles">

Resulting error:

Object doesn't support property or method replace:
I hope I can get some code that replaces linebreaks with
 tags

Here are some pictures to explain the desired outcome.
Before:

After:

There is one line and some
 tags replacing each new line

A: You need to access the textarea value

var gtcontbtnafterTA = document.getElementById("contbtnafterTA");
var gtRequesttextarea = document.getElementById("Requesttextarea");

gtcontbtnafterTA.onclick = function(event) {
  "use strict";
  Requesttextarea.value = Requesttextarea.value.replace(new RegExp('\r?\n', 'g'), '
');
}
#Requesttextarea {
  font-family: Traditional Arabic;
  font-size: 14pt;
  color: #000099;
  font-weight: bold;
  text-align: center;
  direction: rtl;
  width: 80%;
  height: 100px;
  border: 3px double #FF0000
}

#contbtnafterTA {
  font-family: Traditional Arabic;
  font-size: 14pt;
  color: #0000FF;
  font-weight: bold;
  width: 450
}

<textarea rows="50" name="Requesttextarea" cols="50" dir="rtl" id="Requesttextarea"></textarea>

<input type="button" value="الخطوات التالية" name="contbtnafterTA" dir="rtl" id="contbtnafterTA" class="buttonstyles">


text:
Q: reference to type 'const QVariant' could not bind to an rvalue of type 'void' I am trying to save the following modification : to enable the pushButton_4.
void Vessels::SaveSettings()
{
    QSettings setting("My_vessels","My_selected_vessels");
    setting.beginGroup("Vessels");
    setting.setValue("selected",ui->pushButton_4->setEnabled(false));
    setting.endGroup();
}

When I run, I get this error:
vessels.cpp:838:33: error: reference to type 'const QVariant' could not bind to an rvalue of type 'void'
qsettings.h:167:55: note: passing argument to parameter 'value' here
All what I wanna know, is how to setvalue for an object from this window. I mean enabling the button is just an example.

A: setting.setValue("selected",ui->pushButton_4->setEnabled(false));

QWidget::setEnabled returns void, which you can't convert to a QVariant in QSettings::setValue. Did you mean ui->pushButton_4->isEnabled()?


text:
Q: Unir varios archivos .txt en un único DataFrame Tengo un carpeta con 2000 archivos .txt. Cada archivo txt contiene la siguiente información de la siguiente manera:
<CATEGORIA>Noticias Articulo Categoria</CATEGORIA>
<ENCABEZADO>Noticias Articulo Encabezado</ENCABEZADO>
<ARTICULO>Noticias Articulo Text</ARTICULO>
<CATEGORIA>Noticias Articulo Categoria</CATEGORIA>

Por ejemplo:
<CATEGORIA>CULTURA</CATEGORIA>
<ENCABEZADO>LAS PINTURAS DE DALI</ENCABEZADO>
<ARTICULO>ENTRE LAS PINTURAS DE DALI PODEMOS ENCONTRAR ... ETC. </ARTICULO>

Lo que necesito hacer es coger la información de cada una de esos 2000 archivos .txt (las 2000 noticias) y convertirlas en un único data frame con las columnas: noticias_categoria, noticias_titular, noticias_articulo.
Pero no se como combinarlos todos en un unico data frame de la manera mencionada.
Soy nuevo en Python así que disculpad si es un poco tonta la pregunta.
He conseguido sacar una lista con los nombres de cada archivo .txt usando:
ruta_carpetas  = '../directorio/..'
nombres_carpetas = os.listdir(ruta_carpetas)

Pero no he podido continuar.

A: Procesar el contenido
Ya que el formato de los contenidos se parece ligeramente a un XML, es posible usar la biblioteca BeautifulSoup para extraer la información relevante.
Por ejemplo una función como la siguiente podría recibir una cadena que sería el contenido de un fichero, y devolverte un diccionario con la información ya procesada:
from bs4 import BeautifulSoup

def procesar_contenido(contenido):
    procesado = BeautifulSoup(contenido, 'html.parser')
    campos = ["categoria", "encabezado", "articulo"]
    return { campo: procesado.find(campo).text for campo in campos }

Ejemplo de lo que haría esa función:
contenido = """
<CATEGORIA>CULTURA</CATEGORIA>
<ENCABEZADO>LAS PINTURAS DE DALI</ENCABEZADO>
<ARTICULO>ENTRE LAS PINTURAS DE DALI PODEMOS ENCONTRAR ... ETC. </ARTICULO>
"""

datos = procesar_contenido(contenido)
print(datos)

Resultaría:
{'articulo': 'ENTRE LAS PINTURAS DE DALI PODEMOS ENCONTRAR ... ETC. ',
 'categoria': 'CULTURA',
 'encabezado': 'LAS PINTURAS DE DALI'}

Procesar todos los ficheros
Iterando por la lista de ficheros, puedes ir abriendo uno, leyendo su contenido y usando la función anterior para convertirlo en un diccionario. Puedes ir recopilando todos esos diccionarios en una gran lista (que al final tendría 2000 diccionarios).
Algo así:
todos = []  # Inicialmente vacía
ruta_carpetas  = '../directorio/..'
for fichero in os.listdir(ruta_carpetas):
    with open(fichero) as f:
       contenido = f.read()
       datos = procesar_contenido(contenido)
       todos.append(datos)

Crear dataframe
Una vez tienes la lista de los 2000 diccionarios, del resto se ocupa pandas:
import pandas as pd

df = pd.DataFrame(todos)

Por ejemplo, yo no tengo tus 2000 ficheros, pero puedo crear una lista todos que repita 10 veces el mismo diccionario:
contenido = """
<CATEGORIA>CULTURA</CATEGORIA>
<ENCABEZADO>LAS PINTURAS DE DALI</ENCABEZADO>
<ARTICULO>ENTRE LAS PINTURAS DE DALI PODEMOS ENCONTRAR ... ETC. </ARTICULO>
"""

datos = procesar_contenido(contenido)
todo = [datos] * 10
df = pd.DataFrame(todo)

El resultado en este caso es:


text:
Q: SQL server Data Tools- can not browse the deployed cube I'm trying to browse the deployed cube, but it doesn't work. I have this error: "Element "return" was not found. Line 5, position 2". I've made the connection with database and it worked (I saw that when I created dimensions and cubes). Also the deployment completed successfully. How can I fix this problem?
Advanced Information:

Program Location:    at System.Xml.XmlReader.ReadStartElement(String
  name)    at
  Microsoft.AnalysisServices.AdomdClient.XmlaReader.ReadStartElement(String
  name)    at
  Microsoft.AnalysisServices.AdomdClient.XmlaClient.SupportsProperty(String
  propName)    at
  Microsoft.AnalysisServices.AdomdClient.XmlaClient.Connect(ConnectionInfo
  connectionInfo, Boolean beginSession)    at
  Microsoft.AnalysisServices.AdomdClient.AdomdConnection.XmlaClientProvider.Connect(Boolean
  toIXMLA)    at
  Microsoft.AnalysisServices.AdomdClient.AdomdConnection.XmlaClientProvider.Microsoft.AnalysisServices.AdomdClient.AdomdConnection.IXmlaClientProviderEx.ConnectIXmla()
  at
  Microsoft.AnalysisServices.AdomdClient.AdomdConnection.ConnectToIXMLA(Boolean
  createSession)    at
  Microsoft.AnalysisServices.AdomdClient.AdomdConnection.Open()    at
  Microsoft.AnalysisServices.Browse.ConnectionsManagerBase.Connect()
  at
  Microsoft.AnalysisServices.Browse.DimensionBrowser.ConnectionManager.Connect()
  at
  Microsoft.AnalysisServices.Browse.DimensionBrowser.EstablishConnection()
  at Microsoft.AnalysisServices.Browse.DimensionBrowser..ctor(String
  nameOfDimension, Object dimensionObject, IServiceProvider
  iserviceProvider, DesignerPageRelevantData designerPageRelevantData,
  UserContextData securityContextData)    at
  Microsoft.AnalysisServices.Browse.DimensionBrowserHostControl.CreateBrowser()
  at Microsoft.AnalysisServices.Browse.BrowserHostControl.LoadBrowser()

Thanks in advance

A: I also ran into this issue - it seems to have something to do with the connection timing out. Changing the connection time-out value in the connection options to a higher value (30, 60, etc) fixed the issue.


text:
Q: Help understanding VCF schematic I'm trying to build an adjustable active filter for an audio mixer and stumbled upon this design.

I'm completely lost. I understand first order passive filters and Sallen Key's.

A: The heart of the design is a twin T notch filter: -

This type of circuit normally rejects a small band of frequencies but, when placed within the negative feedback loop of an op-amp, The lack of negative feedback at those frequencies means the gain of the op-amp circuit is very high - thus a band pass fitler is created.
The LED is acting as a voltage controlled resistor varying R/2 in my circuit. This of course pulls the centre frequency up or down. It's a bit crude but relies on the slope of the LED V-I characteristic: -

Look at the red curve - with barely a volt across the LED the slope of the curve is very low but progressively gets more as the voltage is increased. If you translate this to V/I (resistance), you get a variable resistor controlled by a DC voltage. There will be a little distortion of the superimposed AC but as it is an "effect" it probably doesn't matter a great deal.

A: Interesting. I think what this is doing is adjusting the bias current of the LED, which changes the ac impedance seen at the feedback node. Considering that even the author doesn't think much of this filter ("decent fake lowpass response") I'm not sure it's the kind of think you want in an audio mixer.


text:
Q: Added comma separated on the foreach Velocity loop What should I added to the following foreach loop (Velocity codes) to get the final result like appNames=A,B,C
   #if($approval.has())
   #foreach($item in $approval.rejected)
   #set($appNames =$item.appName)
   #end
   #end

Thanks

A: I'd suggest using $foreach.hasNext for a cleaner code:
#if($approval.has())
  #foreach($item in $approval.rejected)
    #set($appNames =$item.appName)
    #if( $foreach.hasNext ),#end
  #end
#end

A: Just simply do add separator to it in the loop and String concatenation
#if($approval.has())
#set($appNames ="")
#set($separator="")
#foreach($item in $approval.rejected)
#set($appNames  =$appNames  +$separator +$item.appName)
#set($separator = ",")
#end
#end

appNames= $appNames
output
appNames= A,B,C


text:
Q: Displaying JSON Data in AngularJS in array I'm new to angularjs. I'm trying to display data from a php controller returned to server. I'm fetching that data in angular but there is a problem since data is not getting displayed. my code is attached.
Controller Action Method
public function actionAhmed(){
$unit = Units::model()->findAll();
$unitList = array();
foreach($unit as $value){
$unitList[] = $value->attributes;
}
return json_encode($unitList);
}

Angular Controller
    var myModel = angular.module('MyModel', []);
    app.controller('myCtrl', function($scope, $http) {
    $http.get('http://localhost/tutorial/index.php/units/ahmed')
    .then(function (response) {
        $scope.parsedData = response.data;
});
});

HTML code

        {{ x.Name + ', ' + x.Country }}


text:
Q: Assign value to data frame in R to all elements conditionally I try to assign value to all cells in a dataframe having a specific value
by this code
train_data <- read.csv("train_set.csv",header=TRUE)
train_data[train_data == "<NA>"] <- 0

But it does not work, I still see the values unchanged. How can I change  values? Data in CSV is as below
spec1   spec2
NA      NA
NA      NA
NA      NA
NA      NA
NA      NA
NA      NA
NA      NA
NA      NA
SP-0013 SP-0063
SP-0013 SP-0063
NA      NA
NA      NA
NA      NA
NA      NA
NA      NA
NA      NA

A: As @akrun and others have mentioned we may need an actual copy of your data, but give this a shot:
train_data <- read.csv("train_set.csv", header=TRUE, na.strings = c("NA", "<NA>"), stringsAsFactors=FALSE)

train_data[is.na(train_data)] <- 0


text:
Q: c# Linq method is not following one of my conditions that I set I'm trying to create a list like you see below.
For some reason, it follows the first two conditions, isPublished and IsRPG == false.  But it ignores the ShelfDate.
I want all games where the ShelfDate is greater than or equal to the current date.
But it will show games that have any ShelfDate...
BTW ShelfDate is of type DateTime.
Here is my code:
var games = await _context.Game
   .Where(x => x.IsPublished == isPublished && x.IsRPG == false && x.ShelfDate >= DateTime.Now)
   .Select(x => new GameEntity
   { ... }

Here are the models for Game and GameEntity:
public partial class Game
{
    public long Id { get; set; }
    public string Title { get; set; }
    public DateTime ShelfDate { get; set; }
    public DateTime IsPublished { get; set; }
    public bool IsRPG { get; set; }
    public string Description { get; set; }
}

public partial class GameEntity
{
    public string Title { get; set; }
    public DateTime ShelfDate { get; set; }
    public DateTime IsPublished { get; set; }
    public bool IsRPG { get; set; }
}

Am I doing anything wrong?
I am getting no errors.
Thanks!

A: Putting the response here.
DateTime.Now is not recognized by your data provider, and needs to be set earlier and not be evaluated by the query, assuming you're using Entity Framework.


text:
Q: porque el servidor me envía respuestas distintas en el login con laravel sanctum estoy usando laravel sanctum para autenticar usuarios, en local hice una prueba logueando un usuario y que me envíe una respuesta (1era foto ) con datos de dos tablas en la respuesta de la sesion
cuando lo subo al servidor y hago la misma peticion nuevamente para loguearme, me envía otra respuesta diferente, solo me muestra el mensaje de sesion iniciada pero no los datos que necesto, que podría revisar ?
mi login funcion
public function login(Request $request) {
    $request->validate([
        "rut" => "required",
         "dv" => "required",
        // "email" => "required|email",
        "password" => "required"
    ]);

  >first();

 $user = User::where("rut", "=", $request->rut)->first();

    if( isset($user->rut) ){
        if(Hash::check($request->password, $user->password)){
            //creamos el token
            $token = $user->createToken("auth_token")-
     >plainTextToken;
            //si está todo ok
            $user  = DB::table('users')
            ->join('lideres', 'lideres.rut_persona',
     'users.rut')
            ->select('lideres.grupo_id','users.tipo',
      'users.nombre')
            ->where("rut", "=",$request->rut)->first();

            if($user)
            $tipo=$user->tipo;
            if($tipo ==1){
                return response()->json([
                    "status" => 1,
                    "msg" => "¡Usuario logueado exitosamente! - tipo miembro",
                    "data" => $user,
                    "access_token" => $token
                ]);

            }else{
                return response()->json([
                    "status" => 0,
                    "msg" => "¡Usuario logueado exitosamente!
         - otro",
                    "data" => $user,
                    "access_token" => $token
                ]);
            }

        }else{
            return response()->json([
                "status" => 0,
                "msg" => "La password es incorrecta",
            ], 404);
        }

    }else{
        return response()->json([
            "status" => 0,
            "msg" => "El rut es incorrecto",
        ], 404);
    }
}


text:
Q: NVM not found in AWS CI-CD Pipeline I am new to create a pipeline in aws. I want to create a ci-cd pipeline for my nuxt project.
I create a yml file in which I want to install nvm and then install node version 12.18.3
The problem is I am getting the nvm not found error.
Can you please check and let me know if there is any error in my yml file:
version: 0.2
phases:
  install:
   commands:
     - echo Installing nvm...
     - curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
     - export NVM_DIR="$HOME/.nvm"
     - '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"'
     - '[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"'
  pre_build:
    commands:
      #install dependencies
      - echo Installing node...
      - nvm install 12.18.3
      - echo Installing npm...
      - npm install
  build:
    commands:
      #build
      - echo building...
      - npm run generate
artifacts:
  files:
    - '**/*'
 base-directory: dist
cache:
  paths:
    - node_modules/**/*

Thank you.

A: You don't actually need to use nvm to install specific node.js version on AWS CodeBuild.
You can use runtime-versions option which would install some version, but you don't have much control over this.
phases:
  install:
    runtime-versions:
      nodejs: 12.x

But AWS standard 5 image comes with n preinstalled (haven't checked 4 but it should be there as well), so you can use it like:
phases:
  install:
    commands:
      - n 12.18.3

and it would install that version same as nvm.

A: Working Solution
For some reason, It doesn't recognize nvm in the next line. I did not get a chance to investigate it further. The following configuration works. The idea is to set the nvm configurations and install node in the same line.
version: 0.2
phases:
  install:
    commands:
      - echo Installing nvm...
      - curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
      - export NVM_DIR="$HOME/.nvm"
      - '[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"'
      - '[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"'
  pre_build:
    commands:
      #install dependencies
      - . "$NVM_DIR/nvm.sh" && nvm install 12.18.3 && echo "node installed by arun"
      - echo Installing node...
      #- nvm install 12.18.3
      - echo Installing npm...
      - npm install
  build:
    commands:
      #build
      - echo building...
      - npm run generate
cache:
  paths:
    - node_modules/**/*

Troubleshoot in local environment.
In order to troubleshoot the buildspec.yaml, you can run the build locally. here is how to run the buildspec locally.


text:
Q: Mysql interval is not working after new year I am making a query on a website that i am working on that selects the top 1 user based on number of count it figures in a table between a specific interval of 1 year or 365 days it was working well last week but today i tried it and it is not working. I made some tests and i found out the problem is with the interval section. When i run the query it gives 0 results back. So I need your help please
SELECT user_posted_to, COUNT(*)
FROM activity_log_table
WHERE post_type = 'discussion'
   AND activity_type = 'Like'
   AND activity_timestamp >= CURRENT_DATE - INTERVAL 365 DAY
   AND activity_timestamp <= CURRENT_DATE
GROUP BY user_posted_to
ORDER BY COUNT(user_posted_to) DESC LIMIT 0, 1

A: Assuming activity_timestamp is an INT, a unix timestamp, you must use UNIX_TIMESTAMP function to convert dates to unix timestamps:
AND activity_timestamp >= UNIX_TIMESTAMP(CURRENT_DATE - INTERVAL 365 DAY)
AND activity_timestamp <= UNIX_TIMESTAMP(CURRENT_DATE)


text:
Q: Get asynchronously loaded html (via ajax) from url in Android I want to grab data from a webpage and display it in my Android app. The problem is, the elements I want from the HTML must be first created by an ajax call.
Because the data is loaded via Javascript my approach is to use a Webview to return the HTML. I use the method outlined by jluckyiv here : How do I get the web page contents from a WebView?
However, I realized this doesn't work because the ajax calls have not returned by when the javascript has finished running.
Are there any solutions? I don't have the access to modify the code on the webpage.

A: Do you use setJavaScriptEnabled(true) ?


text:
Q: AngularJS Table Rendering Slow in IE but fast in Chrome I'm hoping someone could give me some insight on the following issue I'm having. I have a table that when rendered in Chrome it's usable without any issues. However, in IE the page is completely unusable and slow. it locks up. The page itself uses more memory than I would like but in chrome it seems the GC frees up the memory after you navigate away from the page and in IE it does not.
Here is the code for the table rendering

{{::item.Date | date : 'MM/dd/yyyy'}}

                {{area}}

 0 && blah.NumberOfAvailableUnits < 2, green: blah.NumberOfAvailableUnits >= 2}"
                    ng-repeat="blah in item.items"
                    ng-if="blah.AreaName == area">
                    {{::blah.NumberOfAvailableUnits}}
                </div

This isn't something that can be fixed with pagination as the table is displayed on one page.
as you can see I tried to use one way binding (I think) to help alleviate the issue but it did not make a difference.
Thank you in advance.