text:
Q: Cómo Recargar datos mysql automaticamente en MaterialDataTable v.10 para angular 10 Buen Día, Adjunto código de un MaterialDataTable que filtra, ordena y pagina con información de un API Rest de laravel, todo funciona bien, pero; cuando ingreso información directamente en la tabla de la Base de Datos, esta información no se ve reflejada en el MaterialDataTable sino hasta que manualmente se cambia de URL con el menú de la APP o se refresca la pantalla.
Aunque se este usando MatTableDataSource y la documentación indica que las operaciones las hace del lado del cliente, esto no debería ser impedimento para que el servicio este llamando constantemente al get de la API. Se usa Angular: 10.0.11 y Material-Angular: 10.1.3
Por favor si me pueden indicar que debo agregar al código (tal vez en el observable del servicio en el componente) para que constantemente este verificando y actualizando la información de la BD y refrescando el MaterialDataTable. Muchas Gracias.
El código:
[Modelo]
export interface PaisesItem {
    idPaises?:number;
    pais:string;
    nacionalidad:string;
}

[Servicio]
  constructor(private http: HttpClient) { }

  public listar():Observable<PaisesItem[]>{
    return this.http.get<PaisesItem[]>(this.RUTA_API+'/paises');
  }
}

[ts]
ngAfterViewInit() {
    this.paisesService.listar().subscribe((row: PaisesItem[])=>{
      this.dataSource = new MatTableDataSource(row);
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    });
  }

[html]

      <ng-container matColumnDef="idPaises">
         ID
         {{row.idPaises}}
      </ng-container>
...


