text:
Q: Find Quarter based on Weeks in Java I am trying to get the quarter in the year using calender class in Java. I am getting current date as below and use WEEK_OF_YEAR variable to get the week as below but below output is not making much sense to me as this week is not 3rd week in this year.
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
System.out.println("week of year: "+cal.WEEK_OF_YEAR);

output: 2014/02/17
week of year: 3

What i wanted to do is, i want to have below quarter (Currently Quarter1 is running and next Quarter is Quarter2) as result and use this on my application.
Quarter1 is from Week 1 to Week 12.
Quarter2 is from Week 13 to Week 24.
Quarter3 is from Week 25 to Week 37.
Quarter4 is from Week 38 to the end of the year.

Please help me with this and let me know how do i find out Quarters as mentioned above.

A: Calendar.WEEK_OF_YEAR is a constant. You wanted cal.get(Calendar.WEEK_OF_YEAR).
However, you should note that "week of year" is not as simple as you might expect, as a concept. For example, it can be 53 on January 1st, which belongs to the previous week-year in some years. Are you happy for the first quarter of a year to start later than January 1st?
(Unless you really need to use a week-year/week-of-week-year/day-of-week representation for business purposes, year/month/day is much easier to get your head around.)
If you do need to translate the week-of-year into a quarter after reading those caveats, you can just use:
public static int getQuarter(Calendar calendar) {
    int weekOfYear = calendar.get(Calendar.WEEK_OF_YEAR);
    return weekOfYear < 13 ? 1
         : weekOfYear < 25 ? 2
         : weekOfYear < 38 ? 3
         : 4;
}

A: The answer by Jon Skeet is correct and should be accepted. With bonus points for that ternary sorcery. :-)
If you search StackOverflow, you'll find the more general question of determining quarters (and month, and weeks) asked and answered multiple times already. Also, search StackOverflow for "java week" to find helpful explanations about handling spans of time. Add "joda" to that search and you'll be even better off.
Keep in mind that time zone is critical, and that defines the first moment of day which defines first of month.
In one answer of mine, I show how you can use Joda-Time to get first of month, and then repeatedly add 3 months, if that is your definition of when quarters start.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime q1_2014 = new DateTime( 2014, 1, 1, 0, 0, 0, timeZone );
DateTime q2_2014 = q1_2014.plusMonths( 3 );
…

Joda-Time offers 3 classes for defining spans of time that may be of use to you: Period, Duration, and especially, Interval.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime yearStart = new DateTime( 2014, 1, 1, 0, 0, 0, timeZone );
Interval q1 = new Interval( yearStart, yearStart.plusMonths( 3 ) );
Interval q2 = new Interval( q1.getEnd(), q1.getEnd().plusMonths( 3 ) );
…
boolean isNowInQ1 = q1.contains( DateTime.now() );

Interval uses the "half-open" approach to comparisons, meaning the start is inclusive and the end is exclusive. This is a sensible and useful approach to time spans.
Again, search StackOveflow for much more discussion and many examples.


text:
Q: MySQL - move a subset of a table into another table I would like to move old records from a table to another one.
If I do this:
INSERT INTO archived_item SELECT * FROM item WHERE is_sold=1 AND sold_at < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH)

I would just copy rows. But I need to move them.
I don't think running this query after the previous one is ideal:
DELETE FROM item WHERE is_sold=1 AND sold_at < DATE_SUB(CURRENT_DATE, INTERVAL 6 MONTH)

I wouldn't like to use any external tool either.
Is it possible to achieve that via SQL?

A: As far as I know, it's not possible. You will have to explicitly issue a delete command if you want to remove data from the old table.

A: As far as I know, the only way to do this is to run the INSERT query and then run a delete query on the source table. There is no other way to achieve it.

A: There is nothing wrong in doing the two commands together. It is a proper way to do what you want.
To guarantee that you are actually deleting only the ones that you have moved you need to wrap the the commands in a transaction.
Now, the only thing that you can still question is the actual decision to have different tables for archive and working set.
There could be two reasons for this:

*

*performance

*different data integrity rules applied to the two sets

Performance alone should not be an issue, with proper indexes, until you hit some very, very large number of records. And it will increase complexity of your user interface, reporting which translate to maintenance (as stated above - if different rules apply to archive records, or if the structure of the data is not the same, justification is easier).

redpajama_set_name: RedPajamaStackExchange


text:
Q: WARN 15720 --- [io-7000-exec-10] o.s.web.servlet.PageNotFound : No mapping for GET /"http" I am trying to built a springboot project and I got stuct with this issue. Whwn I am calling the API localhost:7000/dashboard/project-overview I am getting this error in the chrome:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing
this as a fallback.

Tue Aug 06 05:19:40 ICT 2019
   There was an unexpected error (type=Not Found, status=404).
   No message available
And in the console I am getting this error
WARN 7248 --- [nio-7000-exec-9] o.s.web.servlet.PageNotFound             :
No mapping for GET /dashboard/project-overview

How can I solve this issue?
Here is my model
@Entity
@Table(name="project")
public class ViewProjectOverview {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private String id;

@Column(name="project_name")
private String projectName;

@Column(name="doc_url")
private Clob docUrl;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getProjectName() {
    return projectName;
}

public void setProjectName(String projectName) {
    this.projectName = projectName;
}

public Clob getDocUrl() {
    return docUrl;
}

public void setDocUrl(Clob docUrl) {
    this.docUrl = docUrl;
}

public ViewProjectOverview() {
    super();
}
}

Here is my repository
@Repository
public interface ViewProjectOverviewRepository extends
JpaRepository<ViewProjectOverview, String> {

}

Here is my service
@Service
public class ViewProjectOverviewService {

@Autowired
ViewProjectOverviewRepository vpor;

public List<ViewProjectOverview> findAll(){
    return vpor.findAll();
}

}

Here is my controller
@RestController
@RequestMapping(path = "/dashboard")
public class ViewProjectOverviewController {

@Autowired
ViewProjectOverviewService vpos;

