text:
Q: OSX: programmatically get uptime? Something similar to linux
cat /proc/uptime

which returns the uptime in seconds, and preferably not parsing uptime(1).

A: If anyone is trying to do this programmatically using sysctl.h and is expecting a string back like what you see in the command line, the returned value that I get is a 16 byte array, not a string:
sysctlbyname("kern.boottime", value, &size, NULL, 0);
An example for what gets put into value in hex starting from the [0] index:
a9 af c6 4e 0 0 0 0 0 0 0 0 28 be 92 55
The first 4 bytes (maybe the first 8, won't know until Jan 2012) is the epoch time in little endian byte order.

A: Old question, I know, but I needed to do the same thing so I thought I'd post the code I'm using, which I got from http://cocoadev.com/wiki/FindingUptime
#include <time.h>
#include <errno.h>
#include <sys/sysctl.h>

double uptime()
{
    struct timeval boottime;
    size_t len = sizeof(boottime);
    int mib[2] = { CTL_KERN, KERN_BOOTTIME };
    if( sysctl(mib, 2, &boottime, &len, NULL, 0) < 0 )
    {
        return -1.0;
    }
    time_t bsec = boottime.tv_sec, csec = time(NULL);

    return difftime(csec, bsec);
}

A: The Uptime article on Wikipedia has an interesting lead:

Using sysctl
There is also a method of using sysctl
to call the system's last boot
time: $ sysctl kern.boottime
kern.boottime: { sec = 1271934886,
usec = 667779 } Thu Apr 22 12:14:46
2010

Which references sysctl(8), which references sysctl(3).

A: correct way:
CFTimeInterval getSystemUptime(void)
{
    enum { NANOSECONDS_IN_SEC = 1000 * 1000 * 1000 };
    static double multiply = 0;
    if (multiply == 0)
    {
        mach_timebase_info_data_t s_timebase_info;
        kern_return_t result = mach_timebase_info(&s_timebase_info);
        assert(result == noErr);
        // multiply to get value in the nano seconds
        multiply = (double)s_timebase_info.numer / (double)s_timebase_info.denom;
        // multiply to get value in the seconds
        multiply /= NANOSECONDS_IN_SEC;
    }
    return mach_absolute_time() * multiply;
}

also you could use CACurrentMediaTime() from QuartzCore.framework (which has same code probably) - Available since OS X v10.5 and iOS 2.0

A: There is a function UpTime declared in DriverServices.h.  I believe this is equivalent to another function mach_absolute_time.  Both seem to be undocumented.

A: Unfortunately the "sysctl kern.boottime" returns the seconds of the timestamp, not elapsed seconds..  Multiple calls do not increase the second count, but must be seconds from epoc of the boot date itself.

A: A simple Lua script to do exactly what you ask for:
local now=tonumber(io.popen("date +%s"):read())
local boottime=tonumber(io.popen("sysctl -n kern.boottime"):read():match("sec = (%d+)"))
local uptime=now-boottime


text:
Q: Angular Material Routed Dialog with Routed Tabs To start: my StackBlitz contains the exact case I'm trying to solve.
Like the title says I have a routed dialog (dialog that opens based on the route) and inside this dialog I want to have a tab control. Every tab should also be bound to a route, so I think my dialog should somehow also get a <router-outlet/>
But when I add this extra <router-outlet/> without the name argument the rendering (I think) goes frenzy -> result: unresponsive app.
When I add the name argument and I also configure the routing it doesn't work either.
const routes: Routes = [
  {path: '', redirectTo: '/home', pathMatch: 'full'},
  {path: 'home', component: HomeComponent, children: [
    {path: 'dialog', component: DialogWrapperComponent},
    {path: 'routed-dialog',
     children: [
       {path: '', component: RoutedDialogWrapperComponent},
       {path: 'first', component: FirstComponent
          //, outlet:'test' // Adding this does not work
       }
     ]
    }
  ]},
]

So, the RoutedDialogWrapperComponent looks like this:
import { Component } from "@angular/core";
import { MatDialog } from "@angular/material/dialog";
import { RoutedDialogComponent } from "./routed-dialog.component";
import { Router, ActivatedRoute } from "@angular/router";

@Component({
  template:''
})
export class RoutedDialogWrapperComponent{
  constructor(private dialog:MatDialog, private router:Router,
    private route: ActivatedRoute){
    this.openDialog();
  }

  private openDialog(){
    let dialog = this.dialog.open(RoutedDialogComponent);

    dialog.afterClosed().subscribe(result => {
      this.router.navigate(['../'],
        {
          relativeTo: this.route
        });
    });
  }
}

and the HTML of the RoutedDialogComponent like this:

  First
  Second
  Third

<router-outlet name='test'></router-outlet>

In the end I want to have an url like: '/home/routed-dialog/first' and inside the dialog, under the tab-nav, I want to see the FirstComponent but I don't know how to...
Other cases like having the correct tab 'activated' is something I'm confident enough about to fix, but on this one I need some help because my Angular knowledge (as goes for its slang) is pretty limited :-)

A: You can find solution with named router outlets here 'router-outlet' in MatDialog is not working in Angular 7
But if you really want to have clean links without strange constructions like /routed-dialog(popupContent:first) then you can do the following trick:

*

*define all tabbed components as children of RoutedDialogWrapperComponent:
{
  path: "routed-dialog",
  component: RoutedDialogWrapperComponent,
  children: [
    {
      path: "first",
      component: FirstComponent
    },
    {
      path: "second",
      component: SecondComponent
    },
    {
      path: "third",
      component: ThirdComponent
    },
    {
      path: '**',
      redirectTo: 'first'
    }
  ],
}

*put <router-outlet> in template of RoutedDialogWrapperComponent and wrap it with <ng-template>
<ng-template>
  <router-outlet></router-outlet>
</ng-template>

*grab reference to that wrapper in component class:
export class RoutedDialogWrapperComponent {
  @ViewChild(TemplateRef, { static: true }) templateRef: TemplateRef<any>;

*pass that reference to RoutedDialogComponent:
export class RoutedDialogWrapperComponent implement OnInit {
   ngOnInit() {
     this.openDialog();
   }

   private openDialog() {
     const dialog = this.dialog.open(RoutedDialogComponent);
     dialog.componentInstance.contentTemplate = this.templateRef;
     ...
   }
}

*finally, render it within RoutedDialogComponent:

  First
  Second
  Third

<ng-template [ngTemplateOutlet]="contentTemplate"></ng-template>

Forked Stackblitz

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get Html.DropdownFor() to select current element? I must be missing something simple here. This code was working and i can't seem to figure out why it stopped.
First, I generate a selectlist in the controller like this:
        // Select List
        ViewData["FieldTypesList"] = new SelectList(
            genesisRepository.FieldTypes, "ftID", "ftName"
            );

The View that uses this select list looks like this:
    <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Genesis.Domain.Entities.Stream2FieldTypes>" %>
    <%@ Import Namespace="Genesis.Domain.Entities" %>
    <%: Html.DropDownListFor(
            model => model.FieldTypeID,
            (SelectList)ViewData["FieldTypesList"]
            )%>
    <%:Model.FieldTypeID.ToString() %>

However... the HTML that gets generated shows this:
<select id="Stream2FieldTypes_0_" name="Stream2FieldTypes[0]"><option value="1">Text Area</option>
    <option value="2">Text Box</option>
    <option value="3">Rich Text</option>
    <option value="4">Image</option>
    <option value="5">DateTime</option>
    <option value="6">Decimal</option>
    <option value="7">Integer</option>
</select>
3 <!--FYI: current value-->

I am completely missing why the view does not render html that selects 3 (Rich Text).
Do you guys see anything wrong with my thought process?

A: I think you forgot to pass the selected value to the constructor
ViewData["FieldTypesList"] = new SelectList(
    genesisRepository.FieldTypes, "ftID", "ftName", myModel.FileTypeID)
);

A: You can handle it in your Controller with an overload of the SelectList Constructor
    ViewData["FieldTypesList"] = new SelectList(
        genesisRepository.FieldTypes, "ftID", "ftName"
        new (ftID=3, ftName="Rich Text");

A: Thanks to @hunter and @John_Hartstock for pointing me to the selectlist instance rather than focusing on the DropDownListFor() method.
I ended up solving the bug by constructing the selectlist in the view instead of the controlelr. The controller was edited to this:
ViewData["FieldTypesList"] = genesisRepository.FieldTypes;
// Returns IEnumerable of FieldTypes

Changed the view to this:
<%: Html.DropDownListFor(
            model => model.FieldTypeID,
            new SelectList((IEnumerable<FieldTypes>)ViewData["FieldTypesList"],
            "ftID",
            "ftName",
            Model.FieldTypeID ))
%>

This works perfectly.


text:
Q: How to return the column heading for multiple matches, from multiple criteria, in Excel? I'm working with 40+ price lists for different groups of customers. By entering the item number and price, I'd like to show the names of all the price lists that match that item/price. I've set up the items and pricing lists like the table below. Some items have the same prices in multiple price lists, and some price lists do not list all items.
Item     ListPrice  Red    Blue   Green    Grey
Hosaka2  $200       $180   $188            $171
TrodesH  $460       $410   $380   $400     $380
TrodesL  $810       $680   $680   $720
Shuri    $80        $72           $72      $70

I'd like to enter TrodesH and $380 into cells and have the formula return Blue & Grey. Or enter Hosaka2 and $200 and have the formula return ListPrice.
I've used this Index array formula in the past to return multiple matches to a single entry. To, for example, list all the account numbers whose address matches the zip code I enter. It's very handy. But here I'm looking for the combination of item and price. Any ideas how I might move forward?
Edit: For better legibility in the Excel file, I've placed the above data in a worksheet named "Matrix" and the lookup formulas in a worksheet named "Check."

A: Let's assume that A1:F5 contains the data, and H2 contains the item of interest, such as TrodesH, and I2 contains the price of interest, such as $380, try...
J2:

=COUNTIF(INDEX($B$2:$F$5,MATCH($H2,$A$2:$A$5,0),0),$I2)

K2, confirmed with CONTROL+SHIFT+ENTER, and copied across:

=IF(COLUMNS($K2:K2)<=$J2,INDEX($B$1:$F$1,SMALL(IF(INDEX($B$2:$F$5,MATCH($H2,$A$2:$A$5,0),0)=$I2,COLUMN($B$1:$F$1)-COLUMN($B$1)+1),COLUMNS($K2:K2))),"")

Hope this helps!

A: Taking the diagram below as a model (adjust it to your own data layout and places), you can enter this formula at J1 and copy/paste into the colored area:
J1:
=IFERROR(INDEX($1:$1,AGGREGATE(15,6,COLUMN($B$2:$F$5)
  /($A$2:$A$5=$H1)/($B$2:$F$5=$I1),COLUMN(A:A))),"")


text:
Q: leaflet marker element style not working I try to change marker style by js.
but when I typed this code:
let markerElement = marker.getElement();
markerElement.style.transform = 'rotate(90deg)';

I have an exeption that said that markerElement is undifined.
any help.
(or just a way to rotate the marker by the typescript)

A: Have you tried using this package?
https://github.com/bbecquet/Leaflet.RotatedMarker


text:
Q: maas-import-pxe-files error with md5sum ![I am building a private cloud maas using ubuntu 12.04 LTS. I have some experience in previous cloud server with the same iso. But now I have got an error in running sudo maas-import-pxe-files. "failled to verify MD5SUMS via /usr/share/keyrings/ubuntu-archive-keying.gpg (http://archive.ubuntu.com/ubuntu//dists/quantal/main/installer-amd64/current/images//MD5SUMS)". And then command is stopped. what happen? I have no idea to solve. Give me some advice please.]

A: I had this problem was well, as I didn't need quantal images I just edited the /etc/maas/import_pxe_files. I changed the releases line to
RELEASES="precise"

I ran the command again and it worked


text:
Q: Can we increment each record in a table using one of the records from the last row? Can we keep incrementing column B using column A in redshift-sql. Example:

Column A Column B

0            0
1            1 (0+1)
2            3 (2+1)
3            6 (3+3)
4            10 (4+6)
5            15 (10+5)
6            21 (15+6)

A: If memory serves, Amazon-Redshift does have window functions
This was tested in SQL Server
Declare @Table table (ColumnA int)
Insert into @Table values
(0),
(1),
(2),
(3),
(4),
(5),
(6)

Select ColumnA
      ,ColumnB = sum(ColumnA) over (Order by ColumnA)
 From @Table

Returns
ColumnA ColumnB
0       0
1       1
2       3
3       6
4       10
5       15
6       21


text:
Q: How to count field values in mysql My table -
pid     id  subject section
1        1  7            0
2        1  12           0
3        1  13           1
4        1  13           2
5        1  13           3
6        1  14           3
7        1  14           4
8        2  15           1
9        2  16           1

Result to be obtained -
id subject total
1    7      1
1    12     1
1    13     3
1    14     2

My Query -
SELECT DISTINCT(SUBJECT), count(section)
FROM mytable
GROUP BY section
WHERE id = 1

But this is throwing an error, let me know what I am doing wrong
Error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE id = 1' at line 4: SELECT DISTINCT(SUBJECT), count(section) FROM mytable GROUP BY section WHERE id = 1

A: The syntax error is due to a misplaced WHERE clause. It needs to go before GROUP BY. Additionally:

*

*You are grouping by the column you want to sum.

*You are using DISTINCT unnecessarily.

Query should be on this line:
SELECT SUBJECT, count(section)
FROM mytable
WHERE id = 1
GROUP BY SUBJECT

A: You need to group by subject since this is the distinct value. In that group you want to count the appearances of section.
SELECT 1 as id, subject, count(section) as total
FROM mytable
WHERE id = 1
GROUP BY subject

And since the id column is not in the group, you can select that static value or you could replace it with an aggregate function like min(id) as id instead of 1 as id

A: You want to group by subject rather than section.  And you don't need distinct--it is redundant with GROUP BY.
SELECT id, subject, count(section)
   FROM mytable
   WHERE id = 1
   GROUP BY id, subject

A: SELECT SUBJECT, count(section)
FROM mytable
WHERE id = 1
GROUP BY SUBJECT


text:
Q: How to clone a pluggable database in Oracle I'm new to Oracle's pluggable databases (we still use Oracle 11.2 at work). For a test of partitions and subpartitions, I'll need to create a couple of dozen tablespaces. I thought, I'd quickly clone my current database, do the tests, and drop the database afterwards.
I was able to clone the database:
CREATE PLUGGABLE DATABASE ora193p2 FROM ora193p1
 FILE_NAME_CONVERT = (
   '/opt/oracle/oradata/ORA193C/ORA193P1/',
   '/opt/oracle/oradata/ORA193C/ORA193P2/');

Pluggable database ORA193P2 created.

but got an error ORA-01109: database not open when trying to connect to it.
I've tried to open it, but get an error message, too (ora193c is the name of the cdb):
ALTER DATABASE ora193p2 OPEN;
ORA-01509: specified name 'ORA193P2' does not match actual 'ORA193C'

I used the database from vagrant-boxes.

A: For pluggable databases you need to add key word pluggable database followed by pdb name
SQL> create pluggable database pdbclone from orclpdb;

Pluggable database created.

SQL> show pdbs

    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
---------- ------------------------------ ---------- ----------
         2 PDB$SEED                       READ ONLY  NO
         3 ORCLPDB                        READ WRITE NO
         4 PDBCLONE                       MOUNTED

SQL> alter pluggable database pdbclone open;

Pluggable database altered.

SQL> show pdbs

    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
---------- ------------------------------ ---------- ----------
         2 PDB$SEED                       READ ONLY  NO
         3 ORCLPDB                        READ WRITE NO
         4 PDBCLONE                       READ WRITE NO
SQL> alter pluggable database pdbclone save state;

Pluggable database altered.

A: From 12.1.0.2 onward, you can preserve the PDB startup state through CDB restart. The 12.1.0.2 patchset introduced SAVE STATE and DISCARD STATE options:
ALTER PLUGGABLE DATABASE pdb_name OPEN;
ALTER PLUGGABLE DATABASE pdb_name SAVE STATE;

To discard the saved state:
ALTER PLUGGABLE DATABASE pdb_name DISCARD STATE;

For 12.1.0.1 and before, you could create an after startup trigger:
CREATE OR REPLACE TRIGGER open_pdbs
  AFTER STARTUP ON DATABASE
BEGIN
   EXECUTE IMMEDIATE 'ALTER PLUGGABLE DATABASE ALL OPEN';
END open_pdbs;
/

It creates a after startup system level trigger in CDB.
See Oracle 12c Post Installation Mandatory Steps


text:
Q: kotlin AlertDialog Custom null I want to use AlertDialog by kotlin, and this is just a demo.
However, this doesn't works. When I push positiveButton, it returns
java.lang.IllegalStateException
Can anyone fix this error. Here is the code
override fun onClick(view: View?) {
    val customLayout = layoutInflater.inflate(R.layout.component_time_table_dialog, null)
    AlertDialog.Builder(this).apply {
        setTitle("QUESTION")
        setView(customLayout)
        setPositiveButton("ACCEPT", DialogInterface.OnClickListener { dialogInterface, which ->
            Toast.makeText(mContext, subjectName.text.toString(), Toast.LENGTH_SHORT).show()
        })
        setNegativeButton("REJECT", null)
        create()
        show()
    }
    Toast.makeText(this, " Clicked", Toast.LENGTH_SHORT).show()
}

component_time_table_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/subjectName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="SubjectName"/>

</LinearLayout>

A: I suggest you do the following:
val alertBuilder = AlertDialog.Builder(this)

alertBuilder.setMessage("MESSAGE")

alertBuilder.setTitle("QUESTION")

alertBuilder.setPositiveButton("ACCEPT") { dialog, which ->
    Toast.makeText(this, "TOAST", Toast.LENGTH_SHORT).show()
}

alertBuilder.setNegativeButton("REJECT") { dialog, which ->
    // ...
}

val alertDialog = alertBuilder.create()
alertDialog.show()


text:
Q: Schema input type always "LinkedHashMap cannot be cast..." My schema.grapqls looks like...
scalar BigDecimal
...
input TemplateLineItemInput {
    partMasterId: String!
    partMasterIdPath: String!
    actionType: String!
    actionQuantity: BigDecimal!
}
...
type Mutation {
    ...
    createLineItem(id: ID! input: TemplateLineItemInput!): TemplateBom
}

My POJOs are all Lombok-ie and were working great until I tried to create that input.
import lombok.Builder;
import lombok.Data;

import java.math.BigDecimal;

@Data
@Builder
public class TemplateLineItemInput {
  private final String partMasterId;
  private final String partMasterIdPath;
  private final String actionType;
  private final BigDecimal actionQuantity;
}

I believe I have the mutation it wired up correctly...
@Component
public class TemplateBomDataWiring  implements RuntimeWiringBuilderCustomizer {
  private static final Logger LOG = LoggerFactory.getLogger(TemplateBomDataWiring.class);

  private final TemplateBomService templateBomService;

  public TemplateBomDataWiring(TemplateBomService templateBomService) {
    this.templateBomService = templateBomService;
  }

  @Override
  public void customize(RuntimeWiring.Builder builder) {
    builder.scalar(Scalars.GraphQLBigDecimal);
    builder.scalar(GraphQLDate);
    builder.type("Query", typeWiring -> typeWiring.dataFetcher("templateBom", env -> {
      final String id = env.getArgument("id");
      return templateBomService.getTemplateBom(id);
    }));
    builder.type("Mutation", typeWiring -> typeWiring.dataFetcher("create", env -> {
      final String partMasterId = env.getArgument("partMasterId");
      return templateBomService.createTemplateBom(partMasterId);
    }));
    builder.type("Mutation", typeWiring -> typeWiring.dataFetcher("createLineItem", env -> {
      final String id = env.getArgument("id");
      final TemplateLineItemInput input = env.getArgument("input");
      return templateBomService.createTemplateLineItem(id, input);
    }));
  }

But I can't get the query to parse in GraphiQL. I get no stacktrace server side, I just get this in the GraphiQL UI...
{
  "errors": [
    {
      "message": "class java.util.LinkedHashMap cannot be cast to class com.example.boa.domain.TemplateLineItemInput (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; com.example.boa.domain.TemplateLineItemInput is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @617a9621)",
      "locations": [
        {
          "line": 42,
          "column": 3
        }
      ],
      "path": [
        "createLineItem"
      ],
      "extensions": {
        "classification": "INTERNAL_ERROR"
      }
    }
  ],
  "data": {
    "createLineItem": null
  }
}

I'm working pretty much off the https://www.graphql-java.com/documentation/v16/ docs
How do I get my input type to map into the TemplateLineItemInput POJO on graphql-java:16.2?

A: You can use spring boot to automatically define your runtime wiring.
And you can write query fetchers or mutation fetchers by implementing
GraphQLQueryResolver
GraphQLMutationResolver

If you are doing the runtime wiring, the complex input parameters other than basic types will always be passed as key, value pairs in a LinkedHashmap.
So you have to convert the passed linkedHashmap into the class you expect as below.
ObjectMapper objectMapper = new ObjectMapper();
            String input = objectMapper.writeValueAsString(env.getArgument("input"));
            final String arg = env.getArgument("input");
            return templateBomService.createTemplateLineItem(id, objectMapper.readValue(arg,TemplateLineItemInput.class));


text:
Q: How to implement custom @Enable annotation? I've created annotation @EnableMyConfiguration
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MyConfiguration.class)
public @interface EnableMyConfiguration{
}

And created simple configuration
@Configuration
@Slf4j
public class MyConfiguration {
    @Bean
    public String testStringBean() {
        String s = "Hello world";
        log.info("TeST LOG = {}", s);
        return s;
    }
}

Dependencies in pom.xml for this library:

*

*org.springframework.boot:spring-boot-starter:2.3.2.RELEASE

I've tried to use this starter in my test project
This project has following dependencies:

*

*org.springframework.boot:spring-boot-starter-parent:2.3.1.RELEASE

*dependency with my library

And in Main class
@SpringBootApplication
@EnableMyConfiguration
public class MainTest{
    public static void main(String[] args) {
        SpringApplication.run(MainTest.class, args);
    }
}

But it is not worked. My bean is not created. Could you please help me? What I could lose ?

A: Make sure your library application has the spring-boot-maven-plugin enabled:
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

If you're using gradle, use the gradle equivalent.
Everything you have so far is correct on the java end.


text:
Q: Trouble in solving a question related to differentiation. The question is :

Let $g : \mathbb {R} \longrightarrow \mathbb {R}$ be a differentiable function such that $|g'(x)| \leq M$ for all $x \in \mathbb {R}$. For what values of $k$ will the function $f(x) = x + kg(x)$ be necessarily one-to-one?

Is there any possible value of $k$ other than $0$? Please let me know. Thank you in advance.

A: The above comments by Merlin and daruma are both correct. In what follows I aim to fill in all of the details so the result is 100% clear.
In order to prove that the derivative being strictly positive guarantees that the function is strictly increasing, we can use the mean value theorem. What follows mirrors Theorems 5.9-5.11 in Rudin's Principles of Mathematical Analysis with some modifications.
Let $f$ be a differentiable real function $\mathbb{R} \to \mathbb{R}$, and let $x_2 > x_1$. Put $$h(t) = [f(x_2) - f(x_1)]t - (x_2 - x_1)\cdot f(t)$$ Then $h$ is continuous on $[x_1,x_2]$ and differentiable on $(x_1,x_2)$. Moreover, $$h(x_1) = f(x_2)x_1 - f(x_1)x_2 = h(x_2)$$ If we show that $h'(x)=0$ for some $x \in (x_1, x_2)$ then it will follow that for this $x$: $$f(x_2)-f(x_1) = (x_2 - x_1) \cdot f'(x) $$ If $h$ is constant, then this holds automatically for any $x \in (x_1, x_2)$.
Thus, assume without loss of generality that $h$ is not constant. Because $h(t)$ is continuous, it attains both its minimum and maximum on $[x_1, x_2]$ (possibly at the endpoints). Because we are assuming that $h(t)$ is not constant on $[x_1, x_2]$, it follows that for some $t \in (x_1,x_2)$, we have either $h(t) > h(a)$ or $h(t) < h(a)$ (because if $h(t)=h(a)$ for all $ t \in (x_1, x_2)$, $h$ would be constant).
If $h(t) > h(a)$, then let $x$ be the point in $(x_1, x_2)$ where $h$ attains its maximum, and if $h(t) < h(a)$, let $x$ be the point in $(x_1, x_2)$ where $h$ attains its minimum. Because $h(x_1)=h(x_2)$ and $h$ is not constant, we know that in the former case that the maximum cannot occur at the endpoints of the interval, and in the latter case that the minimum cannot occur at the endpoints of the interval.
That $h'(x)=0$ in either case follows from this lemma (Theorem 5.8 in Rudin): If $h$ is defined on  $[x_1,x_2]$ and $h$ has a local maximum or minimum at $x \in (x_1, x_2)$ and $h'(x)$ exists, then $h'(x)=0$.
Proof: (of lemma) Assume $x$ is a local minimum. Choose $\delta$ such that for all $y \in (x-\delta, x+\delta) \cap [x_1,x_2]$, we have $h(x) < h(y)$. Then for all $t \in (x-\delta, x) \cap [x_1,x_2]$ we have $$\frac{h(t) - h(x)}{t-x} \le 0$$ Letting $ t \to x^-$, we get $h'(x) \le 0$. Likewise, for all $t \in (x, x+\delta) \cap [x_1, x_2]$, we have $$\frac{h(t)-h(x)}{t-x}\ge 0$$ and thus letting $t \to x^+$, we get $h'(x) \ge 0$. Therefore $h'(x)=0$.
The case for $x$ a local maximum is entirely similar; or alternatively one can just use the above proof for $-h(x)$, in which case $x$ is a local minimum. $\blacksquare$
Thus we have shown that in $(x_1, x_2)$, there must exist an $x \in (x_1, x_2)$ such that $$f(x_2) - f(x_1) = (x_2 - x_1)\cdot f'(x) $$ By the assumption that $x_2 > x_1 \implies (x_2 - x_1) >0$ and that $f'(x)$ was strictly positive, i.e. $f'(x) > 0$, it follows that $f(x_2) - f(x_1) > 0  \implies f(x_2) > f(x_1)$. Thus we have shown that, for all $x_1, x_2$ such that $x_1 < x_2$, we have $f(x_1) < f(x_2)$.
Likewise, if $f'(x) <0$, i.e. is strictly negative, then it follows immediately that $f(x_1) > f(x_2)$ for $x_1 < x_2$. (The proof is exactly analogous, or substitute $-f(x)$ into the above, since $-f'(x) >0$.)
How does the function being strictly increasing or decreasing ensure that it is $1-1$? First we show that $f$ must be surjective. Since $f$ is continuous (since it is differentiable) and defined on all of $\mathbb{R}$, by a corollary the intermediate value theorem (use the exhaustion of the real line by compact intervals), the only way that its range would not be all of $\mathbb{R}$ is if it were bounded above or below. However, this is impossible since $f$ is defined on all of $\mathbb{R}$ (which is unbounded) and is strictly increasing/decreasing. Now we show that $f$ must be injective. Let $x_1, x_2$ be such that $f(x_1)=f(x_2)$. Since $x_1 \not= x_2$ we have either $f(x_1) > f(x_2)$ or $f(x_2) < f(x_1)$ due to the fact that $f$ is strictly increasing/decreasing; since neither of these two holds, we must have $x_1 = x_2$ and thus it follows that $f$ is injective. Being both injective and surjective, it follows that $f$ is 1-1.
So a sufficient condition to ensure that $f(x)=x+kg(x)$ is 1-1 is that either $f'(x)$ remains strictly positive or that $f'(x)$ remains strictly negative.
In the first case, we want to have $f'(x) = 1 +kg'(x) >0$. As you correctly noted, $k=0$ works for this, so we can divide this into two sub-cases: $k >0$ and $k<0$. In the first sub-case, we have $1+kM >1 + kg'(x) > 1 +k(-M) > 0$. The first inequality is redundant, so it reduces to $1 + kg'(x) > 1-kM > 0$. This implies that $0< k < \frac{1}{M}$. Now for the second sub-case, $k < 0$, then we have $1 + k(-M) > 1+kg'(x) > 1 +kM > 0$. As before, the first inequality is redundant, and thus the condition reduces to $1 + kg'(x) > 1 + kM > 0$ which implies $kM > -1 $ and thus that $0>k>\frac{1}{M}$.
Thus, as you noted in the comments, for $f'(x)>0$, we have $|k|<\frac{1}{M}$.
Now for the case $f'(x) = 1 + kg'(x) <0$. Unlike last time, $k=0$ clearly does not work. Let us consider $k>0$ briefly; if this held for any such $k$, we would have: $1+k(-M) < 1 +kg'(x) < 1+kM < 0$. However, since $M>0$, there is no $k>0$ such that this holds. Therefore, we now consider the sub-case of $k<0$; we get $1+kM < 1 + kg'(x) < 1 +k(-M) <0$. However, this again is impossible, since $k(-M)>0$.
Therefore, the correct answer, as you said, is $|k|<\frac{1}{M}$.


text:
Q: Closed form of $\sum_{k=0}^p \binom{k+m-1}{m-1}?$
Question: Is there a closed form for the summation
  $$\sum_{k=0}^p \binom{k+m-1}{m-1}?$$

By writing out the summation, we have
$$\binom{m-1}{m-1} + \binom{m}{m-1} + \binom{m+1}{m-1}+...+\binom{p+m-2}{m-1}+\binom{p+m-1}{m-1}$$
$$ = 1 + m + \frac{m(m+1)}{2} + \frac{m(m+1)(m+2)}{3!}+...+\frac{m(m+1)...(m+(k-1))}{k!}+...+\frac{m(m+1)...(m+(p-1))}{p!}.$$
However, I do not see a closed form for it.

A: In the summation $$\sum_{k=0}^p \binom{k+m-1}{m-1},$$ make a change of variable by letting $i = k + m - 1$.  When $k = 0$, $i = m-1$; when $k = p$, $i = p+m-1$.  The required summation becomes $$\sum_{i=m-1}^{p+m-1} \binom{i}{m-1}.$$  Apply the Hockey-stick identity $${\sum _{i=r}^{n}{i \choose r}={n+1 \choose r+1}}$$ with $n = p+m-1$ and $r = m - 1$, so that $$\sum_{k=0}^p \binom{k+m-1}{m-1} = \sum_{i=m-1}^{p+m-1} \binom{i}{m-1} = {p+m \choose m}.$$


text:
Q: Memory leak org.jboss.vfs.spi.JavaZipFileSystem 1582384 We have a large number of objects created for org.jboss.vfs.spi.JavaZipFileSystem ,
We are using 6.4.0.GA with jre 1.7.0_40-b43 and Windows Server 2008 R2
Below is screenshot from yourkit :
huge number of objects


text:
Q: How do I clear up this ambiguous call to Arrays.copyof()? I'm running AIDE on my Android phone, and am having trouble compiling the following bit of Java code:
elements = Arrays.copyOf(elements, elements.length * 2);
Here elements is of type int[]. The error I'm getting from AIDE is
Several methods are applicable to (int[], int): 'java.util.Arrays.copyOf(int[], int)' and 'java.util.Arrays.copyOf<T>(T[], int)'
I would've expected the compiler to pick the former option, but it doesn't. How can I resolve this?

A: This is a compiler/IDE problem. However, Arrays.copyOf is a quite trivial function, so simply write your own version of it if the problem can't be fixed with IDE/compiler updates. Another way would be to use reflection to call it. But it comes with some runtime overhead and  also makes the code look awkward, so I suggest implementing your own version.
Here is the code:
public static int[] copyOf(int[] original, int newLength) {
    int[] copy = new int[newLength];
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

Of course, if you then get the same problem for System.arraycopy, then this does not work. Simply try it. If it does not work, you can place it in a helper class and use a non-buggy compiler to compile this helper class.


text:
Q: Can I prevent Outlook from stripping webkit-text-size-adjust in HTML signatures? I've got an HTML email signature that's working really well in all email clients, unless it's being sent from Outlook.
The main problem is that it's stripping out the webkit-text-size-adjust css so that emails received by iOS devices have huge malformed text.
How can I prevent Outlook from stripping this from the inline styles? Or is there a way to create styles that get ignored by not stripped by Outlook?


text:
Q: image control don't change the source when binding changed I use event in my code to notify if image was scanned
in my ViewModel :
public BitmapImage ImageSelected
{
   get{return _imageSelected;}
   set
   {
        if (_imageSelected == value)
        {
            return;
        }
        _imageSelected = value;
        RaisePropertyChanged(() => ImageSelected);
   }
}

public ICommand CmdScan
{
   get
   {
       return new DelegateCommand(Scan);
   }
}
WpfTwain twainInterface = null;
private BitmapImage _imageSelected = null;

private void Scan()
{

    twainInterface = new WpfTwain();
    twainInterface.TwainTransfer += new TwainTransferReadyHandler(TwainWin_TwainTransfer);
    twainInterface.Acquire(true);
}

private void TwainWin_TwainTransfer(BitmapImage imageSources)
{
    ImageSelected = imageSources;
}

in My XAML
<Image Margin="151,12,356,12" Stretch="Fill" Source="{Binding ImageSelected}" />

when scanning multiple images the image in windows don't change until all scan complete, even I make a break point in TwainWin_TwainTransfer and it been called in evry image scanned and the RaisePropertyChanged also, and when scan is completed it show only the last image
any suggestions are welcome, I'm new in MVVM
Update
the code for scan in class TwainLib (called by twainInterface.Acquire(true); )
do
{
   pxfr.Count = 0;
   hbitmap = IntPtr.Zero;

   TwImageInfo  iinf = new TwImageInfo();
   rc = DSiinf( appid, srcds, TwDG.Image, TwDAT.ImageInfo, TwMSG.Get, iinf );
   if( rc != TwRC.Success )
   {
      CloseSrc();
      return pics;
   }

   rc = DSixfer( appid, srcds, TwDG.Image, TwDAT.ImageNativeXfer, TwMSG.Get, ref hbitmap );
   if( rc != TwRC.XferDone )
   {
      CloseSrc();
      return pics;
   }

   rc = DSpxfer( appid, srcds, TwDG.Control, TwDAT.PendingXfers, TwMSG.EndXfer, pxfr );
   if( rc != TwRC.Success )
   {
      CloseSrc();
      return pics;
   }
   pics.Add(hbitmap);
   BitmapImage bitmapImage = /*converting hbitmap to BitmapImage  */
   TwainTransferReady(bitmapImage);
}
while( pxfr.Count != 0 );

and I also try get the  twainInterface.Acquire(true); in a task but same result,

A: I replaced
private void TwainWin_TwainTransfer(BitmapImage imageSources)
{
ImageSelected = imageSources;
}

with
App.Current.MainWindow.Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() => ImageSelected = imageSources));