text:
Q: Multiple marker in google map using JSON I have to make a multiple marker google map using JSON parsing. Any one having helping code of it. So that i can gain an idea on it. The activity i have made is not working exactly what i want.
This is my activity
public class MapsActivity extends MapActivity{
private MapController mapControll;
private GeoPoint geoPoint=null;
private MapView mapview;
private MyItemizedOverlay userPicOverlay;
private MyItemizedOverlay nearPicOverlay;
private Drawable userPic,atmPic;
private OverlayItem nearatms[] = new OverlayItem[50];
public static Context context;
public double latitude;
public double longitude;

private List<String> lat = new ArrayList<String>();
private List<String> lon = new ArrayList<String>();
private String[] get_lati;
private String[] get_long;

@Override
protected void onCreate(Bundle icicle) {
    // TODO Auto-generated method stub
    super.onCreate(icicle);
    context = getApplicationContext();
    setContentView(R.layout.map);
    lat.clear();
    lon.clear();
    Intent in = getIntent();
    if(in!=null){
    get_lati = in.getStringArrayExtra("LAT_KEY");
    get_long = in.getStringArrayExtra("LONG_KEY");
    System.out.println("lat===="+get_lati.length+" lon==="+get_long.length);
    }
    for(int i = 0;i<get_lati.length;i++){
        String lt = null;
        String ln = null;
        lt =get_lati[i];
        ln =get_long[i];

        System.out.println("lt=="+lt+"==ln=="+ln);
    }
    showMap();
}

public void showMap() {
    // TODO Auto-generated method stub

    try {
        double lat_dbl = Double.parseDouble(get_lati[0]);
        double lon_dbl = Double.parseDouble(get_long[0]);
        geoPoint = new GeoPoint((int)(lat_dbl * 1E6),(int)(lon_dbl * 1E6));
        mapview = (MapView)findViewById(R.id.mapView);
        mapControll= mapview.getController();
        mapview.setBuiltInZoomControls(true);
        mapview.setStreetView(true);
        mapControll.setZoom(16);
        mapControll.animateTo(geoPoint);

        userPic = this.getResources().getDrawable(R.drawable.pin);
        userPicOverlay = new MyItemizedOverlay(userPic);
        OverlayItem overlayItem = new OverlayItem(geoPoint, "I'm Here!!!", null);
        userPicOverlay.addOverlay(overlayItem);
        mapview.getOverlays().add(userPicOverlay);

        atmPic = this.getResources().getDrawable(R.drawable.pin);
        nearPicOverlay = new MyItemizedOverlay(atmPic);
        for (int i = 0; i < 5; i++) {
            nearatms[i] = new OverlayItem(new GeoPoint((int)((latitude) * 1E6), i),"Name", null);//just check the brackets i just made change here so....
            nearPicOverlay.addOverlay(nearatms[i]);
        }
        mapview.getOverlays().add(nearPicOverlay);
        //Added symbols will be displayed when map is redrawn so force redraw now
        mapview.postInvalidate();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}

public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {

    private ArrayList<OverlayItem> myOverlays ;

    public MyItemizedOverlay(Drawable defaultMarker) {
        super(boundCenterBottom(defaultMarker));
        myOverlays = new ArrayList<OverlayItem>();
        populate();
    }

    public void addOverlay(OverlayItem overlay){
        myOverlays.add(overlay);
        populate();
    }

    @Override
    protected OverlayItem createItem(int i) {
        return myOverlays.get(i);
    }

    // Removes overlay item i
    public void removeItem(int i){
        myOverlays.remove(i);
        populate();
    }

    // Returns present number of items in list
    @Override
    public int size() {
        return myOverlays.size();
    }

    public void addOverlayItem(OverlayItem overlayItem) {
        myOverlays.add(overlayItem);
        populate();
    }

    public void addOverlayItem(int lat, int lon, String title) {
        try {
            GeoPoint point = new GeoPoint(lat, lon);
            OverlayItem overlayItem = new OverlayItem(point, title, null);
            addOverlayItem(overlayItem);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Override
    protected boolean onTap(int index) {
        // TODO Auto-generated method stub
        String title = myOverlays.get(index).getTitle();
        //Toast.makeText(MapActivity.this, title, Toast.LENGTH_LONG).show();
        return super.onTap(index);
    }
}

}

A: You are creating a geopoint with latitude but 'i' instead of longitude.
new GeoPoint((int)((latitude) * 1E6), i)

instead of:
new GeoPoint((int)((latitude) * 1E6), (int)((longitude) * 1E6)) // + some variation based on i

Thus all the points fall very near to each other.
I assume that you're using 'i' in order to create separate point near your location, and that in the final product you would use an ATM point DB. I suggest that you create a function that is supposed to retrieve ATM locations, and for testing purposes either return fixed (but real) locations, or randomize around your lat/lng. (This is also a better coding practice.)
For debug purposes, log the actual points you are creating, after you created them. if all lat/lng numbers look the same, you have a clue at what's going on. if only two points are logged... that's a different problem. :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: I.V.P. $\frac{dy}{dx}=f(y),y(0)=a.$ Consider the I.V.P. $$\frac{dy}{dx}=f(y(x)),y(0)=a\in\mathbb{R}$$ where $f:\mathbb{R}\rightarrow\mathbb{R}.$  which of the following statements are necessarily true?
$1.$ There exist a continuous function $f$ and a real number $a$ such that the above problem does not have a solution in any neighbourhood of zero.
$2$. The above problem has a unique solution for ever real $a$ when $f$ is Lipschitz continuous.
$3.$ When$f$ is twice continuously differentiale the maximum interval of existence for the above problem is $\mathbb{R}$.
$4.$ The maximum interval of existence for the above problem is $\mathbb{R}$ when $f$ is bounded and continuously differentiable.
According to me by Picard existence and uniqueness theorem first option is false and second one is true. I have no result regarding existence of solution in whole real line $\mathbb{R}$. For option number three I have counter example if $y =y^{2}$ .Please suggest me some result regarding this so that I can understand last option.  Thanks a lot.


text:
Q: Maintaining the acyclic property of a DAG faster than O(n) time Given a graph in which we can insert vertices and edges, and we can also remove them. Before finishing the edge insertion operation, I would like to check whether the graph would still be acyclic if I added that new edge, and cancel the operation if not.
I can easily check whether the graph is acyclic at each operation in O(n) time using a simple depth first search. However this will not scale well for extremely large graphs.
I was wondering whether we could maintain some additional information in the vertices / edges, so that there is an asymptotically faster way to detect whether the graph would become cyclic. E.g. I could do an O(log(n)) operation at each graph mutating operation, and maintain some information that magically make my acyclicity check faster, kind of how balanced binary search trees make it possible to always query the smallest element in O(log(n)) time.

A: It seems that there is a long line of research on this problem. The magic phrase is "incremental cycle detection". The newest paper I could find is this; it contains a large number of references to earlier papers.
The gist of it is that there are algorithms for doing this in sublinear time (e.g., on the order of $\sqrt{n}$ times something polylogarithmic per update), but according to the authors of the linked paper "we are far away from designing an algorithm that has polylogarithmic update time". The best algorithm also depends on whether the input graphs are sparse or dense, and whether you are happy with a randomized algorithm. Implementing some of these algorithms seems to be non-trivial but not hopeless. If you want to try, this looks like a nice choice.


text:
Q: Set a different color for a path I have a weighted graph,G, extracted from a text file:
i   j   distance
1   2   6000
1   3   4000
2   1   6000
2   6   5000
....

And I have specific a route (not a shortest path) that I want to plot on graph G, i.e. [1, 2, 6, 7] that starts from node 1, end at node 7 by visiting node 2 and node 6. Here the code I've tried. But since Im new in python and networkx package as well, I couldn't get the result that Im looking for.
G = nx.read_edgelist('Graph.txt', data=(('weight',float),))
r=[1,2,6,7]
edges=[]
route_edges=[(r[n], r[n+1]) for n in range (len(r)-1)]
G.add_nodes_from(r)
G.add_edges_from(route_edges)
edges.append(route_edges)
pos=nx.spring_layout(G)
nx.draw_networkx_nodes(G,pos=pos)
nx.draw_networkx_labels(G, pos=pos)
nx.draw_networkx_edges(G,pos=pos,edgelist=edges)

I want to plot whole edges and the path that I defined with different colors and also I want to add different color to node 6.

A: To highlight a specific path in a different color, it's just a matter of setting a different color edge color for the path edges. For you can define a set containing the list's pairs of nodes as tuples, and set a color or another to the graphs' edges depending on whether the path is contained in the set:
#graph defined with from_pandas_edgelist for simplicity
G = nx.from_pandas_edgelist(df.rename(columns={'distance':'weight'}), 'i', 'j', 'weight',
                            create_using=nx.DiGraph)

I've added some more edges so the plot seems a little clearer:
G.edges(data=True)
# OutEdgeDataView([(1, 2, {'weight': 6000}), (1, 4, {'weight': 3200}), (1, 3, {'weight': 4000}),
#                  (2, 3, {'weight': 1000}), (2, 6, {'weight': 5000}), (4, 8, {'weight': 4000}),
#                  (6, 7, {'weight': 3000})])

We can define a dictionary for the edge colors, and a list for the nodes' color as:
path =  [1, 2, 6, 7]
path_edges = set(zip(path[:-1], path[1:]))

# set edge colors
edge_colors = dict()
for edge in G.edges():
    if edge in path_edges:
        edge_colors[edge] = 'magenta'
        continue
    else:
        edge_colors[edge] = 'lightblue'

nodes = G.nodes()
node_colors = ['orange' if i != 6 else 'lightgreen' for i in nodes]

Which we could use to plot the graph as:
fig = plt.figure(figsize=(12,8))
pos = nx.spring_layout(G, scale=20)
nx.draw(G, pos,
        nodelist=nodes,
        node_color=node_colors,
        edgelist=edge_colors.keys(),
        edge_color=edge_colors.values(),
        node_size=800,
        width=4,alpha=0.6,
        arrowsize=20,
        with_labels=True)


text:
Q: Handling variadic function arguments of type 'std::size_t' I am trying to get the hang of variadic function/template parameters. However, in the two functions below, I am very confused as to why SumIndices does not compile (I get the compiler error "expansion pattern 'std::size_t' {aka 'long unsigned int'} contains no parameter packs") while SumValues does.
template <typename ...t_data_type>
constexpr auto SumValues(t_data_type ..._values) {
  return (_values + ...);
}

constexpr auto SumIndices(std::size_t ..._indices) {
  return (_indices + ...);
}

I would much appreciate it if anyone can clarify this confusion for me!

A: In first case you have parameter pack.
In second case, you have variadic function from C.
Variadic templates allow you to type-safely pass different types into your function.
Example of print with this:
// Create this function to terminate argument depended lookup
void PrintValues(std::ostream&){}
template<typename TFirstArg, typename ...TArgs>
void PrintValues(std::ostream& output, const TFirstArg& arg, const TArgs... other_args){
   // Recursive call to another function which has N-1 args
   // If other_args are empty, it would call `void PrintValues(std::ostream&)`
   // If they are non empty, it would call another instantiation of this template
   PrintValues(output << arg, other_args...);
}

And this can be called this way:
PrintValues(std::cout, 5LL, 7.59, "Hello world", std::string{"bingo"});

With varargs you can do this:
void PrintFewNumbers(size_t number_of_args, ...)
{
    va_list args;
    va_start(args, number_of_args);
    for (size_t idx_of_arg, idx_of_arg < number_of_args; ++idx_of_arg){
        size_t current_arg = va_arg(args, size_t);
        std::cout << current_arg;
    }
    va_end(args);
}

And you can call it using this:
PrintFewNumbers(0);
PrintFewNumbers(5, 1,2,3,4,5);

You should prefer variadic templates to variadic args because they are type safe. However, they are not always usable.

A: With C++20, you can create your SumIndices easily with the Concept library:
#include <concepts>
auto SumIndices(std::same_as<std::size_t> auto ... indices);

However, do note that this have a strict rule on only data of std::size_t or equivalent types can be passed to the function.
Instead, you might consider to use std::integral or std::unsigned_integral, which would allow other integral types to be used:
auto SumIndices(std::integral auto ... indices);


text:
Q: IO Other Operations Performance Counter Explanation I have received perfmon counters from customer site. We noticed unusual values in \\COMPUTERNAME\Process(PROCESS_NAME)\**IO Other Operations/sec**.
The best explanation for the counter I came up with is:-

The average rate at which the process
  is issuing I/O operations that are
  neither read nor write operations (for
  example, a control function). This
  counter counts all I/O activity
  generated by the process to include
  file, network and device I/Os. This
  counter is equivalent to the perfmon
  counter Process\IO Other
  Operations/sec.

On Technet, its description does not appear.
Who knows what this counter (**IO Other Operations/sec**) actually counts? Which system call may cause this counter to be increased and how it can be monitored.
We are working with C++.

A: I don't think a documented list of operations exist as it is too broad. However, you can use the Process Monitor tool to find out what operations are performed by a running process in real-time. If you watch the movement of the I/O Other Operations metric of a process (such as in the Task Manager - Details tab with added column "I/O other"), while having  Process Monitor running with a filter on the process PID, this should give you good indications on which operations affects the counter.


text:
Q: How to display console result on a Web Server Please forgive me if this question may not fit this site. I have recently installed Pure-FTPd service running on CentOS. To view current connects, I run the command pure-ftpwho, below is the screen output:
+------+---------+-------+------+-------------------------------------------+
| PID  |  Login  |For/Spd| What |                 File/IP                   |
+------+---------+-------+------+-------------------------------------------+
| 7233 | login001| 00:00 | IDLE | ->     xxx-xx-xx-xxx.mydomain.com         |
|  ''  |    ''   |   ''  |  ''  |                                           |
+------+---------+-------+------+-------------------------------------------+
| 7532 | login002| 00:05 | IDLE | ->                 xxxxxx.xxxxx.com       |
|  ''  |    ''   |   ''  |  ''  |                                           |
+------+---------+-------+------+-------------------------------------------+

or pure-ftpwho -s
7233|login001|56|IDLE||xxx-xx-xx-xxx.mydomain.com|ftpserver1|21|0|0|0|0
7532|login002|338|IDLE||xxxxxx.xxxxx.com|ftpserver1|21|0|0|0|0

I have another server running Apache Web Service and I am thinking of creating an html or php page that will display the same result for my end users.
I just need a little bit of guide on how I can approach this either using php, javascript, or JQuery.
Thanks

A: You could start by looking into http://php.net/system and http://php.net/exec and http://php.net/passthru
However, if you really do not need a real real-time output, the best approach might be that you actually run this command in a scheduled job (cron?), every minute or so, and redirect it's output to text file, which you later pass in php.
For example, every minute you run pure-ftpwho -s > /var/www/who and then get the file contents with <? $who = file_get_contents("/var/www/who"); ?> in PHP.
Let me know if something like this works for you.


text:
Q: Recommended Auto Grow settings suitable for database whose size is 867666.25 MB I need recommendations for setting/modifying the auto grow options for our production database.
size of FUNDSDB  867666.25 MB
Also,
I have attached the current autogrowth statistics , looks like it is set to 200 MB which I think is considerably less considering the database size and also it should be modified to some realistic value else these auto-growth events can cause performance degradation for our current db transactions.

Can anyone suggest the auto growth settings best suitable for this heavy OLTP production database?
We are using SQL Server 2012 standard RTM version currently.
The main reason we are planning to change the autogrowth factor is that we have observed, we are experiencing frequent up to 11 times auto grow a day and also, many frequent CPU spikes.

A: Set it to 1024MB.  If it is still happening too often, then 4096MB.  Until you measure your actual growth needs, it guesswork.
Or, manually grow it to 950GB, or an even 1TB and let Autogrow not be a factor, which is what you should be doing anyway.
Is Instant File Initialization turned on?  You didn't mention the version of SQL Server.
And change the Log file from % to MB.
And just for bonus - please get them onto separate drives.
Kevin3NF

A: You might want to consider analysing the growth of your database over the last n days. This can be achieved by analysing the backup information in the msdb database. The following scripts are two variations of how to achieve this:
-- Transact-SQL script to analyse the database size growth using backup history.
DECLARE @endDate DATETIME,
        @months SMALLINT;
SET @endDate = GETDATE();  -- Include in the statistic all backups from today
SET @months = 6;           -- back to the last 6 months.
;
WITH HIST AS
     (
         SELECT BS.database_name AS DatabaseName,
                YEAR(BS.backup_start_date) * 100
                + MONTH(BS.backup_start_date) AS YearMonth,
                CONVERT(NUMERIC(10, 1), MIN(BF.file_size / 1048576.0)) AS MinSizeMB,
                CONVERT(NUMERIC(10, 1), MAX(BF.file_size / 1048576.0)) AS MaxSizeMB,
                CONVERT(NUMERIC(10, 1), AVG(BF.file_size / 1048576.0)) AS AvgSizeMB
         FROM   msdb.dbo.backupset AS BS
                INNER JOIN msdb.dbo.backupfile AS BF
                     ON  BS.backup_set_id = BF.backup_set_id
         WHERE  NOT BS.database_name IN ('master', 'msdb', 'model', 'tempdb')
                AND BF.file_type = 'D'
                AND BS.backup_start_date BETWEEN DATEADD(mm, - @months, @endDate) AND @endDate
         GROUP BY
                BS.database_name,
                YEAR(BS.backup_start_date),
                MONTH(BS.backup_start_date)
     )

SELECT MAIN.DatabaseName,
       MAIN.YearMonth,
       MAIN.MinSizeMB,
       MAIN.MaxSizeMB,
       MAIN.AvgSizeMB,
       MAIN.AvgSizeMB
       -(
           SELECT TOP 1 SUB.AvgSizeMB
           FROM   HIST AS SUB
           WHERE  SUB.DatabaseName = MAIN.DatabaseName
                  AND SUB.YearMonth < MAIN.YearMonth
           ORDER BY
                  SUB.YearMonth DESC
       ) AS GrowthMB
FROM   HIST AS MAIN
ORDER BY
       MAIN.DatabaseName,
       MAIN.YearMonth

Reference: Database size growth as a list (Microsoft Technet)
Or alternatively use the following script:
SELECT DISTINCT
    A.[database_name]
,   AVG( A.[Backup Size (MB)] - A.[Previous Backup Size (MB)] ) OVER ( PARTITION BY A.[database_name] ) AS [Avg Size Diff From Previous (MB)]
,   MAX( A.[Backup Size (MB)] - A.[Previous Backup Size (MB)] ) OVER ( PARTITION BY A.[database_name] ) AS [Max Size Diff From Previous (MB)]
,   MIN( A.[Backup Size (MB)] - A.[Previous Backup Size (MB)] ) OVER ( PARTITION BY A.[database_name] ) AS [Min Size Diff From Previous (MB)]
,   A.[Sample Size]
FROM
(
    SELECT
        s.[database_name]
    --, s.[backup_start_date]
    ,   COUNT(*) OVER ( PARTITION BY s.[database_name] ) AS [Sample Size]
    ,   CAST ( ( s.[backup_size] / 1024 / 1024 ) AS INT ) AS [Backup Size (MB)]
    ,   CAST ( ( LAG(s.[backup_size] )
            OVER ( PARTITION BY s.[database_name] ORDER BY s.[backup_start_date] ) / 1024 / 1024 ) AS INT ) AS [Previous Backup Size (MB)]
    FROM
        [msdb]..[backupset] s
    WHERE
        s.[type] = 'D' --full backup
    --ORDER BY
    --  s.[database_name]
    --, s.[backup_start_date]
) AS A
ORDER BY
    [Avg Size Diff From Previous (MB)] DESC;
GO

Reference: Identify SQL Server Database Growth Rates (mssqltips.com)
Based on the information provided with these scripts you could then set the Growth Setttings of your database to be near the GrowthMB (Microsoft Technet Script) value or near the Max Size Diff From Previous (MB) value (Mssqltips.com Script).
If you interpolate into the future, you could possibly set the Max Size of the database files (*mdf) to be a multiple of the returned values (12 month worth?) plus the current DB size.


text:
Q: Why is tubed space curve not exported in stl files after rotation? Following up a comment on this question, as part of some image, I want to make a tubular shape and export it for 3d printing like here:
curve = ParametricPlot3D[{a^2, (1 - a)^2, 2*a*(1 - a)}, {a, 0, 1}] /. Line -> (Tube[#, 0.02] &)
Export ["test1.stl", curve]

This works.  Now, in a bigger design I need to rotate the curve, so I do this:
curve2 = Graphics3D[Rotate[First@Show[curve],ArcCos[1/Sqrt[3]], {1, -1, 0}, {0, 0, 0}]]
Export["test2.stl", curve2]

which displays the curve rotated, but export now fails:
Export::nodta: "Graphics3D contains no data that can be exported to the \!\(\"STL\"\) format. "

and in indeed, in the bigger design the curve is displayed correctly, but on stl export everything but curve is exported.

A: I'm surprised that the first example works. There is an issue with converting Tube objects to MeshRegion objects, and in fact DiscretizeGraphics fails on curve1 and curve2 alike.  You can use the trick from this page, to convert to a MeshRegion before export as STL.
<< "http://pastebin.com/raw/FQXgqhn3" (*Import the TubeMesh function from pastebin*)

curve2 = Graphics3D[
   Rotate[First@
     ParametricPlot3D[{a^2, (1 - a)^2, 2*a*(1 - a)}, {a, 0, 1}],
    ArcCos[1/Sqrt[3]], {1, -1, 0}, {0, 0, 0}]];
path = First@Cases[Normal@curve2, Line[l_] :> l, Infinity];
tube = TubeMesh[path, 1/50]

If you still want to combine this with other Graphics3D objects, you can extract the polygons, and what you have is just like the original curve2 from the OP, except that it can be exported to STL easily
curve2G3D =
 Graphics3D[{ColorData[97][1], EdgeForm[None],
   MeshPrimitives[TubeMesh[path, 1/50], 2]}]


text:
Q: how can i loop through a json array requested from an api? im requesting information from the instagram api in php like this:
<?php $relation = $instagram->get('users/'.$item->id.'/relationship');
..

which return this json data array for me:
object(stdClass)#58(2){
    [
        "meta"
    ]=>object(stdClass)#59(1){
        [
            "code"
        ]=>int(200)
    }[
        "data"
    ]=>object(stdClass)#60(3){
        [
            "outgoing_status"
        ]=>string(7)"follows"[
            "target_user_is_private"
        ]=>bool(true)[
            "incoming_status"
        ]=>string(4)"none"
    }
}

note: i used var_dump($relation) to bring this out
what I'm trying to do is loop through this array and display the outgoing status and the incoming status i.e
loop(json-array){
echo outgoing_status;
echo incoming_status;
}

thank you very much..

A: You have an object (instance of stdClass, the generic object), not an array.
$outgoing_status = $response->data->outgoing_status;
$incoming_status = $response->data->incoming_status;

As a side note, use json_decode($json, TRUE) to return the data as an associative array instead of an object.


text:
Q: Navigation Drawer header image not clickable The imageview is not clickable . how do i make it clickable its located inside the drawer for showing a profile pic .
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    CircleImageView imageView = (CircleImageView)findViewById(R.id.imageView);
    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(DashboardMain.this, "image", Toast.LENGTH_SHORT).show();
        }
    });