 @GetMapping(path= {"/project-overview" })
 public List<ViewProjectOverview> getAll(){
        return vpos.findAll();
    }


text:
Q: Is it possible to use EmrFS role mapping for EMR on EKS We are playing around with EMR on EKS to run spark jobs on it. In our environment we access S3 buckets in multiple accounts and therefore we like to keep the role mapping for emrfs as we have it in "classic" EMR on EC2.
We set the emrfs configuration with --configuration-overrides when running a spark job via aws emr-containers start-job-run:
{
"classification": "emrfs-site",
"properties": {
  "fs.s3.authorization.roleMapping": "arn:aws:iam::12345:role/our-profile=p:s3://some_bucket/"
}}

While running a sample job we get this exception:
Caused by: java.lang.RuntimeException: EmrFS role mapping is not supported outside of EC2
This supposes that emrfs role mapping is indeed not available. The docs do not mention the topic of emrfs at all, so we are kind of sad to hit a limitation.
Yes, there is set up cross-account access for Amazon EMR on EKS, but that limits you to specify exactly one role_arn..
Has anybody have a good solution for this?


text:
Q: How to check if any alert is present on Selenium test with function subTest Q: What i need?
A: I need to check ANY alert is present, if user click on <a href="#"> to remove row on table. I cant use "Try-except" feature for Selenium test. I need something like:
with self.subTest('Testing alert in transaction {}'.format(value['link'])):
    driver.find_element_by_xpath('//table/tbody/tr[1]/td[last()]/a/i[@class="fa fa-remove"]').click()
    self.assertTrue(EC.alert_is_present(), 'Alert is present')

EC.alert_is_present()

What operator i can use to check alerts?


text:
Q: Taxonomy Filed Issue while Copying Document Library Item Using CSOM in Sharepoint Online I am trying to Copy a Document having the Managed Metadata(Termsets) fields from one site collection to another site collection in SharePoint online using CSOM. The  Managed Metadata Fields are there in both the Document libraries with different Internal names but with same display name.  The Columns names are shown in below image. After Copying the document only Topic filed data is copied without any additional  coding.

So I tried the below code  to copy  Managed Metadata(Termsets) fields after Uploading the file with internals names but the fields are not updating.
foreach (var stritem in Taxonomyfiledarray)
    {
    TaxonomyFieldValueCollection sourceValue = SourcelistItem[stritem.Source] as TaxonomyFieldValueCollection;
    string[] termValuesarrary;
    List<string> termValues = new List<string>();
    foreach (TaxonomyFieldValue taxProductFieldValue in sourceValue)
    {
     termValues.Add(taxProductFieldValue.Label + "|" + taxProductFieldValue.TermGuid);
    }
    termValuesarrary = termValues.ToArray();
    string termValuesstring = string.Join(";", termValuesarrary);
    itemToCreate[stritem.Destination] = termValuesstring;
    }
    itemToCreate.Update();

Any Suggestion please..

A: With assumption that both of the field use same TermSet, ExecuteQuery() is also called after this, try modified code:
foreach (var stritem in Taxonomyfiledarray)
{
TaxonomyFieldValueCollection sourceValue = SourcelistItem[stritem.Source] as TaxonomyFieldValueCollection;
string[] termValuesarrary;
List<string> termValues = new List<string>();
foreach (TaxonomyFieldValue taxProductFieldValue in sourceValue)
{
 termValues.Add("-1;#" + taxProductFieldValue.Label + "|" + taxProductFieldValue.TermGuid);
}
termValuesarrary = termValues.ToArray();
string termValuesstring = string.Join(";#", termValuesarrary);
itemToCreate[stritem.Destination] = termValuesstring;
}
itemToCreate.Update();

A: @Alok Kumar Gupta: Thanks for you guidance. Your guidance and the linkSetting a Managed Metadata Field with the Client Object Model driven me to fix the issue.
                 foreach (var stritem in Taxonomyfiledarray)
                    {
                        try
                        {

                            TaxonomyFieldValueCollection newtermValues = null;
                            Field field = fields.GetByInternalNameOrTitle(stritem.Destination);
                            destinationContext.Load(field);
                            destinationContext.ExecuteQuery();
                            TaxonomyField txField = destinationContext.CastTo<TaxonomyField>(field);
                            if (txField.AllowMultipleValues)
                            {
                                TaxonomyFieldValueCollection sourceValue = SourcelistItem[stritem.Source] as TaxonomyFieldValueCollection;
                                string[] termValuesarrary;
                                List<string> termValues = new List<string>();
                                foreach (TaxonomyFieldValue taxProductFieldValue in sourceValue)
                                {
                                    // termValues.Add(taxProductFieldValue.Label + "|" + taxProductFieldValue.TermGuid);
                                    termValues.Add("-1;#" + taxProductFieldValue.Label + "|" + taxProductFieldValue.TermGuid);
                                }
                                termValuesarrary = termValues.ToArray();
                                string termValuesstring = string.Join(";#", termValuesarrary);
                                newtermValues = new TaxonomyFieldValueCollection(destinationContext, termValuesstring, txField);
                                txField.SetFieldValueByValueCollection(itemToCreate, newtermValues);
                                itemToCreate.Update();
                                destinationContext.Load(itemToCreate);
                                destinationContext.ExecuteQuery();
                            }

                        }
                        catch (Exception ex)
                        {
                            lbl_Error.Text = ex.Message.ToString();
                        }
                    }


text:
Q: Prove that $\pi$ is irrational help I am working through Cartwright's proof for $\pi$ being irrational; specifically, the problem states:
Given $$A_n=\int_{-1}^{1}(1-x^2)^n\cos\left(\frac {\pi x}{2}\right)\,dx$$
Prove:
$$A_n=\frac {8n(2n-1)A_{n-1}-16n(n-1)A_{n-2}}{\pi ^2}.$$
I must prove it using integration by parts and have gotten really close to the answer but I am stuck at this step:
$$A_n=\frac{-16n(n-1)}{\pi^2}\int_{-1}^{1}x^2(1-x^2)^{n-2}\cos\left(\frac {\pi x}{2}\right)+\frac {8n}{\pi^2}A_{n-1}.$$
Specifically, I'm wondering how one could get rid of the $x^2$ term out of the integral to get $A_{n-2}.$
Thanks in advance!

A: OK it is simple, you have $$A_n = -\frac{16n(n-1)}{\pi^2}\int_{-1}^1x^2(1-x^2)^{n-2}\cos(\frac{\pi x}{2})dx + \frac{8n}{\pi^2}A_{n-1}$$
$$=-\frac{16n(n-1)}{\pi^2}(-A_{n-1}+A_{n-2}) + \frac{8n}{\pi^2}A_{n-1}$$
$$= \frac{8n}{\pi^2}(2n-1)A_{n-1} - \frac{16n(n-1)}{\pi^2}A_{n-2} $$

A: I haven't worked it out, but I wonder if this is the missing step:
$$
\int_{-1}^{1}(1-x^2)(1-x^2)^{n-2}\cos\left(\frac {\pi x}{2}\right)\,dx
= \int_{-1}^{1}(1-x^2)^{n-2}\cos\left(\frac {\pi x}{2}\right)\,dx
-\int_{-1}^{1}x^2(1-x^2)^{n-2}\cos\left(\frac {\pi x}{2}\right)\,dx
$$
So
$$
\int_{-1}^{1}x^2(1-x^2)^{n-2}\cos\left(\frac {\pi x}{2}\right)\,dx
= \int_{-1}^{1}(1-x^2)^{n-2}\cos\left(\frac {\pi x}{2}\right)\,dx
 -\int_{-1}^{1}(1-x^2)^{n-1}\cos\left(\frac {\pi x}{2}\right)\,dx
$$


text:
Q: How to get a `background-color` effect when clicking on a `url#header4` link How to get a background-color effect when clicking on a url#header4 link
like for instance here on stackoverflow. if you would select this on:
How to shutdown my system via a php site using LAMP server?
That is a link with an id and when u click it you would go to that link, to that header, and get a fancy background affect with a fading effect.
how can i get that effect on my website?

A: You can do it using CSS 3 (Animation & keyframes). No javascript needed at all.
.targetbox:target {
    animation: 2s ease 0s normal none 1 trgt;
}

@keyframes trgt {
    0% { background: #ff3; }
    100% { background: #ffa; }
}

…

See my fiddle: http://jsfiddle.net/SCQev/1/


text:
Q: PHP selecting multiple items from same colums to render in page I guys I am having a bit of an issue with this
I have a select statement which looks like this belows
$stmt = $conn->prepare("SELECT * FROM Product WHERE id=:id");
    $stmt->bindParam('id',$id);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if($row) {];
        ?>
<div>  <?echo $row['Name']; >? </div>
<div>  <?echo $row['Type']; >? </div>

$stmt1 = $conn->prepare("SELECT * FROM user WHERE Username IN ('john',
                                'sarah', 'james')");
        $stmt1->bindParam('id',$id);
        $stmt1->execute();
        $row1 = $stmt1->fetch(PDO::FETCH_ASSOC);
        if($row1) {];
            ?>
    <div>  <?echo $row1['username']; ?>' </div>

      <? } ?> //closing for the second select statement

<? } ?>  //closing for the first select statement

The problem
The page render but where I have use SELECT * FROM user WHERE Username IN ('john',
                                    'sarah', 'james') it is only showing one name instead of 3 names.
I know the select statement works because I try it in phpmyadmin and it does show all 3 names

A: Try:
Instead of if($row1) use while($row1)
With if the loop only runs once but with while it runs as long there are results to loop through.

A: Try this:
while($row1 = $stmt1->fetch(PDO::FETCH_ASSOC)) {
?>
<div><?php echo $row1['username']; ?> </div>
<?php } ?>

Also remove $stmt1->bindParam('id',$id);
Because if($row1) only reads first row, you need to loop through the output by calling $stmt1->fetch(PDO::FETCH_ASSOC) each time for retrieving rows.


text:
Q: Does haproxy have weight support We are setting up a new server with some different configs and software versions of previous installations we have. This server will be connected to our haproxy server, but I want to limit/reduce the flow of traffic to the new server. Is it possible to add a weight value to a server in haproxy to accomplish this, or some other config setting to achieve the same goal?

A: Yes it does have weighting.
server smtp01 smtp01.example.com weight 45 check inter 15000
server smtp02 smtp02.example.com weight 45 check inter 15000
server smtp03 smtp03.example.com weight 10 check inter 15000

The example is for tcp proxy. That means it will send 10 smtp connections out of 100 when using a roundrubin balance. And before asking such a question, you should google it.


text:
Q: How do I Render the Market Cap automatically to the page which is a result of stock price * shares outstanding I was doing a 45 day coding with ReactJS challenge am on day 2 and I have encountered a slight issue ,
I was wondering how I could render the Marketcap without the need to click submit button onto to the page and also the form space
import React, {Component} from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'

class App extends Component{

    constructor(){
        super()
        this.state= {
                StockName:"",
                StockPrice:"",
                Volume:"",
                MarketCap:""

        }
        this.handleChange=this.handleChange.bind(this)
        this.Calculate=this.Calculate.bind(this)

    }
    handleChange(event){
        const{name,value}=event.target
        this.setState({
            [name]:value
        })

    }

    Calculate(event){
        alert('$Market Cap is calculated')

    }

    render(){

        return(

Enter Company Details Below

            <form >
            <input
            class="form-control form-control-lg"
            value= {this.state.StockName}
            onChange ={this.handleChange}
            name ="StockName"
            placeholder="Stock" />

            <input
            class="form-control form-control-sm"
            value= {this.state.StockPrice}
            onChange ={this.handleChange}
            name="StockPrice"
            placeholder="$ Stock Price" />

           <input
           class="form-control form-control-sm"
            value= {this.state.Volume}
            onChange ={this.handleChange}
            name="Volume"
            placeholder="Shares Outstanding" />

           <input
           class="form-control form-control-sm"
            value= {this.state.MarketCap}
            onChange ={this.handleChange}
            name="MarketCap"
            placeholder="$ Market Cap" />

            <button onClick={this.Calculate}>Calculate</button>

                </form>

                Company:
{this.state.StockName}

                SharePrice:
${this.state.StockPrice}

                Shares Outstanding :
{this.state.Volume}

                Market Cap:
${this.state.MarketCap}

        )
    }
}

export default App

A: I'm not quite sure what you mean by rendering MarketCap, but if the point is to update it with every change you can trigger the calculate method from the change method. Example: https://codesandbox.io/embed/345yr934x5


text:
Q: org.apache.zeppelin.interpreter.InterpreterException: sparkr is not responding when i am executing simple sparkr script in Zeppelin :
code %spark.r 2 + 2
I am finding following error:
org.apache.zeppelin.interpreter.InterpreterException: sparkr is not  responding
R version 3.0.2 (2013-09-25) -- "Frisbee Sailing"
Copyright (C) 2013 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

at org.apache.zeppelin.spark.ZeppelinR.open(ZeppelinR.java:165)
at org.apache.zeppelin.spark.SparkRInterpreter.open(SparkRInterpreter.java:91)
at org.apache.zeppelin.interpreter.LazyOpenInterpreter.open(LazyOpenInterpreter.java:69)
at org.apache.zeppelin.interpreter.remote.RemoteInterpreterServer$InterpretJob.jobRun(RemoteInterpreterServer.java:618)
at org.apache.zeppelin.scheduler.Job.run(Job.java:186)
at org.apache.zeppelin.scheduler.FIFOScheduler$1.run(FIFOScheduler.java:139)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at

even i have set SPARK_HOME and JAVA_HOME in zeppline.env.sh

A: Most likely the R process is dead, please check the spark interpreter log


text:
Q: how do i use multiple  tag in single polymer element? I am trying to access same data in single element for two times, one for desktop navigation and one for responsive navigation(drawer toolbar). For this I use two content tags but it takes only one. In this this case what to do
<app-drawer-layout force-narrow>

  <app-drawer id="drawer">

    <app-toolbar></app-toolbar>

    <!-- Nav on mobile: side nav menu -->
    <paper-menu selected="{{selected}}" attr-for-selected="name">
      <template is="dom-repeat" items="{{items}}">
        <paper-item name="{{item}}">{{item}}</paper-item>
      </template>
    </paper-menu>

  </app-drawer>

  <app-header-layout>
    <app-header class="main-header">

      <app-toolbar>
        <paper-icon-button class="menu-button" icon="menu" drawer-toggle hidden$="{{wideLayout}}"></paper-icon-button>
      </app-toolbar>

      <app-toolbar class="tabs-bar" hidden$="{{!wideLayout}}">
        <!-- Nav on desktop: tabs -->
        <paper-tabs selected="{{selected}}" attr-for-selected="name" bottom-item>
          <template is="dom-repeat" items="{{items}}">
            <paper-tab name="{{item}}">{{item}}</paper-tab>
          </template>
        </paper-tabs>
      </app-toolbar>

    </app-header>
  </app-header-layout>

</app-drawer-layout>

<iron-media-query query="min-width: 600px" query-matches="{{wideLayout}}"></iron-media-query>

Polymer code:
Polymer({
  is: 'x-app',
  properties: {
    selected: {
      type: String,
      value: 'Item One'
    },
    wideLayout: {
      type: Boolean,
      value: false,
      observer: 'onLayoutChange',
    },
    items: {
      type: Array,
      value: function() {
        return ['Item One', 'Item Two', 'Item Three', 'Item Four'];
      }
    }
  },
  onLayoutChange: function(wide) {
    var drawer = this.$.drawer;
    if (wide && drawer.opened) {
      drawer.opened = false;
    }
  }
});

I have this type of code. What should I do to add menu element without using array. I want to add them separately from index at both app-header and app-drawer. but in index it should written one time as shown below.
   <wt-header logo="logo url" enable-menu="true" enable-topbar="false">
        <wt-menu>
        <wt-tab name="TabName" action="http://example.com/action" />
        <wt-tab name="TabName1" action="http://example.com/action2" />
        <wt-tab name="TabName3" action="http://example.com/action3" />
        </wt-menu>
    </wt-header>

A: I think you need to provide it twice. <content> doesn't "produce" what you pass to an element, it just projects the content - <content> is just a slot where the passed content is shown.
If you want to provide it twice, then you need to add a select=".some" to at least one <content> to define what part of the projected content (the one that matches the selector .some) should be projected to this <content select=".some"> and what content should be projected to the other <content> element.
An alternative approach is to pass the content within a <template>...</template> and then use templatizer to append the content of the template multiple times. This is for example how <template is="dom-repeat"> or <iron-list> are doing it


text:
Q: Can't turn back to Homescreen (stacked with a Drawerscreen) with WillPopScope I'm building a language learning app and on my homepage there are specific topics like colors etc. which you can choose and a learning page (via JSON) opens. My problem is that I can't find a solution on how to get back to the Homescreen. It's a Stack.
here's the code from my HomePage class with the Stack:
  static const String id = 'home_page';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          DrawerScreen(),
          HomeScreen(),
        ],
      ),
    );
  }
}