text:
Q: transformation from xml document to relational model with t-sql I need to insert into table data from xml docs (in relational model) that i have in other table. I'm using sql server 2005.
example of structure of xml:
<order id="123">
<products>
    <product prodId="2120">
        <name>Product1</name>
        <quantity>2</quantity>
    </product>
    <product prodId="1200">
        <name>Product2</name>
        <quantity>4</quantity>
    </product>
    <product prodId="945">
        <name>Product3</name>
        <quantity>1</quantity>
    </product>
</products>
</order>

... and result table:
OrderID  ProductID  Name      Quantity
123      2120       Product1  2
123      1200       Product2  4
123      945        Product3  1

I solve this problem with openxml tool but it's bit slow.
How can i do this in XQuery?
What is the best metod to solve tasks like this?

A: DECLARE @xml_str XML =
   '<order id="123"> <products>
    <product prodId="2120">
        <name>Product1</name>
        <quantity>2</quantity>
    </product>
    <product prodId="1200">
        <name>Product2</name>
        <quantity>4</quantity>
    </product>
    <product prodId="945">
        <name>Product3</name>
        <quantity>1</quantity>
    </product> </products> </order>'

SELECT
    c.value('(../../@id)', 'int') AS OrderID,
    c.value('(@prodId)[1]', 'int') AS ProductID,
    c.value('(./name)[1]', 'varchar(20)') AS Name,
    c.value('(./quantity)[1]', 'int') AS Quantity