A: Try
View header = navigationView.getHeaderView(0);
CircleImageView mImgView= (CircleImageView) header.findViewById(R.id.imageview);

if you have multiple headers
navigationView.getHeaderCount()

Ref:https://code.google.com/p/android/issues/detail?id=190226#c31

A:     View headerLayout = navigationView.getHeaderView(0);

    CircleImageView imageView = (CircleImageView)headerLayout.findViewById(R.id.imageView);


text:
Q: Red X on all folders So I have used Eclipse for a couple years now, and recently switched to Netbeans. I switched back to Eclipse, so I can work on some SQL projects, but when I opened Eclipse, a whole bunch of red x's appeared. I have never come across this before and don't know how to get rid of it.

A: Clean your projects, then check your JVM settings.
Open the "Project" menu and choose "Clean..." and then select "Clean all projects" and click "OK".
If this doesn't work, then check the project settings.  Make sure it is configured to use a JVM which is actually installed on your system.  My guess, since I can see standard JVM classes highlighted, is that you had chosen to globally use a specific JVM which is no longer installed on your system.


text:
Q: Django - Attach data to model that will not be saved to the database I need my django users to belong to an Office.
I did the following to extend the default user model:
class UserProfile(models.Model):
  user = models.OneToOneField(User)
  office = models.ForeignKey('Office')

My post_save signal for the user model calls this function:
def create_user_profile(sender, instance, created, **kwargs):
  if created:
    profile = UserProfile.objects.create(
      user = instance,
      office = instance.office
    )

I basically want to attach office to "instance". Which means when I create the user I do the following:
user = User(
      office = office,
      username = username,
      email = email,
      password = password
    )

But I get the error:

'office' is an invalid keyword argument for this function

Which is normal because office is not a field for the User model.
But is there a way to tell django to ignore this field, that this field is only here to "carry" information temporarily?

A: Just set the office as a simple attribute:
user = User(username=username, email=email)
user.set_password(password)
user.office = office
user.save()


text:
Q: Binary data in post request I have read the docs about http requests and wrote final this headers:
int *binary = new int[bufferLength]; // And fill it

std::stringstream out;
out << "POST /push1_pub?id=game HTTP/1.1\r\n";
out << "User-Agent: Lotosoft soccer client\r\n";
out << "Host: localhost\r\n";
out << "Accept: */*\r\n";
out << "Content-Type: application/octet-stream\r\n";
out << "Content-Length: " << bufferLength << "\r\n\r\n";

// Take out string from stream
std::string headers = out.str();
// Length of new array of bytes (headers + binary data + \0)
const int rawLen = headers.size() + bufferLength*sizeof(int) + 1;

char *raw = new char[rawLen];
// Copy headers data into bytes array
strcpy(raw, headers.c_str());
// Apply offset to bytes array and fill another part with binary array of ints
memcpy(raw+headers.size(), binary, bufferLength*sizeof(int));

std::cout << raw << std::endl;

// Send it to socket
if (socket.send(raw, rawLen) == -1)
{
    std::cout << "Failed to send headers\n";
}

Post request sends successfull, but I'm not sure everything is fine with my idea to fill everything into byte array. Is that the right way to pass binary data as post-request body?