I already tried these solutions for my BackButton, but the app either crashes (when using the WillPopScope) or I'm getting a black screen (when using the
Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitDown, DeviceOrientation.portraitUp]);
    return WillPopScope(
      onWillPop: () {
        return showDialog(
            context: context,
            builder: (context) => AlertDialog(
                    title: Text('Möchtest du das Quiz beenden?'),
                    actions: <Widget>[
                      RaisedButton(
                        child: Text('Ja'),
                        onPressed: () =>
                            Navigator.pushNamed(context, DrawerScreen.id),
                      ),
                      RaisedButton(
                        child: Text('Nein'),
                        onPressed: () => Navigator.of(context).pop(false),
                      ),
                    ]));
      },
      child: Scaffold(
        body: Padding(
          padding: const EdgeInsets.fromLTRB(8.0, 64.0, 8.0, 8.0),
          child: Column(
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  BackButton(),
                ],
              ),
              Expanded(
                flex: 3,
                child: Container(
                  padding: EdgeInsets.all(15.0),
                  alignment: Alignment.bottomCenter,
                  child: Stack(
                    children: [
                      AnimatedOpacity(
                        opacity: opacity1,
                        duration: Duration(seconds: 1),
                        child: Center(
                          child: Text(
                            mydata[0][i.toString()],
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 48.0,
                              fontFamily: "Circular",
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                      AnimatedOpacity(
                        opacity: opacity2,
                        duration: Duration(seconds: 2),
                        child: Center(
                          child: Text(
                            mydata[1][i.toString()],
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 48.0,
                              fontFamily: "Circular",
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              Expanded(
                flex: 6,
                child: AbsorbPointer(
                  absorbing: disableAnswer,
                  child: Container(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        choicebutton1('a'),
                        choicebutton2('b'),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

 IconButton(
                      onPressed: () {
                        Navigator.of(context).pop();
                      },
                      icon: Icon(
                        Icons.arrow_back,
                        size: 30,
                        color: Colors.black,
                      ),
                    ),

A: onPressed: () => Navigator.of(context).pop(false)

remove the false


text:
Q: Change vars in JS file with grunt task Let's say you have a file that contains these 2 vars, but also other content
//Other code above
var endpoint='...';
var redirectUrl='...';
//Other code below

Now, is there a way for Grunt to change the value of those vars depending on build params?
Thanks.

A: If you enclose your line with something easily matchable. (Or if the original values are unique enough, it can be fine as well.)
You can use this plugin:
https://github.com/outaTiME/grunt-replace
To replace it with something else.


text:
Q: Testing an Apache Camel route with vm and file component over ftp I have two very simple routes (Code below is not the original classes, I have simplified it like removing setters, logs and so on)
The first route:
public static final String MESSAGE_CONSUMER = "vm:myMessage";

public String myXmlProducer; //and getter method then

myXmlProducer = "file:myFileLocation?autoCreate=true&fileName="+ myFileName;
from(MESSAGE_CONSUMER)
    //some process here
    .to(myXmlProducer);

and the second one:
public String fileConsumer = "file:myFileLocation";
public String ftpProducer = "ftp://ftpIp?username=username&password=password&maximumReconnectAttempts=0";

from(fileConsumer)
    .to(ftpProducer );

I am trying to write some test for these two routes, here is some part of my test class,
configuration part in class:
public static final String MOCK_OUT = "mock:out";
public static final String DIRECT_IN = "direct:in";
public static final String MOCK_XML_URI = "mock:xmlFile";
...
@EndpointInject(uri = MOCK_OUT)
MockEndpoint mockOut;

@EndpointInject(uri = MOCK_XML_URI)
MockEndpoint mockXmlUri;
...

@Override
public RouteBuilder[] createRouteBuilders() {
    final MyRoute route = new MyRoute();
    route.setFtpProducer (MOCK_OUT);

    RouteBuilder testHarness = new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from(DIRECT_IN).routeId("testHarness.in")
                .to(MyRoute.MESSAGE_CONSUMER)

            from(route.getMyXmlProducer())
                .convertBodyTo(Byte.class)
                .to(mockXmlUri)
        }
    };
    return new RouteBuilder[] {route, testHarness};
}

@Before
public void getTestData() throws IOException {
    testInputData = IOUtils.toString(this.getClass().getResourceAsStream("/myTarget/inputData.txt"));
}

This test method is green:
@Test
public void testRoutingOk() throws InterruptedException {
    mockOut.setExpectedMessageCount(1);
    mockOut.message(0).body().isEqualTo(testInputData);

    template.sendBody("file:myTestFileLocation", testInputData);
    assertMockEndpointsSatisfied();
}

The problem is the following test, I am quiet new in camel, and have googled to find why, but cannot figure it out by myself:
@Test
public void testRoutingOk() throws InterruptedException {
    mockXmlUri.setExpectedMessageCount(1);
    mockXmlUri.message(0).body().isEqualTo(testInputData);

    template.sendBody(DIRECT_IN, testInputData);
    assertMockEndpointsSatisfied();
}

I get assetion error, no message at all:
java.lang.AssertionError: mock://xmlFile Received message count. Expected: <1> but was: <0>

Is there anyone who can help me, please.

A: After some days struggling, I found what the problem was. I am sending a message to body but, this message will be used by another route. I am using version 2.10, the solution to have a green unit test is to stop the route. With current version (2.10) it will be a little bit complicated, since I should change my main classes just for unit tests sake. But I can use controlbus: instead, if we upgrade our camel to 2.11+.


text:
Q: PDF2image on AWS Lambda - resulted PNG has wrong fonts I am using pdf2image convert_from_bytes on my own PDFs in order to get them in PNG format. The context is AWS Lambda, py 3.8.
...
images = convert_from_bytes(infile,
                            dpi=DPI,
                            fmt=FMT)

for page_num, image in enumerate(images):
    location = "png/" + event.key.split('.')[0] + "-page" + str(page_num) + '.' + FMT

    buffer = BytesIO()
    image.save(buffer, FMT.upper())
    buffer.seek(0)
    ...

Although I am able to generate a PNG "correctly" (meaning with all the info & text), the resulted PNG seems to be using Times New Roman during the process as the font for every single paragraph I have in the PDF. Meanwhile the PDF itself shows correctly with the right fonts and I made sure it has the fonts embedded through properties. The problem happen only when I try to convert it to PNG format. Also I am not trying to use any fancy fonts, only Courrier-Bold and Helvetica.
Here an example of a pdf (part of it):

And the result image:

What did I try so far ?

*

*I tried to convert my PDFs using some online tools to see if this works or if the PDF itself was an issue. The PNG image was correct with the right fonts.

*I tried to process some random PDFs with my Lambda function and the generated PNG had correct fonts as well so the conversion seems to work on most PDFs.

*I tried with a few different fonts and same result.

*I tried to embbed the font in AWS lambda following somewhat this Include custom fonts in AWS Lambda but no luck

But at this point I am clueless. Any idea how can I debug ?
EDIT:
PDF font properties

EDIT2:
I wrote a small python program to generate a sentence per existing base font.

Then when I pass it through the lambda I get this:


text:
Q: Input of my python function gives namerror: name "b" is not defined When I define a function I want my input to just be like "b3" for example, not in brackets. But whenever my input has any kind of letter for example func(b)
it says name "b" is not defined.
def position(x) :
y=[]
a=str(x)
   if a[0]==b :
   y.append(0)
   else:
   y.append(1)
   return y

So basically I want position(b3) to give me [0] but went I put position(b3) is says "b3" is not defined

A: change you code to this:
def position(x) :
    y=[]
    a=str(x)
    if a[0]=='b' : # is a variable and it's not defined but 'b' is a string
        y.append(0)
    else:
        y.append(1)
    return y

A: As Barmar mentions in the comments:

What do you expect position(b3) to do if you haven't assigned a value to the variable b3? It should be position("b3")

All I needed to do was change my input from position(b3) to position("b3") and it works.


text:
Q: How to reorder cluster leaves (columns) when plotting pheatmap in R? I am plotting a set of 15 samples clustered in three groups A, B, C, and the heatmap orders them such as C, A, B. (I have read this is due to that it plots on the right the cluster with the strongest similarity). I would like to order the clusters so the leaves of the cluster are seen as A, B, C (therefore reorganising the order of the cluster branches. Is there a function that can help me do this?
The code I have used:
library(pheatmap)

pheatmap(mat, annotation_col = anno,
    color = colorRampPalette(c("blue", "white", "red"))(50), show_rownames = F)

(cluster_cols=FALSE would not cluster the samples at all, but that is not what I want)
I have also found on another forum this, but I am unsure how to change the function code and if it would work for me:

clustering_callback callback function to modify the clustering. Is
  called with two parameters: original hclust object and the matrix used
  for clustering. Must return a hclust object.

A: Hi I am not sure if that is of any help for you but when you check?pheatmap and scroll down to examples the last snippet of code actually does give that example.
# Modify ordering of the clusters using clustering callback option
callback = function(hc, mat){
    sv = svd(t(mat))$v[,1]
    dend = reorder(as.dendrogram(hc), wts = sv)
    as.hclust(dend)
}

pheatmap(test, clustering_callback = callback)

I tried it on my heatmap and the previously defined function actually sorted the clusters exactly the way I needed them. Although I have to admit (as I am new to R) I don't fully understand what the defined callback function does.
Maybe you can also write a function with the dendsortpackage as I know you can reorder the branches of a dendrogram with it.

A: In this case, luckily clustering of the columns coincides with sample number order, (which is similar to dendrogram) so I added cluster_cols = FALSE and solved the issue of re-clustering the columns (and avoided writing the callback function.
pheatmap(mat,
         annotation_col = anno,
         fontsize_row = 2,
         show_rownames = T,
         cutree_rows = 3,
         cluster_cols = FALSE)

A: # install.packages("dendsort")
library(dendsort)

sort_hclust <- function(...) as.hclust(dendsort(as.dendrogram(...)))

cluster_cols=sort_hclust(hclust(dist(mat)))


text:
Q: Knowledge Tab not able to see in Production - giving error User is not able to see Knowledge Tab.
I have checked below settings, User is knowledge User also Knowledge One is enable on his profile. But Tab for Knowledge is set to Default Off. When I try to change it. It is giving me an below error. Can any one please help me. I am performing this activity in production. So bit worried before changing anything,

Permission Manage All Related Contacts depends on permission(s): Read
  All Accounts Permission Read All Related Contacts depends on
  permission(s): Read All Accounts

A: I don't really understand what is an error, can you please help me with the exact error.
Make sure the object settings in the profile.

A: I have solved the issue. As Error say - I have added Read All permission on Account Object and then tried to Change Knowledge tab settings to Default On and it worked. Then I reverted account obj related changes


text:
Q: Hibernate: Criteria & createSQLQuery: how to get proper JSON? When I try this I get the proper JSON as a result, but it takes a lot of time:
        Criteria c = sessionFactory.getCurrentSession().createCriteria(User.class);
        List<User> users = c.list();
        List<User> specialUsers = new ArrayList<>();

        for (User user : users) {
            List<Perm> userPerms = user.getProfile().getPerms();

            for (Perm perm : userPerms) {
                if (perm.getId().equals(SPECIAL_ID)) {
                    specialUsers.add(user);
                }
            }
        }

        return specialUsers;

and the JSON is like:
[{"id":111,"name":"Name111"},{"id":222,"name":"Name222"}]

In attempt to improve performance I tried code below. In SQL app the results are OK, a few records of users:
        String sql = "SELECT u.id, u.name FROM app.user u inner join app.perms p where u.profile = p.profile AND p.right= :rightId";
        List<User> specialUsers= (List<User>)sessionFactory.getCurrentSession()
                .createSQLQuery(sql)
                .setParameter("rightId", SPECIAL_ID)
                .list();

        return specialUsers;

Now the 'JSON' however looks like this:
[[111,"Name111"],[222,"Name222"]]

I tried several things, like select *, criteria.add(Restrictions...) but to no effect. What I noticed is that in the first case specialUsers.toString returns proper data, in the second case it returns meaningless Strings like Ljava.lang.Object;@23e1469f.
Any hints how to solve this?

A: I managed to solve this in this way, may not be perfect:
        // get ids of all special users
        String sql = "SELECT u.id FROM app.user u inner join app.perms p where u.profile = p.profile AND p.right= :rightId";
        List<Integer> intIds = sessionFactory.getCurrentSession()
                .createSQLQuery(sql)
                .setParameter("rightId", SPECIAL_ID)
                .list();

        // convert to long values
        List<Long> longIds = intIds.stream()
                .mapToLong(Integer::longValue)
                .boxed().collect(Collectors.toList());

        // get all special users
        Criteria c = sessionFactory
                .getCurrentSession()
                .createCriteria(User.class)
                .add(Restrictions.in("id", longIds));

        List<User> specialUsers = c.list();
        return specialUsers;
    }


text:
Q: How to disable the use of verb tunneling using such headers or query parameters in .NET? I'm failing a security scan that is saying my .NET application is allowing verb tunneling and the recommendation is to disable this. The application needs to accept PUT and DELETE headers as well as GET and POST.
The scan is sending these headers to an endpoint that accepts POSTs:
X-HTTP-METHOD: PUT
X-HTTP-Method-Override: PUT
X-METHOD-OVERRIDE: PUT

I've done a lot of researching and am having a hard time finding a way to "disable" verb tunneling. It seems that these methods need to be allowed, not the other way around.
For example, in .NET the HttpMethodOverrideExtensions method is what allows these types of headers. I'm see multiple tutorials on how to allow the three headers posted above.
Am I correct in my response saying the application by default does not allow verb tunneling, as the methods to allow it are not in the application's code base?

A: I only have experience resolving this issue in Java, but I hope my solution has some translation to .NET that helps you. It looks like you're getting the issue "Often Misused: HTTP Method Override" reported by Fortify's WebInspect scanner. To resolve this for my team I implemented a filter that listens for our bad headers (x-http-method, x-http-method-override, x-method-override), sets status to 405 and breaks if they are found. See code below. I know this is not the most graceful solution, but it is the only one I found that satisfies the scan (throwing an error and booting the user did not satisfy).
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest hsReq = (HttpServletRequest) req;
    HttpServletResponse hsRes = (HttpServletResponse) res;

    hsRes.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
    hsRes.setHeader("Pragma", "no-cache");
    hsRes.setDateHeader("Expires", 0);
    hsRes.setHeader("X-XSS-Protection", "1; mode=block");
    hsRes.addHeader("X-Content-Type-Options", "nosniff");
    hsRes.setHeader("Content-Security-Policy", "frame-ancestors 'none'; default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'");
    hsRes.setHeader("X-FRAME-OPTIONS", "DENY");
    hsRes.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains;");

    // This resolves "Often Misused: HTTP Method Override"
    hsRes.setHeader("Access-Control-Allow-Methods", "GET, POST");
    String methodParam = hsReq.getParameter("_method");
    if (methodParam != null){
        LOG.error("\n Bad actor is attempting to use HTTP Method Tunneling. \n");
        hsRes.reset();
        hsRes.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    String xhmHeader = hsReq.getHeader("x-http-method");
    String xhmoHeader = hsReq.getHeader("x-http-method-override");
    String xmoHeader = hsReq.getHeader("x-method-override");
    if ((xhmHeader != null) || (xhmoHeader != null) || (xmoHeader != null)){
        LOG.error("\n Bad actor is attempting to use HTTP Method Tunneling. \n");
        hsRes.reset();
        hsRes.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    chain.doFilter(req, res);
}

A: I found this solution on another stackoverflow question:
https://stackoverflow.com/questions/66032991/how-do-i-ensure-that-x-http-method-headers-are-ignored

In short, this is the most accepted answer on that question where this is added to your web.config:
 <system.webServer>
    ...
 <security>
      <requestFiltering>
        <requestLimits>
          <headerLimits>
            <add header="X-Http-Method-Override" sizeLimit="0" />
            <add header="X-Method-Override" sizeLimit="0" />
            <add header="X-HTTP-Method" sizeLimit="0" />
          </headerLimits>
        </requestLimits>
        ...
      </requestFiltering>
    </security>
   ...
  </system.webServer>


text:
Q: sed command returns error I was trying to execute this command:
sudo sed -i 's/^\$projectroot.*/\$projectroot = \\"\\/home\\/repo\\";/' /etc/gitweb.conf

It returned an error:
sed: -e expression #1, char 42: unknown option to `s'

I don't understand why s is used in sed command. Please help

A: Your command should be:
sed -i 's/^\$projectroot.*/\$projectroot = \"\/home\/repo\";/'

Sample:
$ cat File

aaaaaaaaaa
bbbbbbbbbb
$projectroot
dddddddddd

$ sed 's/^\$projectroot.*/\$projectroot = \"\/home\/repo\";/' File

aaaaaaaaaa
bbbbbbbbbb
$projectroot = "/home/repo";
dddddddddd


text:
Q: Jquery UI autocomplete does not select all field text I have a problem with Jquery UI autocomplete: it only selects the start of the text which is typed in the field (characters preselection), not the whole text. For example : "stra" is selected instead of "strategy".
Here is my js code:
$(document).ready(function() {
   function doTag(iId, sLibelle) {
       $.ajax({
        type: "GET",
        url: "../../bobookmarks/content/json/put_tag_in_session.php",
        contentType : "application/json; charset=utf-8",
        dataType: "json",
        data: {iId: iId,
               sLibelle : sLibelle },
        success: function(data) {
                        if (data=="erreur") {
                            sErreur = "Une erreur est survenue";
                            console.log(sErreur + "bo.js:L18");
                            alert(sErreur);
                            return false;
                        }
        },

        error: function(jqXHR, textStatus, errorThrown) {
           var s = "Une erreur est survenue";
           alert(s);
        }
    })

    var sLi;
    sLi = "
";

    sLi += ""+$("#tag").val()+"";

    sLi += "";

    sLi += "
";

    $("#tags_liste").append(sLi);

    $("#tag").val("");
    return true;
 } // -- doTag()

 if ($("#tag").length > 0) {
    $("#tag").autocomplete({
        minLength:3,
        source: function(request,response) {
                    $.ajax({
                        type        : "GET",
                        url         : "../../bobookmarks/content/json/get_tags.php",
                        contentType : "application/json; charset=utf-8",
                        dataType    : "json",
                        data        : { term: $("#tag").val() },
                        success     : function(data) {
                                        if (data=="erreur") {
                                            alert("Une erreur est survenue");
                                            return false;
                                        }

                                        response($.map(data,   function(item) {
                                            return { id: item.catv_num,
                                                     value: item.catv_v_libelle
                                                   }
                                        }) // -- fin response
                                        )}, // -- fin success

                        error: function(jqXHR, textStatus, errorThrown) {
                           var s = "Une erreur est survenue";
                           console.log(s+" (bo.js:L74)");
                           alert(s);
                        }
                    }) // -- fin ajax
        }, // -- fin source

    });

    $("#tag").on("autocompleteselect", function(event, ui) {
        $("#tags_autocomplete_flag").val(1);
        console.log("tags_autocomplete_flag val (dans autocompleteresponse) : "+$("#tags_autocomplete_flag").val());
        doTag(ui.id, ui.value);
    });

    $("#tag").blur( function() {

        console.log("tags_autocomplete_flag val (entrée blur) : "+$("#tags_autocomplete_flag").val());

          if ($("#tags_autocomplete_flag").val()==1) {
            console.log("tags_autocomplete_flag val (blur(), conditon ==1) : "+$("#tags_autocomplete_flag").val());
            // Le tag vient de la base (autocomplétion)
            // la mise en session a déjà été traitée ci-dessus (L80 à 84)
            // on remet le flag à 0
            $("#tags_autocomplete_flag").val(0);
        } else { // Le tag ne vient pas de la base
            console.log("tags_autocomplete_flag val (si = 0 condition  else) : "+$("#tags_autocomplete_flag").val());
            doTag(0,  $("#tag").val());
        }
    });
 }
 });

Thank you in advance for your help.

A: When you call:
doTag(ui.id, ui.value);
this is not getting the right content. If you review the API, you will see:

select( event, ui ) Type: autocompleteselect
  Triggered when an item is selected from the menu. The default action is to replace the text field's value with the value of the selected item.
Canceling this event prevents the value from being updated, but does
  not prevent the menu from closing.
event
Type: Event

ui
Type: Object

item
Type: Object
An Object with label and value properties for the selected option.

You should be calling:
doTag(ui.id, ui.item.value);
to get the complete selected value from the AutoComplete list. Tested here: https://jsfiddle.net/Twisty/bpq3vxd1/


text:
Q: Increase size of parent div as image gets bigger My situation is the following: I have page that shows an image but sometimes it's too small, so I need to get the it bigger. I used CSS Transform to do that and works fine.
The problem is that the parent DIV's size does not increase, and there is space in the page for it to do so!
Using overflow on the parent does not help me because it crops the image or add a scroll bar. I need it to grow.
So, I managed to replicate a little what I am talking about here: http://jsfiddle.net/viniciuspaiva/7jJXQ/
When you click in the "Zoom" button, I want the div to grow and the pager below to get down. But I also want the page to load as it is, with the pager on top. Hope it's clear.
As you can see, I use bootstrap on my page. And the zoom button just adds a class to the image:
javascript:var img = $('img.center'); img.addClass('zoom');

Thanks!

A: Try doing it the other way. Have the image fit to the div, and resize the div instead.
Add this style to the image (assuming .myimg is the class).
.myimg {
  display: block;
  width: 100%;
}

A: Try placing this inside of your current div at the end of it before you close your current div.  It will force the div to expand to contents.

So your div opens, the contents inside, then add the code above, then close the div.

A: Here's an example of Joseph the Dreamer's implementation. Check it out here. It only relies on setting display: block; and width: 100%;.


text:
Q: How should one name "admin" user? The ubuntu has user "root" of unlimited privileges, apparently, it exists to not be used. The "admin" is already taken by something.
So, assuming the computer is not connected into any sort of omnipresent domain with individual tracking of every person. What would be the default snappy name to slap onto account used for occasional administrative tasks on such computer?
To clarify: suppose there is non-sudoer account named "user" which is used most of the time. The first idea for admin account to pair up with that user is, well, "admin". That's out of possibility on ubuntu. Is there some other generic name for such accounts? I mean vocabulary is not exhausted by the 'root' and 'admin', but those are short, concise and most relevant. What substitutes to those if any, were coined by creators\ agreed by community?

A: On a default Ubuntu install (checked on my 16.04), the username admin should not be taken yet. However, there can be a system group named admin, which has similar effects as the sudo group. As every new user automatically gets assigned a primary group with the same name as the username, creating a user called admin might fail. It is not recommended to try that name therefore.
Anyway, I am not aware of any other common usernames that are recommended to be used for admin accounts except the obvious administrator and maybe toor (root spelled backwards).
Generally you are free in your name choice, as  long as it does not contain any forbidden characters (use only lowercase letters, digits, dots, dashes and underscores). Just make sure your name is not taken yet.
Here's a command to list all existing user names and group names (duplicates eliminated) on your machine for comparison, so that you know what not to take:
grep -hPo '^.+?(?=:)' /etc/passwd /etc/group | sort -u

Just to point it out again, and "admin" user on Ubuntu does not mean a second root-like account. It means a normal unprivileged user account with the addition of some group memberships, like the sudo group which allows you to run commands as root using the sudo command, and a few other less relevant ones.
Related older questions of mine:

*

*Difference between admin/normal accounts except the right to use "sudo"?

*Security risk in everyday use of an admin account (not root)?

A: As zondo aptly pointed out, the only administrator on a Linux system is root. If you want to do administrative tasks, you can log in as root like this:
$ sudo su - root

When you're done, log out using the exit command:
$ exit 0

But, that's considered somewhat dangerous by many because out of sheer laziness people tend to log in as root once and never log out. You don't really want to do user-related things as root because you might mistype something and harm your system by deleting important files, for example. That's why the sudo utility was created. So, you don't need to have an account aimed specifically at doing administrative tasks. Just use sudo whenever you need elevated privileges for whatever you're doing.

A: Honestly, just create your own user as the "admin" user. During normal day to day use you will simply be a normal user who can only access your own files the way any other user can. When you need to perform administrative tasks you have to use sudo "command" and need to put your password in. It's the best thing to do because 1)you'll not have to log out to perform administrative tasks yet you'll still only be a normal user until you specifically ask for higher privileges by using sudo and 2) you'll never forget your admin login details because you'll be using them every day.
I'd recommend against using sudo su because you're then left with a terminal with elevated privileges where you can easily forget you've got root rights and inadvertently do damage with the wrong command. Just use sudo to prefix any commands you need root privileges for and you'll only run that single command with the higher authority of being root.


text:
Q: Remove postgresql and daemon user entries in Ubuntu Logon Screen I installed ubuntu 13.10 and installed some software. Now I see two new users in the logon screen called daemon and postgres. How can this happen? Is there a way to remove these entries from logon screen without removing these two user roles (I think these two roles are essential for certain applications).

A: indeed they're essential for certain services but if you just want to hide them, edit /etc/lightdm/users.conf file (the line that says hidden-users =) and append those users which you don't want to be shown.


text:
Q: Problem logging in with PHP's $SETTINGS I'm trying to get the user's login details from the database using $SETTINGS["admin_username"] and also the password. I have defined them as 'user' (for username) and pass (for password), and I want them to be pulled from database table userLogin.
Any ideas? Please help, I have tried everything but the page either doesn't open or it doesn't work at all.
<?php
error_reporting(0);
$SETTINGS["admin_username"]='user';
$SETTINGS["admin_password"]='pass';
$SETTINGS["mysql_user"]='user';
$SETTINGS["mysql_pass"]='pass';
$SETTINGS["hostname"]='localhost';
$SETTINGS["mysql_database"]='db_db';

$connection = mysql_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"]) or die ('request "Unable to connect to MySQL server."'.mysql_error());

$db = mysql_select_db($SETTINGS["mysql_databas… $connection) or die ('request "Unable to select database."');
?>

A: I can't read your code, so I try to write it again, here:
<?php

error_reporting(0);

$SETTINGS["admin_username"]='user';

$SETTINGS["admin_password"]='pass';

$SETTINGS["mysql_user"]='user';

$SETTINGS["mysql_pass"]='pass';

$SETTINGS["hostname"]='localhost';

$SETTINGS["mysql_database"]='db_db';

$connection = mysql_connect($SETTINGS["hostname"], $SETTINGS["mysql_user"], $SETTINGS["mysql_pass"]) or die ('request "Unable to connect to MySQL server."'.mysql_error());

$db = mysql_select_db($SETTINGS["mysql_database", $connection) or die ('request "Unable to select database."');

$sql = "SELECT * FROM userLogin LIMIT 1";
$rs = mysql_query($sql, $connection) or die(__LINE__.":".mysql_error());
while(false !== ($r = mysql_fetch_assoc($rs)))
{
    $SETTINGS["admin_username"]=$r['field_user'];
    $SETTINGS["admin_password"]=$r['field_pass'];
}

?>

Notice this line:
$sql = "SELECT * FROM userLogin LIMIT 1";

I use this in assumption that you only have 1 entry on table userLogin. If it's not, maybe you can use the following alternative query (because I don't know your current table's schema):
$sql = "SELECT * FROM userLogin WHERE field_user = 'admin'";

A: For starters, you've got an error in your syntax, Line 12 (and so does silent in his reproduction):
$db = mysql_select_db($SETTINGS["mysql_databas… $connection) or die ('request "Unable to select database."');

I'm guessing you want
$db = mysql_select_db($SETTINGS["mysql_database"], $connection) or die ('request "Unable to select database."');


text:
Q: Trying to run Python using Reticulate giving a module not found error, but it is installed I am trying to source data from a python script to use in R. I am using Articulate and PyCharm.
The script imports the module GetOldTweets3 and runs fine on its own, but when I try to run it using Articulate, I get Exception: ModuleNotFoundError: No module named 'GetOldTweets3'
py_config() gives me:
python:         C:/Users/<username>/AppData/Local/r-miniconda/envs/r-reticulate/python.exe
libpython:      C:/Users/<username>/AppData/Local/r-miniconda/envs/r-reticulate/python36.dll
pythonhome:     C:/Users/<username>/AppData/Local/r-miniconda/envs/r-reticulate
version:        3.6.10 |Anaconda, Inc.| (default, Mar 23 2020, 17:58:33) [MSC v.1916 64 bit (AMD64)]
Architecture:   64bit
numpy:          C:/Users/<username>/AppData/Local/r-miniconda/envs/r-reticulate/Lib/site-packages/numpy
numpy_version:  1.18.1

Running conda list in a terminal shows it there (in the pypi channel).
I am calling the python script using source_python().

A: Make sure you activate the conda virtual environment
It looks like numpy is installed in your personal r-retuculate python virtual environment. Make sure you activate the virtual environment associated with your installed python packages.
library(reticulate)
use_virtualenv("r-reticulate")


text:
Q: Currency Discord.py Bot Problem with files So here is my code:
@client.command()
async def beg(message):
    x = message.author.id
    idk = str(x) + ".wallet"
    file = open(idk, "w")
    file.close()
    file = open(idk, "r")
    first = file.read(1)
    if not first:
        file.close()
        file = open(idk, "w")
        file.write(str(0))
    file.close()
    file = open(idk, "r")
    money1 = file.readline()
    money1 = int(money1)
    a = random.randint(1, 750)
    money1 = money1 + a
    print(money1)
    money1 = str(money1)
    print(money1)
    file.close()
    file = open(idk, "w")
    print(money1)
    file.write(money1)
    print(money1)
    file.close()
    await message.channel.send(f"You got {a} dollars from begging congrats")

@client.command()
async def bal(message):
    x = message.author.id
    idk = str(x) + ".wallet"
    file = open(idk, "r")
    moni = file.readline()
    await message.channel.send(f'You have {moni} in your wallet right now.')

Please assume that I have all the necessary imports.
I figured that the problem was these few lines:
if not first:
    file.close()
    file = open(idk, "w")
    file.write(str(0))

Where even if the file isn't empty it still rewrites over the file and writes 0. I don't know how to fix this though. Thank you in advance! All help is appreciated.

A: The problem is the file open mode w opens the file and rewrites the whole thing. If you want to add a string, you have to open it with the append mode.
with open('file.txt', 'a') as f:
    f.write('something')

this will add something to the file.
If you want to modify the file
with open('file.txt', 'r') as f:
    file_str = f.readlines()
modify(file_str)
with open('file.txt', 'w') as f:
    f.write(file_str)


text:
Q: How to start a numbered list on the same line as its label or heading Example: 1. Item1
         2. Item2
         3. Item3

I am new to latex and trying to achieve something like above in latex (instead of Example: there can be any text). I have read answers with the same effect for a bulleted list but did not find any for a numbered list. How can I do it?

A: One way to achieve your formatting objective is to place the enumerate environment inside a minipage[t] environment.

\documentclass{article}
\usepackage{enumitem} % for fancy 'enumerate' and 'itemize' environments
\begin{document}

Example:
\begin{minipage}[t]{0.8\textwidth} %  choose a suitable width
\begin{enumerate}[nosep,left=0pt]
\item Item1
\item Item2
\item Item3
\end{enumerate}
\end{minipage}

\end{document}

A: Using the  wide= key of enumitem:
\documentclass{article}
\usepackage{calc}
\usepackage{enumitem}

\begin{document}

Example:
    \begin{enumerate}[wide=\widthof{Example: \hspace{1.5em}}, label=\arabic*., nosep,%
    before=\vspace*{-\baselineskip},]
        \item Item 1.
        \item Item 2.
        \item Item 3.
    \end{enumerate}

\end{document}

A: This will also do what you want. The advantage of this approach is 1) you don't have to specify widths, and 2) it automatically breaks across pages.
\documentclass{article}
\usepackage{enumitem}
\begin{document}

\begin{itemize}
\item[Example:]\begin{enumerate}[nosep]
\item Item1
\item Item2
\item Item3
\end{enumerate}
\end{itemize}

\end{document}


text:
Q: Library/ functions from TAH.h - There is no response in my code #include <Mouse.h>
#include <Keyboard.h>
#include <IRLib.h>
#include <IRLibMatch.h>
#include <IRLibRData.h>
#include <IRLibTimer.h>
#include <TAH.h>

TAH myTAH;

int mode, joyX, joyY, dPad, Buttonpadtag;

char val;          // Store Value of Buttonpadtag
char mem = ' ';    // Store Value of Buttonpadtag till getting new Value

void setup()
{
    Keyboard.begin();
    Mouse.begin();
    Keyboard.releaseAll();

    Serial.begin(9600);
    myTAH.begin(9600);

    myTAH.enterCommandMode();

    myTAH.setName("Play");
    myTAH.setWorkRole(SLAVE);
    myTAH.setAuth(OPEN);
    myTAH.setWorkMode(REMOTE_CONTROL);
    myTAH.setiBeaconMode(ON);

    myTAH.exitCommandMode();
}

void loop()
{
    // if there's any serial available, read it:
    if (myTAH.available())
    {
        ///// Parsing Value From Left Controller

        mode = myTAH.parseInt();

        joyX = myTAH.parseInt();

        joyY = myTAH.parseInt();

        dPad = myTAH.parseInt();

        Buttonpadtag = myTAH.parseInt();

        // joystick value mapping
        joyX = map(joyX, -128,128, 0, 255);
        joyY = map(joyY, 128, -128, 0, 255);

        // look for the newline. That's the end of your
        // sentence:
        if (myTAH.read() == 'P')
        {
            if(mode == 0) // App is in PS mode
            {
                // Always be getting fresh data
                dataForController_t SonycontrollerData = SonygetControllerData();
                // Then send out the data over the USB connection
                // Joystick.set(controllerData) also works.
                Joystick.setControllerData(SonycontrollerData);
            }
            else if(mode == 1) // App is in Computer Joystick Mode
            {
                /////////  Button Pad mapped to User Defined Computer Keys  ////////////
                if(Buttonpadtag >> 0  && Buttonpadtag != 5 && Buttonpadtag != 6)
                {
                    val = Buttonpadtag;
                    mem = val;
                    Keyboard.press(val);

                }
                else
                {
                    val = mem;
                    Keyboard.release(val);
                }

                if(Buttonpadtag == 5)
                {
                    Keyboard.press(KEY_ESC);
                }
                else
                {
                    Keyboard.release(KEY_ESC);
                }

                if(Buttonpadtag == 6)
                {
                    Mouse.press(MOUSE_LEFT);
                }
                else
                {
                    Mouse.release(MOUSE_LEFT);
                }

                //////////////////////////////////////////////////////////////////////

                /////////  dPad mapped to Computer Arrow Keys  ////////////

                if(dPad == 2 )
                {
                    Keyboard.press(KEY_UP_ARROW);
                    Keyboard.release(KEY_DOWN_ARROW);
                    Keyboard.release(KEY_RIGHT_ARROW);
                    Keyboard.release(KEY_LEFT_ARROW);
                }

                if(dPad == 8 )
                {
                    Keyboard.press(KEY_DOWN_ARROW);
                    Keyboard.release(KEY_UP_ARROW);
                    Keyboard.release(KEY_RIGHT_ARROW);
                    Keyboard.release(KEY_LEFT_ARROW);
                }

                if(dPad == 6 )
                {
                    Keyboard.press(KEY_RIGHT_ARROW);
                    Keyboard.release(KEY_UP_ARROW);
                    Keyboard.release(KEY_DOWN_ARROW);
                    Keyboard.release(KEY_LEFT_ARROW);
                }

                if(dPad == 4 )
                {
                    Keyboard.press(KEY_LEFT_ARROW);
                    Keyboard.release(KEY_UP_ARROW);
                    Keyboard.release(KEY_DOWN_ARROW);
                    Keyboard.release(KEY_RIGHT_ARROW);
                }

                if(dPad == 3 )
                {
                    Keyboard.press(KEY_UP_ARROW);
                    Keyboard.press(KEY_RIGHT_ARROW);
                    Keyboard.release(KEY_DOWN_ARROW);
                    Keyboard.release(KEY_LEFT_ARROW);
                }

                if(dPad == 9 )
                {
                    Keyboard.press(KEY_DOWN_ARROW);
                    Keyboard.press(KEY_RIGHT_ARROW);
                    Keyboard.release(KEY_UP_ARROW);
                    Keyboard.release(KEY_LEFT_ARROW);
                }

                if(dPad == 7 )
                {
                    Keyboard.press(KEY_DOWN_ARROW);
                    Keyboard.press(KEY_LEFT_ARROW);
                    Keyboard.release(KEY_UP_ARROW);
                    Keyboard.release(KEY_RIGHT_ARROW);

                }

                if(dPad == 1 )
                {
                    Keyboard.press(KEY_UP_ARROW);
                    Keyboard.press(KEY_LEFT_ARROW);
                    Keyboard.release(KEY_DOWN_ARROW);
                    Keyboard.release(KEY_RIGHT_ARROW);
                }

                if(dPad == 5)
                {
                    Keyboard.release(KEY_UP_ARROW);
                    Keyboard.release(KEY_DOWN_ARROW);
                    Keyboard.release(KEY_RIGHT_ARROW);
                    Keyboard.release(KEY_LEFT_ARROW);
                }

                //////////////////////////////////////////////////////////////////////
            }

            //print the three numbers in one string as hexadecimal:
            Serial.print(mode, DEC);
            Serial.print(",");
            Serial.print(joyX, DEC);
            Serial.print(",");
            Serial.print(joyY, DEC);
            Serial.print(",");
            Serial.print(dPad, DEC);
            Serial.print(",");
            Serial.println(Buttonpadtag, DEC);

            Serial.flush();
        }
    }
}

I went after this code on Git, then set things up to work as prescribed,  It gives the broken callback function in compiler an error (dataForController_t) to a memory allocation that is pre designated for other data. The slashed text comments should explain it better, left there by the developer. Although my community resources are far from many, I'm a work in progress when it comes to coding. Although I need more help than I can give, I don't think I'm ready to code a book.

From other code examples of function and methods in this sketch, I added a period between the two functions to see if I could have a hand in it. No alternative results given.
///////////// Play Station Data Structure /////////////

Originally written as dataForController_t SonygetControllerData(void)
the error is from syntax given: dataForController_t SonygetControllerData(void)
after the "error" 'dataForController_t' does not name a type
when the in-between period inserted as shown, same error persistent. Have not tried anything more.
dataForController_t.SonygetControllerData(void)
{
    // Set up a place for our controller data
    //  Use the getBlankDataForController() function, since
    //  just declaring a fresh dataForController_t tends
    //  to get you one filled with junk from other, random
    //  values that were in those memory locations before

    dataForController_t controllerData = getBlankDataForController();

    // Since our buttons are all held high and
    //  pulled low when pressed, we use the "!"
    //  operator to invert the readings from the pins

    if(Buttonpadtag == 1)
    {
        controllerData.crossOn = 1;
        Serial.println(" Cross");
    }
    else if(Buttonpadtag == 2)
    {
        controllerData.circleOn = 1;
        Serial.println(" Circle");
    }
    else if(Buttonpadtag == 3)
    {
        controllerData.squareOn = 1;
        Serial.println(" Square");
    }
    else if(Buttonpadtag == 4 )
    {
        controllerData.triangleOn = 1;
        Serial.println(" Triangle");
    }
    else if(Buttonpadtag == 7 )
    {
        controllerData.selectOn = 1;
        Serial.println(" Select");
    }
    else if(Buttonpadtag == 8 )
    {
        controllerData.startOn = 1;
        Serial.println(" Start");
    }

    // Set the analog sticks

    controllerData.leftStickX = joyX;
    controllerData.leftStickY = joyY;

    // And return the data!
    return controllerData;
}

A: The lib you are using is an incomplete version (and WIP). First copy the original library from here there you'll find the missing IRxx.libs. Then you have to define the dataForController_t struct yourself so define in this example program PS3:
int16_t LeftjoyX;
int16_t LeftjoyY;
int16_t RightjoyX;
int16_t RightjoyY;
int16_t Buttonpadtag;

struct  dataForController_t {
  int16_t leftStickX;
  int16_t leftStickY;
  int16_t rightStickX;
  int16_t rightStickY;
  bool  dpadRightOn;
  bool dpadLeftOn;
  bool dpadUpOn;
  bool dpadDownOn;
  bool triangleOn;
  bool squareOn;
  bool circleOn;
  bool crossOn;
  bool l1On;
  bool l2On;
  bool r1On;
  bool r2On;
  bool selectOn;
 bool startOn ;
 bool homeOn ;
} controllerData;

comment out the line
//Joystick.setControllerData(SonycontrollerData)
and add the function
dataForController_t  getBlankDataForController() {
  // Has to be written WIP - JUST DUMMY DATA
  controllerData.leftStickX = 0;
  controllerData.leftStickY = 0;
  controllerData.rightStickX = 0;
  controllerData.rightStickY = 0;
  // And return the data!
  return controllerData;
}

The last one has to be filled with all variables from the defined struct and set them to 0.
 Than the demo compiles. I doubt that it will work properly as the lib is a half finished effort left to the public 2015. So either finish it yourself or forget about using it.


text:
Q: Laravel Postgres calculate time difference and get min/max Hi my table structure is like this i am using laravel and postgres database
id | serving_start_time      | serving_end_time
1  | 2016-10-05 00:24:08.894 | 2016-10-05 00:24:19.003
2  | 2016-10-05 00:24:59.875 | 2016-10-05 00:25:13.728
3  | 2016-10-05 11:43:52.055 | 2016-10-05 11:45:41.561

I want to calculate the 'total_serving_time'(serving_start_time-serving_end_time) and get only the min and max 'total_serving_time'. Is this possible in one query? please help

A: In one query like following?
SELECT
    MIN(serving_end_time - serving_start_time) AS min_total_serving_time,
    MAX(serving_end_time - serving_start_time) AS max_total_serving_time
FROM table;


text:
Q: How to strip tags from html with robobrowser I'm experimenting with http://robobrowser.readthedocs.org/en/latest/readme.html, a new python library based on the beautiful soup library. with some help, I have returned an html page within a django app, but I can't figure out to strip the tags to give me just the text .
My django app contains :
def index(request):

    from django.utils.html import strip_tags
    p=str(request.POST.get('p', False)) # p='https://www.yahoo.com/'
    browser = RoboBrowser(history=True)
    browser.open(p)
    html = browser.response
    stripped = strip_tags(html)
    return HttpResponse(stripped )

when I look at the outputted html I see that it is the same as the original html. Also I don't think robobrowser has the text() method of beautiful soup.
I also tried (from Python code to remove HTML tags from a string):
def remove_html_markup(s):
    tag = False
    quote = False
    out = ""

    for c in s:
            if c == '<' and not quote:
                tag = True
            elif c == '>' and not quote:
                tag = False
            elif (c == '"' or c == "'") and tag:
                quote = not quote
            elif not tag:
                out = out + c

    return out

Same result! How can I remove the html tags and return the text?

A: BeautifulSoup provides the soup::get_text() method for extracting text from a parsed HTML document (somewhat confusingly, this is equivalent to the getText method and the text property). You can access the parsed HTML of the current page using browser.parsed. So, to get the plain text of the current page, try
text = browser.parsed.get_text()

A: I prefer using bleach.
Here's some example code:
import Bleach
varName = ( bleach.clean( result.find_all( class_ = 'className' ),
                          strip  = True
                          )
            ).strip( '[])' )


text:
Q: Copying blob from private blob container to public blob container in Azure We have two blob containers on Azure Storage. One is private and the other is public. I want to make a blob in private container a publicly accessible one on my application.
I am trying to copy blob from private to public container. I have found this on docs - Copy Blob. However, I could not manage to successfully to this operation and cannot find detailed explanations.
Last error I get is about Authorization header are not formed properly. Another previous one was about Date header not proper but I have solved it by new Date().toUTCString() instead of new Date().
What am I missing here?

A: I suggest you can use node.js sdk, then use the method startCopyBlob. By using rest api, it will take a few time to construct the authentication and not easy.


text:
Q: Jolt transformation nested grouping /// I have json input like below
    [{
    "shipment_id": 2,
    "schd_date": "2019-12-10 18:27:06.0",
    "contract_start_date": "2019-11-25 00:00:00.0",
    "contract_id": 1,
    "company_id": 9,
    "device_id": 6123,
    "parameter_name": "Humidity",
    "sensor_upper_threshold": "12",
    "sensor_lower_threshold": "10",
    "parameter_unit": "RH",
    "route_id": 6642,
    "source_stop_id": 10379,
    "stop_seq_no": 1,
    "route_efctv_from_dt": "2014-10-24 00:00:00.0",
    "route_efctv_to_dt": "2019-12-31 00:00:00.0"
}, {
    "shipment_id": 2,
    "schd_date": "2019-12-10 18:27:06.0",
    "contract_start_date": "2019-11-25 00:00:00.0",
    "contract_id": 1,
    "company_id": 9,
    "device_id": 6123,
    "parameter_name": "BatteryVoltage",
    "sensor_upper_threshold": "12",
    "sensor_lower_threshold": "10",
    "parameter_unit": "V",
    "route_id": 6642,
    "source_stop_id": 10379,
    "stop_seq_no": 1,
    "route_efctv_from_dt": "2014-10-24 00:00:00.0",
    "route_efctv_to_dt": "2019-12-31 00:00:00.0"
}, {
    "shipment_id": 2,
    "schd_date": "2019-12-10 18:27:06.0",
    "contract_start_date": "2019-11-25 00:00:00.0",
    "contract_id": 1,
    "company_id": 9,
    "device_id": 6123,
    "parameter_name": "Shock",
    "sensor_upper_threshold": "12",
    "sensor_lower_threshold": "10",
    "parameter_unit": "G",
    "route_id": 6642,
    "source_stop_id": 10379,
    "stop_seq_no": 1,
    "route_efctv_from_dt": "2014-10-24 00:00:00.0",
    "route_efctv_to_dt": "2019-12-31 00:00:00.0"
}, {
    "shipment_id": 2,
    "schd_date": "2019-12-10 18:27:06.0",
    "contract_start_date": "2019-11-25 00:00:00.0",
    "contract_id": 1,
    "company_id": 9,
    "device_id": 6123,
    "parameter_name": "Vibration",
    "sensor_upper_threshold": "12",
    "sensor_lower_threshold": "10",
    "parameter_unit": "Hz",
    "route_id": 6642,
    "source_stop_id": 10379,
    "stop_seq_no": 1,
    "route_efctv_from_dt": "2014-10-24 00:00:00.0",
    "route_efctv_to_dt": "2019-12-31 00:00:00.0"
}, {
    "shipment_id": 2,
    "schd_date": "2019-12-10 18:27:06.0",
    "contract_start_date": "2019-11-25 00:00:00.0",
    "contract_id": 1,
    "company_id": 9,
    "device_id": 6123,
    "parameter_name": "Humidity",
    "sensor_upper_threshold": "12",
    "sensor_lower_threshold": "10",
    "parameter_unit": "%",
    "route_id": 6642,
    "source_stop_id": 10379,
    "stop_seq_no": 1,
    "route_efctv_from_dt": "2014-10-24 00:00:00.0",
    "route_efctv_to_dt": "2019-12-31 00:00:00.0"
}, {
    "shipment_id": 2,
    "schd_date": "2019-12-10 18:27:06.0",
    "contract_start_date": "2019-11-25 00:00:00.0",
    "contract_id": 1,
    "company_id": 9,
    "device_id": 6123,
    "parameter_name": "Temperature",
    "sensor_upper_threshold": "12",
    "sensor_lower_threshold": "10",
    "parameter_unit": "C",
    "route_id": 6642,
    "source_stop_id": 10379,
    "stop_seq_no": 1,
    "route_efctv_from_dt": "2014-10-24 00:00:00.0",
    "route_efctv_to_dt": "2019-12-31 00:00:00.0"
}, {
    "shipment_id": 2,
    "schd_date": "2019-12-10 18:27:06.0",
    "contract_start_date": "2019-11-25 00:00:00.0",
    "contract_id": 1,
    "company_id": 9,
    "device_id": 6123,
    "parameter_name": "ACCZ",
    "sensor_upper_threshold": "12",
    "sensor_lower_threshold": "10",
    "parameter_unit": "g",
    "route_id": 6642,
    "source_stop_id": 10379,
    "stop_seq_no": 1,
    "route_efctv_from_dt": "2014-10-24 00:00:00.0",
    "route_efctv_to_dt": "2019-12-31 00:00:00.0"
}]

// Desired conversion using JOlt is like below :
{
"digifleet_id": "",
"shipment_number": "723984223",
"shipment_date": "2019 - 12 - 23",
"contract_number": "",
"customer_id": "",
"device": [{
    "device_id": "738293827472834",
    "sensors": [{
        "type": "temperature",
        "upper_threshold": 12,
        "lower_threshold": 3,
        "uom": "C"
    }]
}],
"route": [{
        "stop_seq_number": 1,
        "stop_id": "",
        "route_efctv_from_dt": null,
        "route_efctv_to_dt": 201912231400
    },
    {
        "stop_seq_number": 2,
        "stop_id": "",
        "route_efctv_from_dt": 201912311923,
        "route_efctv_to_dt": null
    }
]

}


text:
Q: Filling an empty matrix with values from tibble in R I have generated a tibble which is formatted like this:
  V1 n
1 "Sam,Chris" 30
2 "Sam,Peter" 81
3 "Jeff,James" 5
4 "David,Jones" 6
5 "Harry,Otto" 8

I also have a large matrix where every row and column is titled after a name, and each name appears once. So I need to split each row of V1, So that the index of the matrix that is:
   [Sam]
[Chris]30

For example, so I'd need to somehow split by the comma and then fill the matrix, how would I go about it?

A: We may need to use separate_rows
library(tidyverse)
df1 %>%
  separate_rows(V1, sep=",")

If we want to get the output as a matrix
df1 %>%
   separate(V1, into = c("V1", "V2"), sep=",") %>%
   spread(V2, n, fill = 0) %>%
   column_to_rownames("V1")
#    Chris James Jones Otto Peter
#David    0    0    6   0    0
#Harry    0    0    0    8    0
#Jeff     0     5   0   0  0
#@Sam      30    0    0   0   81

It can be converted to a square matrix, by including the first and last names both in row and column names
tmp <- df1 %>%
       separate(V1, into = c("V1", "V2"), sep=",")
lvls <- sort(unique(unlist(tmp[1:2])))
tmp %>%
  mutate_at(vars(V1, V2), factor, levels = lvls) %>%
  spread(V2, n, fill = 0, drop = FALSE)

data
df1 <- structure(list(V1 = c("Sam,Chris", "Sam,Peter", "Jeff,James",
"David,Jones", "Harry,Otto"), n = c(30L, 81L, 5L, 6L, 8L)),
 class = "data.frame", row.names = c("1",
"2", "3", "4", "5"))


text:
Q: how to split the elements in list and combine with another list in python list1 = ['APPLE - BANANA - (40-0)', 'BANANA :', 'ORANGE', 'MELON', 'MILK :', 'SET - "A" FISH', '$ 750', 'RANK :'
First, I would like to split the [0] and [5]
Output like:
'APPLE','BANANA','(40-0)' and 'SET','A','FISH'
how can I split it? For more information, actually I only need
'APPLE','BANANA','ORANGE','SET','A' for my next use, is it possible to take them out?
and here is
list2[0] = ['3', '10', 'JASON', 'T361', 'ZAC', 'ANDY', '120', '1085', '3', '2-1/2', '4', '7', '3', '0:57.80', '4.7']  here is the [0] position means there are some more like this format below.
so follow up the first part, i would like to insert
'APPLE','BANANA','ORANGE','SET','A' into list2's every elements and maybe take JASON be the first element. Could anyone tell me how to do it? thank you.

A: list1 = ['APPLE - BANANA - (40-0)', 'BANANA :', 'ORANGE', 'MELON', 'MILK :', 'SET - "A" FISH', '$ 750', 'RANK :']
list2 = []
list2.append(list1[0])
name_of_array = []
str = ""
for i in list2:
  for t in i:
        if t == '-' or t == '(' or t == ')' or t == ':' or t == "4" or t == "0":
           pass
        elif t == ' ':
           name_of_array.append(str)
           str = ""
        else:
           str += t
list3 = []
name_of_array1 = []
list3.append(list1[5])
str2 = ""
for r in list3:
    for e in r:
        if e == '-' or e == '(' or e == ')' or e == ':' or e == '"':
           pass
        elif e == ' ':
           name_of_array1.append(str2)
           str2 = ""
        else:
           str2 += e
name_of_array1.append(str2)
compose_2_lists = name_of_array + name_of_array1
big_list = []
for i in compose_2_lists:
    if i =='':
        pass
    else:
        big_list.append(i)

That's how I would do it. I hope I helped. If you not happy please talk with me, I'll try to explain in other way.


text:
Q: Proving some prooperty in finite p-groups when $\theta_g$ is inner automorphism induced by element $g$ Let $G$ be a finite p-group $(p\ge3)$ and $\theta_g$ be the inner automorphism induced by element $g$.
If $[G,g]\le Z_2(G)$ (upper central series) and $Z_2(G)$ is an abelian non-cyclic group of order $p^3$ is this enough to get
1. $\gamma_2G^p\le Z_2(G)$ (lower central series)
2. $g\in Z_2(G)$
3. $g\in Z_3(G)$
I know if (2) is right then (3) is right too I wrote both because I'm not sure (2) is right
$[G,g]=\langle [x,g]|x\in G\rangle$

A: Consider the following matrix group, upper traingular group, over $\mathbb{Z}_p$ (integers modulo $p$).
$$
\begin{bmatrix}
1 & * & * &  \cdots & * & *\\
0 & 1 & * &  \cdots      & \cdots & * \\
0 & 0 & 1 &  *       & \cdots & \cdots \\
\cdots & \cdots & \cdots &  \cdots      & \cdots & \cdots \\
0 & 0 & \cdots  &  0      & 1 & * \\
0 & 0 & \cdots &  0      & 0 & 1 \\
\end{bmatrix}
$$
Here $Z_2(G)$ is  "top-right triangle"
$$
\begin{bmatrix}
1 & 0 & \cdots &  0 & * & *\\
0 & 1 & 0 &  \cdots      & 0 & * \\
0 & 0 & 1 &  0       & \cdots & 0 \\
\cdots & \cdots & \cdots &  \cdots      & \cdots & \cdots \\
0 & 0 & \cdots  &  0      & 1 & 0 \\
0 & 0 & \cdots &  0      & 0 & 1 \\
\end{bmatrix}
$$
Take for $g$ the following type element:
$$
g=\begin{bmatrix}
1 & 0 & \cdots &  \alpha & * & *\\
0 & 1 & 0 &  \cdots      & \beta & * \\
0 & 0 & 1 &  0       & \cdots & \gamma \\
\cdots & \cdots & \cdots &  \cdots      & \cdots & \cdots \\
0 & 0 & \cdots  &  0      & 1 & 0 \\
0 & 0 & \cdots &  0      & 0 & 1 \\
\end{bmatrix}
$$
Here one of $\alpha,\beta,\gamma$ is non-zero, $*$ at top-right corner can be anything; remaining entries are zero.
Then taking matrix size arbitrarily, but at least $4$, we can check that $g$ and $Z_2(G)$ satisfy conditions in your theorem.
However, take matrix size very large so that $G$ will contain element of large prime power order, and so $G^p$ will also contain element of large prime power order. I don't believe then that $\gamma_2G^p\leq Z_2(G)$ will hold.


text:
Q: R: Writing values into matrix according to x & y coordinates given Hello everyone out here!
I have a 63x6 matrix mat (Columns: x-coordinates, y-coordinates, value_1,value_2, etc).
The value_1 should be written into a 7x9 matrix according to its coordinates given.
This solution doesn't work: (like many others I've tried..)
for (r in 1:nrow(df))   {
    for (c in 1:ncol(df))  {
      df[r,c] <- mat$value_1[mat$x == c && mat$y == r]

    }
}

Could anyone help? Thanks!
@Mael: I dont know if you meant it that way:
NMIN_struct <-
  structure(
    list(
      x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 1),
      y = c(1,
            1, 1, 1, 1, 1, 1, 1, 1, 2),
      Sample_ID = c(1, 1, 1, 2, 2, 2, 3,
                    3, 3, 4),
      Nmin1 = c(
        11.1788110878291,
        11.1788110878291,
        11.1788110878291,
        5.17227718787078,
        5.17227718787078,
        5.17227718787078,
        5.39282332521486,
        5.39282332521486,
        5.39282332521486,
        2.76320633985937
      ),
      Nmin2 = c(
        2.16160208812242,
        2.16160208812242,
        2.16160208812242,
        1.89355337232599,
        1.89355337232599,
        1.89355337232599,
        1.82901181814765,
        1.82901181814765,
        1.82901181814765,
        1.37989208438326
      ),
      Nmin3 = c(
        1.01043537292747,
        1.01043537292747,
        1.01043537292747,
        1.05972539906962,
        1.05972539906962,
        1.05972539906962,
        0.901859608440133,
        0.901859608440133,
        0.901859608440133,
        0.710021005623553
      )
    ),
    row.names = c(NA,-10L),
    class = c("tbl_df", "tbl", "data.frame")
  )

A: The base [ primitive accepts a 2-column matrix as an argument, where column 1 identifies rows and column 2 identifies columns. For instance, using a contrived matrix re-assigning 4 values in mtcars:
mat <- data.frame(row=c(1:3,3), col=c(2,3,1,3), val=90000:90003)

head(mtcars)
#                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
# Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

mtcars[ as.matrix(mat[,c("row","col")]) ] <- mat$val
head(mtcars)
#                       mpg   cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4            21.0 90000   160 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag        21.0     6 90001 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710        90002.0     4 90003  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive       21.4     6   258 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout    18.7     8   360 175 3.15 3.440 17.02  0  0    3    2
# Valiant              18.1     6   225 105 2.76 3.460 20.22  1  0    3    1

(This works on frames and matrices alike.)


text:
Q: Classes does not working stable First class(Player.java);
public class Player{
    int[] playercash = {1500,1500,1500,1500,1500,1500};
    int[] playerinvertory = {0,0,0,0,0,0};
    int[][] playeritemlist = new int[6][20];
    int[][] playeritemdurability = new int[6][20];

    int getCash(int playerid) {
        return playercash[playerid-1];
    }

    void giveCash(int playerid, int add) {
        playercash[playerid-1] += add;
    }
}

Second Class(Robot.java);
public class Robot {
    Player p = new Player();//Call player class

    void giveCash(int playerid) {
        p.giveCash(1,-3000);
    }
}

Main;
public class Main {
    public static void main(String[] args) {
        Player player = new Player();
        Robot robot = new Robot();
        player.giveCash(1, -2000);//1500-2000 = -500
        System.out.println(player.getCash(1)); //Write -500
        robot.giveCash(1);
        System.out.println(player.getCash(1)); //Write -500
    }
}

That is to say, robot.giveCash does not give cash. İ think robot class does not call player class. I want to write -3500 but it shows -500.

A: Robot is already existing class in JAVA.

This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.

https://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html

A: You make the Mistake, that you create a new Player in your Robot class, which is not the same as the Player you create in your Starter class. Therefore you have 2 different Players. You try to add some cash to the Player in your Main class, but the Robot has a different Player he adds cash to. To resolve this problem, pass the player to the giveCash method of your Robot class like this:
public class Robot{

    void giveCash(int playerid, Player p) {
        p.giveCash(1, -3000);
    }
}

A: Your Robot class is creating and updating a separate Player instance. One solution is to pass your Player instance into the constructor:
public class Robot {
    private final Player p;//Call player class

    public Robot(Player p) {
        this.p = p;
    }

    public void giveCash(int playerid) {
        p.giveCash(1,-3000);
    }
}

You would call it like this:
Player player = new Player();
Robot robot = new Robot(player);


text:
Q: помогите с python помогите, пожалуйста, что за ошибка? Не могу понять.
fruit == 'apple'
if fruit is 'apple'
print("fruit is apple")
else:
   print("lala")

A: *

*Имя fruit не определено, Вы используете оператор сравнения (==), вместо оператора присваивания (=).

*Пропущено двоеточие после условия

*Нет отступа перед телом цикла

*Вы используете оператор is, вместо оператора сравнения (==)

Пример:
fruit = 'apple'

if fruit == 'apple':
    print('fruit is apple')
else:
    print('lala')

stdout:
fruit is apple

A: Двоеточия нет и отступ неверный.

A: После if должно быть : и таб, то есть:
if fruit == 'apple':
     print("fruit is apple")

Но не понятно, что значит fruit == 'apple' # сравнение, что просто вернет false
Наверное, должно было быть: fruit = apple # присваивание
И ещё тут не подходит оператор is, почитайте зачем он нужен


text:
Q: Java installations are not working for me So I have been having some troubles with Java. It turned out I had the 32 bit version installed of jdk, not sure why. I uninstalled it to install the 64 bit version instead. However I can't get the installation to work. The installation .exe is not doing anything. When I click it I get the prompt from Windows asking if I'm ok with them making changes to my device etc. I click yes and nothing happens at all. This has happend with the newest versions of JDK and JRE, older versions of JDK and JRE, openjdk and even netbeans refuses to install JDK. Checked the processes to see if anything Java related was running, but there wasn't. Not getting any error messages either except for the netbeans installation which gives me an error code: -80.
Tried to google it, no results. I have checked various websites to no avail. Tried to check if I uninstalled the 32 bit version correctly, which I seem to have done. Tried using registry cleaners, did not help. Tried turning off background programs, did not help. I don't know anymore what I could try right now to fix it and since it's not really clear what's going on and what's causing the problems.
I am using Windows 10 64 bit.
I have been stuck with this for quite a while now and I really want to fix it. I hope someone here knows something I could try or what is causing the issue. To me it seems the only option I still have left is to reinstall Windows completely which I do not really want to do..
EDIT: I should note that I have also tried to apply the solution here: Java JDK 7u4 64 Bit Install Not Launching
I am not entirely sure however what is meant here by "deny delete/delete sub for each listed role/user" So this did not work for me.


text:
Q: Algorithm to determine if a given polynomial over $\mathbb{Q}$ is irreducible over the $p$-adic number field Let $\mathbb{Q}_p$ be the $p$-adic number field.
Let $f(x) \in \mathbb{Q}[x]$ be a polynomial of degree $\ge 1$.

Is there an algorithm to determine whether $f(x)$ is irreducible over $\mathbb{Q}_p$ or not?

The motivation is that there is indeed such an algorithm if we replace $\mathbb{Q}_p$ by $\mathbb{R}$

A: By googling "p-adic irreducibility", I found this link to a paper by D. Cantor and D. Gordon. Evidently there are algorithms, but let me point out to you where some the difficulties may lie.
In the real case, it's easy, 'cause an irreducible polynomial can have degree only $1$ or $2$; and for a quadratic polynomial, you determine irreducibility by looking at the sign of the discriminant.
In the $p$-adic case, there are irreducible polynomials of all degrees, by Eisenstein, which tells you that $x^n-p$ is irred. The general methods of showing reducibility are Hensel's Lemma in the strong form, which says that if $f(X)\in\mathbb Z_p[X]$ factors into two relatively prime factors as an $\Bbb F_p$-polynomial, then it factors over $\Bbb Z_p$. And the Newton polygon as a general tool, which says that if the (nonvertical part of) the polygon has more than one segment, the polynomial is reducible.
The $p$-adic irreducibility techniques that I'm aware of are, again the Newton polygon, which says that if the polygon's unique nonvertical segment passes through no integral points in the plane other than its endpoints, then the polynomial is irreducible; and the obvious condition that if the associated $\Bbb F_p$-polynomial is irreducible, then the original $\Bbb Z_p$-polynomial is irreducible. Note that the familiar Eisenstein Criterion for irreducibility is a special case of the Newton-polygon method I mention above.
Finally, note that to apply the second irreducibility criterion I mentioned before, you need to determine whether an $\Bbb F_p$-polynomial is irreducible. This is already a difficult problem.
I leave it at that, and refer you to the Cantor-Gordon paper, and any others that you surely will find when you dig deeper.


text:
Q: Borderlands 2 First SMG After playing BL2 on the PC through Steam with two different characters in three separate games. I played up to level seven roughly.
I cannot find/buy any SMGs. So, wondering if anyone else has come across this phenomenon. I've googled and didn't find anything, further to this since loot is random guns don't really have locations.
When do SMGs come later in the game?
Or have I just not come across any yet?
Thanks for you time.

A: Yeah they come a tad bit later, don't worry about it. Once you come to Sanctuary and start doing quests from that point you'll be getting lots of SMG's as drops and they will be available in the shops.

A: I can't remember when I did find my first SMG, but I'm certain that SMGs drop in the "later game". I can't tell you whether there is an area/level/progression restriction and I can't tell you exactly when they "start to drop".
Maybe it's just you having no luck in finding any, I had the same going for sniper rifles until I hit level 11.