FROM @xml_str.nodes ('(/order/products/product)') AS t(c)
GO

OrderID     ProductID   Name                 Quantity
----------- ----------- -------------------- -----------
123         2120        Product1             2
123         1200        Product2             4
123         945         Product3             1

(3 row(s) affected)


text:
Q: Read strongly typed yaml file in Typescript? I have the following yaml file:
trainingPhrases:
- help me
- what to do
- how to play
- help

I readi it from disk using readFile from node and parse it using load from js-yaml:
import { load } from "js-yaml";
import { readFile } from "fs/promises";

const phrases = load(await readFile(filepath, "utf8")).trainingPhrases as string[];

I get the following eslint warning:
ESLint: Unsafe member access .trainingPhrases on an any value.(@typescript-eslint/no-unsafe-member-access)

Instead of suppressing the warning, I would like to map it into a concrete type for the YAML file (as it happens in axios for example: axios.get<MyResponseInterface>(...) - performs a GET and MyResponseInterface defines the structure of the HTTP response).
Is there a dedicated library for that?

A: From what I can see when using @types/js-yaml is that load is not generic, meaning it does not accept a type parameter.
So the only way to get a type here is to use an assertion, for example:
const yaml = load(await readFile(filepath, "utf8")) as YourType;
const phrases = yaml.trainingPhrases;