A: Ask yourself this question: "What is the first byte of post data that I send to the server?". Do you see that you don't know -- it's whatever your platform happens to store as the first byte of the array, which will depend on how your particular CPU stores integers.
The server has no idea how your CPU stores integers, so you are sending it information there is no possible way it could make sense out of. You have to send the server a query that consists of bytes in whatever format the server expects, not whatever server your platform likes.
Also, you tell the server that you are going to send it bufferLength bytes, but then you send it bufferLength*sizeof(int) bytes. You must be consistent. (Presumably, you aren't on a platform that uses one-byte integers.)


text:
Q: Rudin's Topological Definition of an Open Set -- Does it Disagree with the Metric Space Definition? I wanted to share this definition of an open set, which made me uncomfortable. It comes from Rudin's Real and Complex Analysis and begins with the definition of a topology:
A collection $\tau$ of subsets of a set $X$ is called a topology in $X$ if $\tau$ has the following three properties:

*

*$\emptyset \in \tau$ and $X \in \tau$.

*If $V_i \in \tau$ for $i=1,\ldots,n$, then $V_1 \cap V_2 \cap \cdots \cap V_n \in \tau$ (closure under finite intersections).

*If $\{V_{\alpha}\}$ is an arbitrary collection of members of $\tau$ (countable or uncountable), then $\bigcup\limits_{a} V_{\alpha} \in \tau$ (closure under infinite unions).
If $\tau$ is a topology in $X$, then the ordered pair $(X,\tau)$ is called a topological space, and the elements of $\tau$ are called the open sets in $X$.
My question is -- doesn't this general definition disagree with the definition of open and closed sets from metric spaces? For example, what if we take $X=[0,5]$, which we would all agree is a closed set. By definition of the topological space $(X, \tau)$, we will have $[0,5] \in \tau$. So, then, according to the definition of an open set, since $[0,5]$ is a member of the topology we would call $[0,5]$ an open set. This seems wrong!
Or worse: What if we take one of the $V_i \in \tau$ to be the set $\{3\}$. Then $\tau = \{\emptyset, \{3\}, [0,5]\}$, which meets the three criteria above. Then since $\{3\} \in \tau$, then by this definition we would call $\{3\}$ an open set! We would never call a singleton an open set.
Or for a third example, let's put in one more set in the topology. What if we took a set we know to be open, say the interval $(1,3)$. Then our topology becomes
\begin{equation}
\tau=\{\emptyset, (1,3), \{3\}, (1,3], [0,5]\}
\end{equation}
since $(1,3) \cup \{3\}=(1,3]$. Now our topology has both open, closed, and clopen members!
Hopefully you guys can see why I'm bothered with this definition of an "open set".
Thanks for your thoughts!

A: There are multiple ways to define a valid topology on a given set. You are talking about all these things such as '$[0,5]$ cannot be an open set' in the context of standard topology on $\mathbb{R}$, which includes as 'open sets' all subsets that can be written as unions of disjoint open intervals, but if you define the topology on $\mathbb{R}$ otherwise things will be different.

A: This is an enlarged comment.
You seem to have a misunderstanding. What is the definition of a topology? Let's look at your first bullet. You have that $X\in\tau_X$. So, if $X=[0,5]$, then $[0,5]\in\tau_{[0,5]}$.
Why would a singleton not be an open set? Let $X$ be a topological space endowed with the discrete topology, and let $x\in X$. Then, since $\{x\}\subset X$, and $X$ has the discrete topology, we have that $\{x\}$ is an open set!
The usual topology is different from the discrete topology, etc., on any topological space. You're only considering the usual topology, which is what one learns in high-school calculus, etc.
I will not address the metric topology, as I believe that the other answers explain it pretty clearly. However, I will remark that the usual topology on $\mathbf{R}$, or on any subset of it, is the ordered topology, and this can be shown to coincide with the metric topology, which is what you're thinking about.

A: Started to write a comment, turned out too long.

$[0,5]\notin\tau$ in the Euclidean topology; $[0,5]^c=(−∞,0)\cup(5,∞)\in\tau$. $\tau$ denotes the collection of open sets; closed sets are not included in $\tau$. This axiomatic characterization of topological spaces should be thought of as the definition of a topology. In metric spaces, we're dealing with a special topology, the metric topology. According to this, a set $U$ is defined to be open if $\forall x\in U$ $\exists\varepsilon_x>0$ such that $B(\varepsilon_x,x)\subseteq U$. You can check that this construction of a metric topology satisfies the topology axioms. But, once again, this is merely a special case.
You say you would never call a singleton an open set. You're right if you are working with the standard Euclidean metric topology on $\mathbb R$. But, then again, this is only a special case of a topology, albeit a very natural and appealing one. In fact, you can define, on any non-empty set, a topology according to which every subset is open (and also closed). This is called the discrete topology. There are many possible ways to endow a set with topologies.
Also, when you define topologies on $\mathbb R$ other than the Euclidean metric topology, you should immediately forget about thinking in terms of the latter when talking about open sets in the new topology. Trying to compare which sets are open in different topologies can be very confusing if you're accustomed to the Euclidean definition of openness.

A: A metric space $X$ here isn't just a space that happens to have both a topology and a metric $d$; it's one in which the topology is generated by the open balls $B_r(x) = \{y\in X:\, d(x, y) < r\}$. Thus, for example, $\mathbb{R}$ with the usual topology and the metric $d(x, y) = |x - y|$ is a metric space; $\mathbb{R}$ with the finite-complement topology is just a topological space that happens to have a nice function defined on it.

A: Rudin is defining the concept of a topology on a set. For any given set, there may be several different topologies on it.
On a metric space $(X,d)$, one can define a topology on it by using the open balls as a basis. This will give one possible topology on $X$, the metric topology given by $d$ which you are probably familiar with.
However there are other topologies on $X$. For example, the discrete topology on $X$ consist of all subsets of $X$. This is the largest possible topology on any set $X$. Another example in the indiscrete topology consisting of just $X$ and $\emptyset$, which is the smallest topology.

A: Here is the abstract construction of the topology induced by a metric  $d$ on some space $X$. There is a base of open sets called open balls of radius $r$ centered at some point $x$ which is defined as the set $\{y \in X : d(x, y) < r\}.$ We allow $r$ to vary over the entire positive reals and $x$ to vary over all of $X$ to get a collection of open sets $B(r, x)$ for each such $r$ and $x$.
Then to construct the full topology, we throw in all unions of such sets (finite intersections automatically get added this way.)
In the example of the real numbers this implies that the open sets are exactly the unions (possibly infinite) of the open intervals $(a, b)$.
Where I think you've got confused is in the notion of "a" topology on the real numbers versus the topology induced by the metric. The collection $\tau$ that you defined, after throwing in the entire real line is certainly "a" topology on the reals but it is not the topology that comes from the metric space structure.


text:
Q: Java - How to use a variable(non hardcoded) value in printf statement after decimal point? I want to use a non hard coded value after decimal point in printf statement . Below is my code . Instead of 4 I want to set to x.
int x = sc.nextInt();
double d=103993d/33102d;
System.out.printf("%.4f", d);

A: Declare a variable and concatenate with the formatting string as below
double d=103993d/33102d;
int x=9;
System.out.printf("%."+x+"f", d);

OUTPUT:-
3.141592653

A: Use String in printf.
    int x = sc.nextInt();
    double d=103993d/33102d;
    String s1 = Integer.toString(x);
    String s="%."+s1+"f";
    System.out.printf(s,d);


text:
Q: correlation of pairs of features I have $N$ subjects, $s_1,s_2,\dots,s_N$. I calculated the similarity of each pair of those subjects based on certain features which results in a similarity matrix, $S\in\mathbb{R}^{N\times N}, 0\le S_{ij}\le1, S_{ii}=0$. I also have the ages of the subjects, $a_1,\dots,a_n$. I want to test the hypothesis that if two subjects are very similar, then they are also in the same age group. More specifically, I am interested in finding the relationship between the most similar subjects per each row of the matrix $S$ (In other words, the subjects pair that gives the max similarity per each row) and their ages. Formally, let the set $D$ represents the pairs of subjects that have the highest similarity per each row, $D=\{(s_1,s_{k_1}),\dots,(s_N,s_{k_N})\},s_{k_1}\in\{2,\dots,N\}, ,s_{k_2}\in\{1,3,\dots,N\},\dots,s_{k_N}\in\{1,\dots,N-1\}$
Let the set $A$ be the corresponding age pairs of the set $D$, $A=\{(a_1,a_{k_1}),\dots,(a_N,a_{k_N})\}$. I would like to test the hypothesis if $d(s_1,s_{k_i}) \rightarrow 0$, then $d(a_1,a_{k_i})\rightarrow 0$, where $d$ is the distance.
Here is a thought but I think it is statistically not robust as it does not give a p-value for my hypothesis: I create another similarity matrix based on the ages $S^a\in\mathbb{R}^{N\times N}, 0\le S_{ij}^a\le1$. However, one caveat is that the similarity function that is used for ages is not the same as the similarity function used in calculating the similarity for the subjects' features. Nontheless, I vectorize the two similarity matrices and then calculate the cosine similarity


text:
Q: Oracle10g database DMBS_CRYPTO error I have the following source code modified from this example to use NUMBERS instead of VARCHAR2.
CREATE OR REPLACE PACKAGE gen_encr
AS
    FUNCTION encrypt (p_PlainText NUMBER) RETURN RAW DETERMINISTIC;
    FUNCTION decrypt (p_Encrypted RAW) RETURN NUMBER DETERMINISTIC;
END;
/

CREATE OR REPLACE PACKAGE BODY gen_encr
AS
EncryptionType PLS_INTEGER := DBMS_CRYPTO.ENCRYPT_AES256
                           + DBMS_CRYPTO.CHAIN_CBC
                           + DBMS_CRYPTO.PAD_PKCS5;

EncryptionKey RAW (32) := UTL_RAW.cast_to_raw('ThisTextIsMyEncryptionKeyForThisPackage');

FUNCTION encrypt (p_PlainText NUMBER) RETURN RAW DETERMINISTIC
    IS
        encrypted_raw      RAW (1024);
    BEGIN
        encrypted_raw := DBMS_CRYPTO.ENCRYPT
        (  src => UTL_RAW.CAST_FROM_NUMBER (p_PlainText),
           typ => EncryptionType,
           key => EncryptionKey
        );
   RETURN encrypted_raw;
END encrypt;

FUNCTION decrypt (p_Encrypted RAW) RETURN NUMBER DETERMINISTIC
    IS
        decrypt_raw      RAW (1024);
    BEGIN
        decrypt_raw := DBMS_CRYPTO.DECRYPT
        (   src => p_Encrypted,
            typ => EncryptionType,
            key => EncryptionKey
        );
    RETURN (UTL_RAW.CAST_TO_NUMBER (decrypt_raw));
END decrypt;
END;
/

However, when i ran the statement SELECT sys.gen_encr.encrypt(sal) FROM emp, I get the following error.
ORA-06502: PL/SQL: numeric or value error: raw variable length too long
ORA-06512: at "SYS.GEN_ENCR", line 13

Some google searching suggested the error might be that the RAW datatype can only accept 2000bytes.
However, in this case I don't see why there is an error. Any help is appreciated.

A: This is dead simple: your key is too long.  It is 37 characters which you're attempting to stuff into a RAW(32) variable.  Shorten it to 32 characters and that error will disappear.


text:
Q: Getting to grips with Google Guice I'm just starting to play around with Google Guice as a dependency injection framework and am attempting to retrofit it to a small to medium size project I recently wrote.  I understand the basics of how Guice works, but am a bit vague on some of the approach details.  For example:
1) Modules are used to define your bindings, which are then fed into the injectors.  Do you tend to put everything into one module or do you tend to break things down into lots of smaller modules?
2) Do you have one injector at the top level which injects the entire object tree or multiple injectors dotted about which only inject those dependencies you really need to inject?  I'm thinking here of my own code base which, of course, has many dependencies, but only a small handful which I need to control during testing.
3) I'm slightly stuck on the best way to get my system/integrations tests using test-environment-only modules instead of the production verions.  This question is likely implementation specific, but I'm curious what methods people use.  For reference, my app is a servlet based web app.
Any other pointers?

A: 1) Typically you'll break things down into multiple modules. One of the goals of Guice is to help make code modular, and that's what modules are there for. How you break this down is up to you (and obviously, you don't absolutely have to). One advantage of finer grained modules is that you can define modules within a particular package and make the classes that implement the interfaces package-private. Since the module is in the package, it can bind those concrete classes and they can be used for configuring the Injector (in another package). Additionally, you make your code more flexible when you can change how something is done by just changing out one module for another, rather than having to change code in a single monolithic module.
2) Yes, one injector at the top level injecting the whole object tree is the way things should generally be done. This comes back to the modules thing... use them to break dependencies down in to groups and use one injector.
3) Use a different entry-point class that configures the injector. For a standalone app, I'd have a different main class... for a webapp, I suppose you could make a separate GuiceServletContextListener for testing. Then you can replace whole modules with modules for testing, or use Modules.override to override a binding in a specific module, etc.

A: Take a look at the book Dependency Injection - it covers both Guice and Spring, so is very handing transitioning from one framework to the other. Definitely good if you already understand the principles behind IoC already.


text:
Q: addEventListener onload can be set or not I have the follow code
cost.addEventListener('keyup', updateInput);
quantity.addEventListener('keyup', updateInput);

they update inputs if I change something but I have a input that must be autofilled when page load
The input 1 has the product price cost comming from MySQL
I have another input quantity with default value set to 1
The input 3 changes to total cost perfect using cost * price IF I change quantity manually but when page load it show some addEventListener to the cost * quantity onload and not only when I manually do it editing quantity?
something like
totalcost.addEventListener('onpageload', updateInput);

A: If you want to run some code when the page first loads, you can do that in jQuery with this (you tagged your question with jQuery so you may as well use it):
$(document).ready(function() {
    // put your code here that runs when the page first loads
});

Or, you can do this in plain Javascript:
window.addEventListener("load", function() {
    // put your code here that runs when the page first loads
});

A: when you're using addEventListener to register event handlers, you need to pass the event name as string without on, so it should be load event in case of page load
window.addEventListener('load', updateInput);

For a complete list of supported browser events, have a look at this.

A: So, assuming your situation, I have put together a demo with the following code. All you need to do is to invoke the function that does the calculation when page is loaded as well.

var f = document.querySelector("#first");
var s = document.querySelector("#second");
var r = document.querySelector("#result");

function updateInput() {
    r.value = parseFloat(s.value) * parseFloat(f.value);
}

f.addEventListener("keyup", updateInput);
s.addEventListener("keyup", updateInput);

//Additional line to trigger the function when page is loaded.
window.addEventListener("load", updateInput);
<input type="text" id="first" value="10" />
<input type="text" id="second" value="3" />
<input type="text" id="result" value="" readonly="" />

The values of the first 2 inputs are multiplied and the result is displayed in the last input, on key up and page load. Hope that helps.


text:
Q: how to select unselected (not :selected) items in jquery? I'm looking for that selector that is the inverse of :selected.
It has to select every checkbox that are not selected.
I have tired this way, but it does not worked:
$("#cont").find("input[type=checkbox]:not(:selected)")

A: Selector :selected is used primarily for options in <select>. For checkboxes and radio buttons you should use :checked selector.
$("#cont").find("input[type=checkbox]:not(:checked)");

A: Checked property is of input
$("#cont").find("input[type=checkbox]:not(:checked)");


text:
Q: How can i chose my icon based on a string I am getting a lot of strings whos' names are those of icons. If I try to create and Icon with a string as name
Icon(
   Icons._transactionType
)

I get 'the getter _transactionType is not defined for for the class 'Icons''.
That is all the ideas I had so far, and also the flutter docs for icon and icons didn't help.
As of now i have hardcoded the icons in, but since i am now storing them in .json, i can only save them in strings, and i want to avoid a method that goes through all icons and choses the one i need.
Here you see it working now, and i want to get the icon istead of with 'Icons.train' with 'Icons._transactionType'

A: One way is to create a map
Map<String, IconData> iconMapping = {
 'train' : Icons.train,
 'airplane' : Icons.airplanemode_active,
 ...
};

and while using, instead of Icon(Icons._transactionType) use Icon(iconMapping[_transactionType])


text:
Q: Performance of JavaScript else if Just wanted to understand if following two statements differ in performance and execution (I understand the best practice though)
if (condition) {
    do something;
}
else if (another condition) {
    do something else;
}

and
if (condition) {
    do something;
} else {
    if (another condition) {
        do something else;
    }
}

Thanks

A: For explaining sake this:
if (condition) {
    do something;
}
else if (another condition) {
    do something else;
}

could be written like that:
if (condition) {
    do something;
}
else
    if (another condition) {
        do something else;
    }

Since the else has only one statement (the if statement) in its body, the braces ({ and }) are optional so the second code above is the same (with or without the braces) as:
if (condition) {
    do something;
}
else {
    if (another condition) {
        do something else;
    }
}

