text:
Q: MPMoviePlayerController still leaking I release the MPMoviePlayerController but the memory allocation and the living objects are still higher than before the object allocation. However if I reallocate the object it doesn't leak more.
My application actually uses a lot of media files and the memory consumption is high. I would like to free up completely the unneeded memory to avoid memory warnings.
Movie player release:
        player.initialPlaybackTime = -1;
        [player.view removeFromSuperview];
        [player stop];
        [player release];

Movie player alloc:
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"video0_hd.mov" ofType:nil]];
    player = [[MPMoviePlayerController alloc] initWithContentURL:url];
    player.view.frame = placeholder.frame;
    [self.view addSubview:player.view];
    [player play];

A: I also had this issue.
The cache used by the iPad for preloading the video stream, was not emptied completely.
So each time, this page with the video player was cleaned up and released, the allocated memory after cleanup still contained the cached memory. For big video's, this could be up to 50 MB.
This is actually not a memory leak:
If the page was opened again, the cache was re-allocated. But still frustating as you want a clean exit situation, meaning when this page is left and cleaned up, all memory used by this page should be released, including the memory used for caching the video stream....!
After some serious tweeking, this sequence of commands seems to do the job:
======================
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerPlaybackDidFinishNotification
                                                  object:myMoviePlayer];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerDidExitFullscreenNotification
                                                  object:myMoviePlayer];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMoviePlayerLoadStateDidChangeNotification
                                                  object:myMoviePlayer];

    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:MPMovieDurationAvailableNotification
                                                  object:myMoviePlayer];
    [myMoviePlayer pause];
    myMoviePlayer.initialPlaybackTime = -1;
    [myMoviePlayer stop];
    myMoviePlayer.initialPlaybackTime = -1;
    [myMoviePlayer.view removeFromSuperview];
    [myMoviePlayer release];

=================================
In steps:
1 - REMOVE all notifiers you are using for your movie player.
2 - Pause the movie
3 - set the Playback time to start
4 - stop the movie
5 - set the Playback time again to start
6 - now remove the movie View
7 - and finally release the movie player
Resulting in my case in also the video cache memory being released on my iPad (OS 4.2.)
and leaving a clean allocated memory situation, equal to the size before the page with the video player was openen. So same enter and exit memory.
Hope this helps......

A: Have you tried Build and Analyze (Build>Build and Analyze), this could show you the exact line memory is leaking (if any).
Right now, I've got a feeling the problem is where you define the NSURL.

A: Are you running this code on a device or on the simulator?  The simulator gives a bunch of false leaks (such as in AudioToolbox, CoreVideo, etc.).  Also, the simulator seems to cache the entire video and not release it properly whereas the device buffers only what it needs along the way.
I tested your code on the simulator with an mp4 video and I had similar results to what you were saying (10 live objects each time a video was played, with none dying... 20mb allocated, and 5mb left even after releasing). The living objects and memory allocation would keep growing and growing on the simulator.
However, on my iPhone (with a 20mb video) it only allocated 900kb of memory total for the app, with no appreciable change when starting/stopping/releasing the video.  It always stayed right around 900kb for the 10 times I tested it (starting/stopping/releasing).
Looks like just another time you can't trust the simulator.
The code I was testing with:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"SomeMovieFile" ofType:@"mp4"]];

MPMoviePlayerController *newPlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];

self.player = newPlayer;
[newPlayer release];

[self.view addSubview:player.view];  // for my example, I didn't set the frame location, but no difference that would do
[player play];

Then in another button I stopped it and released the player:
[player.view removeFromSuperview];
player.initialPlaybackTime = -1;
[player stop];
self.player = nil;  // this is just a habit of mine.. calling stop should unload the buffers though
[player release];


text:
Q: Facebook like status url detection I am wondering if there is a script similar to the facebook status update thing,
What I mean, is when for ex. I paste a youtube/other video site/image/link it automatically detects the contents of the page and associates an embed code with it (if its a video)..
So I'm wondering if there is a ready script that has a large database of websites and can associate video site url's with embed codes.
I could actually do something like that by myself but the problem is that I want to support a lot of websites, like facebook does.
Please help me find a solution.
Thanks.

A: Take a look at the Embedly API: http://api.embed.ly/
It gets the embed code for a lot of the popular video sites out there and also for some images sites. I highly recomend it,
you can try it out here.

A: You really wouldn't have to scan that large of a database.  With videos, you could keep track of maybe the top three or so uploading sources (youtube, vimeo, metcafe...) and their embed codes.
As for images and links, those are pretty easy to detect and don't require any special embed code.  By pretty easy, I mean very simple.  Just use a simple regular expression to search for a link in their post.
If it's a picture, you can easily tell by looking at the file extension of the link (jpg, png, gif, etc.).  If so, do whatever is proper to embed any old image.  If it's just an ordinary old link (doesn't match any of your video sites, or doesn't end in a file extension for an image), just use the link itself.
The only marginally tricky part would be getting the unique embed codes for the video sites.  But perhaps there is some external library/api that could do that small part for you (another answerer has provided has a proper API/pre-built library for this).  However, images and links are mostly pretty simple.
EDIT It seems I misread your problem, and that you are only looking for pre-built libraries with video embed codes.  In that case, the other answer is exactly what you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Expected Value Gambling Qn Question: If a video poker player has found a 0.1% edge on a game and their goal is to make as much money from this play as they possibly can, with an average hourly EV of 20 dollars per hour. If they experience positive variance and say are up 50,000 dollars after 20 hours of play (assuming they play 800 hands per hour), when on average they should only be up 400 dollars, what would be the point of playing for another 2480 hours if their statistical expectation is that they will end up with exactly the same amount of profit as they currently have? There is no monetary value in playing for an additional 2480 hours in this scenario is there?? Thanks!
This question is important because it addresses problem gambling myths and it should be asked on this site as it is a probability and statistics question, which is a branch of mathematics!
My response to the 'statistics have no memory' rebuttal:
"What about the law of large numbers and statistical expectations? One can assume that after 2 million hands @ 25 dollars per hand (the required number of hands required to make 50,000 dollars profit with a 0.1% edge and 20 dollars per hour EV), they could expect with a high degree of certainty to be close to the statistical expectation of 50,000 dollars profit. So what is the point of continuing to play if the longer you play, the more likely your observed results are to converge to the statistical expectation?".

A: Your question is ill-posed.  It has a couple of hidden issues with it.
Your problem has multiple components, some of which are not addressed in your post.  They cannot be answered without knowing them.
The first element is that your game appears to have a stopping rule of some kind.  People are permitted to stop playing.  You take it for granted, it seems.  If early stopping is permitted, then that opens up other issues.  Do you want to create a Bayes action, a decision rule, or choose the combination of the two by minimizing integrated risk?  You must have a utility function of wealth for any of this.  You may also need to specify the utility of an estimation rule.
Without considering a stopping rule, consider the following utilities of wealth, $$\mathcal{U}(w)=\log(w),$$ and $$\mathcal{U}(w)=\begin{cases}w&\text{if } w\le{E}(w)\\ E(w)&\text{otherwise}\end{cases}$$
In the first utility function, additional wealth is always valued.  In the second utility function, wealth past a threshold, in this case, the long-run expected value, has no added utility.  Both utilities are real-world functions, and there are countless others (well, maybe they could be countable as they are rules).
The next issue is about whether there are other costs.  Can you get tired?  Are you willing to accept an interior solution for a reason not mentioned?  For example, if your spouse wants you to go swimming with them, have you specified it in your utility function.  The example is meant to be fanciful and get the point across.
Your question currently reads that a highly unspecified video poker machine exists.  A strategy has been discovered that gives an edge.  In the case where there are a large number of initial winnings, should that fact be considered?
It appears to assume that an expected value is relevant in the decision making, but it may not be.  Remember that $$\mathcal{U}(E(x))\ne{E}(\mathcal{U}(x))$$ in the general case.
The stated edge is ill-specified.  Does that edge exist in all configurations of observed cards?  Are the cards shuffled, or is there a memory?  Are there different edges under differing circumstances?  Is the edge sometimes negative or zero?
If the "edge" is estimated, it creates another host of issues.  Only Bayesian tools are coherent.  A decision would be coherent if a competitor could not create a game of "heads I win, tails you lose" by using your probabilities against you.
I do believe, as do other commentators, that you felt that winning early would imply a reversal later.  In systems without memory, that is not true.
Nonetheless, you also lack a rule of how much money to bet.  That should also optimize utility and any constraints.  Are bets in discrete units or real ones?  This is math; mathematicians let you get away with real-valued bets.  If the bets are discrete and there are no loans available, then you can run out of money in many typical situations.  If you made that much extra up, it is likely you could collapse down too.
Does your decision rule consider total failure in the allocation or stopping decisions?  What about in hand specific decisions?  Would you change your bets if you had a flush showing in seven card stud?
How does this machine handle bets?  What are the rules?
As shown in the comments, if the game is memoryless, you have won a fixed sum already, and you will continue to have a positive expected value, then the prior win should not impact the future patterns of wins.
However, that does not imply that you should continue playing.
Finally, I would argue that statistics, at least, is not a branch of mathematics, but as is often pointed out by Cosmo Shalizi, a branch of rhetoric.  Decisions, of course, are the property of statistical decision theory, psychology and/or microeconomics.  If this video poker is an MMOG, then also add in game theory.
I hope this post did not come across as snarky.  You left things out, but that is okay too.  Placing money at risk in a state of uncertainty is a profession in itself.  It is a gigantic field.  I wanted to be certain that you were thinking carefully.


text:
Q: Provide TabIndex number into angularJs ng grid I am using ng grid and each row of the grid have a text box. I want to access all the textbox inside and outside of the grid using TAB Key according to provided tabIndex.
My plunker is here : http://plnkr.co/edit/ce4xnHJtYhRdwe6JvZSA?p=preview

A: set noTabInterference: true in gridOptions, updated recently


text:
Q: Given a continuous function $f$, is there any interval on which $f$ is not either weakly convex or weakly concave? Given a continuous function $f$, is there any interval on which $f$ is not either weakly convex or weakly concave?
If not, is there some class of functions that are only either weakly convex or weakly concave?

A: You may just consider a function of the form
$$ f(x)=\sum_{n\geq 1}\frac{\sin(n^3 x)}{n^2}. $$
This is a continuous function since it is given by a totally convergent series of continuous functions, but it is not weakly convex or weakly concave over any interval. Its graph has a fractal structure:


text:
Q: Monoidal cats and string diagrams for a semantics of object oriented programming languages It seems to me that in a statically typed, object oriented language, there is a striking similarity to wiring diagrams.  Wires (objects) of type $X$ go into functions (boxes) of input type $X$.  Is the corresponding string calculus that of a symmetric monoidal category?
Edit:  it has been suggested that I formulate a more specific question.  Here goes:  let the programming language have private member variables.  At this point you cannot copy arbitrary objects because the data is hidden. I guess you also have to assume that there is no generic copy method for all types.  Becasue copying isn't allowed arbitrarily, we might need a monoidal category to handle the semantics.  Is this the case?