Or in short:
const phrases = (load(await readFile(filepath, "utf8")) as YourType).trainingPhrases;

If you absolutely want a generic function, you can easily wrap the original, like:
import {load as original} from 'js-yaml';

export const load = <T = ReturnType<typeof original>>(...args: Parameters<typeof original>): T => load(...args);

And then you can use it as:
const phrases = load<YourType>('....').trainingPhrases;


text:
Q: Android progressbar setprogress() function doesn't work I would setting progress of the progressbar in Android. But setprogress function doesn't work.
Codes XML:
<ProgressBar
        android:id="@+id/hamlebar"
        android:layout_width="140dp"
        android:layout_height="25dp"
        android:progressDrawable="@drawable/progressbarr"
        android:layout_centerHorizontal="true"
        style="@style/Widget.AppCompat.ProgressBar.Horizontal"
        android:layout_below="@+id/oyunhamletv"
        android:layout_marginTop="25dp"
/>

<TextView
        android:id="@+id/bartext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hamle"
        android:textStyle="bold"
        android:layout_alignStart="@+id/hamlebar"
        android:layout_alignEnd="@+id/hamlebar"
        android:layout_alignTop="@+id/hamlebar"
        android:layout_alignBottom="@+id/hamlebar"

/>

Progress drawable codes (progressbarr.xml) :
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@android:id/background">
    <shape>
        <gradient
                android:startColor="#ffffff"
                android:centerColor="#ffffff"
                android:centerY="0.75"
                android:endColor="#ffffff"
                android:angle="270"
        />
    </shape>
</item>

<item android:id="@android:id/secondaryProgress">
    <clip>
        <shape>
            <gradient
                    android:startColor="#234"
                    android:centerColor="#234"
                    android:centerY="0.75"
                    android:endColor="#a24"
                    android:angle="270"
            />
        </shape>
    </clip>
</item>

<item android:id="@android:id/progress">
    <clip>
        <shape>
            <gradient
                    android:startColor="#144281"
                    android:centerColor="#0b1f3c"
                    android:centerY="0.75"
                    android:endColor="#f6101d"
                    android:angle="270"
            />
        </shape>
    </clip>
</item>

</layer-list>

Set progress codes (Java codes) :
hamlebar.setMax(oyunhamle);
oyunhamle = oyunhamle - 1;
hamlebar.setProgress(0);
hamlebar.setProgress(oyunhamle);

Note : I don't had a good English. I hope you can understand. Pardon me.
How I can resolve this problem?

A: I have checked your code its working fine at my end -
I think you might have initialize oyunhamle = 0;(WRONG)
you just need to initialize - oyunhamle = 100; and then set max value of progressbar like - hamlebar.setMax(oyunhamle);
what you are doing wrong is you are substracting only 1 from the max value 100 so its not clearly visible oyunhamle = oyunhamle - 1;(WRONG)
try oyunhamle = oyunhamle - 50; and then set hamlebar.setProgress(oyunhamle);
it should work;