When a for, while, if or else has only one statement in its body the braces become optional. So this:
for(var i = 0; i < 7; i++)
    if(i == 5) {
        do something;
    }

is the same as:
for(var i = 0; i < 7; i++) {
    if(i == 5) {
        do something;
    }
}

THE SHOCKING TRUTH IS THAT THERE IS NO SUCH THING AS else if. IT'S JUST AN if STATEMENT INSIDE THE BODY OF AN else STATEMENT.


text:
Q: HEAD request missing content-type on redirect (301) requests.head('http://randwalk.com/s/s16.pdf',timeout=1).headers

gives me
{'date': 'Sat, 23 Nov 2019 05:08:07 GMT', 'location': 'https://randwalk.com/s/s16.pdf', 'Age': '862', 'Set-Cookie': 'crumb=BZlltCLt+KDBZWFjYTlkODk3NzJjMTY0OThkOGI0M2FhMjQyNWZk;Path=/', 'x-contextid': '5hfZYmvv/QLoMH3KZ', 'server': 'Squarespace'}

It would be better if it had the content-type field.
For example, if I put the redirect URL straight in
requests.head('https://static1.squarespace.com/static/4ff39269c4aaf3fdb14faa05/t/50e6153fe4b0b7c7226f31a9/1357255999121/s16.pdf',timeout=1).headers

I get
{'timing-allow-origin': '*', 'content-type': 'application/pdf', 'cache-control': 'public, max-age=94608000', 'pragma': 'cache', 'x-contextid': '03YpYLSg/2vS31Z4Q', 'server': 'Squarespace', 'Via': '1.1 varnish, 1.1 varnish', 'Content-Length': '3429468', 'Accept-Ranges': 'bytes', 'Date': 'Sat, 23 Nov 2019 05:24:44 GMT', 'Age': '79996', 'Connection': 'keep-alive', 'X-Served-By': 'cache-dfw18628-DFW, cache-tyo19924-TYO', 'X-Cache': 'HIT, HIT', 'X-Cache-Hits': '1, 1', 'X-Timer': 'S1574486684.023261,VS0,VE5', 'Vary': 'Accept-Encoding', 'Tracepoint': 'Fastly'}

A: Setting
    allow_redirects=True
did the trick.
I thought that was the default, guess not.


text:
Q: How to solve "Manage your energy"? I read an optimisation problem about energy in Google Code Jam. (The contest is over now, so it's okay to talk about it)

You've got a very busy calendar today, full of important stuff to do.
  You worked hard to prepare and make sure all the activities don't
  overlap. Now it's morning, and you're worried that despite all of your
  enthusiasm, you won't have the energy to do all of this with full
  engagement.
You will have to manage your energy carefully. You start the day full
  of energy - E joules of energy, to be precise. You know you can't go
  below zero joules, or you will drop from exhaustion. You can spend any
  non-negative, integer number of joules on each activity (you can spend
  zero, if you feel lazy), and after each activity you will regain R
  joules of energy. No matter how lazy you are, however, you cannot have
  more than E joules of energy at any time; any extra energy you would
  regain past that point is wasted.
Now, some things (like solving Code Jam problems) are more important
  than others. For the ith activity, you have a value vi that expresses
  how important this activity is to you. The gain you get from each
  activity is the value of the activity, multiplied by the amount of
  energy you spent on the activity (in joules). You want to manage your
  energy so that your total gain will be as large as possible.
Note that you cannot reorder the activities in your calendar. You just
  have to manage your energy as well as you can with the calendar you
  have.
Input
The first line of the input gives the number of test cases, T. T test
  cases follow. Each test case is described by two lines. The first
  contains three integers: E, the maximum (and initial) amount of
  energy, R, the amount you regain after each activity, and N, the
  number of activities planned for the day. The second line contains N
  integers vi, describing the values of the activities you have planned
  for today.
Output
For each test case, output one line containing "Case #x: y", where x
  is the case number (starting from 1) and y is the maximum gain you can
  achieve by managing your energy that day.

How can this problem be solved? I was thinking if it could be solved by Dynamic Programming. Any leads?

A: It can simply be done by recursion, code attached below: here status is the array for v as in problem
    public static long calculate(long limit,long initialEnergy,long R,long[] status,int start){
    long leftEnergy = 0;
    long  maxGain = 0;
    if(start + 1 > status.length){
        return  0;
    }
    for(long taskEnergy = initialEnergy; taskEnergy>=0;taskEnergy--){
        leftEnergy = initialEnergy - taskEnergy + R;
        if(leftEnergy > limit){
            leftEnergy = limit;
        }
        long gain = status[start] * taskEnergy + calculate(limit,leftEnergy, R, status, start +1);
        if(gain > maxGain){
            maxGain = gain;
        }
    }
    //System.out.println(start + " " +  maxGain);
    return maxGain;
}

A: Imagine the energy spent on each activity as a coordinate in a multi-dimensional space. Imagine the gain earned as the temperature of the point in that multi-dimensional space. (Treat impossible combinations as having zero gain.) This reduces the problem to "find the hottest point in a room". And that's easy -- start anywhere (probably, for simplicity, start with zero energy spent on each activity since at least that's guaranteed to be legal), keep moving in any direction that makes it hotter, and stop when no direction makes it hotter.
Intuitively, it seems to me like you can't get stuck in a local maximum (because the output is a linear, clamped function of the input). But if you're worried about it, when you stop, "kick yourself" in a random direction and try again. If you repeat this a few times and land consistently in the same spot, you can be reasonably confident that's the global maximum.
To use a gravity metaphor, essentially, you map the problem to a space. You map the best solution to the lowest point in the space. Then it's as easy as just falling to the bottom.


text:
Q: Binding to NSUserDefaults that Contains an Array of Dictionaries I have an NSUserDefaults item that is an array of dictionaries. Each dictionary in this array corresponds to an object that defines the properties I care about on an NSMenuItem. One of those key/value properties in each dictionary is a boolean that defines whether the menu item should be shown or hidden. The key for this value is "show". Here's a visual example:
MenuItems      (Array)
  Item 0       (Dictionary)
    label      (String)      "Menu Item 1"
    show       (Boolean)     YES
  Item 1       (Dictionary)
    label      (String)      "Menu Item 2"
    show       (Boolean)     NO

In this case, the first menu item would be shown but the second wouldn't. I want this to dynamically update as user defaults change (through a preference pane).
Ideally I'd like to bind the "hidden" attribute on the NSMenuItem directly to the corresponding "show" value. Unfortunately, according to NSMenuItem Bindings, hidden is not something that can be bound. But I tried anyway, and am not sure what I'm doing will even work. The difficulty lies in the fact that this is an array of dictionaries, and it's not clear to me how bindings would work here. I have an NSArrayController bound to the sharedUserDefaults MenuItems, and I can see the various pieces of data through the arrangedObjects while debugging.
I've tried lots of things:

*

*Binding directly to the dictionary value

*Creating a wrapping NSObjectController for each dictionary and binding to the keypath "content.show"

*Observing the dictionary itself through addObserver:forKeyPath:options:context

*Observing the wrapped NSObjectController as described above.

None of these cause anything to happen. Observing the NSArrayController's arrangedObjects directly does, however, trigger observeValueForKeyPath:... but that's really not much different than just going for the whole hog and using NSUserDefaultsDidChangeNotification.
Is there a way to tackle this through bindings or KVO that will get me down to the level of detail I'm looking for?

A: MenuItem hidden property can be bound, it's in the list of choices in IB.  However, you can't bind to an object in an array, there's now way to say, in effect, array.object1.  I think you could do what you want if you make your user defaults a dictionary of dictionaries -- the keys at the top level could be "menuItem1", "menuItem2", etc with the value being a dictionary with all the other keys you need.  It's hard to tell if this would work without knowing what else you have in your user defaults.  If it could work, you could get to the info you want with valueForKeyPath: like dict.menuItem1.show


text:
Q: How to make a text with smaller width stay on a image with 100% width even if the screen is resized? How to make a text with smaller width stay on a image with 100% width even if the screen is resized? I want that the text stays on the background. At the moment the text goes outside of the image when I make the screensize smaller I tried everything and I can't find a good solution for it. Please help!
HTML(Ruby on Rails)

 <%= image_tag("x.png" class="background") %>

 Feel free to reach out to me with anything that's on your mind. I'm always
   happy to hear from people and I'll respond as quickly as possible.

CSS Part
.outer-wrapper {
}

.background {
min-width: 100%;
margin: 0 auto;
display: block;
position: relative;
height: 900px;
}

.inner-wrapper {
width: 41%;
height: 100%;
margin: 2% auto;
left: 0;
right: 0;
position: absolute;
top: 172%;
}


text:
Q: Monitoring PostgreSQL backup I am new to PostgreSQL and have questions regarding the backup procedure.
How do I check whether a PostgreSQL database was backed up successfully?
And how do I monitor the backup?
I have tried the following command to backup the database, but there's no output:
pg_dump [connection-option...] [option...] [dbname]

A: The test is to restore the backup somewhere else.
Monitoring can be done via the return code of pg_dump: if that isn't 0, something went wrong.


text:
Q: CSS rotate 2 images in opposite directions over avatar image When hover the central image this should animate 2 circles parts in opposite directions at the same time. Until now i only manage to animate them separetly by hovering the 2 objects separetly.
Here is the goal:

Here is my CodePen:
http://codepen.io/beng_beng/pen/Azstr

A: You should use :hover on the a#rotator instead:
a#rotator:hover > img{
 -webkit-transform: rotate(-360deg);
 -moz-transform: rotate(-360deg);
 -o-transform: rotate(-360deg);
 -ms-transform: rotate(-360deg);
}

a#rotator:hover span img{
 -webkit-transform: rotate(360deg);
 -moz-transform: rotate(360deg);
 -o-transform: rotate(360deg);
 -ms-transform: rotate(360deg);
}

Demo.


text:
Q: Visual Studio 2013 libgit2 error I'm trying to set up git with VS2013 by following these instructions:
How do I add an existing Solution to GitHub from Visual Studio 2013
However in Home | Unsynced Commits, I get the following error:
An error occurred. Detailed message: An error was raised by libgit2. Category = Unknown (Error).
No error message has been provided by the native library

Considering that the error message is very unclear, I don't know where to start troubleshooting.
EDIT: The error occurs not only with Unsynced Commits, but with Changes and Branches as well.

A: Please refer to this answer : https://stackoverflow.com/a/20004092/3286583
I was also getting the libgit2 error. It was an issue because of "Initialize this repository with a README.md".
For removing the solution from source control, close Visual Studio and delete the .gitattributes, .gitignore and ".git" folder. Now reopen the solution and try again with above mentioned answer's method.


text:
Q: How to export CloudWatch Dashboard data to share with people with no AWS account. I set up monitoring and alarms about active connections to the loadbalancer, CPU and Memory usage from all of my instances with CloudWatch. And my client (the owner of the product in the website) wants me to share all these numbers and possibly graphs of those so he can see how the system is behaving, etc. He doesn't have an AWS account.
Is there any feature in CloudWatch that can give me these results, graphs or numbers?

A: We use Datadog for some of our devops analytics.  If you want something more hands on, you can setup Grafana, it has a plugin to pull data from CloudWatch.