A: No full answer but just some random thoughts on the issue:
Concerning the string diagram calculus: It should be that of a mutlicategory (see David Spivaks paper on the Wiring Operad: http://arxiv.org/abs/1305.0297).
Plus I think there's a hidden issue here: Private member variables are only of real concern if the objects are stateful; Otherwise - if they are not observable after object instantiation a.k.a. function call - they can just be considered implementation details. I don't think modelling the wiring between the objects using a multicategory / monoidal category is an approach powerful enough to reason about mutable state. But I guess by adding labels to the diagrams (similar to Petri nets) and let them vary over time this could be fixed. (Again, consult David Spivak for an idea on how to model such a labeling: http://math.mit.edu/~dspivak/informatics/olog.pdf)
EDIT: Concerning the labeling - a rough sketch: A typing of the diagrams at hand shoult propably be used as input to some sort of grothendieck construction and a labeling should then be a lift of the base diagram into the respective fibration. Including Maybe/Option/Exception Types should allow for partial diagrams while the program is still 'booting'.


text:
Q: How to get provider using rainbowkit wallet if connected via walletconnect or browser has no metamask extension 0
I'm using rainbowkit wallet which offers various wallet options such as walletconnect and coinbase.
My question is, if I'm connected via metamask then my web3 instance can use window.ethereum as provider.
But if I'm connected to other wallets like walletconnect or coinbase, can I still go with window.ethereum as provider?
i.e. let web3 = new Web3(window.ethereum);
if not, for other wallets where can I get its provider? is there an option to grab currently connected provider using wagmi?
i am also using
    const { data: signer } = useSigner();
    const provider = useProvider();

what i tried doing is instead of this :

  const web3 = new Web3(Web3.givenProvider);

 I was trying this below :

 const web3 = new Web3((signer?.provider).provider);

this throws error like :

can someone help me with this issue ?
Tx


text:
Q: query for getting unique user Ids I am new to SQL. I have two databases, user and item (name, country, userId) .
I want to get user Ids that all items of the user belongs to country code US and CA.
*user can have multiple items.
Could someone help me with sql query? thanks!!

A: You can select the entries whose country is not 'US' or 'CA' and get the users which don't exist there.
-- This part is for having some test data

with users_t (userid, itemid) as(
    select 'USER1', 'ITEM1' from dual union all
    select 'USER2', 'ITEM2' from dual union all
    select 'USER3', 'ITEM3' from dual),
items_t (name, country, userid) as(
    select 'NAME1', 'US', 'USER1' from dual union all
    select 'NAME2', 'ESP', 'USER1' from dual union all
    select 'NAME1', 'US', 'USER2' from dual union all
    select 'NAME1', 'CA', 'USER2' from dual union all
    select 'NAME1', 'ESP', 'USER3' from dual)

--This is the actual query

SELECT
    userid
FROM
    users_t u
WHERE
    NOT EXISTS (
        SELECT
            1
        FROM
            items_t i
        WHERE
            i.userid = u.userid
            and i. country not in ('US', 'CA')
    );

Output:
USERID
------
USER2


text:
Q: Sorting columns then using cell() function I have a datatable with a sortable column. Clicking the header sorts it. So far so good.
However, after sorting, I then want to iterate the cells in the column. So I do this:
datatable.column(".latest").nodes().each(function (node, index, dt) {
var the_cell = this.cell(index, '.sto_bid').node();

However, this pulls back the cell before the column was sorted. In other words, index=0 is pulling back what is now the last cell in the column. How do you reset the indexes when you sort, so cell(0, '.sto_bid') will return the first cell shown in the table?
The docs seem to suggest that calling draw() does what I need - it resets the data. It doesn't do anything for me when I do this first:
datatable.draw()

The ordering index is still backwards.

A: Here's what I did:
// My custom sort function on the raw data array
sortFilteredGridData();

// Remove all rows from the table
table.clear();

// Add the data back to the table
table.rows.add(filteredGridData);

// I have a fixed header
table.fixedHeader.adjust();

// Re-draw
table.draw();

A: You'll want to apply the searched tag to your returned data:
contentTable.cells({search:'applied'}, ".latest").nodes();

This should get all of the DOM elements of the cells in the .latest column, in the order they exist on the page. It kind of takes a different approach to grabbing the nodes than your code does so I don't know how to exactly apply it to your situation, but this should get you in the right direction


text:
Q: Do all the apps that work in Gnome shell also work in Unity? Do all the apps that work in Gnome shell also work in Unity?
Or if there is a limitation is there some way to know that without actually trying the app?

A: Yeah,it will work if it is specific not specific to the de(Eg. Extensions,indicators etc) because both unity and gnome-shell using gtk3 and gnome3 (in ubuntu 11.10 and higher)

A: All the apps that work in GNOME Shell work in Unity, you might even get added features like a Quicklist (right-click menu on the Launchbar). Unity is like GNOME Shell based on gnome3 technologies, so I expect no problems.

A: They work mostly.  You could check the package in questions bug tracker to see if anyone has had issues yet.  If not, try it.  If it doesn't work report the bug to the package.
In my opinion Ubuntu is free.  Part of what you morally pay for it is trying packages and trying to sort out bugs/report bugs.


text:
Q: Failed to load resource: the server responded with a status of 404 (Not Found) https://websitename.herokuapp.com/js/bootstrap.js I'm running a node.js server on heroku using the express.js framework.
Here is what my server looks like:
var express = require('express');
var app = express();

app.use(express.static(__dirname + '/static'));
var port = process.env.PORT || 8000;

app.listen(port);

My index.html file has the following javascript links:
<script src="/js/chartview.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="/js/bootstrap-select.js"></script>

My directory system looks like this:
server.js
/static
    -index.html
    -/js
        -bootstrap.js
        -bootstrap-select.js
        -chartview.js
    -/css
        -bootstrap.css
        -bootstrap-select.css
        -styles.css

Chrome displays my html page with the appropriate css styles but the console says:
Failed to load resource: the server responded with a status of 404 (Not Found)   https://websitename.herokuapp.com/js/chartview.js
Failed to load resource: the server responded with a status of 404 (Not Found)   https://websitename.herokuapp.com/js/bootstrap.js
Failed to load resource: the server responded with a status of 404 (Not Found)   https://websitename.herokuapp.com/js/bootstrap-select.js

It loads properly when I change my index.html  tags to look like this:
<script src="chartview.js"></script>
<script src="bootstrap.js"></script>
<script src="bootstrap-select.js"></script>

And I change my directory systems to look like this:
server.js
/static
    -index.html
    -bootstrap.js
    -bootstrap-select.js
    -chartview.js
    -/css
        -bootstrap.css
        -bootstrap-select.css
        -styles.css

This is not Ideal, as I would like to have a /js folder.
Any suggestions will be greatly appreciated!

A: From the console error, https://websitename.herokuapp.com/js/chartview.js, the file is not being checked in static folder.
So, change your index.html to include scripts like this.
<script src="js/chartview.js"></script>  i.e remove / from beginning. as path is relative to index.html.
Follow same process for other three files.
Also, you mentioned that the CSS files are loaded correctly. Can you show how exactly are you including those css files? i.e the path for css.
Comment here, if that doesn't help.

A: Try Placing your files in the public folder and use the path like this""

A: Don't use "__dirname"
Only using
app.use(express.static('static'));


text:
Q: Cannot set cookie with jQuery Cookie I'm using jQuery Cookie 1.4.1. Here's my code:
<!DOCTYPE html>

    test

The console shows "undefined"
Could anyone help me?

A: I'm developing on localhost. It seems that Chrome ignores local jQuery cookies:
Why does Chrome ignore local jQuery cookies?


text:
Q: Verilog DUT System Verilog testbench: output to wire assignment 1s replaced with Xs I have a Modelsim testbench in System Verilog testing a Verilog top-level module (ufm1) with another Verilog module (wishbone) used inside it, there's also a System Verilog "stub" (wishbone_sim) that is connected to the DUT in the testbench.
The DUT and the inner module were originally in System Verilog and worked fine but I had to convert them to Verilog to be able to use Diamond LSE (leaving the testbench in System Verilog)
The inner module inside the DUT has an output which I'm connecting to a wire (was originally a reg in the System Verilog version because it gave an error otherwise) inside the DUT and then using the wire to assign to a reg in a procedural block inside the DUT.
Inside the inner module this output is basically assigned directly from an input.
Now when I'm simulating this the input in the inner module is fine but the output (should be the same because it is a direct assign) is different with Xs in place of 1s.
The issue only starts appearing when the output of the inner module (rd_data) is assigned to the wire (wb_rd_data), which looks strange to be because I don't see how connecting an output port to a wire would affect its value.
The wire inside the DUT is wb_rd_data which is connected to the rd_data port of the inner wishbone module.
How do I fix this?
DUT:
module ufm1(clk, ufm_wr_rq, ufm_rd_rq, ufm_wr_data, ufm_wr_ack, ufm_rd_data, ufm_rd_ack, ufm_done, wb_clk, wb_rst, wb_cyc, wb_stb, wb_we, wb_addr, wb_dat_i, wb_dat_o, wb_ack);

input clk;
input ufm_wr_rq, ufm_rd_rq;
input [7:0] ufm_wr_data;
output reg ufm_wr_ack;
output [7:0] ufm_rd_data;
output ufm_rd_ack;
output reg ufm_done = 0;

output wb_clk;
output wb_rst;
output wb_cyc;
output wb_stb;
output wb_we;
output [7:0] wb_addr;
output [7:0] wb_dat_i;
input [7:0] wb_dat_o;
input wb_ack;

      parameter WR_OF = 8'h10;
      parameter WR_CF = 8'h11;
      parameter WR = 8'h12;
      parameter WRE = 8'h13;
      parameter RD = 8'h20;
      parameter RDI = 8'h21;
      parameter JMPI = 8'h30;
      parameter END = 8'h40;

      parameter Z00 = 8'h00;
      parameter FF = 8'hFF;

      parameter WR_CMDS = 4'h1;
      parameter RD_CMDS = 4'h2;
      parameter JMP_CMDS = 4'h3;
      parameter END_CMDS = 4'h4;

      parameter CMD_EN_CFG_I = 8'h74;
      parameter CMD_DIS_CFG_I = 8'h26;
      parameter CMD_RD_ST = 8'h3C;
      parameter CMD_ZERO_ADDR = 8'h47;
      parameter CMD_RD_UFM = 8'hCA;
      parameter CMD_WR_UFM = 8'hC9;
      parameter CMD_ERASE_UFM = 8'hCB;
      parameter CMD_BYPASS = 8'hFF;

      parameter ST_IDL = 3'd0;
      parameter ST_NEXT_CMD = 3'd1;
      parameter ST_WT_WR = 3'd2;
      parameter ST_WT_RD = 3'd3;

      parameter CMDS_NUM = 9'd196;
      parameter WR_PRG_START_INDEX = 9'd103;

      parameter [CMDS_NUM*8-1:0] CMDS = {
            //**** Erase and read
            //Enabled configuration interface
            WR_OF, WR, CMD_EN_CFG_I, WR, 8'h08, WR, Z00, WR, Z00, WR_CF,
            //Read config status register and repeat till not busy
            WR_OF, WR, CMD_RD_ST,    WR, Z00,   WR, Z00, WR, Z00, RD, RD, RD, WR_CF, JMPI,
            //Zero UFM address
            WR_OF, WR, CMD_ZERO_ADDR,WR, Z00,   WR, Z00, WR, Z00, WR_CF,
            //Read UFM page 0 (16 bytes)
            WR_OF, WR, CMD_RD_UFM, WR,   Z00,   WR, Z00, WR, 8'h01,
            RDI,RDI,RDI,RDI,RDI,RDI,RDI,RDI,RDI,RDI,RDI,RDI,RDI,RDI,RDI,RDI,
            WR_CF,
            //Erase UFM
            WR_OF, WR, CMD_ERASE_UFM,WR, Z00,   WR, Z00, WR, Z00, WR_CF,
            //Read config status register and repeat till not busy
            WR_OF, WR, CMD_RD_ST,    WR, Z00,   WR, Z00, WR, Z00, RD, RD, RD, WR_CF, JMPI,
            //Disable configuration interface
            WR_OF, WR, CMD_DIS_CFG_I, WR, Z00, WR, Z00, WR_CF,
            //Bypass (NOP)
            WR_OF, WR, CMD_BYPASS,    WR, FF,  WR, FF,  WR,  FF, WR_CF,

            END,

            //**** Write
            //Enabled configuration interface
            WR_OF, WR, CMD_EN_CFG_I, WR, 8'h08, WR, Z00, WR, Z00, WR_CF,
            //Read config status register and repeat till not busy
            WR_OF, WR, CMD_RD_ST,    WR, Z00,   WR, Z00, WR, Z00, RD, RD, RD, WR_CF, JMPI,
            //Zero UFM address
            WR_OF, WR, CMD_ZERO_ADDR,WR, Z00,   WR, Z00, WR, Z00, WR_CF,
            //Write UFM page 0 (16 bytes)
            WR_OF, WR, CMD_WR_UFM, WR,   Z00,   WR, Z00, WR, 8'h01,
            WRE,WRE,WRE,WRE,WRE,WRE,WRE,WRE,WRE,WRE,WRE,WRE,WRE,WRE,WRE,WRE,
            WR_CF,
            //Read config status register and repeat till not busy
            WR_OF, WR, CMD_RD_ST,    WR, Z00,   WR, Z00, WR, Z00, RD, RD, RD, WR_CF, JMPI,
            //Disable configuration interface
            WR_OF, WR, CMD_DIS_CFG_I, WR, Z00, WR, Z00, WR_CF,
            //Bypass (NOP)
            WR_OF, WR, CMD_BYPASS,    WR, FF,  WR, FF,  WR,  FF, WR_CF,

            END
      };

      reg wb_wr_rq = 0, wb_rd_rq = 0;
      reg [7:0] wb_wr_data = 0;
      wire [7:0] wb_rd_data = 0;
      reg [7:0] addr = 0;

      wishbone wishbone(.clk(clk), .wr_rq(wb_wr_rq), .rd_rq(wb_rd_rq), .wr_data(wb_wr_data), .rd_data(wb_rd_data),
                        .addr(addr), .done(wb_done), .wb_clk(wb_clk), .wb_rst(wb_rst), .wb_cyc(wb_cyc), .wb_stb(wb_stb),
                        .wb_we(wb_we), .wb_addr(wb_addr), .wb_dat_i(wb_dat_i), .wb_dat_o(wb_dat_o), .wb_ack(wb_ack));

      reg [2:0] st = 0;
      reg [2:0] prev_st = 0;
      reg [7:0] prev_cmd = 0;
      reg [CMDS_NUM*8-1:0] cmds = CMDS;
      reg [8:0] cmd_index = 0;
      reg [7:0] lst_rd_data = 0;

      wire [7:0] cur_cmd = cmds[((CMDS_NUM-cmd_index-1)*8)+:8];
      wire [7:0] next_cmd = cmds[((CMDS_NUM-cmd_index-2)*8)+:8];

      assign is_cmd_wre = (cur_cmd == WRE);
      assign is_1cmd_wr = (cur_cmd == WRE || cur_cmd == WR_OF || cur_cmd == WR_CF);

      assign ufm_rd_ack = (prev_st == ST_WT_RD) && (prev_cmd == RDI) && wb_done;
      assign ufm_rd_data = ufm_rd_ack ? wb_rd_data : 0;

      always @(posedge clk)
      begin

        prev_st <= st;
        prev_cmd <= cur_cmd;

        case(st)
          ST_IDL:
          begin
            ufm_done <= 0;
            if(ufm_rd_rq)
            begin
              st <= ST_NEXT_CMD;
            end
            else
            if(ufm_wr_rq)
            begin
              st <= ST_NEXT_CMD;
              cmd_index <= WR_PRG_START_INDEX;
            end
          end
          ST_NEXT_CMD:
            case(cur_cmd[7:4])
               WR_CMDS:
               begin
                 wb_wr_rq <= 1;
                 wb_wr_data <= (cur_cmd == WR_OF) ? 8'h80 :
                           (cur_cmd == WR_CF ? 8'h00 : (is_cmd_wre ? ufm_wr_data : next_cmd));
                 addr <= (cur_cmd == WR_OF || cur_cmd == WR_CF) ? 8'h70 : 8'h71;
                 ufm_wr_ack <= is_cmd_wre;
                 st <= ST_WT_WR;
               end

               RD_CMDS:
               begin
                 wb_rd_rq <= 1;
                 addr <= 8'h73;
                 st <= ST_WT_RD;
               end

               JMP_CMDS:
               begin
                 st <= ST_NEXT_CMD;

                 if(lst_rd_data[4]) //if busy
                 begin
                   cmd_index <= cmd_index - 13; //assuming the previous command is reading the status register
                 end
                 else
                 begin
                   cmd_index <= cmd_index + 1;
                 end
               end

               END_CMDS:
               begin
                 st <= ST_IDL;
                 cmd_index <= 0;
                 ufm_done <= 1;
               end
            endcase

          ST_WT_WR:
          begin
            wb_wr_rq <= 0;
            ufm_wr_ack <= 0;
            if(wb_done)
            begin
               wb_wr_data <= 0; //todo: not necessary, can be removed if doesn't fit
               cmd_index <= cmd_index + (is_1cmd_wr ? 1 : 2);
               st <= ST_NEXT_CMD;
            end
          end

          ST_WT_RD:
          begin
            wb_rd_rq <= 0;
            if(wb_done)
            begin
              lst_rd_data <= wb_rd_data;
              cmd_index <= cmd_index + 1;
              st <= ST_NEXT_CMD;
            end
          end
        endcase
      end

endmodule

Inner Module:
module wishbone(clk, wr_rq, rd_rq, done, addr, wr_data, rd_data, wb_clk, wb_rst, wb_cyc, wb_stb, wb_we, wb_addr, wb_dat_i, wb_dat_o, wb_ack);

input clk;
input wr_rq, rd_rq;
output done;
input [7:0] addr;
input [7:0] wr_data;
output [7:0] rd_data;

output wb_clk;
output wb_rst;
output wb_cyc;
output wb_stb;
output wb_we;
output [7:0] wb_addr;
output [7:0] wb_dat_i;
input [7:0] wb_dat_o;
input wb_ack;

reg wr_in_progress = 0;
reg rd_in_progress = 0;

assign done = wb_ack;
assign wb_clk = clk;
assign wb_addr = (wr_in_progress || rd_in_progress) ? addr : 0;
assign wb_dat_i = wr_in_progress ? wr_data : 0;
assign rd_data = wb_dat_o;
assign wb_rst = 0;
assign wb_cyc = wr_in_progress || rd_in_progress;
assign wb_stb = wb_cyc;
assign wb_we = wr_in_progress;

always @(posedge clk)
begin
    if(!wr_in_progress && !rd_in_progress)
    begin
         if(wr_rq)
         begin
            wr_in_progress <= 1;
         end
         else if(rd_rq)
         begin
            rd_in_progress <= 1;
         end
    end
    else if(wr_in_progress && wb_ack)
    begin
         wr_in_progress <= 0;
    end
    else if(rd_in_progress && wb_ack)
    begin
         rd_in_progress <= 0;
    end
end

endmodule

Testbench:
`timescale 100ps / 100ps

module ufm1_tb;

      parameter WR_OF = 8'h10;
      parameter WR_CF = 8'h11;
      parameter WR = 8'h12;
      parameter WRE = 8'h13;
      parameter RD = 8'h20;
      parameter RDI = 8'h21;
      parameter JMPI = 8'h30;
      parameter END = 8'h40;

      parameter Z00 = 8'h00;
      parameter FF = 8'hFF;

      parameter WR_CMDS = 4'h1;
      parameter RD_CMDS = 4'h2;
      parameter JMS_CMDS = 4'h3;

      parameter CMD_EN_CFG_I = 8'h74;
      parameter CMD_DIS_CFG_I = 8'h26;
      parameter CMD_RD_ST = 8'h3C;
      parameter CMD_ZERO_ADDR = 8'h47;
      parameter CMD_RD_UFM = 8'hCA;
      parameter CMD_WR_UFM = 8'hC9;
      parameter CMD_ERASE_UFM = 8'hCB;
      parameter CMD_BYPASS = 8'hFF;

parameter CD = 200; //100ps*200=20nS (50MHz)
parameter HCD = CD/2;
parameter QCD = CD/4;

parameter IGNORE = 8'h00;
parameter BUSY = 8'h10;
parameter FREE = 8'h00;

parameter [7:0] DATA [] = '{
            //**** erase/read
            //First busy wait
            IGNORE, IGNORE, BUSY,
            IGNORE, IGNORE, FREE,
            //UFM Page 0 read
            8'hA0,8'hA1,8'hA2,8'hA3,8'hA4,8'hA5,8'hA6,8'hA7,8'hA8,8'hA9,8'hAA,8'hAB,8'hAC,8'hAD,8'hAE,8'hAF,
            //Second busy wait
            IGNORE, IGNORE, BUSY,
            IGNORE, IGNORE, BUSY,
            IGNORE, IGNORE, FREE,

            //**** write
            //First busy wait
            IGNORE, IGNORE, BUSY,
            IGNORE, IGNORE, FREE,

            //Second busy wait
            IGNORE, IGNORE, BUSY,
            IGNORE, IGNORE, BUSY,
            IGNORE, IGNORE, FREE
      };

parameter [7:0] DELAYS [] = '{{dut.CMDS_NUM}{8'h0}};
parameter [7:0] WRDATA [] = '{8'hBF,8'hBE,8'hBD,8'hBC,8'hBB,8'hBA,8'hB9,8'hB8,8'hB7,8'hB6,8'hB5,8'hB4,8'hB3,8'hB2,8'hB1,8'hB0};

parameter ST_IDLE = 0;
parameter ST_READING = 1;
parameter ST_WRITING = 2;
parameter ST_FINISHED = 3;

reg clk = 0;

always #(HCD) clk = ~clk;

wishbone_sim
#(
  .CD(CD),
  .DATA(DATA),
  .NUM_OPERATIONS(dut.CMDS_NUM),
  .DELAYS('{{dut.CMDS_NUM}{0'h0}})
)
wb_sim(.wb_clk(dut.wb_clk), .wb_rst(dut.wb_rst), .wb_stb(dut.wb_stb), .wb_cyc(dut.wb_cyc), .wb_we(dut.wb_we), .wb_addr(dut.wb_addr), .wb_dat_i(dut.wb_dat_i), .wb_dat_o(dut.wb_dat_o), .wb_ack(dut.wb_ack));

reg ufm_wr_rq = 0;
reg ufm_rd_rq = 0;
reg [3:0] st = ST_IDLE;
reg [7:0] ufm_wr_data = 8'bZ;
reg [4:0] ufm_wr_data_idx = 0;

wire [7:0] ufm_rd_data;
wire [7:0] wb_addr;
wire [7:0] wb_dat_i;
wire [7:0] wb_dat_o;

ufm1 dut(clk, ufm_wr_rq, ufm_rd_rq, ufm_wr_data, ufm_wr_ack, ufm_rd_data, ufm_rd_ack, ufm_done,
         wb_clk, wb_rst, wb_cyc, wb_stb, wb_we, wb_addr, wb_dat_i, wb_dat_o, wb_ack);

always @(posedge clk)
begin
   case(st)
      ST_IDLE:
      begin
        ufm_rd_rq <= 1;
        st <= ST_READING;
      end
      ST_READING:
      begin
        ufm_rd_rq <= 0;
        if(ufm_done)
        begin
          ufm_wr_rq <= 1;
          ufm_wr_data <= WRDATA[ufm_wr_data_idx];
          ufm_wr_data_idx <= ufm_wr_data_idx + 1;
          st <= ST_WRITING;
        end
      end
      ST_WRITING:
      begin
        ufm_wr_rq <= 0;
        if(ufm_wr_ack)
        begin
          ufm_wr_data <= WRDATA[ufm_wr_data_idx];
          ufm_wr_data_idx <= ufm_wr_data_idx + 1;
        end
        if(ufm_done) st <= ST_FINISHED;
      end
   endcase
end

endmodule

A: The issue was that I had a default value for the wb_rd_data wire inside the DUT:
wire [7:0] wb_rd_data = 0;

So it should have been just
wire [7:0] wb_rd_data;

So it has multiple assignments to the same wire - from the port and the default value and the bits that conflicted came up as Xs.
I had to try to synthesize this in Diamond to find the issue.


text:
Q: C++ Class Serialization I quite recently learned about the C++ classes friend keyword and the uses in serialization and now I need some help in getting it to work.
I have no problem serializing my class to a file, it's working great, however i'm having a hard time trying to read this file into a vector container. I'm sure I need a loop in my code that reads line by line, but since the class has different types I guess I can't use std::getline() and also maybe that approach wouldn't use the istream method i implemented?
A sample output file would be:
Person 1
2009
1

Person 2
2001
0

My code:
class SalesPeople {
    friend ostream &operator<<(ostream &stream, SalesPeople salesppl);
    friend istream &operator>>(istream &stream, SalesPeople &salesppl);

    private:
        string fullname;
        int employeeID;
        int startYear;
        bool status;
};

ostream &operator<<(ostream &stream, SalesPeople salesppl)
{
    stream << salesppl.fullname << endl;
    stream << salesppl.startYear << endl;
    stream << salesppl.status << endl;
    stream << endl;
    return stream;
}

istream &operator>>(istream &stream, SalesPeople &salesppl)
{
    stream >> salesppl.fullname;
    stream >> salesppl.startYear;
    stream >> salesppl.status;
    // not sure how to read that empty extra line here ?
    return stream;
}

// need some help here trying to read the file into a vector<SalesPeople>
SalesPeople employee;
vector<SalesPeople> employees;

ifstream read("employees.dat", ios::in);
if (!read) {
   cerr << "Unable to open input file.\n";
   return 1;
}

// i am pretty sure i need a loop here and should go line by line
// to read all the records, however the class has different
// types and im not sure how to use the istream method here.

read >> employee;
employees.push_back(employee);

By the way, I know that the Boost library has a great serialization class, however I'm trying to learn how serialization would work using the STL library for now.
Thanks a lot in advance for any help that you can give me and for getting me in the right track!

A: It looks like you pretty much have all the code you need already!  I copied your code and compiled it with some changes to read the SalesPeople in from a file in a loop.  I will include the changes below, but since this is for your homework, you may just want to read and think about the following hints before looking at the code.

*

*For reading the SalesPeople in a
loop, I would recommend that you take
a look at this FAQ.  It has an
example of almost exactly what you
need.  FAQ 15.4 will also help
you, I believe.

*For your question on how to handle
the extra empty line when reading
from the file, check out this
link.  You can very simply
extract whitespace this way.

*As jfclavette suggested, I would
recommend looking into
std::getline for reading in the
SalesPerson's full name, since you
need everything on that line into one
string.
I have one question for you, though: what about the employeeID?  I notice that it is being ignored in your sample code.  Is that on purpose?
And now, if you still need help, you can check out the code I wrote to get this to work:
istream &operator>>(istream &stream, SalesPeople &salesppl)
{
    //stream >> salesppl.fullname;
    getline(stream, salesppl.fullname);
    stream >> salesppl.startYear;
    stream >> salesppl.status;
    // not sure how to read that empty extra line here ?
    stream >> ws;
    return stream;
}

while(read >> employee)
{
    // cout << employee; // to verify the input, uncomment this line
    employees.push_back(employee);
}

Also, as jfclavette suggested, it may not be a bad idea to add some input validation (check the stream status after reading from it and verify that it is still good).  Although I would recommend using the while() loop for the reasons stated in FAQ 15.5.

A: Not sure what your problem is.  What exactly are you not understanding ?  The fact that your names are composed of multiple tokens ?  There's no magic way to do it, you might want to get the name trough getline().  Alternatively, you may want to specify the number of tokens when serializing and read the appropriate token count.  ie, your file might look like.
2 Person 1
I assumed that Person was the first name and 1 the last name here.  You might also enforce the notion that there's one first name, and one last name and just read each one separately.
You'll typically loop while (!ifstream.eof()) and read.  Of course, you should always validate the inputs.
Also, why are you adding an extra endl between each record ?  Serialized data need not be pretty. :)


text:
Q: writeline problem in python I have a very basic problem. I am learning my first steps with python & scripting in general and so even this makes me wonder:
I want to read & write lines to new file:
ifile=open("C:\Python24\OtsakkeillaSPSS.csv", "r")
ofile = open("C:\Python24\OtsakkeillaSPSSout.csv", "w")

#read first line with headers
line1 = ifile.readline()
print line1

#read following lines which contain data & write it to ofile
for line in ifile:
    if not line:
        break
    ofile.write(line)

if i print this to the screen i get all my lines done nicely:
0,26100,568,8636
0,11130,555,**3570
0,57100,77,2405**
0,60120,116,1193
0,33540,166,5007
0,95420,318,2310
0,20320,560,7607
0,4300,692,3969
0,65610,341,2073
0,1720,0,0
0,78850,228,1515
0,78870,118,1222

If i write it to ofile i end up missing some 15 lines:
0,6100,948,8332
0,26100,568,8636
0,11130,555

I would appreciate if someone could point out to me what is it that i don´t understand?
Reg,
Jaani

A: #read following lines which contain data & write it to ofile
for line in ifile:
    if not line:
        continue          #break stops the loop, you should use continue
    ofile.write(line)

A: You should be calling ofile.close() according to python docs.
I'm not sure that writes are fully flushed out to a file without an explicit close.
Also, as SilentGhost mentioned, check for empty lines in your input file.
And as mentioned by stefanw below, that "if.. break" statement isn't necessary in a for in.

A: The "if not line:" - Check is unnecessary.
for line in ifile:
    ofile.write(line)

A: Why are you using python2.4? the latest is python2.6
and then you can use
from contextlib import nested
ipath = "C:\Python24\OtsakkeillaSPSS.csv"
opath = "C:\Python24\OtsakkeillaSPSSout.csv"
with nested(open(ipath,'r'), open(opath,'w') as ifile, ofile:

    #read first line with headers
    line1 = ifile.readline()
    print line1

    #read following lines which contain data & write it to ofile
    for line in ifile:
        ofile.write(line)

A: oh, why does it look so foolish, the formation i mean?
Give it another go...
hi,
I have a very basic problem. I am learning my first steps with python & scripting in general and so even this makes me wonder:
I want to read & write lines to new file:
ifile=open("C:\Python24\OtsakkeillaSPSS.csv", "r")
ofile = open("C:\Python24\OtsakkeillaSPSSout.csv", "w")
read first line with headers
line1 = ifile.readline()
print line1
read following lines which contain data & write it to ofile
for line in ifile:
    if not line:
        break
    ofile.write(line)
if i print this to the screen i get all my lines done nicely:
0,26100,568,8636
0,11130,555,3570
0,57100,77,2405
0,60120,116,1193
0,33540,166,5007
0,95420,318,2310
0,20320,560,7607
0,4300,692,3969
0,65610,341,2073
0,1720,0,0
0,78850,228,1515
0,78870,118,1222
If i write it to ofile i end up missing some 15 lines:
0,6100,948,8332
0,26100,568,8636
0,11130,555
I would appreciate if someone could point out to me what is it that i don´t understand?
Reg,
Jaani


text:
Q: cardview size not decreasing in my recycler view in my app I am very new to Android.  I am trying to resize my cardview but it has no effect and reverts to its previous size.  Can any one help me ?
Here is my cardview and Recyclerview code.
Recyclerview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="1dp"
    android:paddingBottom="3dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/fragment_primary" tools:context=".Primary">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:paddingBottom="3dp"
        android:paddingLeft="3dp"
        android:paddingRight="3dp"
        android:paddingTop="2dp" />
</RelativeLayout>

cardview layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:layout_width="wrap_content"
    android:layout_height="360dp"
    android:layout_margin="8dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView
            android:id="@+id/row_image"
            android:layout_width="fill_parent"
            android:layout_height="250dp"
            android:layout_alignParentTop="true"
            android:scaleType="centerCrop"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
        <TextView
            android:id="@+id/row_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/row_image"
            android:maxLines="3"
            android:padding="8dp"
            android:textColor="#222"
            android:textStyle="bold"
            android:textSize="22dp" />
        <TextView
            android:id="@+id/row_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/row_title"
            android:maxLines="3"
            android:padding="8dp"
            android:textColor="#666"
            android:textSize="14dp" />
    </RelativeLayout>
</android.support.v7.widget.CardView>

A: If you want to resize full CardView i think you need to change these lines:
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

Nowadays, you only changed height of the image:
    android:layout_height="250dp"

Read also this: What's the difference between fill_parent and wrap_content?
EDIT: Delete paddings in RecyclerView - the take some space.
If have more question, please free to ask


text:
Q: NPM install and npm run dev giving error I have installed package npm i vue-admin-paper-dashboard. And after that when I run
npm install I am getting below error:
npm ERR! Windows_NT 10.0.15063
npm ERR! argv "c:\\Program Files\\nodejs\\node.exe" "c:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install"
npm ERR! node v6.10.2
npm ERR! npm  v3.10.10
npm ERR! path E:\xampp\htdocs\VUEjs Templates\VUEjs-1\vue-paper-dashboard\node_modules\js-beautify\js\bin\css-beautify.js
npm ERR! code ENOENT
npm ERR! errno -4058
npm ERR! syscall chmod

npm ERR! enoent ENOENT: no such file or directory, chmod 'E:\xampp\htdocs\VUEjs Templates\VUEjs-1\vue-paper-dashboard\node_modules\js-beautify\js\bin\css-beautify.js'
npm ERR! enoent ENOENT: no such file or directory, chmod 'E:\xampp\htdocs\VUEjs Templates\VUEjs-1\vue-paper-dashboard\node_modules\js-beautify\js\bin\css-beautify.js'
npm ERR! enoent This is most likely not a problem with npm itself
npm ERR! enoent and is related to npm not being able to find a file.
npm ERR! enoent

And when I run npm run dev, I am getting below error:
npm ERR! Windows_NT 10.0.15063
npm ERR! argv "c:\\Program Files\\nodejs\\node.exe" "c:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "dev"
npm ERR! node v6.10.2
npm ERR! npm  v3.10.10
npm ERR! code ELIFECYCLE
npm ERR! vue-admin-paper-dashboard@1.0.0 dev: `cross-env ENABLE_ESLINT=true node build/dev-server.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the vue-admin-paper-dashboard@1.0.0 dev script 'cross-env ENABLE_ESLINT=true node build/dev-server.js'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the vue-admin-paper-dashboard package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     cross-env ENABLE_ESLINT=true node build/dev-server.js
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs vue-admin-paper-dashboard
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls vue-admin-paper-dashboard
npm ERR! There is likely additional logging output above.<br />

NOTE: I have installed cross-env package globally.
EDIT:
I have tried cloning the project: LINK, and then run npm install still I am getting same error.

A: JS-Beautify 1.7.0 is broken, version 1.6.14 must work:
https://stackoverflow.com/a/46275582/2953376
https://github.com/beautify-web/js-beautify/issues/1247

A: to fix the JS-Beautify 1.7.0 be sure you are using the node version >= 8. add the package-lock.json in the project root
add the version of JS-Beautify in the "dependencies" like this:
 {
  "name": "my project name",
  "version": "1.0.0",
  "lockfileVersion": 1,
  "dependencies": {
    "js-beautify": {
      "version": "1.6.14",
      "resolved": "https://registry.npmjs.org/js-beautify/-/js-beautify-1.6.14.tgz",
      "integrity": "sha1-07j3Mi0CuSd9WL0jgmTDJ+WARM0=",
      "dev": true
    }
  }
}

A: Have you tried installing using flags --save or --save-dev?


text:
Q: How can I execute a jar and capture the output? With Objective-C in a cocoa app, I want to execute a jar with some arguments and capture the output (stdout). How can I do this?

A: Launch the jar using NSTask. From NSTask you can get an NSPipe or NSFileHandle that represents the stdout of the launched process.


text:
Q: Asset catalog with PDF Vector Image does not export @3x resolution for iOS I am trying to use PDF Image in my Asset Catalogs files to automatically generate png files. This feature as been presented in WWDC 2014, video 411 (What's new in Interface Builder)
On iOS XCode is supposed to render the PDF to @1x, @2x, @3x PNG at the build time.
It checked at my generated archives using cartool (cannot post the link as I lack reputation on SO) and it seems only the @1x and @2x resolutions are generated.
I looked a bit around the internet and found this post and this one. The later provides a sample project, which I tried. It also only generated those 2 resolutions.
Did anyone tried this and lucky generated @3x images?
Regards
Nicolas

A: Found a fork that someone made.  Seems to have worked for me to also get the @3x PNG files.  Hope this helps!
https://github.com/G-P-S/cartool


text:
Q: How to specify floating point separator in astropy.io.ascii? I have a table, where decimal separator is ,. When I am trying to read this table using astropy ascii module, the numbers are of numpy.str_ type.
from astropy.io import ascii
data = ascii.read(inputName)

If I manually replace , to . then it's numpy.float, which is what I want. Is there any way to tell to astropy.io to use , as decimal separator character?


text:
Q: What is the difference between np.array and np.stack applied to a list of images I have a list containing numpy arrays of identical 2D shape
I wanna pack those images for a ConvNet Classifier and I tried two approaches as shown below :
X_train = np.array(lst_imgs).reshape(m, 24, 40, 1)/255
XX_train = np.stack((lst_imgs), -1).reshape(m, 24, 40, 1)/255

both tensors yield shape of : (4828, 24, 40, 1)
However they don't contain the same elements at each index. Can someone please explain to me what is the difference between np.array and np.stack for this purpose and which one is the most suitable ?
Thank you very much !

A: np.stack and np.array provide exactly the same array, unless you pass a specific axis to the second one.
Let us look at a smaller example on a tiny list of 2d arrays
>>> lst = [i for i in np.arange(8).reshape(2,2,2)]
>>> lst
[array([[0, 1],
       [2, 3]]), array([[4, 5],
       [6, 7]])]

Ok, it is indeed a list of 2 2D arrays each of shape (2,2)
>>> np.array(lst)
array([[[0, 1],
        [2, 3]],

       [[4, 5],
        [6, 7]]])
>>> np.stack(lst)
array([[[0, 1],
        [2, 3]],

       [[4, 5],
        [6, 7]]])

Ok, we have the same result
>>> np.stack(lst, -1)
array([[[0, 4],
        [1, 5]],

       [[2, 6],
        [3, 7]]])

But if we stack of the third axis (-1 here means last), we also get a 3D array but with elements in a different order.
Here I cannot know which is the correct order for you use case. I have just explained why you get different results.


text:
Q: home web/file server At Home we have a lot of media Content on three computers. I was thinking of centralizing them on one single machine that runs a web server that hosts all the content, and when we fetch a URL like : http://localhost/music it will show a HTML file that lists all the music files on the computer, and when we click  on a file,  it gets downloaded.
I don't  know  what to use so as to make this thing, I think Apache as a server  and PHP as a language..., any suggestions?

A: Install FreeNAS on your machine
http://www.freenas.org/

A: You don't even need to go that far.  Just install apache on a computer and have your music folder be a web directory.  You should be able to navigate to the page like so:  http://whateverip/music/ and apache will serve up that html page like you are suggesting.

A: If using windows, XAMPP is a pretty good solution.  You don't really need the PHP part, because all you need on the server after installing a WAMP solution, is to place all your content in the folder that the server uses.
If using Linux, definately install LAMP, there is an easy install of it whether using Ubuntu or other Linux distrubtions.
If using a MAC, there are similar solutions as LAMP.  Some are hassle-free.
In any case, all of these use Apache as the server; that is the way to go.  It's not as hard as you think, just install the software, and put your files in the appropriate directory, then from each of the other machines, to find the files you would probably type this into your address bar:
http://192.168.1.101/

Which of course is the address of the web server on your Local area network.  It is very likely an address that is very similar to that, maybe ending with two different last two numbers.

A: I would second the freenas route if what you want to store is valuable to you in terms of time or money or electricity. It makes a great headless fileserver with web GUI, supports ZFS filesystem (similar to  software RAID5 so you can lose a disk and not lose your data). More valuable to me it also supports replication to a duplicate server.
It can run on very low power hardware using freeBSD as the OS. I measured one of my boxes and it uses about 45 Watts. The OS loads from a USB stick so all your disks become data disks. It holds the system in RAM so your USB does not get any writes to it so the USB lasts a very long time. It will serve CIFS for your windows boxes, AFP for your macs, and NFS for your linux systems. Plug-ins allow for such things as DLNA media servers. I have had three boxes running stable with no reboots for over a year with 6x 3TB drives per box.
A typical hardware setup might be ASUS C60M1-I AMD Fusion board (combined CPU/VGA/NICC/6SATA)for about 75 bucks, 16GB RAM, PSU, USB stick - and voila - add 3 hard drives and you have a low-power RAID fileserver. Get two and you can replicate one server to another in a different physical location.


text:
Q: ASM Вставки iDIV //Pascal
NumX:=-40;

//Assm
MOV     EAX,NumX
MOV     ECX,4
IDIV    ECX
MOV     IntPart, EAX

Почему IntPart возвращает 1073741815?

A: Потому что значение беззнаковое.
У вас в EAX помещается преобразованное в беззнаковое 4-байтное целое -40, что дает значение FFFFFFD8, или 4294967256 в десятичном виде.
Делим на 4, получаем 3FFFFFF6, или 1073741814 в десятичном виде.
Вот как правильно должен выглядеть ваш код:
MOV     EAX,NumX
CDQ
MOV     ECX,4
IDIV    ECX
MOV     IntPart, EAX

Знаковое расширение EAX в EDX:EAX забыто...


text:
Q: How to add Twitter card image to individual documentation page? Is it possible to add a Twitter card image to the individual documentation page? I know that I can use Meta image in docusaurus.config.js but this is a site-wide setting.

A: You can use the front matter at the top of each .md page to add metadata, as well as the image that will be used in the Twitter card.
---
title: Page Title
description: Page description
slug: page-slug
tags:
  [
    some, tags
  ]
image: https://i.imgur.com/mErPwqL.png
---

# Page Title

Hello world


text:
Q: Md5 and Salt in Mysql how can "decode" the password stored in various e-commerce adding "salt". I'm not crypth experts... so, in past, i used something like:
SELECT * FROM mytable WHERE email=@email AND passwd=MD5(@pwd)

MySql MD5 function accept only one parameter... How can i do if i have a Salt string ?
Thanks

A: You need to add a column in mytable called salt and then retrieve this value when creating the MD5 Hash:
SELECT * FROM mytable WHERE email=@email AND passwd=MD5(salt + ':' +@pwd)

When inserting the record you would do:
INSERT INTO mytable(email, salt, passwd)
VALUES (@email, @salt, MD5(salt + ':' + @pwd)

A: Salt is a  string you add to the beginning of text which should be encrypted.
Do it like: SELECT * FROM mytable WHERE email=@email AND passwd=MD5(CONCAT(@salt, @pwd))

A: That logic should be in the application, then you'll simply compare the calculated value against what's stored in the database.
(If not in the application, you could use functions in MySQL, but I wouldn't recommend that approach. I like to keep all application logic in one place if possible, not spread in different parts.)
If you run functions like that in the WHERE clauses of your query, MySQL will be unable to use an index on passwd because it has to calculate something for every value in the passwd column. Instead, do your salting and hashing in your application, then compare that final string against your stored info in a plain query that can use an index, like this
SELECT * FROM mytable WHERE email=@email AND passwd=@pwdhash


text:
Q: How to solve Cyclic Dependency public class NotificationService: INotificationService{

    private ILogService _logService;

    public NotificationService(ILogService logService){

        _logService = logService;

    }

}

public class LogService: ILogService{

    private INotificationService _notificationService;

    public LogService(INotificationService notificationService){

    _notificationService = notificationService;

    }

}

I came into a situation where two classes depends on each other. I am using Ninject.
Bind<INotificationService>().To<NotificationService>();
Bind<ILogService>().To<LogService>();

The codes above are causing Cyclic Dependency.
What is the proper way to solve this? Please share some codes.

A: A cyclic dependency is an indication of a design or modeling problem in your software. Although you can construct your object graph by using property injection, you will ignore the root cause and add another problem: property injection causes Temporal Coupling.
Instead, the solution is to look at the design closely. Often you will find that there is a third 'hidden' service that needs to be abstracted. Both services can depend on this new service.
Since your question is quite high-level with just the interface names and the dependencies between the components, it's hard to be specific, but here's an possible solution:
public class Logger : ILogger { }

public class NotificationService : INotificationService{
    private ILogger _logger;

    public NotificationService(ILogger logger){
        _logger = logger;
    }
}

public class LogService : ILogService {
    private ILogger _logger;

    public LogService(ILogger logger){
        _logger = logger;
    }
}

A: Use property injection for one (or both) of the classes:
Cyclic dependency with ninject
public class NotificationService: INotificationService{

    ILogService LogService { set; }
}

public class LogService: ILogService{

    private INotificationService _notificationService;

    public LogService(INotificationService notificationService){
    {
        notificationService.LogService = this;
    }
}


text:
Q: How to pass generic list to WCF? I'm trying get a complex object from my service. I have class PackedObject that passed fine. But when I'm trying to get List<PackedObject> nothing happen.
How to pass generic lists through WCF?
Here is a source code:
My interface
 [ServiceContract(SessionMode = SessionMode.Required, CallbackContract=typeof(ICallbackInterface))]
public interface IManager
{
    ...

    [OperationContract(IsOneWay = false, IsInitiating = false, IsTerminating = false)]
    List<PackedObject> GetByQuery(string typeName, string query);

    [OperationContract(IsOneWay = false, IsInitiating = false, IsTerminating = false)]
    PackedObject GetFirstByQuery(string typeName, string query);

    ...
}

Packed object
  [DataContract]
public class PackedObject
{
    [DataMember]
    private String _objTypeName;

    [DataMember]
    private Guid _id;

    [DataMember]
    private Dictionary<string, object> _fields = new Dictionary<string,object>();
    ...
}

Interface implementation:
    public List<PackedObject> GetByQuery(string typeName, string query)
    {
        ServerTableManager stm = getTableManager(typeName);
        List<DataRow> ldr = stm.GetByQuery(query);
        List<PackedObject> lpo = PackedObject.Pack(ldr,typeName);

        //PackedObjectList pol = new PackedObjectList(lpo);
        return lpo;
    }

A: I think the problem is in the other place.
While debugging  i found that DataContractSerializer refused to serialize PackedObject with null value in the Dictionary.

A: *

*Try making your class serialized.

*Type cast result at client end.

Hope these two will solve your issue.


text:
Q: How to make my bot skip over urls that don't exist Hey guys I was wondering if there was a way to make my bot skip invalid urls after 1 try to continue with the for loop but continue doesn't seem to work
def check_valid(stripped_results):
  global vstripped_results
  vstripped_results = []
  for tag in stripped_results:
    conn = requests.head("https://" + tag)
    conn2 = requests.head("http://" + tag)
    status_code = conn.status_code
    website_is_up = status_code == 200
    if website_is_up:
      vstripped_results.append(tag)
    else:
      continue

stripped results is an array of an unknown amount of domains and Subdomains which is why I have the 'https://' part and tbh I'm not even sure whether my if statement is effective or not.
Any help would be greatly appreciated I don't want to get rate limited by discord anymore from sending so many invalid domains through. :(

A: This is easy. To check the validity of a URL there exist a python library, namely Validators. This library can be used to validate any URL for if it exist or not. Let's take it step by step.
Firstly,
Here is the documentation link for validators:
https://validators.readthedocs.io/en/latest/

How do you validate a link using validators?
It is simple. Let's work on command line for a moment.
This image shows it. This module gives out boolean result on if it is a valid link or not.

Here for the link of this question it gave out True and when it would be false then it would give you the error.
You can validate it using this syntax:
validators.url('Add your URL variable here')

Remember that this gives boolean value so code for it that way.
So you can use it this way...

I wouldn't be implementing it in your code as I want you to try it yourself once. I would help you with this if you are unable to do it.
Thank You! :)

A: Try this?
def check_valid(stripped_results):
global vstripped_results
vstripped_results = []
for tag in stripped_results:
  conn = requests.head("https://" + tag)
  conn2 = requests.head("http://" + tag)
  status_code = conn.status_code
  website_is_up = status_code == 200
  if website_is_up:
    vstripped_results.append(tag)
  else:
    #Do the thing here


text:
Q: Point division Elliptic Curve in Java Suppose I have G(x,y) = k.P(x,y). I know G(x,y) and P(x,y).
How do I calculate k?

A: If G(x,y) and P(x,y)are on a secure elliptic curve for ECC, the problem of solving k is called "elliptic curve discrete logarithm problem", or ECDLP. It is infeasible to find k on a secure elliptic curve.
If you're not on such curve, enumerating all possible k and see if G=kP is a reasonable approach.


text:
Q: citation numbering order issue for multiple citations I have cited a reference in the source body as reference 1, then reference 2, and reference 3 followed in order, but the issue is, after recompiling at the position of reference 1 it appeared as [2] and in Bibliography section the reference 1 goes down and stated as the Reference 2.
Renewable energy was shared around 11\% of total global energy
consumption and 29\% of electrical power generation in 2020 only
\cite{r1}. Among the sources of renewable energy wind energy is
the most abundant worldwide and cost-effective than renewable
sources, which is using since ancient times for milling, pumping
and grinding grains purposes \cite{r2,r3_Yannopoulos2015}.


text:
Q: Hiding the pins/markers from the map view through method in iPhone In my viewDidLoad: method to show the different locations of number of vehicles I have used some pins/markers/annotations.
What I want to know is that if user selects only one vehicle then how can I hide the other pins/markers.
Is it possible?
How to do that?

A: Yes, this is possible. You first need to add an observer to each annotationView to detect when a user selects an annotation. First you must add:
static NSString * const GMAP_ANNOTATION_SELECTED = @"gMapAnnotationSelected";

to the top of your implementation (right below @implementation). You then must add an observer to each annotationView. This is done by:
-(MKAnnotationView *)mapView:(MKMapView *)localMapView viewForAnnotation:(id<MKAnnotation>)annotation

//Create your custom annotation called annotationView

[annotationView addObserver:self forKeyPath:@"selected" options:NSKeyValueObservingOptionNew context:(void*)("gMapAnnotationSelected")];

return annotationView;

Then add the following function to the same file which gets called when the annotationView is selected:
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)localContext {
char *actionCharStr = (char*)localContext;
NSString *action = [NSString stringWithCString:actionCharStr encoding:NSStringEncodingConversionAllowLossy];

if ([action isEqualToString:GMAP_ANNOTATION_SELECTED]) {
    BOOL annotationSelected = [[change valueForKey:@"new"] boolValue];

    CustomAnnotationView *customAnnotationView;
    if (annotationSelected) {
        currentAnnotationView = (CustomAnnotationView*)object;
        //Go through each annotation in [yourMap annotations] and remove from map if not equal to [currentAnnotationView annotation]
    } else {
        currentAnnotationView = (CustomAnnotationView*)object;
        //Add the annotations back once the annotation is no longer selected
    }
}}

For more information, look at:
How to detect AnnotationView selected
MKMapViewDelegate


text:
Q: Javascript creating array of arrays runtime How to best create this in runtime?
var fields = ["abc", "def", "somepar", "otherpar"];
var toSet = "foo";
// How to genereate this variable from code
var valuepairs = [["Progress", progress], [fields[0], toSet], [fields[1], toSet], [fields[2], toSet]]; // [fields[n], toSet]

Regards
Larsi

A: Use the .push method to append to an array...
var valuepairs = [["Progress", progress]];
for (var k = 0; k < fields.length; ++ k)
   valuepairs.push([fields[k], toSet]);

A: var valuepairs = new Array(new Array('progress',progress)); //first line is hardcoded...
for (var i=0; i<fields.length; i++) {
   valuepairs.push(new Array(fields[i],toSet));
}


text:
Q: App Bar button on the right side of the screen Windows 8 metro style apps I am developing the metro style windows 8 app using html,javascript and css.
I am using app bar at bottom in my application.Following is the html code.
<div id="appbarbottom" data-win-control="WinJS.UI.AppBar" data-win-options="{layout:'custom',placement:'bottom'}">
    <button id="playerBut" data-win-control="WinJS.UI.AppBarCommand" data-win-options="{section:'global',label:'Player', icon:'placeholder',type:'flyout',flyout:sportsFlyout}" type="button"></button>

</div>

I rad the official document it said that section:'global' will make the button to the right side. I did that but it has no effect.
I had tried with section:'selection'  but still button remains on the left side
I have searched for alternative solution but everyone says the same thing so how can I achieve my goal.Please give me helpful hand.
Thank You.

A: I had removed  'layout:custom' from data-win-options="{layout:'custom',placement:'bottom'}
of the data-win-control="WinJS.UI.AppBar"  and it solved my problem.
I almost wasted 4 hours on this.
I hope this will help others.
Thanks.


text:
Q: Overloading template operators I am trying to overload the += opperator on my template Vector class.
template<unsigned int dimensions, typename TValue>
class Vector
{
private:
    std::array<TValue, dimensions> m_values;
public:
    Vector(){
        for (int i = 0; i < dimensions; i++){
            m_values[i] = TValue();
        }
    };
    Vector(std::array<TValue, dimensions> elements){
        for (int i = 0; i < dimensions; i++){
            m_values[i] = elements[i];
        }
    };

    inline void set(VectorDimensions dimension, TValue value){
        m_values[dimension] = value;
    };

    inline TValue get(VectorDimensions dimension) const{
        return m_values[dimension];
    };

    inline unsigned int getSize() const{
        return dimensions;
    };

    const std::array<TValue, dimensions> getValues() const{
        return m_values;
    };

    friend ostream& operator<<(ostream& os, const Vector<dimensions, TValue>& vt) {
        array<TValue, dimensions> values = vt.getValues();
        os << '[';
        for (unsigned int i = 0; i < vt.getSize(); i++){
            os << values[i] << values[i+1] ? ", " : "";
        }
        os << ']';
        return os;
    };

    friend Vector<dimensions, TValue>& operator+=(const Vector<dimensions, TValue>& vt) {
        array<TValue, dimensions> values = vt.getValues();
        for (unsigned int i = 0; i < vt.getSize(); i++){
            m_values[i] += values[i];
        }
        return *this;
    };

};

Upon adding the overload for the += opperator I get many of the following errors:

error C2805: binary 'operator +=' has too few parameters
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2334: unexpected token(s) preceding '{'; skipping apparent function body.
error C2238: unexpected token(s) preceding ';'
syntax error : missing ';' before '<'
error C2143: syntax error : missing ';' before '++'
error C2143: syntax error : missing ')' before ';'
error C2059: syntax error : 'return'
error C2059: syntax error : 'for'
error C2059: syntax error : ')'

An explanation as to why or how these errors actually get caused by whatever it is that I have done wrong may be useful. Thanks

A: I was able to stop the errors by removing the friend keyword from before the += operator definition. According to this page http://en.cppreference.com/w/cpp/language/operators
class X {
 public:
  X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
  {                           // but often is, to modify the private members)
    /* addition of rhs to *this takes place here */
    return *this; // return the result by reference
  }

  // friends defined inside class body are inline and are hidden from non-ADL lookup
  friend X operator+(X lhs,       // passing first arg by value helps optimize chained a+b+c
                    const X& rhs) // alternatively, both parameters may be const references.
  {
     return lhs += rhs; // reuse compound assignment and return the result by value
  }
};

This is how the + and += opperators should be overloaded.


text:
Q: Custom HealthIndicator not registered when autowiring other beans I'm trying to implement a custom actuator HealthIndicator to show a downstream API status, but autowiring a RestTemplate results in the HealthIndicator not showing up in the details at all.
Im using spring-boot-starter-actuator version 2.1.4.RELEASE
This code which doesn't include an autowired component works and appears in the list of details under /actuator/health
@Component
public class ApiHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {
        return Health.up()
            .build();
    }
}

Response from /actuator/health:
{
    "status": "UP",
    "details": {
        "api": {
            "status": "UP"
        },
        "diskSpace": {
            "status": "UP",
            "details": {
                "total": 253883043840,
                "free": 75249156096,
                "threshold": 10485760
            }
        }
    }
}

But as soon as I add an autowired RestTemplate, the whole healthindicator isnt registered, neither is any exception thrown:
@Component
public class ApiHealthIndicator implements HealthIndicator {

    private RestTemplate apiRestTemplate;

    @Autowired
    public void setDefaultPegaRestTemplate(RestTemplate apiRestTemplate){
        this.apiRestTemplate = apiRestTemplate;
        System.out.println("No exception thrown");
        //Breakpoint here also reveals RestTemplate is not null and autowired correctly
    }

    @Override
    public Health health() {
        // Breakpoint here is never reached
        return Health.up()
            .build();
    }
}

Response from /actuator/health:
{
    "status": "UP",
    "details": {
        "diskSpace": {
            "status": "UP",
            "details": {
                "total": 253883043840,
                "free": 75249156096,
                "threshold": 10485760
            }
        }
    }
}

I've been trying to figure out why the HealthIndicator is completely ignored in this case even after the autowiring passes successfully.


text:
Q: how to use timestamp in sql i use this but it having some error

CREATE TABLE notifications (   id int,   postdate timestamp NULL
  DEFAULT CURRENT_TIMESTAMP,   descriptions varchar(200) DEFAULT NULL,
  notitype varchar(20) DEFAULT NULL,   PRIMARY KEY (id) )

A: Try to change
postdate timestamp NULL DEFAULT CURRENT_TIMESTAMP

to
postdate DATETIME NULL DEFAULT GETUTCDATE()

I thought you are using MS SQL, aren't you? Your tags were asp.net and so on. Now you checked mysql, are you sure you need mysql?

A: try this one plz

CREATE TABLE notifications ( id int, postdate DATETIME NULL DEFAULT
  GETUTCDATE(), descriptions varchar(200) DEFAULT NULL, notitype
  varchar(20) DEFAULT NULL, PRIMARY KEY (id)  )

A: Taken from here
CREATE TABLE example_timestamp (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
data VARCHAR(100),
cur_timestamp TIMESTAMP(8)

 +----+--------------------------+---------------------+
 | id | data                     | cur_timestamp       |
 +----+--------------------------+---------------------+
 |  1 | The time of creation is: | 2004-12-01 20:37:22 |
 +----+--------------------------+---------------------+


text:
Q: Codeigniter sessions with database not working in localhost but working in server I am tring to  get the session information in home page on my localhost but I am not getting it. But getting this information on my server.
In Localhost:-
enter image description here
In Server:-
enter image description here
I am trying to get with following code:-

print_r($this->session);

A: You can set data to session simply like this in Codeigniter:
$this->load->library('session');
$this->session->set_userdata(array(
    'user_id'  => $user->uid,
    'username' => $user->username,
    'groupid'  => $user->groupid,
    'date'     => $user->date_cr,
    'serial'   => $user->serial,
    'rec_id'   => $user->rec_id,
    'status'   => TRUE
));

and you can get it like this:
$u_rec_id = $this->session->userdata('rec_id');
$serial = $this->session->userdata('serial');


text:
Q: DevExpress React Grid Reordering along with fixed column not working There is a problem with @devexpress/dx-react-grid-material-ui when reordering the columns and if the grid has a fixed column in place , if we drop the column on another column and not drop it in the given spot , it moves the column to right ( after fixed column ).
Expected is if its not dropped in either right of left of a column it has to go back to its original location.
Imports code :
 import {
  ...
  TableColumnResizing,
  TableFixedColumns,
  ...
} from '@devexpress/dx-react-grid-material-ui';

Fixed column code :
  <TableFixedColumns
      leftColumns={[fixedColumns.concat('action'), TableSelection.COLUMN_TYPE]}
      rightColumns={['command']}
      cellComponent={FixedCell}
    />

Column reordering code :
 <TableColumnReordering defaultOrder={columns.map((column) => column.name)} />


text:
Q: NestList with lower and upper limit I'm creating a series of centered lines in {0,0} tilted from a set of angles.
The first angle is $30°$ and the last one is $110°$.
I want to control the number of lines between these two angles, but I can not use Subdivide because the angles are not evenly spaced.
The idea is that each angle has a relative proportion to the previous angle.
I did a test with $quant=20$:
ClearAll["Global`*"]
quant = 20;
ang = NestList[#*1.067121 &, 30, quant]
p = FromPolarCoordinates[{5, # Degree}] &/@ ang // N;
Graphics[{Line[{{0, 0}, #}] & /@ p}]

And another test with $quant=10$:
ClearAll["Global`*"]
quant = 10;
ang = NestList[#*1.138747 &, 30, quant]
p = FromPolarCoordinates[{5, # Degree}] &/@ ang // N;
Graphics[{Line[{{0, 0}, #}] & /@ p}]

In both codes I had to test the values $1.067121$ (First code) and $1.138747$ (Second code) to reach the last angle of $110°$.
Is there something in "NestList" that I can increase?
If you have another idea outside of that, it is also an option.
EDIT
I tried this and almost got it:
Solve[Last[NestList[#*coeff &,30,20]]==110,{coeff}]//N

A: So the answer is:
ClearAll["Global`*"]
quant = 20;
ang = NestList[#*Exp[Log[110/30]/quant] &, 30, quant]
p = FromPolarCoordinates[{5, # Degree}] &/@ ang // N;
Graphics[{Line[{{0, 0}, #}] & /@ p}]

A: ClearAll[fun] ;
fun[num_,rad_:1] := Block[
  {ang, poi, lin},
  ang = N[Map[Function[Rescale[Slot[1],{1,num},{30,110}]]][Range[num]]] ;
  poi = Map[Function[First[CirclePoints[{rad,Slot[1] Degree},1]]],ang]  ;
  lin = Map[Function[Line[{{0.,0.},Slot[1]}]],poi]
] ;
Graphics[{Red,fun[2,1],Blue,fun[5,0.8],Green,fun[7,0.6]}]

A: Another way:
Block[{quant = 20, a = 30., b = 110.},
 ang = Exp[Log[a] + Log[b/a] Range[0., quant]/quant];
 p = 5 Transpose@Through[{Cos, Sin}[ang Degree]];
 lines = Transpose@ArrayReshape[p, Prepend[Dimensions@p, 2], 0.];
 Graphics@Line@lines
 ]

Alternatives for ang and lines:
ang = Exp[Log[a] + Log[b/a] Range[0., quant]/quant]
ang = a (b/a)^(Range[0., quant]/quant)
ang = Array[Exp, quant + 1, Log@{a, b}]

lines = Transpose@ArrayReshape[p, Prepend[Dimensions@p, 2], 0.]
lines = Transpose[{ConstantArray[0., Dimensions@p], p}]
lines = Transpose[{0. p, p}]


text:
Q: How to put session value store into database? I wanted to retrieve session array and put into other model But throws `

Call to a member function pluck() on array

Controller I used :
$orders =  $request->session()->get('order');
$order = new Order();
$order->school_id = $orders->pluck('school_id');
$order->order_date = $orders->pluck('order_date');
$order->time_slot = $orders->pluck('time_slot');

How do i access the session data and put into other model?
Here is the response I get when i dd() the session :
array:1 [▼
  0 => array:3 [▼
    "school_id" => "4"
    "order_date" => "11/25/2017"
    "time_slot" => "10am - 8pm"
  ]
]

A: try like this,
$orders =  $request->session()->get('order');
print_r($orders);

if you getting orders of school id array then you can get it by $orders['school_id']; and if you getting std object then you can retrieve it by $orders->school_id;
Use as per output of print_r(orders)
Then you can store it by
If std object ::
$order = new Order();
$order->school_id = $orders[0]->school_id;
$order->order_date = $orders[0]->order_date;
$order->time_slot = $orders[0]->time_slot;
$order->save();

If array ::
$order = new Order();
$order->school_id = $orders[0]['school_id'];
$order->order_date = $orders[0]['order_date'];
$order->time_slot = $orders[0]['time_slot'];
$order->save();

A: I would use the array_get helper.
https://laravel.com/docs/5.5/helpers#method-array-get
array_get($orders, 'school_id');

Additionally you can use a fallback as third parameter in case the value is not present in the session.

A: Session holds all data in Array and not Collection. Function pluck() can only be used for the collection.
Try doing array_get($orders, 'school_id'); as already mentioned by Marc or just $request->session()->get('order')['school_id'];

A: it depends on how did you store it into session, so if you used push, then it will be stored as array.
anyways change your code to the following:
$orders =  $request->session()-> pull('order',$defaultOrdersArrayCanBeHere);
$order = new Order();
$order->school_id = $orders['school_id'];
$order->order_date = $orders['order_date'];
$order->time_slot = $orders['time_slot'];

UPDATE:
Did you push it to session as so: session()->push('order', $order);
where:
$order = [
'school_id'=> $schoolId;
'order_date'=> $orderDate;
'time_slot'=> $timeSlot;
]

A:
Call to a member function pluck() on array

Your $orders variable is an array so you can't use pluck. You can do $order['key'] to access their values. Or as others suggested, use the helper function array_get


text:
Q: Difficulty in using Patterns and Matchers in a single invocation Salesforce example:
Boolean Test = Pattern.matches('a*b', 'aaaaab');

I'm attempting to use regular expression on a condition to check if a string has "You Order # 1234: ", but it's always returning false. What's wrong with it?
String OrderInfo = 'Hello: Purchased: Your Order # 1234: Processed.';
Boolean Test = Pattern.matches('Your Order # \\d{4}: ', OrderInfo);
System.debug(' Test : ' +Test);

Thanks.

A: You're mixing up match() which returns true if the entire input string matches the regex, and find() which returns true if the input string contains the regex. The following code returns true for both cases:
String OrderInfo = 'Hello: Purchased: Your Order # 1234: Processed.';
Boolean Test = Pattern.matches('.* Your Order # \\d{4}: .*', OrderInfo);
System.debug(' Test : ' +Test);
Boolean Test2 = Pattern.compile('Your Order # \\d{4}:').matcher(OrderInfo).find();
System.debug(' Test2 : ' +Test2);


text:
Q: Angular : how to get the loading time of a component after receiving the api response Angular : how to get the loading time of a component after receiving the api response
Hi Friends,
In my angular application (v13), I need to find the loading time of components after getting the api response. Is there any way to find it.
Thanks in advance
Regards

A: How about this?
You can render the component via Angular's component Renderer, Renderer2. Then measure the time passed in the same function.
You can automatize this step for all the components & or maybe you can write them as test cases, but you should provide all the necessary inputs to the component you create.


text:
Q: To Map AggregateIterable to a class I am performing an aggregation pipeline over mongodb database. Generated result is in the form of AggregateIterable  which is needed to be mapped to java pojo class.
#MyClass.java
@Getter
@Setter
@ToString
@Document(collection = "myCollection")
public class ODSMongo {

    @Field("_id")
    @Id
    private String _id;
    private String Key;
    private String projectKey;
    private Long highestIndex;
    private Long type;
    private Long exists;
}

#app.java
AggregateIterable<Document> output = collection.aggregate(Arrays.asList(
                match(new Document("projectKey", "myProject")),
                new Document("$group", new Document("_id", "$Key")
                        .append("maxQuantity", new Document("$max", "$highestIndex"))
                        .append("docs", new Document("$push", new Document("_id", "$_id").append("Key", "$Key")
                                .append("highestIndex", "$highestIndex").append("exists", "$exists").append("type", "$type")))),
                new Document("$project",
                        new Document("_id", 0L).append("docs",
                                new Document("$filter", new Document("input", "$docs").append("as", "doc").append(
                                        "cond",
                                        new Document("$eq", Arrays.asList("$$doc.highestIndex", "$maxQuantity"))))))));

Iterator<Document> iterator = output.iterator();
    while (iterator.hasNext()) {
        System.out.println(iterator.next().get("docs"));
    }

After performing above operations, the output which get is
[Document{{_id=56, Key=AGS, highestIndex=1, exists=1, type=0}}]
[Document{{_id=41, Key=GFT, highestIndex=1, exists=1, type=0}}]
[Document{{_id=78, Key=ZAS, highestIndex=85, exists=1, type=0}}]
[Document{{_id=42, Key=O.ZAD, highestIndex=85, exists=1, type=0}}]
[Document{{_id=12, Key=MAH, highestIndex=936, exists=1, type=0}}]
[Document{{_id=21, Key=GOA, highestIndex=85, exists=1, type=0}}]

Please let me know how can I fetch each value of the key as well as map the entire result to the ArrayList.


text:
Q: Check if any arrays in object contain empty values I have an object called newEntries which has 2 entries so far:
(2) [{…}, {…}]
0: {name: "test", website: "", sector: "", house: ""}
1: {name: "", website: "", sector: "", house: ""}
length: 2
__proto__: Array(0)

As it is visible, currently only one field of one index is filled. I need to return true if all the fields for all elements are filled and false otherwise.
How can I do so in javascript?

A: Using .some:
const filled = !(arr.some(obj => Object.values(obj).some(v => !v)))

A: Using combo of .every and .some will work for us :-

const array1 = [
{name: "test", website: "fdf", sector: "fdf", house: "fdf"},
{name: "fds", website: "fsd", sector: "fds", house: "fsdf"}]

const array2 = [
{name: "test", website: "", sector: "fdf", house: "fdf"},
{name: "fds", website: "fsd", sector: "fds", house: "fsdf"}]

function checkArray(array){
  return array.every(item =>
    !Object.values(item).some(value => value === "")
  );
}

console.log(checkArray(array1));
console.log(checkArray(array2));

A: Just loop thru' all array items and all fields with a flag to check:
var newEntries = [
    {name: "test", website: "", sector: "", house: ""},
    {name: "",     website: "", sector: "", house: ""}
];

for (let i=0; i<newEntries.length; i++){
    let entry     = newEntries[i];
    let allFilled = true;

    for (let field in entry)
        if (entry[field]==""){
            allFilled = false;
            break;
        }

    if (allFilled)
        console.log(entry);
}

A: Loop over the array, and then for each object within it, loop over its properties. If they're empty, return false.
Otherwise, it'll get to the end and return true. :)
function checkAll() {
    for (let entry of newEntries) {
        for (let property in entry)
            if(entry[property] === "") return false;
    }
    return true;
}

A: hi this is the best way:

var newEntries = [
    {name: "test", website: "", sector: "", house: ""},
    {name: "",     website: "", sector: "", house: ""}
];

let result = true;

for (let i=0; i<newEntries.length; i++){
    let data = newEntries[i];
    let t = Object.values(data).some(val => val);
    if (!t) {
        result = false;
    }
}

console.log(result);

A: Loop through all the items
        var newEntries = [
                {name: "test", website: "", sector: "", house: ""},
                {name: "",     website: "", sector: "", house: ""}
            ];
            newEntries.forEach(myFunction);
            function myFunction(item) {
            if (array === undefined || array.length == 0) {
              return false;
            }
            else{
            return true;
            }
            }

A:

var arr = [{a:1,b:"",c:"bhj"},{a:1,b:"hgh",c:"bhj"}]
var result = arr.filter(a => a.a != "" && a.b != ""&& a.c != "");
if(result.length===arr.length){
  console.log(true)
}else{
 console.log(false)}


text:
Q: Pencil-like functionality I've been searching around for a way to use D3 and a hand drawn pencil like capability. Is this something that is doable? I've looked around the different examples on mbostock site, but couldn't find anything that allowed you to manually draw within the zoomable area.

A: This might be OK to get going...
(it's a modified particle pattern with gravity, charge and friction set to zero)

;(function() {
      var w = 900, h = 400, nodes = [], touch,

          svg = d3.select("#vizcontainer").append("svg")
          .attr("width", w)
          .attr("height", h),

          force = d3.layout.force()
          .size([w, h])
          .gravity(0)
          .charge(0)
          .friction(0),

          outputDiv = d3.select("body").insert("div", "#vizcontainer").attr("id", "output").attr("class", "output"),
          touchesDiv = d3.select("body").insert("div", "#output").attr("id", "touches")
          .style("margin-right", "10px").attr("class", "output");

      force.on("tick", function (e) {

        outputDiv.text("alpha:\t" + d3.format(".3f")(force.alpha())
          + "\tnodes:\t" + force.nodes().length)

        svg.selectAll("circle")
        .attr("cx", function (d) { return d.x; })
        .attr("cy", function (d) { return d.y; });
      });

      svg.on("mousemove", onMove);
      svg.on("touchmove", onTouch);
      svg.on("touchstart", onTouch);

      function onMove() {
        updateMethod.call(this)
      }
      function onTouch() {
        d3.event.preventDefault();
        d3.event.stopPropagation();
        updateMethod.call(this)
      }

      function idiomatic() {
        force.nodes(nodes);
        return function () {
          var pointM = d3.mouse(this), pointT = d3.touches(this),
              point = pointT.length ? pointT[0] : pointM,
          node = { x: point[0], y: point[1] };

          nodes.push(node);

          svg.selectAll("circle")
          .data(nodes)
          .enter().append("circle")
          .attr("r", 3)
          .each((function (n) {
            return function (d, i) {
              var i = nodes.indexOf(n);
              nodes.splice(i, 1)
            }
          })(node));

          force.start();
        }
      } /*idiomatic*/

      updateMethod = idiomatic();
    })()
body, html {
      width:100%;
      height:100%;
  }
    #vizcontainer {
      width: 100%;
      height: 100%;
    }

   svg {
      outline: 1px solid red;
      width: 100%;
      height: 100%;
    }

    .output {
      pointer-events: none;
      display: inline-block;
      z-index: 1;
      margin: 10px;
    }

Trying to get touch going on Mark's solution...

var svg = d3.select('body')
      .append('svg')
      .attr('width', 1000)
      .attr('height', 1000);

    var color = d3.scale.category20();

    var line = d3.svg.line();

    var drawObj = {
      isDown: false,
      isTouched: false,
      dataPoints: [],
      currentPath: null,
      color: 0
    }

    svg.on("mousedown", function () {
      drawObj.isDown = true;
    });

    svg.on("mousemove", function () {
      if (drawObj.isTouched) {
        lift(); drawObj.isTouched = false
      };
      draw.call(this);

    });

    svg.on("touchmove", function () {
      d3.event.preventDefault();
      d3.event.stopPropagation();
      drawObj.isDown = drawObj.isTouched = true;
      draw.call(this);
    });
    svg.on("touchstart", function () {
      if (drawObj.isTouched) {
        lift(); drawObj.isTouched = false
      };
    })

    function draw() {
      if (drawObj.isDown) {
        var pointM = d3.mouse(this), pointT = d3.touches(this),
            point = pointT.length ? pointT[0] : pointM,
            node = { x: point[0], y: point[1] };

        drawObj.dataPoints.push(
          [node.x, node.y]
        );
        if (!drawObj.currentPath) {
          drawObj.currentPath = svg.append("path")
            .attr("class", "currentPath")
            .style("stroke-width", 1)
            .style("stroke", color(drawObj.color))
            .style("fill", "none");
        }
        drawObj.currentPath
          .datum(drawObj.dataPoints)
          .attr("d", line);
      }
    };
    svg.on("mouseup", lift)
    function lift () {
      drawObj.isDown = false;
      drawObj.currentPath && drawObj.currentPath.attr("class", "oldPath");
      drawObj.dataPoints = [];
      drawObj.currentPath = null;
      if (++drawObj.color > 19) {
        drawObj.color = 0;
      }
    }
svg {
      outline: 1px solid red;
    }

A: I like @coolblue's solution but here's an alternative.  It uses a path element to really feel like drawing:

<!DOCTYPE html>

Plunker here.


text:
Q: Confused about starting YoutubePlayerView from a fragment I am trying to start a youtubeplayer view from a fragment with a button click.
I am getting an error that is really causing me to scratch my head a lot ....
Now - I have tried this approach:
1. I made a separate intent to launch the YouTubePlayer View.
2. from the fragment i am trying to call the new intent (mentioned in #1) to launch the YouTubeplayerView from a Button
3. putting a button in the Fragment
My issue is that I am getting an error about calling a null reference with the code I have written.
The app compiles fine (the base of the app is a navigation drawer based app, so each selection produces a fragment). But when i chose an option with the coded approach above zi get this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
            at blackstone.software.sunnahboxtvmenu.AlNabawiFragment.onCreate(AlNabawiFragment.java:62).

It is pointing to this line of code as the source of the problems:
btnNabawiLive = (Button) getView().findViewById(R.id.btnNabawiLive);

here is the fragment code:
public class AlNabawiFragment extends Fragment implements View.OnClickListener {

    public AlNabawiFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_al_nabawi, container, false);

        TextView text = (TextView) rootView.findViewById(R.id.nababwitext);
        //text.setText("your text!");

        InputStream is = getResources().openRawResource(R.raw.nabawi);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        String entireFile = "";
        try {
            while((line = br.readLine()) != null) { // <--------- place readLine() inside loop
                entireFile += (line + "\n"); // <---------- add each line to entireFile

            }
        }

        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //TextView text = null;
        //text.setText(entireFile); // <------- assign entireFile to TextView
        //assert text != null;
        if (text != null) {
            text.setText(entireFile);
        }

        return rootView;
    }

    Button btnNabawiLive;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.fragment_al_nabawi);

        btnNabawiLive = (Button) getView().findViewById(R.id.btnNabawiLive);
        btnNabawiLive.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        //Intent inent = new Intent(this, NabawiVideo.class);
        Intent inent = new Intent(getActivity(), NabawiVideo.class);

        // calling an activity using <intent-filter> action name
        //  Intent inent = new Intent("com.hmkcode.android.ANOTHER_ACTIVITY");

        startActivity(inent);
    }

    /* public void onClick (View v) {

        Intent intent = new Intent(getActivity(), NabawiVideo.class);
        startActivity(intent);

    } */

}

Now ... what I am confused on is:
1. where do i extend the YouTubeplayer class?
2. Where and how do I call the onclicklistener for the button to launch the other intent that calls the youtubeplayerView??
Thanks.
ironmantis7x

A: If you look at the fragment's life cycle, you'll see that onCreate is called before onCreateView, thus getView() will return null.
Instead move your code from onCreate to onCreateView and use rootView rather than getView().


text:
Q: Processing lists I am trying to figure out how to process a list like this:
[ [[4,6,7], [1,2,4,6]] , [[10,4,2,4], [1]] ]

This is a list of a list of list of integers
I want my function take take this list as input and return a list of integers that are in the list without duplicates. The result should be [4,6,7,1,2,10]. But I am having trouble in figuring out how to traverse it.
My first idea was to take a process each list of integer lists separately like:
1st = [ [4,6,7], [1,2,4,6] ]
2nd = [ [10,4,2,4] , [1] ]
the main function will call another function to handle these recursively, but how will the function remember what was in the final list when it comes to handle the 2nd list? I dont think an accumulator will even work.

A: The type of that list is (Num a) => [[[a]]] so you can just use concat to flatten the structure and then nub to remove duplicates:
nub . concat . concat $ [[[4,6,7], [1,2,4,6]], [[10,4,2,4], [1]]]
-- [4,6,7,1,2,10]

Live demo
Depending on how the data is actually structured and based on statistical considerations it might be more efficient to remove duplicates within internal lists before concatenating.