text:
Q: Parse a JSON (array with tabs and arrays) with PHP I have been trying to parse a JSON response since few days without success.
    I've read on the internet and this site how to parse with a foreach but I think            the structure of json is too different from the examples I've found.
    So here is the JSON:
 array(1)

        { ["matches"]=> array(10)
            { [0]=> array(13) { ["matchId"]=> int(2125878813)
                                ["region"]=> string(3) "EUW"
                                ["platformId"]=> string(4) "EUW1"
                                ["matchMode"]=> string(7) "CLASSIC"
                                ["matchType"]=> string(12) "MATCHED_GAME"
                                ["matchCreation"]=> float(1432656547642)
                                ["matchDuration"]=> int(1852)
                                ["queueType"]=> string(15) "RANKED_SOLO_5x5"
                                ["mapId"]=> int(11)
                                ["season"]=> string(10) "SEASON2015"
                                ["matchVersion"]=> string(9) "5.9.0.318"
                                ["participants"]=> array(1)
                                    { [0]=> array(10) {
                                    ["teamId"]=> int(200)
                                    ["spell1Id"]=> int(7)
                                    ["spell2Id"]=> int(4)
                                    ["championId"]=> int(67)
                                    ["highestAchievedSeasonTier"]=> string(8) "PLATINUM"
                                    ["timeline"]=> array(9)
                                        { ["creepsPerMinDeltas"]=> array(3)
                                            { ["zeroToTen"]=> float(6.2)
                                              ["tenToTwenty"]=> float(7.4)
                                              ["twentyToThirty"]=> float(4.4) }
                                              ["xpPerMinDeltas"]=> array(3)
                                                { ["zeroToTen"]=> float(336.2)
                                                  ["tenToTwenty"]=> float(428.3)
                                                  ["twentyToThirty"]=> float(396) }
                                                    ["goldPerMinDeltas"]=> array(3) {
                                                    ["zeroToTen"]=> float(270.7)
                                                    ["tenToTwenty"]=> float(363.6)
                                                    ["twentyToThirty"]=> float(294.8) }

If I understand well this is an array with tabs inside and arrays also ?

I would like for example to display the 10 matches id :
  matches->matchId
      matches->participants->championId
      matches->participants->timeline->creepsPerMinDeltas->zeroToTen

Here is what I've done so far to display the matchId :
 $decodeHisto = json_decode ($resultHisto,true);

    //var_dump($decodeHisto);
    foreach ($decodeHisto{[matches]} as $d)
    {

    echo $d->{[matchId]}-;

    }

Can anyone help me please ?

A: Your code is not JSON, as JSON is exactly defined like this:
{
"Herausgeber": "Xema",
  "Nummer": "1234-5678-9012-3456",
  "Deckung": 2e+6,
  "Waehrung": "EURO",
  "Inhaber": {
    "Name": "Mustermann",
    "Vorname": "Max",
    "maennlich": true,
    "Hobbys": [ "Reiten", "Golfen", "Lesen" ],
    "Alter": 42,
    "Kinder": [],
    "Partner": null
  }
}

You can convert a JSON array to PHP with this code:
$array = json_decode($json);

But as I said before, your code is not JSON. It seems to be even a PHP array. Then you can access with:
$arr["matches"][0]["matchId"]

for example.

A: Given the additional information you provided by posting an own "answer" to your question here I would like to point out this:
So if what you posted in your question is a dump of the result you got back from a call to json_decode(), then what you have simply is an array. An associative, multi level array, but still just a normal php array. This is also what the documentation of the json_decode() function clearly states: http://php.net/manual/en/function.json-decode.php
There is absolutely no reason to somehow "parse" an array. The "tabs" or whitespaces you can see in the dump are not part of the result you have, so of the array. Those are artefacts by the dumoing function you use to visualize the array. You can simply access all members (or members of members...) of the array sirectly by their associative "path", as you will see in all examples of php code you can find on google. Here an example:
$value = $decodedJson['matches'][0]['matchDuration'];

Given $decodedJson is the result array as posted in your question, then $value will now hold the integer value 1852.
You can access whatever part or element of the array you like. you can iterate over parts of the array using php's iteration constructs like foreach and the like. You can search in the array by means of php's array functions(http://php.net/manual/en/ref.array.php).


text:
Q: Changing spacing for \thanks generates empty line In a double-spaced article, I'm trying to keep the \thanks note single-spaced. I use this topic to change the spacing of \thanks back to single-spacing. This works, but it also generates an empty line at the start of the note. How do I get the text to start on the same line as the * symbol?
\documentclass{article}
\usepackage[doublespacing]{setspace}
\usepackage{lipsum}

\begin{document}

\title{\vspace{-4cm}Title goes here}
\author{Author Goes Here\thanks{\protect\singlespacing\protect\lipsum[1]}}
\date{\today}

\maketitle

\begin{abstract}
\noindent \lipsum[2]
\end{abstract}

\section{First section}
\lipsum[5]

\end{document}

A: My initial MWE was too minimal. The problem turns out to be the order of loading packages. Specifically, loading \usepackage{setspace} after \usepackage{hyperref} creates a double-spaced thanks-note. Trying to correct that by adding \protect\singlespacing to the thanks-note generates the white line in the thanks-note.
Loading \usepackage{setspace} before \usepackage{hyperref} keeps the thanks-note single-spaced.
Alternatively, Egreg's solution to add \protect\linespread{1}\protect\selectfont to the thanks-note works regardless of the order of loading packages.
For completeness, the full preamble of the actual document is as follows.
\documentclass[letterpaper,12pt]{article}

\usepackage{amsfonts, amsmath, amssymb}
\usepackage{url}
\usepackage[left=1in,top=1.5in,bottom=1.5in,right=1in,nohead]{geometry}
\usepackage[disable,section]{easy-todo}
\usepackage[longnamesfirst]{natbib}

%% Swap the next two packages to correct the double-spaced thanks-note
\usepackage{hyperref}
\usepackage[doublespacing]{setspace}

\usepackage[font=normalsize]{subfig}
\usepackage{graphicx}
\usepackage{multirow}
\usepackage{booktabs}
\usepackage{dcolumn}

\usepackage{pdflscape}
\usepackage{textcomp}
\usepackage{xcolor}
\hypersetup{
    colorlinks,
    linkcolor={red!50!black},
    citecolor={blue!50!black},
    urlcolor={blue!80!black}
}
\usepackage{color}
\usepackage{changepage}
\usepackage{rotating}
\usepackage{array}
\usepackage{xtab}
\usepackage{etoolbox}

\AtBeginEnvironment{xtabular}{\singlespacing}
\AtBeginEnvironment{abstract}{\onehalfspacing}

\usepackage{lipsum}

\begin{document}

\title{\vspace{-4cm}\textsc{Title goes here}}

\author{Author \textsc{Goes Here}\thanks{\protect\lipsum[1]}}

\date{\vspace{1.5em}\today}
\maketitle

 \begin{abstract}
 \noindent \lipsum[2]
 \end{abstract}

\clearpage
\section{First section}
\noindent \lipsum[5]

\end{document}


text:
Q: Using HttpClient to get data from a json file in typescript I am building an angular application.
I am trying to fetch some image files' locations in the asset directory through a json file. In the json file the locations of the images are mentioned. But after running the application I am getting error 404 and and says it can't locate my json file.
The browser displays this error message.
Object { headers: {…}, status: 404, statusText: "Not Found", url: "http://localhost:4200/landingPageData.json", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost:4200/landingPageData.json: 404 Not Found"

My specifications :
Angular CLI: 15.0.5
Node: 18.10.0
Package Manager: npm 8.19.2
Node : v18.10.0
OS: linux x64
I have a json file 'landingPageData.json' in the /src directory of my angular application. The data looks like this in the file.
{
    "photos":[
        {
            "img": "assets/images/landing1.jpg",
            "description": "Learn 100 english words effectively in 1 day!"
        },
        {
            "img": "assets/images/landing2.jpg",
            "description": "What you will learn"
        },
        {
            "img": "assets/images/landing3.jpg",
            "description": "Join today!"
        }

    ]
}

In my app.component.ts file, I am trying to fetch only the image files' location from the json data and store those into an Array landingScreens.
import { Component, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http'
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
@Injectable()
export class AppComponent {
  public landingScreens: any;
  constructor(private http:HttpClient){
    this.http.get('./landingPageData.json').subscribe((response) => {
      this.landingScreens = response;
    })
  }
}

And then in the template app.component.html file I am displaying those images given I have the locations of those images.
//
//

<mat-tab-group>
    <mat-tab label="About"></mat-tab>
        <mat-card *ngFor="let img of landingScreens; let i=index">
            <img mat-card-image src="{{img.img}}">
        </mat-card>
    <mat-tab label="Courses"></mat-tab>
    <mat-tab label="Contact"></mat-tab>
</mat-tab-group>

//
//

I am trying not to import the json data cause in the future I will use an api to fetch the response which will be in json format. Am I messing up the subscribe part ? or giving the right directory location?
The landingPageData.json file is in /src folder and the app.component.ts file is in */src/app *folder. And the images are in assets/images folder.
I have gone through all the relevant answers from stackoverflow but majority of them are very old angular versions or the answers told them to import the json file.

A: I did not put the <mat-card> tag within the <mat-tab> first. So after I did that I put the landingPageData.json file inside the assets folder.
This link helped which was suggested by @JanatbekOrozaly

app.component.ts
export class AppComponent{
  landingScreens: any = [];
  constructor(private httpClient:HttpClient){
    this.httpClient.get("assets/landingPageData.json").subscribe(data => {
      this.landingScreens = data;
    })
  }
}

app.component.html
<mat-tab-group>
    <mat-tab label="About">
      <mat-card *ngFor="let img of landingScreens; let i=index">
        <img mat-card-image src="{{img.img}}">
    </mat-card>
    </mat-tab>
    <mat-tab label="Courses"></mat-tab>
    <mat-tab label="Contact"></mat-tab>
</mat-tab-group>


text: Q: "Anomalous" Interference Maxima from a Diffraction Grating When shining a red diode laser ($\lambda = 635$ nm) laser through a diffraction grating (5276 lines/cm), I'm observing what I consider to be anomalous maxima near each of the expected maxima for the laser/diffraction grating combination. (See the pictures below.) I used this grating in an introductory physics lab on double slit interference and diffraction gratings. I was unable to explain the anomalous maxima, and simply told my students to ignore them for the purposes of the lab (and they got good results (i.e. the spacing of the maxima, along with the known wavelength of the laser, allowed them to determine the lines/cm of the grating to a reasonable accuracy) by doing this). But, I'm hoping that someone here might be able to explain where these spots are coming from, or at least hypothesize why they're showing up. The grating is fairly old (I'm guessing 20 or so years), and it could probably use some cleaning, but I also observed this effect with a newer grating, which appears to be clean, at least to my eyes. Any ideas what is likely to be causing this?


text:
Q: Im trying to have multiple lines of imput, and store the strings, integers into three seperate variables So, I'm trying to store multiple lines of code and add each input up under its certain array. So basically, a person enters the name of the game, this gets stored into an array called 'game', then they enter on that same line the score they have achieved and that's should be stored into aray 'score' and the same for the minutes played. You get my drift.
the input should be as followed...
<name of player>
<game name> : <score> : <min played>

The data should be split at the delimiter ":"....
However, my problem is that my code does not add each part of the user input and only stores the first line and does not go onto the next line. The code I have is beneath. I would highly appreciate any advice I can get. Thank you.
import java.util.Scanner;

public class Report {
    public static void main(String[] args) {
        String name;
        String gameName;
        int gameScore;
        int minPlayed;
        String[] game = new String[100];
        int[] score = new int[100];
        int[] min = new int[100];

        String[] name1 = new String[100];
        int nextLine = 0;

        System.out.println("Can you enter your name, game, achievement score, and time played in the following format as shown below:");
        System.out.println("<NAME>");
        System.out.println("<GAME> : <SCORE> : <TIMEPLAYED>");
        System.out.println("Once you have finished your input please notify the program you have finished with the command 'quit':");

        for (int index = 0; index < 100; index++) {
            Scanner keyboard = new Scanner(System.in); // initialise Scanner
            name = keyboard.nextLine(); // assign next line of input to name

           if (name.compareToIgnoreCase("quit") == 0) {
              break;
            }
            name1[index] = name;
            nextLine = nextLine + 1;

            String input = keyboard.nextLine(); // next line of input
            String[] variables = input.split(":"); // perform split
            if (variables.length != 3) {
                // handle invalid input here
            }
            game[index] = variables[0].trim(); // first token trimmed of whitespaces
            try {
                score[index] = Integer.parseInt(variables[1].trim()); // parse second token as int
                min[index] = Integer.parseInt(variables[2].trim()); // parse third token as int
            } catch (NumberFormatException e) {
                // handle invalid input here
            }
        }

        for (int index = 0; index < nextLine; index++) {

            System.out.println("Players name: " + name1[index]);
            System.out.println("-------------------------------");
            System.out.println("Total games: " + game[index]);
            System.out.println("Overall score: " + score[index]);
            System.out.println("Total minutes played: " + min[index]);

            System.out.println(game[index]);
        }
    }
}

This is what my typical ouptput should look like...
PLayers Name: ......
Number of games: 12
Total Score: 467
Total minutes played: 1045

This is what it actually looks like....
PLayers Name: Matty
Number of games: GTA IV
Total Score: 12
Total minutes played: 124

As you can see it basically only splits the first line and puts it into these headings when I want it to add each part up and put them like in the the actuall output I want. It only splits the first games data and does not add it up with the other lines beneath it.
Here it is my pseudo code....
get name of player and store in a variable
loop for 100
    get input
    if it is "quit" then break
    split up input
    if I don't get 3 things then it is invalid
    else if I do get 3 things
        store the first one in an array for game names
        store the second one in an array for scores
        store the third one in an array for times
        if I can't convert scores &/or times - it is invalid
end loop

output player's name
output a line of "------------------------"
loop for how many valid games we have
    output a line containing gamename, score, minutes played
end loop

Then add all the games up and change into a int for the final output as shown above, then do the same with all the scores and minutes and print out as shown above...

A: I don't know if i understand properly, but do you whant something like this?
import java.util.Scanner;

public class Report
{
    public static void main(String[] args)
    {
        String name;

        String[] game = new String[100];
        int[] score = new int[100];
        int[] min = new int[100];

        int nextLine = 0;

        System.out.println("Can you enter your name, game, achievement score, and time played in the following format as shown below:");
        System.out.println("<NAME>");
        System.out.println("<GAME> : <SCORE> : <TIMEPLAYED>");
        System.out.println("Once you have finished your input please notify the program you have finished with the command 'quit':");

        Scanner keyboard = new Scanner(System.in); // initialise Scanner
        name = keyboard.nextLine(); // assign next line of input to name

        for (int index = 0; index < 100; index++)
        {
            String input = keyboard.nextLine(); // next line of input

            if (input.compareToIgnoreCase("quit") == 0)
            {
                break;
            }
            nextLine = nextLine + 1;

            String[] variables = input.split(":"); // perform split
            if (variables.length != 3)
            {
                // handle invalid input here
            }
            game[index] = variables[0].trim(); // first token trimmed of whitespaces
            try
            {
                score[index] = Integer.parseInt(variables[1].trim()); // parse second token as int
                min[index] = Integer.parseInt(variables[2].trim()); // parse third token as int
            }
            catch (NumberFormatException e)
            {
                // handle invalid input here
            }
        }

        for (int index = 0; index < nextLine; index++)
        {

            System.out.println("Players name: " + name);
            System.out.println("-------------------------------");
            System.out.println("Total games: " + game[index]);
            System.out.println("Overall score: " + score[index]);
            System.out.println("Total minutes played: " + min[index]);

            System.out.println(game[index]);
        }
    }
}


text:
Q: NSOrderedSet vs NSArray indexOfObjectPassingTest: The NSOrderedSet Class Reference Overview says:

You can use ordered sets as an alternative to arrays when the order of elements is important and performance in testing whether an object is contained in the set is a consideration— testing for membership of an array is slower than testing for membership of a set.

Which methods are considered "testing for membership"? Just containsObject:? Or, will indexOfObjectPassingTest: also be faster?
I'm asking because if I just have the object's ID (from the server for example) and want to check if the ordered set contains an object with that ID, I'd use indexOfObjectPassingTest:. But, that method, since it tests every object in the collection, seems that it'd be just as slow as it is for an array. On the other hand, containsObject: seems that it'd be faster since it takes advantage of the NSObject methods hash & isEqual:. I could just create a probe object with the ID I have, and then use containsObject:. But then, if the ordered set already contains an object with that ID, I'll just discard of the probe object and update the properties on the object already in the ordered set. It seems like extra work to have to create a probe object first. In that case, is it even worth using an ordered set over an array?
Also, I would be sorting objects by their date, not their ID.
I'd use an NSMutableDictionary with object IDs mapping to objects, as St3fan suggested, but I also want to display the objects in a UITableView.

A: You can override -isEqual: and -hash in you class. If you do, it'll work with NSOrderedSet's fast lookup. It can be as simple as:
- (BOOL)isEqual:(id)otherObject
{
    return self.myID == otherObject.myID;
}

- (NSUInteger)hash
{
    return self.myID;
}

Here's a full example:
#import <XCTest/XCTest.h>

@interface MyClass : NSObject
@property (nonatomic) NSInteger myID;
@property (nonatomic, strong) NSDate *date;
@end

@implementation MyClass

- (BOOL)isEqual:(MyClass*)otherObject
{
    return self.myID == otherObject.myID;
}

- (NSUInteger)hash
{
    return self.myID;
}

@end

@interface MyTests : XCTestCase

@end

@implementation MyTests

- (void)testExample
{
    MyClass *obj1 = [[MyClass alloc] init];
    obj1.myID = 1;
    obj1.date = [NSDate dateWithTimeIntervalSince1970:20000];

    MyClass *obj2 = [[MyClass alloc] init];
    obj2.myID = 2;
    obj2.date = [NSDate dateWithTimeIntervalSince1970:10000];

    MyClass *obj3 = [[MyClass alloc] init];
    obj3.myID = 1;
    obj3.date = [NSDate dateWithTimeIntervalSince1970:30000];

    MyClass *obj4 = [[MyClass alloc] init];
    obj4.myID = 3;
    obj4.date = [NSDate dateWithTimeIntervalSince1970:30000];

    NSOrderedSet *set = [[NSOrderedSet alloc] initWithArray:@[obj1, obj2]];
    XCTAssertEqualObjects(((MyClass *)[set firstObject]).date, obj1.date);
    XCTAssertEqualObjects(((MyClass *)[set lastObject]).date, obj2.date);
    XCTAssertTrue([set containsObject:obj1]);
    XCTAssertTrue([set containsObject:obj3]);
    XCTAssertFalse([set containsObject:obj4]);
}

@end

A: The best way to test this is by writing some small benchmarks. I don't know how many objects you are dealing with but if it is less then a few hundred then you probably won't notice much difference between containsObject:, indexOfObjectPassingText: or even just iterating over all objects manually.
It sounds like an NSMutableDictionary is more appropriate for your use case actually. Why don't you store your objects in a dictionary that is indexed by your object's ID? Then you can really quickly find them by ID and you can also iterate easily over them if needed.


text:
Q: Sign Powershell Script with Cert from easy-rsa I apologize if this has been answered elsewhere, but I couldn't find anything that quite fit what I'm trying to do here.
I have a CA set up already on a Linux server, and I use it for creating OpenVPN certs. I want to utilize this existing infrastructure if I can.
What I intend to do, is create the signing certificate on my Linux server using easy-rsa, import that into a Server 2012 R2 environment, and sign it from there. After that, I'd import the necessary certs on the servers I'm deploying my scripts to.
Is this possible? Are there limits to the key size? What algorithms can I use? Is EC supported? If so, which curves?
All the literature I've come across talks about creating the CA on a Windows Server, so I'm at a bit of a loss here.

A: It took 3 years and I asked the same question, and the answer is - Yes!
Requirements: easy-rsa, openssl
Step 1: Generate RSA private key.
openssl genrsa -out MySPC.key
Step 2: Make certificate request.
openssl req -new -key MySPC.key -out MySPC.req
Step 3: Import certificate request to easyrsa.
easyrsa import-req MySPC.req MySPC
Step 4: Sign certificate request, and make SPC certificate.
easyrsa sign-req code-signing MySPC
Step 5: Make PFX.
openssl pkcs12 -export -out MySPC.pfx -inkey MySPC.key -in MySPC.crt -certfile MyCA.crt
Last step: Import PFX file to Windows Keystore.
Import PFX file to Trusted Publishers Certificate Store.
Now you can use this certificate to sign your powershell scripts and other executables!


text:
Q: is it possible to have multiple country shapes(from default) in shape map visual? Currently,i am using shape map visual to represent country & respective states, but for three countries i have to use three visuals. i have tried using add map option but it requires to select shape(map) from system. is there a way to have multiple countries in one visual from existing map options?

A: For the shape map visual, you import your on file in the topoJSON format, you can't at this time add more that one file to the visual.
However you can get individual topoJSON files for the countries and then merge them together into one file, that then can be displayed in one visual. There is a SO question and answer that outlines how to do this
Hope that helps


text:
Q: Getting number of elements in array not working as expected Here I am implementing a simple sort (insertion), but I'm not getting the correct size of the array. Namely, my length variable is getting set equal to 1. Also, what ways could I optimize my code for this insertion sort algorithm? Thanks
void insertionSort(int a[])
{
    int sorted = 1;
    int length = sizeof(a) / sizeof(int);
    int i = 0;
    int tmp;

    printf("%d   ", length);

    if (length < 2)
        return;

    for (i = 1; i < length - 1; i++)
    {
        sorted = i;
        while (a[sorted] < a[sorted - 1] && sorted > 0)
        {
            tmp = a[sorted];
            a[sorted] = a[sorted - 1];
            a[sorted - 1] = tmp;
            sorted--;
        }
    }
}

A: int length = sizeof(a) / sizeof(int);

This returns the size of a pointer a,  divided by the size of an int.  Always equal to one.
You will have to pass length to the function, void insertionSort(int a[], size_t length){
The function that creates the array has to keep track of the number of elements that are active in the array in order to do this.

A: C arrays doesn't really exists. This essentially means that you don't have good abstract support for arrays in C. As an example of this, if I give you (you are the function insertionSort)  an array (say a) you won't be able to determine it size! Arrays have no size in C.
So what is sizeof(a)? First a is not an array but a constant pointer to the memory address of the first element; that's all. Then sizeof(a) just gives you the size of the pointer a.
If you want to manage arrays in C, you must use a variable to store its length. This is why most of functions that deals with arrays have additional parameters length.


text:
Q: running same script over many machines I have setup a few EC2 instances, which all have a script in the home directory. I would like to run the script simultaneously across each EC2 instance, i.e. without going through a loop.
I have seen csshX for OSX for terminal interactive useage...but was wondering what the commandline code is to execute commands like
ssh user@ip.address . test.sh

to run the test.sh script across all instances since...
csshX user@ip.address.1 user@ip.address.2 user@ip.address.3 . test.sh

does not work...
I would like to do this over the commandline as I would like to automate this process by adding it into a shell script.
and for bonus points...if there is a way to send a message back to the machine sending the command that it has completed running the script that would be fantastic.

A: will it be good enough to have a master shell script that runs all these things in the background?  e.g.,
#!/bin/sh
pidlist="ignorethis"
for ip in ip1 ip2
do
    ssh user@$ip . test.sh &
    pidlist="$pidlist $!" # get the process number of the last forked process
done

# Now all processes are running on the remote machines, and we want to know
# when they are done.

# (EDIT) It's probably better to use the 'wait' shell built-in; that's
# precisely what it seems to be for.
while true
do
    sleep 1
    alldead=true
    for pid in $pidlist
    do
        if kill -0 $pid > /dev/null 2>&1
        then
            alldead=false
            echo some processes alive
            break
        fi
    done
    if $alldead
    then
        break
    fi
done

echo all done.
it will not be exactly simultaneous, but it should kick off the remote scripts in parallel.


text:
Q: Screen doesn't work properly - iPhone SE I have an iPhone SE in almost perfect conditions (I never dropped it). I bought it 9 months ago, but since 3 weeks (and maybe more) the touch screen don't always works, I mean that when I touch, sometimes it doesn't understand that I'm touching, and that's very very annoying. The problem happened at least 1 time per hours and I already tried to clean the screen and restart my iPhone, do you have any ideas?

A: If you have a screen protector or case on your phone, try removing them as that may be your issue.
Otherwise, it's most likely a hardware issue. Head to getsupport.apple.com to get help from Apple or visit a nearby Apple store.


text:
Q: Setting text color of a TD in xsl I need to display some columns in different color, i have a .xsl file that contains definition of my table. In the below code i am setting the color of the columns to red, the 'Name' column displays in red, but the 'Date' column does not display in red. If I remove the dataType="date" from the Date td, the Date column also starts displaying in red, i am using the dataType="date" only for formatting the date value from my java-script code.  Is there anything extra i have to add to change the color in this place.

    <xsl:value-of select="Date"/>

    <xsl:value-of select="Name"/>

The java-script code is as below, this will just format the date to dd/mm/yyyy format.
function formatTable(table)

{
  var formatedDate;
  var colTDs = table.all.tags("TD");
  for (var i = 0; i < colTDs.length; i++)
  {
      var td = colTDs[i];
var sDataType = td.getAttribute("dataType");
if (sDataType == null)
  continue;
td.dataType = sDataType;
formatedDate = applyFormatDate(td.innerText); //This will just format the date to dd/mm/yyyy
td.innerText = formatedDate;

}
}

A: Try:

    <xsl:value-of select="Date"/>

Your CSS properties should be assigned like this:
Properties:value;

not like this:
Properties=value;

EDIT :
dataType=""

is not a valide HTML5 attribute and should be :
data-Type=""


text:
Q: Maven alternate pom Is there an argument when calling a maven build to specify an alternate file in place of the standard pom.xml file name?
Basically, I have a need to run the test goal of my maven build with a variety of configurations.  Right now I am having to use an external script to update the standard pom with this configurations, then revert the file after.  I would much rather just be able to maintain several seperate configuration files and call maven with the specific one I need.
What I am wondering is if there is some way to override the pom.xml such as
mvn clean test   (uses standard pom.xml)
mvn clean test -Dmaven.source=alternate.xml
mvn clean test -Dmaven.source=alternate2.xml

Is this possible?

A: I will leave the accepted answer as just that, since it is the proper solution to running with an alternate pom file.  However, for the use case I described above, I now feel the correct methodology would be to use maven profiles within the pom file.
Maven Profiles Introduction
With profiles, all versions of the test configurations can be contained within the master pom file and then executed as follows:
mvn clean test -PstandardConfig
mvn clean test -PalternateConfig
mvn clean test -PanotherConfig

A: use the -f option:
mvn -f <other pom file>

A: I found this very interesting solution when I got the final answer. I follow the following approach:-

mvn -f yourPomfil.xml goal

where the goal can be clean, verify, package, install, deploy and other maven goals


text:
Q: fatal error LNK1104: cannot open file 'opencv_calib3d220d.obj' I am very new to C++ programming and I am compiling a code in visual studio 2010 with opencv 2.2 library on a Windows 7-64 bit OS using a precompiled header. I listed all the library files available in C:\OpenCV2.2\lib in the Project properties>configuration properties>linker>input, but when I run the program it continues to show this error:
fatal error LNK1104: cannot open file 'opencv_calib3d220d.obj',
although I defined 'C:\OpenCV2.2\lib\opencv_calib3d220d' as an input.
I do not know how to resolve the problem.
Any help would be highly appreciated.

A: Did you actually define "C:\OpenCV2.2\lib\opencv_calib3d220d" as the input, or "C:\OpenCV2.2\lib\opencv_calib3d220d .lib"? (No space, can't bold/italics it without the space is why it's there.)
It needs to have that .lib there or it won't work. Even if it's complaining about a .obj
Also: Under Linker-> General -> Additional Library Directories you can put "C:\OpenCV2.2\lib\" and then you won't have to type out the directory each time you add something from that directory to Linker -> Input -> Additional Dependancies : You could just put "opencv_calib3d220d.lib", for example.

A: obj ? no. lib, yes
so, please make sure, you got 'C:\OpenCV2.2\lib\opencv_calib3d220d.lib' etc in your linker input.
also make sure you do the same WITHOUT the 'd' at the end for release
btw, might be a good idea to update to 2.4.6, heap of bug fixes, proper gpu support , facerecognition, do you really want to live without ?


text:
Q: Angular 4 - ngModelChange throw cannot read property '...' of undefined during two select form binding I have the following json model and want to have two select form (dropdown) in which the first dropdown will contain the title while the second dropdown contain the authors with the value depending on the which title to pick (first title has two, second has three).
 {
        "id": 1,
        "title": "bookA",
        "authors": [
            "authorA",
            "authorB"
        ]
},
 {
        "id": 2,
        "title": "bookB",
        "authors": [
            "authorA",
            "authorB",
            "authorC"
        ]
},

I am fairly new to Angular 4, but after searching around I come up with the following code in my html:

            Title

                <select [(ngModel)]="currentInput.book.id" name="bookTitle"
                (ngModelChange)="selectedBook=$event.target.value">
                    <option *ngFor="let b of books | async" value="{{b.id}}">{{b.title}}</option>
                </select>

            Author/label>

                <select [(ngModel)]="currentInput.book.authors" *ngIf="currentInput.book.id" name="author">
                    <option *ngFor="let a of selectedBook" value="{{a.authors}}">{{a.authors}}</option>
                </select>

The first dropdown works as intented, however when the second one is clicked, an error was thrown:
ERROR TypeError: Cannot read property 'value' of undefined

Which part of the code is incorrect?

A: It is target that is undefined in your template. You would want to use $event.id to get the id value from the first dropdown. Also you want to use [ngValue] to bind the whole object in the first dropdown, so that you can show the authors in your next dropdown. So modify your code to something like this:
<select [(ngModel)]="chosenBook" name="bookTitle" (ngModelChange)="selectedBook.id = $event.id">
   <option *ngFor="let b of books | async" [ngValue]="b">{{b.title}}</option>
</select>

Author
<select [(ngModel)]="selectedBook.author">
  <option *ngFor="let a of chosenBook.authors">{{a}}</option>
</select>

Also remember to initialize your selectedBook and chosenBook so that you don't get an undefined error.
StackBlitz

A: Your code should work but it is hard to say right now.
Other way is to use a function as show below,

              //added this condition
        <select [(ngModel)]="currentInput.book.id" name="bookTitle"
                (ngModelChange)="setValue($event)">

setValue(model){
  this.selectedBook=model.target.value;
}


text:
Q: Asp.net request queued in IIS even with low traffic and CPU usage is low (CPU:40%,: 50req/sec,20 concurrent users) I am making some stress tests on a Asp.Net WebApi (.Net 4.7.2 with IIS 10 on a Windows 2019 server/ 8CPU core) and I observe that most of the request seemed to be queued even with a low traffic.
The average response time of the api is of 300 ms.
Here are the http request that I see in debudiag :
HttpContext Report

HttpContext Timeout Completed RunningSince ThreadId ReturnCode Verb             RequestPath+QueryString
65ac4d8 110 Sec     Yes     ---         200 POST                /WS_TEST/Orders/Aborted
65aea9c 110 Sec     Yes     ---         200 POST                /WS_TEST/Orders/Aborted
66bf520 110 Sec     Yes     ---         200 POST                /WS_TEST/Orders/Aborted
6b256ec 110 Sec     No  2 Sec 56    200 POST                /WS_TEST/Orders/Aborted
8506498 110 Sec     Yes     ---         200 POST                /WS_TEST/Orders/Aborted
a5b81ec 110 Sec     Yes     ---         200 POST                /WS_TEST/Orders/Aborted
a752e98 110 Sec     Yes     ---         200 POST                /WS_TEST/Orders/Aborted
c64d35c 110 Sec     Yes     ---         200 POST                /WS_TEST/Orders/Aborted
c843028 110 Sec     Yes     ---         200 POST                /WS_TEST/Orders/Aborted
e562f54 110 Sec     Yes     ---         200 POST                /WS_TEST/Orders/Aborted
e901974 110 Sec     Yes     ---         200 POST                /WS_TEST/Orders/Aborted
108cc6fc 110 Sec    Yes     ---         200 POST                /WS_TEST/Orders/Aborted
126159c4 110 Sec    Yes     ---         200 POST                /WS_TEST/Orders/Aborted
12c08d94 110 Sec    No  2 Sec 61    200 POST                /WS_TEST/Orders/Aborted
1464e364 110 Sec    Yes     ---         200 POST                /WS_TEST/Orders/Aborted
147b4488 110 Sec    No 2 Sec 41         200 POST                /WS_TEST/Orders/Aborted

Here is what windbg give me for the threadpool stats :
0:000> !threadpool
CPU utilization: 48%
Worker Thread: Total: 27 Running: 6 Idle: 17 MaxLimit: 8191 MinLimit: 8
Work Request in Queue: 0

In my load test I have a client with 20 threads running always the same requests in a loop, so I expect to see the CPU doing some more work as there should be always 20 request pending (I have no pause in my client script). But it's not seems to be the case..
After analyzing a lot of dumps , a strange thing that I noticed : I just see at anytime at max 3 to 5 request seems to be handled concurrently.
I do not see any threads blocked or waiting after a synchronization.
So what could be the cause of this behavior?
The default threadpool configuration ?
What should I check next ?

A: it is because your application pool just use one worker Processes .
you can increase your Maximum Worker Processes to more than one
you can do like this
choose your application pool, click Advanced Settings,
find Maximum Worker Processes and changed the number


text:
Q: how can I check the compiler and runtime in netbeans? in one of my questions ,somebody said that I have to make sure that I'm not using compiler 1.6 and 1.5 runtime when i want to execute or debug my program,but I don't know how can i check compiler and runtime in NetBeans ,I am beginner with NetBeans.
my question was:
**I debug my project and the result was :
debug: Have no FileObject for C:\Program Files\Java\jdk1.6.0_02\jre\lib\sunrsasign.jar
Have no FileObject for C:\Program Files\Java\jdk1.6.0_02\jre\classes**
what should i do?
and he answers : you have to make sure that you are not using compiler 1.6 and 1.5 runtime when you want to execute or debug your program

A: Here's what I use to find out everything about my building environment (never felt too warm with Eclipse):
import static java.lang.System.out;

public class Zeug {
    static String[] opts = new String[] { "java.version", "java.vendor",
            "java.vendor.url", "java.home", "java.vm.specification.version",
            "java.vm.specification.vendor", "java.vm.specification.name",
            "java.vm.version", "java.vm.vendor", "java.vm.name",
            "java.specification.version", "java.specification.vendor",
            "java.specification.name", "java.class.version", "java.class.path",
            "java.library.path", "java.io.tmpdir", "java.compiler",
            "java.ext.dirs", "os.name", "os.arch", "os.version",
            "file.separator", "path.separator", "line.separator", "user.name",
            "user.home", "user.dir" };

    public static void main(String[] args) {
        for(String o : opts) {
            out.println(o + ": " + System.getProperty(o));
        }
    }
}

A: Go to Tools-->Java Platform and you should see the JDK you are using listed.  I am using java-6-sun-1.6.0.16 which does indeed have the jar file you need.
Download the latest JDK from Sun.  Go to Tools-->Java Platform and click Add Platform.  Navigate to where you installed the latest JDK, name it something meaningful like JDK 1.6.0.16 or whatever and click Finish.  Right click on the top level of your project and click Properties.  At the top of the popup window change the Java Platform to the one you just added and click ok.  At that point, you should not experience your current problem when you compile.
JDK Download Link

A: You can set the Java version to be used in the project properties (right click on the project).
Edit: after seeing your specific error message: this seems to be a deeper problem. For some reason Netbeans is looking for a file sunrsasign.jar, which is not normally part of the JDK. Looking for the filename on Google indicates that it's part of a cryptography extension, but that seems to have been integrated into the JDK by now. So the JAR is not needed anymore.
I don't know whether it's Netbeans (are you using the most recent version?) or your application that is mistakenly looking for a JAR that has been integrated into the JDK library itselt.


text:
Q: Extending actions of Monads on Endofunctors. Let $X^{X}$ be the category of endofunctors on a category $X$. Then if we define $\otimes :X^{X}\times X^{X}\rightarrow X^{X}$ by $R\otimes S=RS$ on objects and $\tau \otimes \sigma $ to be horizontal composition, then $\otimes$ is a bifunctor and $\left \langle X^{X},1_{X} \right \rangle$ is a strict monoidal category. Now, suppose $\left \langle T,\mu ,\eta \right \rangle$ is a monad in $X$. It's not too hard to show that $\left \langle T,\mu ,\eta \right \rangle$ is a monoid in $X^{X}$.
Now let $R$ be an endofunctor on $X$, such that $R$ can be expressed as $X\overset{R'}{\rightarrow}X^{T}\overset{G^{T}}{\rightarrow}X$ where $G^{T}$ is the forgetful functor. Then if we define $\tau :TR\overset{\cdot}{\rightarrow}R$ to be $G^{T}\epsilon^{T}_{R'}$, it turns out that $\tau $ is an action of $T$ on $R$.
Conversely, if $\tau $ is an action, then we define $R':X\rightarrow X^{T}$ by $R'x=\left \langle Rx,\tau _{x} \right \rangle$ and then, noting that naturality of $\tau $ iimplies that if $f:x\rightarrow x'$ then $Rf$ is a $T$-algebra, on arrows we may simply take $R'f=Rf$. And now we have $R=G^{T}R'$.
Therefore, the actions of $T$ on endofunctors, are completely characterized by this lifting property.
OK, now for the question: Can something similar be said about functors from arbitrary categories $A$ to $X$? In this case, there is no monad whose structure can be exploited to characterize the actions, so the approach will have to be altogether different?


text:
Q: firebase push notification with expo not working I've an app based on react native with expo. For push notifications, i'm trying to use firebase. I've created functions in firebase and tried to send notification from firebase to my iphone. I don't see any issues in the code and verified firebase log too. Getting status "ok" message after this function triggered but still i didn't get notifications in my mobile. Anyone can help?
I'm in firebase paid plan. Same code is firing notification when i run directly from react native app.
const functions = require("firebase-functions");
const fetch = require("node-fetch");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

exports.sendPushNotification = functions.database
  .ref("orders/{id}")
  .onCreate((snapshot, context) => {
    var messages = [];
    const root = admin.database().ref("customers");
    console.log("customers : " + root.path);
    return root
      .once("value")
      .then((snapshot) => {
        snapshot.forEach((childSnapshot) => {
          //alert(expoToken);
          var expoToken = childSnapshot.val().expoPushToken;
          console.log("token : " + expoToken);
          if (expoToken) {
            messages.push({
              to: expoToken,
              title: "hello",
              body: "New Order",
            });
          }
        });
        return Promise.all(messages);
      })
      .then((messages) => {
        const res = fetch("https://exp.host/--/api/v2/push/send", {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
          },
          body: JSON.stringify(messages),
        });
        console.log(res);
        return res;
      });
  });

A: Not sure what was the problem but after i added below line in headers tag, it started working fine.
"Accept-encoding": "gzip, deflate"

A: I was not able to Comment, so i am writing here
for database in firebase what you used actually 1. Cloud Firestore or 2. Realtime Database
If you have used Firestore in this case Change code with

functions.firestore.document('Something\{id}').onCreate({snap, context}) => ...


text:
Q: Why can't a pointer's value be accessed with square bracket syntax when returned from a function? I am learning basic C, and I am still trying to understand arrays and pointers. I am trying to write a push function to mimic the behavior of an array in Javascript, but with a workaround, since arrays cannot be returned in C.
When I access the returned pointer with (*p+3), it yields the correct value, but p[3] does not. However, I can still access the correct value within push() with p[3]. Why is this?
#include <stdio.h>
#include <stdlib.h>

void br() {
    putchar('\n');
}

int *push(int *arr, size_t size, int val) {
    int *arr2 = calloc(size + 1, sizeof(int));
    for (int i = 0; i < size; i++) {
        arr2[i] = arr[i];
    }
    arr2[size] = val;
    return arr2;
}

int main(int argc, char *argv[]) {
    int myNums[] = { 1, 2, 3 };

    int *p = push(myNums, sizeof(myNums), 4);
    printf("%i", (*p + 3));
    br();
    printf("%i", p[3]);
    br();

    return 0;
}

EDIT: I think there is a better solution using structs.
#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int*values;
    int length;
} intArray;

void printInts(intArray * arr){
    for(int i = 0; i < arr->length; i++){
        printf("Value %i: %i\n",i,arr->values[i]);
    }
}

intArray push(intArray * arr, int value){
    arr->length++;
    arr->values = realloc(arr->values, sizeof(int)*arr->length);
    arr->values[arr->length-1] = value;
    return *arr;
}

intArray pop(intArray * arr){
    arr->length--;
    arr->values = realloc(arr->values, sizeof(int)*arr->length);
    return *arr;
}

int main(int argc, char *argv[]) {
    intArray myNums;
    myNums = push(&myNums,15);
    myNums = push(&myNums,30);
    myNums = push(&myNums,45);
    myNums = push(&myNums,60);
    myNums = pop(&myNums);

    printInts(&myNums);

    /* expected output:
    Value 0: 15
    Value 1: 30
    Value 2: 45
    */

    return 0;
}

A: There are two mistakes in the code:

*

*int *p = push(myNums, sizeof(myNums), 4);
sizeof(myNums) is not the length of the array (ie: the number of elements), but its size in bytes.
You can use sizeof(myNums) / sizeof(myNums[0]) to compute the number of elements at compile time.

*printf("%i", (*p + 3));
You first print *p + 3, which is not the same as *(p + 3): you get the expected output only by coincidence because *p, which is equivalent to p[0] happens to have the value 1. Conversely, p[3] accesses the fourth element of the reallocated array, whose value is undefined as it was copied from data beyond the end of the original array passed to push().
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>

int *push(int *arr, size_t count, int val) {
    int *arr2 = calloc(count + 1, sizeof(int));
    for (int i = 0; i < count; i++) {
        arr2[i] = arr[i];
    }
    arr2[count] = val;
    return arr2;
}

int main(int argc, char *argv[]) {
    int myNums[] = { 1, 2, 3 };
    int *p = push(myNums, sizeof(myNums) / sizeof(myNums[0]), 4);
    printf("%i\n", *(p + 3));
    printf("%i\n", p[3]);
    free(p);
    return 0;
}


text:
Q: wx.Radiobox.SetBackgroundColour("pink") won't change the color of RadioButton until mouse pass by I've built a wx.Dialog, with some wx.Radiobox need to validate. If user doesn't make a choice, the validator wouldn't return True and popup a wx.MessageBox tells user that you should choose something. Meanwhile, the background color should have changed to pink.
The problem here is when using RadioBox.SetBackgroundColour("pink"), the Background color of  RadioBox's label text changed to pink, which is perfectly normal, but the background color for RadioButton's label text won't change until mouse pass by.
I'm wondering why this and how to fix it. I've looked up in official docs and googled, but find nothing. Anyone have idea?
The platform is win8.1x64 and python 2.7.3 and wxpython 2.8.12.1. For using Psychopy standalone package, the version of both python and wxpython are quite old.
The Dialog as follow, a quite simple one :
class Dlg(wx.Dialog):
    """A simple dialogue box."""

    def __init__(self):
        global app
        app = wx.PySimpleApp()
        wx.Dialog.__init__(self, None,-1)

        self.sizer = wx.FlexGridSizer(cols=1)

    def show(self, cancelBTN=False):
        """Show a dialog with 2 RadioBox"""

        # add two RadioBox

        RadioBox1 = wx.RadioBox(self, -1, label="Wierd color", choices=["", "choice A", "choice B"], validator=RadioObjectValidator())
        RadioBox2 = wx.RadioBox(self, -1, label="Wierd color", choices=["", "choice A", "choice B"], validator=RadioObjectValidator())
        RadioBox1.ShowItem(0, show=False)  # Hide the first choice
        RadioBox2.ShowItem(0, show=False)  # Hide the first choice

        RadioBox1.GetValue = RadioBox1.GetStringSelection
        RadioBox2.GetValue = RadioBox2.GetStringSelection
        self.sizer.Add(RadioBox1, 1, wx.ALIGN_LEFT)
        self.sizer.Add(RadioBox2, 1, wx.ALIGN_LEFT)

        # add buttons for OK

        self.sizer.Add(wx.Button(self, wx.ID_OK), 1, flag=wx.ALIGN_RIGHT)

        self.SetSizerAndFit(self.sizer)

        if self.ShowModal() == wx.ID_OK:
            pass
            # do something

        self.Destroy()

And Validator as this:
class RadioObjectValidator(wx.PyValidator):
    """ This validator is used to ensure that the user has entered something
        into the text object editor dialog's text field.
    """
    def __init__(self):
        """ Standard constructor.
        """
        wx.PyValidator.__init__(self)

    def Clone(self):
        """ Standard cloner.

            Note that every validator must implement the Clone() method.
        """
        return RadioObjectValidator()

    def Validate(self, win):
        """ Validate the contents of the given RadioBox control.
        """
        RadioBox = self.GetWindow()
        choice = RadioBox.GetValue()

        if not choice:
            wx.MessageBox(u'Choose something please', u'info', wx.OK | wx.ICON_EXCLAMATION)
            RadioBox.SetBackgroundColour("pink")
            RadioBox.SetFocus()
            RadioBox.Refresh()
            return False
        else:
            RadioBox.SetBackgroundColour(
                wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
            RadioBox.Refresh()
            return True

    def TransferToWindow(self):
        """ Transfer data from validator to window.

            The default implementation returns False, indicating that an error
            occurred.  We simply return True, as we don't do any data transfer.
        """
        return True  # Prevent wxDialog from complaining.

    def TransferFromWindow(self):
        """ Transfer data from window to validator.

            The default implementation returns False, indicating that an error
            occurred.  We simply return True, as we don't do any data transfer.
        """
        return True  # Prevent wxDialog from complaining.

And simply run like this:
if __name__ == "__main__":
    test = Dlg()
    test.show()

A: Well, it's a bug in wxpython2.8.12.1, and has fixed in wxpython3.0.0.0, Thanks @GreenAsJade for reminding.


text:
Q: Discord Python Kick Function not working after a certain time So I am making a captcha bot in discord.py and Im trying to kick the user if they dont answer the captcha in a specific amount of time rahter if they get it incorrect or if they dont type. If they get it correct it already will break the loop and that part works. Its just the time issue where it wont kick the user after a specific amount of time if they dont guess the captcha in that given time. I put 10 seconds just for testing. On the last two lines is their any way I can have that work where it will kick the user if they dont answer the captcha in that given time. Everything else works by the way and theirs no error**But heres the code:
from discord.ext import commands
from discord.utils import get
import random
import time
import asyncio
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix="+", intents=intents)
@bot.command()
async def setup(ctx):
  embed=discord.Embed(title="How to get verfiied",
  description="1.Go to the verified channel and use the command $verify\n2.Then from there you should be able to get you role and come into the server.\n\n**YOU HAVE 3 tries and only 15 minutes to solve the captcha or else the bot will kick you. Plesae contact staff if you have any issues**", color=0x0000FF)
  await ctx.send(embed=embed)

@bot.command(name='verify', pass_context = True)
async def verify(ctx):
    def check(m):
        return m.author == ctx.author and m.channel == ctx.message.channel
    image = ("captcha 6.png","captcha10.png","captcha11.png","captcha2.png", "captcha3.png", "captcha4.png", "captcha5.png", "captcha7.png","captcha8.png", "captcha9.png")
    image_random = random.choice(image)
    number = ("b3xpn", "2yggg","ydg8n","pp546","fcne6","cdfen","4f8yp","m8m4x","pdyc8","55w5c","xwx7d")
    await ctx.send(file=discord.File(image_random))
    await ctx.send('Please solve the captcha image')

    for i in range(0, 3):
        guess = await bot.wait_for('message', check=check)
        if guess.content in number:
            await ctx.send('Correct Welcome!')
            role = discord.utils.get(ctx.author.guild.roles, name="member")
            await ctx.author.add_roles(role)
            break

        else:
            await ctx.send("Incorrect")

    else:
        await ctx.send("Incorrect this is your 3rd try please rejoin and try again")
        await asyncio.sleep(3)
        await ctx.author.kick()

    asyncio.sleep(5)
    await ctx.author.kick()

A: Idk if this will fix it or if that is just an post mistake but you are missing awaitat
asyncio.sleep(5)

A: You have to pass the timeout parameter with wait_for() or it will wait for answers for infinite time.
try:
    for i in range(0, 3):
        guess = await bot.wait_for('message', check=check, timeout=20)
        # it will stop listening for messages after 20 seconds
        if guess.content in number:
            await ctx.send('Correct Welcome!')
            role = discord.utils.get(ctx.author.guild.roles, name="member")
            await ctx.author.add_roles(role)
            break

        else:
            await ctx.send("Incorrect")

    else:
        await ctx.send("Incorrect this is your 3rd try please rejoin and try again")
        await asyncio.sleep(3)
        await ctx.author.kick()

except asyncio.TimeoutError:
    await asyncio.sleep(5)
    await ctx.author.kick()


text:
Q: Laravel AH01630: client denied by server configuration on Specific API routes I've a Laravel app which is has an API.
every thing works fine on localhost but when i deploy my app to hosting. I've notice that every API Route with these method (Delete,PUP,DELETE) didn't work, and it gave me the following error:
Forbidden You don't have permission to access this resource.

my Apache Log:
[client 41.254.66.101:27968] AH01630: client denied by server configuration: /home/username/public_html/api

i believe it's something with the server.
my server is running on CentosOS with CWP Panel.

A: Apache is limited to serving files within its document root.
To fix it edit the config and ad another Directory
nano /etc/apache2/apache2.conf
<Directory /your/dir/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>


text:
Q: Using Bootstrap in Live site Hi. I have just started to mess around with Bootstrap. I have learned HTML, CSS, Javascript and PHP over the past nine months. I would like to start putting websites online in this coming summer. For purposes of ease and responsive programming I would like to know if first of all if it is frowned upon in any way? Secondly, in terms of editing bootstrap CSS should I copy the bootstrap one and put in my own edit's? Or is there a better practice for this ?
Regards.

A: In my personal experience, using boostrap isn't frowned upon. Just try to make sure your sites stand out and dont' just look like default boostrap sites which after a while can start to look very template-y.
In regards to the CSS, you should NEVER touch the bootstrap.min.css file. You should make your own CSS file and import that into your files. If you need to override anything in bootstrap, changing it in your other CSS file will override the bootstrap css.