A: From Reduce Time to Resolution with Amazon CloudWatch Snapshot Graphs and Alerts | AWS DevOps Blog:

You can use snapshot graphs to integrate and display CloudWatch charts outside of the AWS
  Management Console to improve monitoring visibility or reduce time to resolution. This feature
  makes it possible for you to display CloudWatch charts on your webpage or integrate charts with
  third-party tools, such as ticketing, chat applications, and bug tracking.

Also see part 2: Building an Amazon CloudWatch Dashboard Outside of the AWS Management Console | AWS DevOps Blog

A: A new AWS feature was added that allows for the creation of a shareable link to any cloudwatch dashboard -- whether or not you are logged in to an AWS account or were granted permissions.  Hand the link to the 3rd party.
We have added them to our wiki pages.  Still trying to figure out how to render the dashboards in confluence pages, but the link itself works fine.
CW dashboard sharing

A: I struggled with the same problem, and came up with an API that you can use to create public versions (semi-public, using a pre-signed s3 url) for Cloudwatch dashboards.
Here's a link to the documentation enter link description here.
Disclaimer : this is not 100% free, for heavy use and frequently updated dashboards, there's a small price using a rapidapi subscription.


text:
Q: The set of all functions from $\mathbb{N} \to \{0, 1\}$ is uncountable? How can I prove that the set of all functions from $\mathbb{N} \to \{0, 1\}$ is uncountable?
Edit:  This answer came to mind.  Is it correct?
This answer just came to mind.  By contradiction suppose the set is $\{f_n\}_{n \in \mathbb{N}}$.  Define the function $f: \mathbb{N} \to \{0,1\}$ by $f(n) \ne f_n(n)$.  Then $f \notin\{f_n\}_{n \in \mathbb{N}}$.

A: Hint: Show that $\{0,1\}^\mathbb N$ is equinumerous with $\mathcal P(\mathbb N)$ and use Cantor's theorem to conclude there is no bijection between $\mathbb N$ and $\mathcal P(\mathbb N)$.

A: You can proof it by contraposition.
I will identify the functions with sequence so $a_{n}$=$a(n)$. Now lets say it's countable, now let $a_{nk}=a_k(n)$ be the $k$-th function. Now we construct the function
$$b(k)=\left\{ \begin{array}{rl} 1 & a_{kk}=0\\ 0& a_{kk}=1\end{array}\right.$$
You should be able to do the rest.

A: Hint : use the diadic developpement of elements of $[0,1]$.

A: Hint: Each function from $\mathbb{N} \to \{0, 1\}$ is isomorphic to a subset of $\mathbb{N}$. Simply count $n \in \mathbb{N}$ to be part of the subset of $f(n) = 1$.


text:
Q: New secret achievements in RETRY The latest version (1.5.0) released last week added a few achievements, "Shoe Size: Monster", "Cryptozoology Breakthrough", "Mechanical Rowboat", "That About Wraps It Up" and "Meow Meow Meow!". They're intended to be secret, since there's no indication how to unlock them at all, except very, very vague hints about where you're likely to find them.
I only managed to unlock the last one because it's obvious to those who finished the game. But what about the others? How to unlock them?

A: For the sake of completeness, I'll just list all the new secret achievements.
Summer, Shoe Size: Monster (originally posted by andbeyond)

 On W1's level 28: Moving Around, fly to the 5th Retry Point. It should be nested in a little cave in which you flip into. There will be a bulldozer above you and a bush below you. If you sit on the retry point for a short while, Bigfoot will start waving at you from the bush. You will earn the achievement without needing to tap anything.

Winter, Cryptozoology Breakthrough

 On W1's level 32: Flying High, go to the 3rd Retry Point, where there is a snowy platform with a gray rock below the runway. Just wait a while and a yeti will come out and wave. You will earn the achievement without needing to tap anything.

Future, Mechanical Rowboat

 On W1's level 38: Clockworks, go to the 4th Retry Point, which is right after the slow-motion section with the three rotating plus-signs. There is a platform in the shape of a small boat below the runway, casting a shadow. Wait until a blue robot comes out of it and waves. You will earn the achievement without needing to tap anything.

Pyramids, That About Wraps It Up

 On W1's level 55: Deep Dive, go to the 5th Retry Point. A platform with a bush should be visible below the runway. Wait until a mummy comes out and waves. You will earn the achievement without needing to tap anything.

Cat, Meow Meow Meow!

 Tap the cat that shows up after beating W1's B11


text:
Q: Multidimensional Array as html-table entries per day among themselves is there a easy way to build from this multidimensional array a HTML-Table in this Format:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Otto Monday
Fritz Tuesday

Christine Thursday

Otto Saturday
Otto Sunday

Anna Monday

$calendar["Monday"][] = "Otto Monday";
$calendar["Monday"][] = "Anna Monday";
$calendar["Tuesday"][] = "Fritz Tuesday";
$calendar["Wednesday"][] = "";
$calendar["Thursday"][] = "Christine Thursday";
$calendar["Friday"][] = "";
$calendar["Saturday"][] = "Otto Saturday";
$calendar["Sunday"][] = "Otto Sunday";

I have this:

    //Make the table header
    <?php
    foreach ($calendar as $printout) {
        echo "" . key($calendar) ."	";
next($calendar);
    }
    ?>

If a want the Names in one row, I understand, but what is the code when I sort the names per day  among themselves?

A: You can achieve this by looping through the array.
$calendar["Monday"][] = "Otto Monday";
$calendar["Monday"][] = "Anna Monday";
$calendar["Tuesday"][] = "Fritz Tuesday";
$calendar["Wednesday"][] = "";
$calendar["Thursday"][] = "Christine Thursday";
$calendar["Friday"][] = "";
$calendar["Saturday"][] = "Otto Saturday";
$calendar["Sunday"][] = "Otto Sunday";

$daynames = array_unique(array_keys($calendar));
echo "
\n
\n";
foreach($daynames as $dayname) {
    echo "$dayname	\n";
}
echo "
\n";

$rownumber = 0;
do {
    $count = 0;
    $notes = [];
    foreach ($daynames as $dayname) {
        $note = $calendar[$dayname][$rownumber] ?? '';
        if($note) {
            $count++;
            $notes[] = $note;
            continue;
        }
        $notes[] = '';
    }
    if($count > 0) {
        echo "
\n", join('', array_map(fn($note) => "$note	", $notes)), "
\n";
        $rownumber++;
    }
} while($count > 0);

echo "
\n";

will give

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Otto Monday
Fritz Tuesday

Christine Thursday

Otto Saturday
Otto Sunday

Anna Monday

Update
Refering to your comment making them Links you could change to
echo "
\n";
foreach($notes as $note) {
    printf("%s	", urlencode($note), $note);
}
echo "
\n";

A: $calendar['Monday'] = [ 'Otto Monday', 'Anna Monday' ];
$calendar['Tuesday'] = [ 'Fritz Tuesday' ];
$calendar['Wednesday'] = [];
$calendar['Thursday'] = [ 'Christine Thursday', 'More Thursday', 'Third Thursday' ];
$calendar['Friday'] = [];
$calendar['Saturday'] = [ 'Otto Saturday' ];
$calendar['Sunday'] = [ 'Otto Sunday' ];

$countOfRows = max(array_map(fn($item) => count($item), $calendar));

for ($index = 0; $index < $countOfRows; $index++) {
  foreach ($calendar as $day => $items) {
    $rows[$index][$day] = ( array_key_exists($index, $items) ) ? $items[$index] : '';
  }
}

print_r($rows);

Output:
Array
(
    [0] => Array
        (
            [Monday] => Otto Monday
            [Tuesday] => Fritz Tuesday
            [Wednesday] =>
            [Thursday] => Christine Thursday
            [Friday] =>
            [Saturday] => Otto Saturday
            [Sunday] => Otto Sunday
        )

    [1] => Array
        (
            [Monday] => Anna Monday
            [Tuesday] =>
            [Wednesday] =>
            [Thursday] => More Thursday
            [Friday] =>
            [Saturday] =>
            [Sunday] =>
        )

    [2] => Array
        (
            [Monday] =>
            [Tuesday] =>
            [Wednesday] =>
            [Thursday] => Third Thursday
            [Friday] =>
            [Saturday] =>
            [Sunday] =>
        )

)

And the HTML can then be generated like this:
$thead = '

';
foreach(array_keys($calendar) as $day) {
  $thead .= "$day	";
}
$thead .= '

';

$tbody = '
';
foreach($rows as $row) {
  $tbody .= "
";
  foreach($row as $value) {
    $tbody .= "$value	";
  }
  $tbody .= "
";
}

$table = "
$thead$tbody
";

echo $table;


text:
Q: Trying to use concat de-muxer in ffmpeg to concatenate files with named pipes I am trying to concatenate files with named pipes in node js using child process and ffmpeg.
I tried to give the text input in this format:
file 'pipe:3'
file 'pipe:4'

But this doesn't work as 'pipe' is not in the whitelist
Then I added 'pipe' to the protocol-whitelist. This doesn't help either, and the console outputs a bunch of gibberish.
What should I do now? This is my current spawn command.
const command = spawn('ffmpeg', ['-f', 'concat', '-safe', '0', '-protocol_whitelist', 'file,pipe', '-i', 'data/' + mergedVideoName + '.txt', '-c', 'copy', '-f', 'ismv', 'pipe:1'], {
        stdio: pipes
    })

Here, pipes are just the array with the required number of 'pipe' strings.
I wanted to pass some streams via pipe method to the input directly instead of using the file system,.
Edit:
I tried this again and now the stderr output is not gibberish, but I still can't get it to work.
Here is the code for the file:
https://pastebin.com/1GgCWGWk
I am able to get the first video as output, but not the next videos.
As for the log from stderr, I mainly get this as the error:
[ismv @ 0000021c2ce14840] Non-monotonous DTS in output stream 0:0; previous: 273834031, current: 159533333; changing to 273834032. This may result in incorrect timestamps in the output file.

I also get this error:
[ismv @ 0000021c2ce14840] Track 0 starts with a nonzero dts 333333, while the moov already has been written. Set the delay_moov flag to handle this case.

And this error right at the end:
data: [concat @ 000001b4bebf5c00] Impossible to open 'pipe:5'
data/4ed57360-d5f8-11ec-b35f-7b4d7aa196cd.mp4.txt: Invalid data found when processing input

How do I solve these problems?


text:
Q: Circuit symbol for ammeter with output What is the correct symbol for an ammeter that measures 0..200 mA and generates 0..2 V proportional output?

A: We don't normally call that an ammeter, but a current-controlled voltage source. One common symbol is this (courtesy of Wikimedia):

Text next to the symbol should indicate how it's controlled. For example, "\$I_1\times{}10\Omega\$".
If you want to represent a physical device that has this function, you'd probably just use a rectangular box with pins corresponding to each of the physical pins.

A: That's the same as a current controlled voltage source, a CCVS. The symbol looks like a diamond with an equation next to it. In your case, V=10A.


text:
Q: C# EF Random Order causes related list disappear I got a Problem with my API. I want to get a random amout of questions back.
The Model of my question has a list of answers and hints:
public class Question
{
    public int Id { get; set; }
    public string Text { get; set; }
    public string Explanation { get; set; }
    public Category Category { get; set; }
    public ICollection<Answer> Answers { get; set; }
    public ICollection<Hint> Hints { get; set; }
}

normally if i call my get method i get a json with all the lists back
return _ctx.Questions.Include(x => x.Answers).Include(x => x.Hints).ToList();

 {
    "id": 1,
    "text": "Test?",
    "explanation": "Test",
    "category": null,
    "answers": [
        {
            "id": 1,
            "text": "Test",
            "isCorrect": true
        },
        {
            "id": 2,
            "text": "Test1",
            "isCorrect": false
        },
        {
            "id": 3,
            "text": "Test2",
            "isCorrect": false
        },
        {
            "id": 4,
            "text": "Test3",
            "isCorrect": false
        }
    ],
    "hints": [
        {
            "id": 1,
            "text": "..."
        },
        {
            "id": 2,
            "text": "..."
        }
    ]
}

But if I want to get random picks with a orderby i only got empty lists
return _ctx.Questions.Include(x => x.Answers).Include(x => x.Hints).OrderBy(o => Guid.NewGuid()).Take(amount).ToList();

{
        "id": 1,
        "text": "test",
        "explanation": "..-",
        "category": null,
        "answers": [],
        "hints": []
    }

Does someone have a Idea to fix this?

A: After sql need to be a list. I got a similar problem a long time ago.
Hope it s help, was with an older version of Ef.
So you have to add a ToList before the OrderBy.
return _ctx.Questions.Include(x => x.Answers).Include(x => x.Hints).ToList().OrderBy(o => Guid.NewGuid()).Take(amount).ToList();


text:
Q: Reactjs how to make the inputs in them work independently of each other, when you add a form button? How can I make the state in the added forms work independently of changes in other similar forms?
Forms are added through locationAdd
    const LocationBody = ({filteredServersData, locationAdd,
       deleteLocationCell, handleChangeFilter,
       filters, locationsData, envsData }) => {
       const classes = useStyles();

    const locationsSelect = locationsData.map((item) => {
       return <MenuItem key={item.locationID} value={item.locationID}>{item.name}</MenuItem>;
    })

    const envsSelect = envsData.map((item, index) => {
       return <MenuItem key={index} value={item.envID}>{item.name}</MenuItem>;
    })

    const serversSelect = filteredServersData.map(item => <Typography variant="h6" component="h1">
    {item.name}
    </Typography>)

       return (
          <div>
             {locationAdd.map(i => <Container className={classes.root} key={i.id}>
                <Grid container spacing={3} className="arr">
                   <Grid item xs={12}>
                      <Box display="flex" justifyContent="space-between">
                         <Typography variant="h5" component="h1">
                            Тестовая локация {i.id}
                         </Typography>
                         <IconButton
                            aria-label="delete" color="secondary"
                            className={classes.margin}
                            onClick={() => deleteLocationCell(i)}>
                            <DeleteIcon fontSize="medium" />
                         </IconButton>

   </Box>
               </Grid>
               <Grid item xs={12} className={classes.filtersContainer}>
                  <Box display="flex" justifyContent="space-between">
                     <Box display="flex" className={classes.fieldsContainer}>
                        <Typography variant="h6" component="h1">
                           Локация
                  </Typography>
                        <FormControl variant="outlined">
                           <Select
                              value={filters.locationID}
                              onChange={handleChangeFilter}
                              label="LocationID"
                              labelId="locationID"
                              name="locationID"
                           >
                              {locationsSelect}
                           </Select>
                        </FormControl>
                        <FormControl variant="outlined">
                           <Select
                              value={filters.envID}
                              onChange={handleChangeFilter}
                              label="EnvID"
                              labelId="envID"
                              name="envID" >
                              {envsSelect}
                           </Select>
                        </FormControl>
                        {serversSelect}
                     </Box>
                  </Box>
               </Grid>
            </Grid>
         </Container>)}
      </div>
   )
}

A: You can create a new component for added forms and each component will handle its own state only, without sharing it with other siblings.
Or, if you don't want to create a new component, and want to keep the current code as it is, you may differentiate each form's state by prefixing it with the form's unique ID.


text:
Q: How to get free/busy information to unlock for "resource calendars" in Outlook with Exchange 2003? So, I know Exchange 2003 isn't supported anymore, there's a migration going on longterm.  However for now, we have to do with what we have.
We created users dedicated to share calendars each representing a resource employees can "borrow", that part is working, can be automated (refusal, acceptance...).
However, the real issue is that I cannot seem to find a consistent way to get resource availability to show.  The users want to be able to see when they can "borrow" it or now, instead of sending an appointment and get a refusal/acceptance.
With my actual process, I can get it to work 10% of the time, like 5-15 minutes after I'm done setting it up, but I don't know what makes it work.
Yes, I tried outlook /cleanfreebusy and gpupdate /force and yes, I do change the # of months to show from 2 to 6 (needed to update)
Any ideas/insights please?


text:
Q: Trouble with NVD3 Graph showing x-axis in order of the data in array I am converting a flash graph to a js NVD3 ( D3 ) based line graph, but am having difficulty with the order of the x-axis.
I would like the x-axis data to display as ( current month counting back 12mths):
Feb, Mar, Apr, May, Jun, Jul, Aug, Sept, Oct, Nov, Dec, Jan
but the chart library is placing Jan to the front and then draws a line from Dec on the right side to jan on the left.
I have the following code:

<script>

nv.addGraph(function() {

 var months = ["Jan","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"];

 var thisYear = [], lastYear = []

 thisYear.push( {x: 2, y: 101034} );
  thisYear.push( {x: 3, y: 229948} );
  thisYear.push( {x: 4, y: 278940} );
  thisYear.push( {x: 5, y: 370409} );
  thisYear.push( {x: 6, y: 254532} );
  thisYear.push( {x: 7, y: 201229} );
  thisYear.push( {x: 8, y: 221323} );
  thisYear.push( {x: 9, y: 210640} );
  thisYear.push( {x: 10, y: 174958} );
  thisYear.push( {x: 11, y: 172434} );
  thisYear.push( {x: 12, y: 13527} );
  lastYear.push( {x: 1, y: 0} );

  lastYear.push( {x: 2, y: 380996} );
  lastYear.push( {x: 3, y: 214687} );
  lastYear.push( {x: 4, y: 123827} );
  lastYear.push( {x: 5, y: 171242} );
  lastYear.push( {x: 6, y: 155463} );
  lastYear.push( {x: 7, y: 163326} );
  lastYear.push( {x: 8, y: 209324} );
  lastYear.push( {x: 9, y: 165603} );
  lastYear.push( {x: 10, y: 147929} );
  lastYear.push( {x: 11, y: 154803} );
  lastYear.push( {x: 12, y: 85055} );
  lastYear.push( {x: 1, y: 9005} );

 var myData = [
    {
      values: thisYear,
      key: 'This Year',
      color: '#ff7f0e'
    },
    {
      values: lastYear,
      key: 'Last Year',
      color: '#2ca02c'
    }
  ];

  var chart = nv.models.lineChart()
                .margin({left: 100})
                .useInteractiveGuideline(true)
                .showLegend(true)
                .showYAxis(true)
                .showXAxis(true);

  chart.xAxis
   .axisLabel('Month of Year')
    .tickValues([1,2,3,4,5,6,7,8,9,10,11,12])
    .tickFormat(function(d){
      return months[d]
    });

  chart.yAxis     //Chart y-axis settings
      .axisLabel('$ ex GST Turnover');

  d3.select('#chart svg')    //Select the <svg> element you want to render the chart in.
      .datum(myData)         //Populate the <svg> element with chart data...
      .call(chart);          //Finally, render the chart!

  //Update the chart when window resizes.
  nv.utils.windowResize(function() { chart.update() });
  return chart;
});
</script>

And it renders a graph that looks like this:

This is an example of the old flash graph:

So my question is: How do I move "Jan" to the right side as per the order in the array?
Thanks for your time and aid.
PS. ( if anyone is wondering all the array pushes is dynamic from server side code )
:)

A: I managed to get the required output by dynamically with server code outputting the order of the months in the months js array as:
var months = ["","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","Jan"];
I did this by looping over the graph data and outputting the first 3 characters of the month as a string name. Position 0 in the array is "" as there is no month 0 in the calendar.
and then in the push lines instead of x = {monthOfYear} i changed it to x = {loop index} so then the data was ordered from 1 - 12. This then when referenced the months array "Jan" was in the 12th position and resulted in "Jan" being placed in the far right side.
Thanks to those that looked into the question.


text:
Q: Check that the Lebesgue $\sigma$-field is a $\sigma$-field $$\newcommand{\R}{\mathbb{R}}$$
Let $\mathcal{L}(\R)$ be the collection of all Lebesgue measurable subsets of $\R$.
That is,
\begin{align}
\mathcal{L}(\R) = \{E\subseteq\R:m^*(A) = m^*(A\cap E) + m^*(A\cap E^\complement),\;\forall A\subseteq\R\}.\tag{$*$}
\end{align}
I want to check that $\mathcal{L}(\R)$ is a $\sigma$-field.
It is clear that plugging $E\gets\R$ into $(*)$ gives $\R\in \mathcal{L}(\R)$ and also that if $E\in\mathcal{L}(\R)$ then $E^\complement\in\mathcal{L}(\R)$, but I have difficulty showing the countable union property.
Explicitly, I am trying to show that if $E_n\in\mathcal{L}(\R)$ for $n\geq1$, then $E:=\bigcup_{n\geq1}E_n\in\mathcal{L}(\R)$.
My approach is as follows:
Consider any $A\subseteq\R$.
Then
\begin{align}
m^*(A\cap E) + m^*(A\cap E^\complement) &= m^*\left(A\cap\big[\cup_{n\geq1}E_n\big]\right) + m^*\left(A\cap\big[\cup_{n\geq1}E_n\big]^\complement\right)\\
&=m^*\left(\overbrace{\bigcup_{n\geq1}\big[A\cap E_n\big]}^{D_1}\right) + m^*\left(\overbrace{\bigcap_{n\geq1}\big[A\cap E_n^\complement\big]}^{D_2}\right)
\end{align}
and I want to use the definition of outer measure
$$m^*(D) := \inf_{D\subseteq \bigcup_{j\geq1} B_j} \sum_{j=1}^\infty m(B_j)$$
for $D_1$ and $D_2$ to eventually show $m^*(D_1)+m^*(D_2)=m^*(A)$, but I am stuck.
Does it work to say that "$\leq$" holds because there can be two separate covers for $D_1$ and $D_2$ and "$\geq$" holds by countable subadditivity of $m^*$?


text:
Q: Laravel Subselect with own table? I have the following query:
    $users = User::join('countries', 'countries.id', '=', 'users.country_id')->select([
        'users.id',
        'users.promoter_id',
        'users.family_name',
        'users.name',
         ...

The users.promoter_id is still an ID from the users table. I want to add the family_name and the name for the promoter in that query too.
How can i make that subquery inside my OWN table?

A: Self-joining scenario. You can do it by creating an alias of your Users table and then joining with Users.
$users = User::join('countries', 'countries.id', '=', 'users.country_id')
                ->leftJoin('users as promoters', 'promoters.id', '=', 'users.promoter_id')->select([
        'users.id',
        'users.promoter_id',
        'users.family_name',
        'users.name',
        'promoters.family_name as promoter_family_name',
        'promoters.name as promoter_name',
        ...

Another way, in your User model define a relation
public function promoter()
{
    return $this->belongsTo(User::class, 'promoter_id', 'id');
}

Now Rewrite your query in controller
$users = User::with('promoter')->join('countries', 'countries.id', '=', 'users.country_id')->select([
         ...

Now you can access promoter details by $user->promoter->name, $user->promoter->family_name and so on.
Also you can do the same for Country too, by defining a country relationship instead of join in your User model and then User::with('promoter', 'country')->...


text:
Q: How to change the user agent of Chrome using javascript? I know there are one or two posts out there concerning a similar question but the answers never helped me or it just didn't work. I wanted to create a chrome extension that has changing a user agent being a part of it (I know there are user-agent changer extensions out there but that's not what I'm trying to make). Thanks

A: You will need the webRequest API.
User agent can be changed in the onBeforeSendHeaders event. In fact, the documentation has a very pertinent example in it.
  chrome.webRequest.onBeforeSendHeaders.addListener(
    function(details) {
      for (var i = 0; i < details.requestHeaders.length; ++i) {
        if (details.requestHeaders[i].name === 'User-Agent') {
          /* change details.requestHeaders[i].value here */
          break;
        }
      }
      return {requestHeaders: details.requestHeaders};
    },
    {urls: ["<all_urls>"]},
    ["blocking", "requestHeaders"]);


text:
Q: Task blocked when moving / resizing window I have a simple view model that contains a modified ObservableCollection which uses SynchronizationContext.Current.Send to execute changes to the collection on the UI thread. This collection is populated by a long running background thread.
This is working fine in all the different ways I've tried doing this, however they all seem to be blocked while moving the window or resizing it.

The gaps in this plot are from pressing and holding the mouse button on the window's title bar.
Different methods I've attempted
Task.Factory.StartNew:
Task.Factory.StartNew(
            () =>
            {
                double y = 0;
                while (true)
                {
                    Values.Add(new ValuePoint(DateTime.Now, Math.Sin(y)));
                    y += 0.1;
                    Thread.Sleep(20);
                }
            });

ThreadPool.QueueUserWorkItem:
ThreadPool.QueueUserWorkItem(GenerateNumbers);

private void GenerateNumbers(object obj)
    {
        double y = 0;
        while (true)
        {
            Values.Add(new ValuePoint(DateTime.Now, Math.Sin(y)));

            y += 0.1;
            Thread.Sleep(20);
        }
    }

new Thread:
_valueSimThread = new Thread(GenerateNumbers);
_valueSimThread.IsBackground = true;
_valueSimThread.Start();

Have I misunderstood something here? My expectations is that work being done in the thread should not be affected by stuff I do on the UI thread. Is it the action of using SynchronizationContext.Current.Send to update the collection the source of my problem?
What is the correct "pattern" for having an ObservableCollection that is updated by a background task?

A:
Is it the action of using SynchronizationContext.Current.Send to
  update the collection the source of my problem?

Yes, it is. SynchronizationContext.Send will end up posting the delegate to your UI thread. While you're moving your screen, the UI is pumped with many message regarding the new location of your window, mouse clicks, etc. So eventually, you're queuing up work to the UI thread, which is currently occupied.
As long as you're using some sort of collection which is bound to the UI, you have no other way then to queue work onto that UI message loop.


text:
Q: Uploadify won't work with my asp.net MVC 2 application When I use uploadify to upload photos to the server I use the following script (The script is placed in the Photo.aspx (this is the view of the UploadController and the Photo action)):
    <script type="text/javascript">
    $(document).ready(function () {
        $("#fileInput").uploadify({
            uploader: "../../Images/uploadify.swf",
            script: "../../Upload/Upload.ashx",
            cancelImg: "../../Images/cancel.png",
            auto: true,
            multi: true,
            folder: "Folder/Photos",
            onError: function (a, b, c, d) {
                if (d.status == 404)
                    alert("Could not find upload script. Use a path relative to: bla ");
                else if (d.type === "HTTP")
                    alert("error " + d.type + ": " + d.info);
                else if (d.type === "File Size")
                    alert(c.name + " " + d.type + " Limit: " + Math.round(d.sizeLimit / 1024) + "KB");
                else
                    alert("error " + d.type + ": " + d.text);
            }
        });
    });
</script>

Found here
Everything works fine until I've selected the files and the script starts uploading. Error HTTP: 404. This means, it doesn't find the script file. I tried everything:
script: "../../Upload.ashx",
script: "../Upload.ashx",
script: "Upload.ashx", etc..
The Upload.ashx is placed in Views/Upload/Upload.ashx (This folder also contains the Photo.aspx from the UploadController which contains the uploadify script). The scripts are loaded at the end of my page. I don't understand why uploadify can't find the script when I use the 'script: "Upload.ashx"' property. Can someone help with this?

A: The reason why you are always getting a 404 is because you should never link directly to a view. Create an action method in a controller that accepts a HttpPostedFileBase file. Here's an article from Phil Haack: http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx


text:
Q: Java Bubble Sort Acting Strange I have a function here for  bubble sort using Java and this code does work and sort an array. However, the issue is that I have no idea how it's sorting it because it does not seem like standard bubble sort.
public static void swap (int [ ] data, int index1, int index2)
// POST: elements at indexes are exchanged
{   int temp = data[index1];                                // temporary to hold first value
    data[index1] = data[index2];
    data[index2] = temp;
}

public static void bubbleSort (int [ ] data)
// POST: elements in data array are sorted in ascending order
{   for (int ct1=0; ct1<data.length-1; ct1++)           // outer loop moves one element into place
    {   for (int ct2=0; ct2<data.length-1-ct1; ct2++)
            if (data[ct2] > data[ct2+1])                    // swap if element on left bigger than right
                swap (data, ct2,ct2+1);
        for (int i = 0; i < data.length; i++) System.out.print(data[i] + " ");
        System.out.println();
    }
}

The bubble sort I understand would take an array {40, 90, 10, 60, 20} and compare the 0th and 1st index. If the 0th index is greater than the 1st index then they would swap. Then, in this case, 40 and 90 would stay where they are and then the 1st and 2nd index would be compared, resulting in 90 and 10 swapping. This would continue n - 1 times where n is the length of the array.
The problem is, using this function seems to give the output:
Bubble sort:
Starting array: 40 90 10 60 20
40 10 60 20 90
10 40 20 60 90
10 20 40 60 90
10 20 40 60 90

Can anybody help explain this please?
It seems to be comparing arbitrary values and does not check the 40 and 90 like it should.

A: Inside your bubbleSort method, you are starting an array from 0 upto the length of array - 1. Instead just make is simple and run it in reverse like this:
public static void bubbleSort(int [] data) {
    int k;
    for (int m = data.length; m >= 0; m--) {
        for (int i = 0; i < data.length - 1; i++) {
            k = i + 1;
            if (array[i] > array[k]) {
                swapNumbers(i, k, array);
            }
        }
      // Time to test this new array here:
    for (int i = 0; i < data.length; i++) {
        System.out.print(data[i] + ", ");
    }
        System.out.println("\n");
    }
}

Check if your solution is printed correctly and let me know

A: it will be swap until the end in a one loop with ct2.
inside loop ,will be going 4 times .
it is like a rock falling into water.
Engilsh is poor ,sorry~

A: Your bubble sort is behaving the way you expect it too.
It is sorting lowest to highest in reverse order (i.e. last column is set first)
I think the problem you are having is that the output sample frequency
does not match what is going on in your head.
if you change the code slightly
public static void swap (int [ ] data, int index1, int index2){
    int temp = data[index1];
    data[index1] = data[index2];
    data[index2] = temp;
}

public static void bubbleSort (int [ ] data) {
    for (int ct1=0; ct1<data.length-1; ct1++) {
        for (int ct2=0; ct2<data.length-1-ct1; ct2++) {
            if (data[ct2] > data[ct2 + 1]) {
                swap(data, ct2, ct2 + 1);
            // non functional change to move sampling point
                for (int i = 0; i < data.length; i++) {
                     System.out.print(data[i] + " ");
                }
                System.out.println();
            }
        }
    }
}

public static void main(String[] args) {
    bubbleSort(new int[]{40,90,10,60,20});
}

this produces the output
40 10 90 60 20
40 10 60 90 20
40 10 60 20 90
10 40 60 20 90
10 40 20 60 90
10 20 40 60 90

which is what I think you expect to see.


text:
Q: Is the space of complex measures on a sigma algebra complete? Let $\mathcal{M}$ a $\sigma$-algebra on a set $X$. A complex measure is a complex function on $\mathcal{M}$ such that
$$
\mu(E) = \sum_i \mu(E_i)
$$
where $E \in \mathcal{M}$ and $\left\{ E_i \right\}$ partition of $E$.
Given a complex measure $\mu$ we define
$$
\left\| \mu \right\|(E) = \sup \sum_{i} |\mu(E_i)|
$$
where the supremum is taken over all the partions of $E$. A norm on the set of complex measures can be defined by
$$
\left\lVert \mu \right\rVert = \left| \mu \right|(X).
$$
Now I wanted to prove, if possible, the space of complex measures is complete.
Therefore let $\left\{ \mu_n \right\}$ a cauchy sequence which means for every $\epsilon > 0$ we have an $n_0$ such that
$$
\left\lVert \mu_m - \mu_n \right\rVert < \epsilon \text{    } \forall m,n \geq n_0
$$
Pick any $E \in \mathcal{M}$ and estimate
$$
\left| \mu_m(E) - \mu_n(E) \right| < \left\lVert \mu_n - \mu_m \right\rVert < \epsilon
$$
Therefore $\mu_n(E)$ converges as a real sequence. I can then define the candidate measure $mu$ by
$$
\mu(E) = \lim_{n\to\infty} \mu_n(E)
$$
For the same cauchy sequence I can the consider
$$
\lim_{n\to\infty} \left\lVert  \mu_m - \mu_n \right\rVert = \left\lVert  \mu_m - \lim_{n\to\infty} \mu_n \right\rVert = \left\lVert  \mu_m - \mu \right\rVert < \epsilon
$$
for every $\epsilon > 0$. Hence every cauchy sequence is convergent, hence the space of complex measures is complete.
Is this argument correct?


text:
Q: SQL Server Report Services (SSRS), Access The properties of a Tablix from its Expresssion Builder While Using SQL Server Report Services (SSRS), I wanted to access the properties of a Tablix from its Expresssion Builder.  My Issue, Three are Three Tablix on the Page. I want to dynamically change the visibility of each tablix based of a parameter I pass to the report. e.g. I am passing the Parameter @ShowTablix with the value "Tablix1"
I expect Tablix1 to be visible while Tablix2 & Tablix3 are invisible.
Now i know a way how to do this.
In The Visibility.Hidden Property for the
Tablix I am setting the expression
=(Parameters!ShowTablix.Value<>"Tablix1")
I have to do this for each tablix so it becomes
for  Tablix2
=(Parameters!ShowTablix.Value<>"Tablix2")
and for Tablix3
=(Parameters!ShowTablix.Value<>"Tablix2")
But I want to use something like this
=(Parameters!ShowTablix.Value<>Me.Name)
i.e. a generic expression i can apply to all my tablixes as is .
any ideas?
by the way ReportItems...=ReportItems("Textbox1").Value is only useful for textboxes

A: You can change the name of the Tablix1 from the Property itself.
Right click and go to tablix properties and than change the Name. Or it can be done from the Properties Window.