text:
Q: Problem when using several functions in the mouseover event handler I am working with d3v5 and currently trying to make a node of a force-directed graph:

*

*fade out the nodes which are not directly connected to the 'mouse-over'ed' node

*enlarge the node at hand

So far I have managed the former but I can not manage for any function to get triggered alongside the fade() function. Consider:
 var node = svg
    .append("g")
    .attr("class", "nodes")
    .selectAll("circle")
    .data(graph.nodes)
    .enter()
    .append("circle")
    .attr("r", function (d) {
      return 1.5 * Math.sqrt(d.weight);
    })
    .attr("fill", function (d) {
      return "red";
    })
    .call(
      d3
        .drag()
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended)
    )
    .on("mouseover", fade(0.2))
    .on("mouseout", fade(1));

and the 'fade' function:
  function fade(opacity) {
    return function (d) {
      // check all other nodes to see if they're connected
      // to this one. if so, keep the opacity at 1, otherwise
      // fade
      node.style("stroke-opacity", function (o) {
        thisOpacity = isConnected(d, o) ? 1 : opacity;
        return thisOpacity;
      });
      node.style("fill-opacity", function (o) {
        thisOpacity = isConnected(d, o) ? 1 : opacity;
        return thisOpacity;
      });
      // also style link accordingly
      link.style("stroke-opacity", function (o) {
        return o.source.name === d.name || o.target.name === d.name
          ? 1
          : opacity;
      });
      text.style("fill-opacity", function (o) {
        thisOpacity = isConnected(d, o) ? 1 : opacity;
        return thisOpacity;
      });
    };
  }

So far everything works as it's supposed to. However as I started looking around to have another function execute on mouseover (and mouseout), I attempted the conventional method, as follows:
  var node = svg
    //...
    .on("mouseover", function (d) {
      console.log("make node bigger")
      fade(0.2);
    })
    .on("mouseout", function (d) {
      console.log("make node smaller")
      fade(1);
    });

The two console messages are outputted, but the fade() function does not execute. I tried putting return fade(...); but to no avail.
I'd appreciate any insight on why this is happening. Thank you.

A: When you do...
.on("mouseover", fade(0.2))

... you're calling fade immediately, and returning its return value, which is itself a function:
return function (d) { //etc...

That d parameter you see correspond to the first argument passed by the selection.on() method. At the end all you have is an idiomatic D3 listener, which is an anonymous function accepting the datum as the first argument.
However, now that you're doing this...
.on("mouseover", function (d) {
    console.log("make node bigger")
    fade(0.2);
})

... you have to refactor the fade function, because the datum is not being passed as an argument anymore. The easiest way is just passing the datum as an argument:
.on("mouseover", function (d) {
    console.log("make node bigger")
    fade(d, 0.2);
    //   ^---- datum here
})

And then, in fade, add a parameter for the datum and remove the return function(d) part:
function fade(d, opacity) {
    //datum---^
    node.style("stroke-opacity", function (o) {
        thisOpacity = isConnected(d, o) ? 1 : opacity;
        return thisOpacity;
    });
    //etc...
}

A: In your fade(), replace:
node.style("stroke-opacity", function (o) {
   thisOpacity = isConnected(d, o) ? 1 : opacity;
   return thisOpacity;
});

with:
node.style("opacity", function (o) {
   thisOpacity = isConnected(d, o) ? 1 : opacity;
   return thisOpacity;
});


text:
Q: Increase OS partition of a MyBook Live I have a MyBook Live 3TB and I want to install a few things in it. One of them is OpenJDK, which takes 185Mb when installed. The filesystem that has / mounted only has 188Mb available which is barely what I need for OpenJDK and not enough for the rest of software I want to install.
MyBookLive:~# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/md0              1.9G  1.6G  188M  90% /
tmpfs                  50M     0   50M   0% /lib/init/rw
udev                   10M  6.7M  3.4M  67% /dev
tmpfs                  50M     0   50M   0% /dev/shm
tmpfs                  50M  4.1M   46M   9% /tmp
ramlog-tmpfs           20M  3.7M   17M  19% /var/log
/dev/sda4             2.8T  111G  2.7T   4% /DataVolume

What I think I need to do:
- Decresae the size of the /dev/sda4 filesystem;
- Increase the size of the /dev/md0 filesystem;
What I need your help with:
- How can I resize the partitions without bricking the MyBook or losing MyBook functionalities?
Thank you all.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails 3 Query Interface: using associated models I'll use the generic blog example.
class Post < ActiveRecord::Base
  has_many :comments
end
class Comment < ActiveRecord::Base
  belongs_to :post
end

When querying Post, how do you access its associations (i.e. :comments)?
This should be the easiest thing in the world, but I haven't found any documentation on it. Even http://edgeguides.rubyonrails.org/3_0_release_notes.html#query-interface and http://m.onkey.org/2010/1/22/active-record-query-interface were unhelpful, basically saying "Now there are methods like joins and includes to do the same thing as SQL statements."  yeah thanks.
So here are very straightforward things I want to do, which do not work, but should be obvious what I'm trying to accomplish:
Post.where(:comments.count >= 10)
Post.where(:comments.author_id == current_user.id)
Post.order(:comments.count)

How can we do these without resorting to ruby code that reeks of SQL (thus defeating the purpose of Active Record)?
Thanks :)

A: If you set up a counter_cache on Post for the comments you can see directly how many comments it has without having to query, this makes it easier and faster.
This would take care of the first and last question you posed.
You can then query them like this,
  Post.where(:comments_count >= 10)
  Post.order(:comments_count)

But you are better off setting up scopes for that.
I'm not sure what you want to do with the second question, do you want to show all posts where the current user has commented on?

A: Post.where(:comments.count >= 10)
Post.find(:all).select{|p| p.comments.count >= 10)

Post.where(:comments.author_id == current_user.id)
Post.find(:all).select{|p| p.comments.select{|c| c.author_id == current_user.id } }

Post.order(:comments.count)
Yikes, this one beats me.

Hey also, my two posts are kinda heavy on the SQL. I know people do it more elgantly with a
Post.find(:all, :conditions => blah blah blah..

But I'm not sure how to put that. Sorry.


text: Q: view file contents from aws s3 in web browser I am storing images in the s3 bucket using java spring-boot and storing the file path in the DB. I am giving the path to the client so that they can view the file instead of download it.I am able to generate pre-signed URL for the s3 object. So, that if I give to the client they can view the file contents But if the person shares it with others, they can also view. I want to make this URL as password protected. Is there any way to do it? Or any other way so that client can view the file?


text:
Q: How to display arrays in void function I'm trying to write a program to create a simple Minesweeper game and I'm not sure what is causing the program to just put out a blank line, but my intentions is to print the chart of numbers for a minesweeper game. The program compiles just fine even though there is an error in running the program before receiving a line which says,

sh: pause: command not found

The program uses void functions and I'm not sure how to define a variable that points to each square on the board.
I'm hoping someone can help me find out where the mistake is in this code that is causing the program to function so strangely.
C++
#include <iostream>
#include <iomanip>
#include <time.h>
#include <fstream>

using namespace std;

// Global Constants
const int MAX_ROWS = 10;
const int MAX_COLUMNS = 10;
const int EMPTY_SQUARE_DIGIT = 0;
const char EMPTY_SQUARE_SYMBOL = '_';
const int BOMB_DIGIT = -1;
const char BOMB_SYMBOL = '#';
char currentCell = 0;

// Function Prototypes
void fillTheGameBoard(int board[MAX_ROWS][MAX_COLUMNS]);
void displayTheGameBoard(int board[MAX_ROWS][MAX_COLUMNS]);
void insertTheMineClues(int board[MAX_ROWS][MAX_COLUMNS]);
void incrementTheNeighborSquares(int board[MAX_ROWS][MAX_COLUMNS], int row, int column);

// ############################################
int main(void)
{
int gameBoard[MAX_ROWS][MAX_COLUMNS];

srand(time(NULL));

fillTheGameBoard(gameBoard);

insertTheMineClues(gameBoard);

displayTheGameBoard(gameBoard);

system("pause");

return 0;
} // End main

// ############################################
void fillTheGameBoard(int board[MAX_ROWS][MAX_COLUMNS])
{
   for (int row = 0; row < MAX_ROWS; row++)
   {
      if ( (row >= 0) && (row < MAX_ROWS) )
      {
      for (int column = 0; column < MAX_COLUMNS; column++)
      {
         if (rand() % (MAX_ROWS - 3) == 0)
         {
            currentCell = BOMB_DIGIT;
         }
         else
         {
            currentCell = EMPTY_SQUARE_DIGIT;
         }
      }
      }
   }
} // End fillTheGameBoard

// ############################################
void displayTheGameBoard(int board[MAX_ROWS][MAX_COLUMNS])
{
   for (int row = 0; row < MAX_ROWS; row++)
   {
      if ( (row >= 0) && (row < MAX_ROWS) )
      {
      for (int column = 0; column < MAX_COLUMNS; column++)
      {
         if (currentCell == BOMB_DIGIT)
         {
            cout << BOMB_SYMBOL;
         }
         else if (currentCell == EMPTY_SQUARE_DIGIT)
         {
            cout << EMPTY_SQUARE_SYMBOL;
         }
         else
         {
            cout << currentCell;
         }
      }
      }
   }
} // End displayTheGameBoard

// ############################################
void insertTheMineClues(int board[MAX_ROWS][MAX_COLUMNS])
{
     for (int row = 0; row < MAX_ROWS; row++)
      {
        if ( (row >= 0) && (row < MAX_ROWS) )
         {
         for (int column = 0; column < MAX_COLUMNS; column++)
            {
               if (currentCell == BOMB_DIGIT)
                  {
                     incrementTheNeighborSquares(board, row, column);
                  }
            }
         }
      }

} // End insertTheMineClues

// ############################################
// The function definition below is finished.  Make no changes to it.
void incrementTheNeighborSquares(int board[MAX_ROWS][MAX_COLUMNS], int bombRow, int bombColumn)
{
for (int row = bombRow - 1; row <= bombRow + 1; row++)
   {
   if ( (row >= 0) && (row < MAX_ROWS) )
      {
      for (int column = bombColumn - 1; column <= bombColumn + 1; column++)
         {
         if ( (column >= 0) && (column < MAX_COLUMNS) && (board[row][column] != BOMB_DIGIT) )
            board[row][column]++;
         } // End for column
      } // End if
   } // End for row
} // incrementTheNeighborSquares


text:
Q: Windings of BLDC motor I learned an algorithm for winding a BLDC motor. This algoithm has the windings crossing several stator teeth similar to this image:

When I google BLDC stator, I see way more images like this :

In this image, the windings mostly go around a single tooth. They do not span multiple teeth awkwardly. This second version looks much easier to wind... So my question is, the second version... Does winding a motor like that make it lose efficiency? If so, how much efficiency? I am building just a practice motor, so I don't really care if its 100% efficient if it would be easier to wind!
Also, can anyone recommend some good modeling software to model the magnetic fields? I saw this program "motorsolve" but it  looks expensive!

A: In short: go for the second motor!
Motor topologies
The second motor has what the litterature refers to as concentrated windings, and the former has distributed windings (and also stator skew encompassing a whole slot).
As I see it, the main benefits for concentrated windings compared to distributed windings are that they:

*

*Are simpler to wound => cheaper

*Have less end windings (more important in short machines)

The main drawback is, as you suspect, losses. The concentrated windings have more harmonic contents in the magnetic flux, due to not having the smoothness gained by distributed windings (and also sometimes stator skew as seen in your first figure above). These harmonics lead to significantly larger magnetic losses in the iron core.
I learned a lot about this by reading Design of Rotating Electrical Machines, by Pyrhönen et al, so that's my recommendation if you want to dive deeper.
Magnetic Fields
How to simulate magnetic fields is actually very well known. There's no need for expensive tools. I used the free FEMM solver for a PhD level course in numerical motor analysis. It can compute quasi-static frequency dependent solutions, and get really nice results when compared to reality. It has some examples to get you started.
From a quick inspection of the Motorsolve package: I think you get nice pre-made geometries with boxes to fill in your sizes and shape factors etc. So the drawback of using a free solver is that you have to draw the geometry yourself. But that's exactly what I did in the course I mentioned earlier: complete reverse-engineering of a professional machine sawed into two. I can recommend it as an exercise.


text:
Q: How to use LLVM test-suite to test my custom pass? I am a Master's student working on an optimization pass on LLVM IR to validate some of my ideas. I currently use a simple script I wrote to test my pass. However, I think it is better to use an existing testing infrastructure. After searching, I find the LLVM test-suite might fit my need. But after reading test-suite guide and some related posts on Stack Overflow, I still have no idea about how to test my custom pass with lit.
I develop my pass out of source, and below is roughly what my script does.

*

*Compile each source file into the corresponding LLVM IR file.

*Use llvm-link to link all IR files into one.

*Run my pass on the IR file.

*Use llc to generate the object file.

*Use clang to generate the executable.

I wonder if it is possible to have lit follow the above steps to generate the executable and run the test. If so, how can I achieve this? In fact, I suspect that maybe what I want to do is not relevant to lit, but don't know what to start with.
I would be grateful for any suggestions.
Thanks!


text:
Q: Pascals triangle advantages Pascal triangle can be used to calculate number of combinations using the recursion formula below:-
(n k) = (n-1 k-1) + (n-1 k)

This can be used in place of formal expansion of (n k) to calculate number of combinations.
But both perform in O(n) time.What are the advantages of using Pascal's triangle method?

A: The main advantage lies in the fact that you can pre-compute all (ni ki) where ni < n and ki <= k in O(n^2) time.
So if you have a problem where you may need to query different values in a Pascal triangle, using the recursion formula method and storing all sub-results will mean your preprocessing time is O(n^2) but your queries are O(1).
On the other hand, using the formula for (n k) in the same application would mean each query is O(n) which is inferior to the former approach if you expect more than n queries.

A: If you need to compute all (n k) for n<=N and 0<=k<=N, Pascal's triangle is very attractive because it just involves one addition per element.
But if you only need the values for a fixed N, then it can be advantageous to use this other recursion:
(n k) = (n k-1).(n+1-k)/k


text:
Q: iPhone app getting XML then refreshing it at intervals I have an app which gets some data from the web via an XML document. I have this working fine and have followed apples SeismicXML example (uses NSURLRequest etc). I am very new to this so I have to admit that I do not totally understand all the code that gets the XML - but it is working. My problem is that my app may be running for some time so I want to be able to refresh the XML every now and again and check to see if it is different. If it is different I need to update my contents. Basically this means my questions are....

*

*Is there a standard way of doing this?

*I was thinking of creating a timer to call the function which parses the XML but I can't figure out which function to call.

If anyone can give me any pointers or even better examples of this it would be fab. Thanks

A: An NSTimer is the way to kick off a process that needs performing every x seconds
[NSTimer scheduledTimerWithTimeInterval:5
                                 target:self
                               selector:@selector(theXMLMethod)
                               userInfo:nil
                                repeats:YES];

This sets a timer of 5 seconds that calls the theXMLMethod method.


text:
Q: How to handle longtap on utfgrid with leaflet I'm trying to get a longtap to work on a utfgrid using leaflet/mapbox.
Normally I'd think jQueryMobiles "taphold" or leaflets "contextmenu" would work (and they do... on the map) but nothing when trying to use it with the utf gridLayer.
I currently use this for a simple tap/click on the grid which works fine.
gridlayer.on('click', function (e) {
    console.log(e.data);
});

But what I really want to do is this.
gridlayer.on("contextmenu", function(e){
   //do something else
});

or
gridlayer.on("taphold", function(e){
   //do something else
});


text:
Q: Check date is expired or not on Moment Date format I have a date Format like this
[{"Exp_Date":"28-Feb-19"},{"Exp_Date":"30-Apr-19"},{"Exp_Date":"28-Jun-19"},{"Exp_Date":"29-Nov-19"}]

Now I have to check whether my Date is less that First value of array of objects. If less then I have to pick First object,
If that date expired then I have to use the next date.
I want to implement this on Moment.
I know the subtract of moment but that not solve my  purpose. Anyone can guide me how to solve this. Any help is really appreciated

A: Try this

const a = [{ "Exp_Date": "28-Feb-19" }, { "Exp_Date": "30-Apr-19" }, { "Exp_Date": "28-Jun-19" }, { "Exp_Date": "29-Nov-19" }];
let i = 0;
while (a[i] && moment().isAfter(moment(a[i].Exp_Date, "DD-MMM-YY"))) {
    i++;
}
if (a[i]) {
    return a[i];
} else {
    return null;
}

You can see it here

A: You could do this check in a loop:
var array = [{"exp_date":"28-Feb-19"},{"exp_date":"10-Feb-19"}];
for(i=0;i<array.length;i++){
    console.log(moment(new Date()).isAfter(moment(new Date(array[i]["exp_date"]))));
}

This uses new Date() objects which seem to be easier on moment

A: const a = [{ "Exp_Date": "28-Feb-19" }, { "Exp_Date": "30-Apr-19" }, { "Exp_Date": "28-Jun-19" }, { "Exp_Date": "29-Nov-19" }];
let i = 0;
while (a[i] && moment().isAfter(moment(a[i].Exp_Date),'DD-MMM-YY')) { // <-- change this
    i++;
}
if (a[i]) {
    return a[i];
} else {
    return null;
}

updated answer of Nguyen

A: Well i dont know about moment but this could easily be done will js.

var dates =[{"Exp_Date":"28-Feb-19"},{"Exp_Date":"30-Apr-19"},{"Exp_Date":"28-Jun-19"},{"Exp_Date":"29-Nov-19"}]

var d = new Date("01-march-19");
// sort the array first, this is optional, then find the current Exp_Date Index
var index = dates
 .sort((a,b)=> new Date(a.Exp_Date) - new Date(b.Exp_Date))
 .findIndex((item)=> new Date(item.Exp_Date) >= d);

console.log(dates[index])


text:
Q: visual studio team services: update json file from ci variables In Visual Studio Team Services, we can update web.config appSetting parameters with the values defined in variables (https://www.visualstudio.com/en-us/docs/release/examples/azure/change-config-azure-webapps).
Is there any way to update json file?

A: Yes, the Tokenize task works with json file too. You just need to add a Tokenize task in your definition and set the "Source filename" to your json file.


text:
Q: Remove + from Telephone in Contact Form 7 I want to remove + from contact form 7 telephone field while submitting the form. The form should be submitted without + in telephone field.

A: Can you add CSS rule then set off symbol if is icon like:
[text text-123 id:very-special-field]

If is simple character you must find code in any file of plugin.


text:
Q: Symfony2: No route found for "GET ..." I implemented my own error-controller so I get an email when there is an error in my project. The project has been online for a while now and now and about once a day I get this error:
There was an error on /dealer/search/     No route found for "GET /dealer/search/"
This route doesn't exist, there is a route /deealer/search/top and /dealer/search/left. Nobody ever complained about an error occurring. This also happens with other pages and it is always the last part of the url that is missing.
It is an intranet which you can only access after logging in, so it can't really be a bot or something. I never received an email yet from someone who experienced this error, so I am a bit stuck where this is coming from.
Does anybody have any idea what could possibly cause this?

A: You did not need to implement a custom error controller for emailing. You already have the Monolog integrated into Symfony2  that can do this and much, much more.
It is quite possible that people just removed the last part of the URL to see what happens.

A: These are exceptions thrown by the router when the page doesn't exists.
In other words, this is how Symfony signals page not found errors internally. By default it displays a 404 Not Found page when these exceptions occur.

A: IMHO the most possible answer would be that the user manually entered the URL, as @Putr suggests already. You might want to check your server log files to see who made the request and how the user got there. You could also write a functional test that checks all generated pages for the broken links. But that is probably a little too much.
In case you decide to do that make sure to check out the LiipFunctionalTestBundle


text:
Q: Replace edit and delete buttons on kendo grid with icons I have implemented edit and command button for my kendo grid and now need to replace the buttons with icons that I have. Could anybody show my how it is done
Following is my view
 @(Html.Kendo().Grid<CC.GRP.MCRequest.ViewModels.TeamViewModel>()
    .Name("GridTeam")
    .Columns(columns =>
    {

        columns.Command(command => { command.Edit(); command.Destroy(); }).Width(250);
        columns.Bound(o => o.TeamID).Hidden();
        columns.Bound(o => o.CountryCode);
        columns.Bound(o => o.TeamName);
        columns.Bound(o => o.TeamDescription);

    })
    .ToolBar(toolbar => toolbar.Create())
     .Editable(editable => editable.Mode(GridEditMode.PopUp)
     .TemplateName("TeamEdit")
        .Window(w => w.Width(500))
     )
    .Pageable()
    .Sortable()
    .Filterable()
    .Scrollable()
    .Groupable()
    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model => model.Id(t => t.TeamID))
        .Create(create => create.Action("Team_Create", "Admin"))
        .Read(read => read.Action("Team_Read", "Admin"))
        .Update(update => update.Action("Team_Update", "Admin"))
        .Destroy(update => update.Action("Team_Delete", "Admin"))
    )
    )

After applying the solution

A: I recently had the same question, and figured it out using the IconClass property of the Command.
          columns.Command(command => {
            command.Edit().Text(" ").IconClass("fa fa-edit");
            command.Destroy().Text(" ").IconClass("fa fa-trash");
          });

Make sure to set Text to a space.  This hides any text.  Then apply whatever classes you want in IconClass.
In my example, I used the Edit and Trash icons from Font Awesome.  You can apply whatever custom classes you want there.

A: You can follow this thread.
Quickly to sum up everything, you'll need to add new event
.Events(e => e.DataBound("onRowBound"))

And then implement JS function
function onRowBound(e) {
    $(".k-grid-edit").find("span").hide()
    $(".k-grid-edit").addClass("custom-icon-class");
}


text:
Q: Regex get string before ending with second occurance The string can be http://url.com/scripts.js:129:1 or http://url.com/scripts.js:129 but I always want http://url.com/scripts.js:129.
Here is what I tried, but it keeps changing array index.
'http://url.com/scripts.js:129:1'.match(/(.+)(\:\d+(?!\:\d+)?)$/);
Help me, why my regex is not working properly.

A: If the point is to get till the first : + number and omit the rest, you can use
^(.+?:\d+)(?::\d+)*$
^.+?:\d+

See this regex demo. ^.+?:\d+ is preferable if you do not need to match the entire string and capture both parts into groups.
Details:

*

*^ - start of string

*(.+?:\d+) -  Group 1 capturing any one or more chars other than line break chars as few as possible and then a : and one or more digits, and then

*(?::\d+)* - zero or more sequences of : and one or more digits

*$ - end of string.

A: Try the following pattern:
/:(\d+)(?::\d+)?$/

It assumes that there may be another colon-number pair, but it's optional.


text:
Q: Can Energy and Momentum Conservation prevent Particle Interactions? I understand that Quantum Numbers must be preserved during particle interactions, which prevents certain interactions from occurring.
However, as Energy and Momentum must also be conserved, are there any particle interactions which are prevented by the none-conservation of these properties?
Specifically, can an interaction be prevented in general, as oppose to in a specific circumstance.

A: Yes. Any interaction that violates either energy or momentum conservation is forbidden. Obviously there is an infinite number of such impossible interactions... like, the spontaneous emission of a photon by a nucleus that already is in its ground state; the absorption of a photon by a free electron; the decay of a electron and a anti-electron-neutrino into a muon and a anti-muon neutrino when the kinetic energies are low, etc. pp.


text:
Q: Can Quickblox provide Javascript-based video chat on iOS? I can't use an app on iOS, it has to be in-the-browser javascript, and it has to be video chat.
Can I support this on quickblox? I know that webRTC is not currently available on iOS.
I am sure this used to be a supported case before the move to webRTC?
Does the deprecated API offer this? Do we know when we can expect webRTC to be supported in the browser on iOS?

A: WebRTC javascript API should work on iOS Opera/Chrome browsers, but not in Safari unfortunately


text:
Q: leading zero in varchar field in settings table In my database I've got a table called settings. It has two columns, name and value.
I'm trying to insert a phone number, for example 0612345678 in it.
It keeps removing the leading zero (result 612345678).
I use $value = strval($value); to be sure that PHP passes the value as a string (which I can confirm, works).
Is this a MySQL default setting or can I fix this?

A: If you want to keep leading zero, you need to store the values in a string column (which I guess is an integer now either in PHP or in MySQL) .
The other option is to add the number while selecting (not recommended )
SELECT LPAD( Column, <lengthOfOriginalNumber>, '0')

A: It looks like either php or MySQL is converting phone number into a number and hence, leading zeros are stripped.

*

*If it's php then you can use strval function to get the String value (explained here). Also, you can try printing the value before it gets sent to MySQL to see the result after conversion.

*If it's MySQL then you need to change the column type to be varchar, e.g.:
ALTER TABLE table MODIFY phone_number VARCHAR(20);


text:
Q: Initialize the code (in a actionscript file) in a different frame How can I initialize this game in a differente frame with the function init? I'm working in Actionscript 3.0.
Hope you can help me.
 Heres the code (the code is in a actionscript file) :
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event

public class Main extends MovieClip{

    //constants
    const gravity:Number = 1.5;            //gravity of the game
    const dist_btw_obstacles:Number = 300; //distance between two obstacles
    const ob_speed:Number = 8;             //speed of the obstacle
    const jump_force:Number = 15;          //force with which it jumps

    //variables
    var player:Player = new Player();
    var lastob:Obstacle = new Obstacle();  //varible to store the last obstacle in the obstacle array
    var obstacles:Array = new Array();     //an array to store all the obstacles
    var yspeed:Number = 0;                 //A variable representing the vertical speed of the bird
    var score:Number = 0;                  //A variable representing the score

    public function Main(){
        init();
    }

    function init():void {
        //initialize all the variables
        player = new Player();
        lastob = new Obstacle();
        obstacles = new Array();
        yspeed = 0;
        score = 0;

        //add player to center of the stage the stage
        player.x = stage.stageWidth/2;
        player.y = stage.stageHeight/2;
        addChild(player);

A: If there are frame (for Adobe Animate projects), use addFrameScript:
someMC.addFrameScript(2, myFunction);

private function myFunction():void{
  this.stop();
}

myFunction work if frame 2 would have existed.
If not, you can use Tween frameworks like TweenLite or TweenMax (Recommended):
TweenLite.to(mc, 1.5, {onComplete:myFunction});
function myFunction():void {
    trace("tween finished");
}

myFunction is run after 1.5 sec


text:
Q: Java EE - How HttpServlet works/creates? When the HttpServlet creates:

*

*every time after it is called by client (by form submit,..)?

*after its project's WAR (for example) is deployed on (tomcat) server?

*after first client's call?

*or on other time..?

I have same question for init method - when is it called?

I want to read data from Oracle (SQL) DataBase and save it in variables, cause don't want to read/get data from database every time client calls doPost method (if I write connection, statement and resultset objects in doPost method...). So, where can I save data, which never changes during Servlet working; this data would be used by every client on form calls.
One told me that it's not right to use class's variables, cause some of them are not thread-safe. So, what is best way to use for data save and use this data for multiple clients' calls?
Sorry for my bad English...

A: I'm not sure I follow your question, but to connect your SQL database you can use MySQL connector, and to store the values, store them in java only.. Use resultset.getString() and resultset.getInt() functions to get values from the database and store it in variables :) hope this helps..
Also for information about servlets read the tab info on stack overflow


text:
Q: Angular2 innerHtml removes styling I am using innerHtml and set the html in my cms the response seems okay and if I print it like this: {{ poi.content }}
it gives me the right content back :
`

       Tes11t

`
But when I use [innerHtml]="poi.content" it gives me this html back:

            Tes11t

Does anybody know why it is stripping my styling when I use [innerHtml]

A: Angular2 sanitizes dynamically added HTML, styles, ...
@Pipe({name: 'safeHtml'})
export class Safe {
  constructor(private sanitizer:DomSanitizer){}

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

[innerHtml]="poi.content | safeHtml"

See

*

*https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html

*In RC.1 some styles can't be added using binding syntax
for more details.


text:
Q: How to filtering of data in List & Label reports from user? We use an MS SQL database directly as a data source for List & Label. All tables, columns and data records are then always available at once.
However, a created report should not always display all data, so we have selected the appearance condition within the report in such a way that only certain data of a table is displayed.
But we don't want to create and offer a separate report for each possible condition in a table, where each one has its own appearance condition. Also the user should not be able to change the report itself in the designer. Is there a simple and user-friendly way that the user can decide from "outside" for the report which data should be displayed?

A: The best way to achieve this is using a report parameter. You can configure them from Project > Report Parameters:

As you can see from the screenshot, the data for the report parameter can come from the database, but you can also offer a choice from a predefined list of entries or even allow the user to freely type a text. There are date pickers for date values etc.
These parameters are shown above the preview in desktop apps. In web apps, you have a separate pane - see the "Chart With Report Parameters" sample here.
Once you have configured the parameter as required, use it in the "Data Filter" property of your report container items. Note that you should look for a filter that translates to your database's syntax. This blog article has more details on the concept.


text:
Q: jQuery copy some text + some additional text in the clipboard Could you please give me an example of jQuery code with the following feature.
While copying some text from the site i would like to add the copied text to the clipboard + some text kinda: content was taken from the following article (with link).
Thanks in advance


text:
Q: Oracle 11g : Sql Developer : How to execute more than one anonymous block I am trying to execute a list of anonymous block in sql developer. But when ever execute a anonymous block example
Begin
 execute do something
end;

it works but if i execute more than one anonymous block such as
Begin
 execute do something
end;
Begin
 execute do something
end;

it throws
PLS-00103: Encountered the symbol "BEGIN"
06550. 00000 -  "line %s, column %s:\n%s"
*Cause:    Usually a PL/SQL compilation error.

A: Use forward slash in between
Begin
 execute do something
end;
/

Begin
 execute do something
end;
/

A: Execute all queries in a same begin end block or wrap all in a begin end block.
Like
Begin
 execute do something;
 execute do something;
End;

Or
Begin
Begin
 execute do something;
end;
Begin
 execute do something;
End;
End;


text:
Q: In Rails, how can I search or create parent model when creating a new child model? I'm fairly new to Rails, so I was wondering what the convention is something like this. I have 2 models, Assignment and Task with has_many/belongs_to relation. I want users to be able to create a Task model, through searching for a Assignment model or creating a new one. So my flow is:

*

*User tries to create new Task

*User asked to input Assignment name

*Search through database for Assignment
a. If a Assignment is found, show details, ask user to confirm
b. If not found, ask user to create a new Assignment

*With Assignment attached, ask user to input Task details

What I was wondering is, should all this be handled under TaskController (task#new) or should step #3 be separately handled under AssignmentController (assignment#search)? Also, where/when should I save the Assignment model, after step #3 or wait until user goes through step #4 (so there are no assignments without tasks)?
Note: Users wouldn't be able to create Parent model by itself, if this makes any difference.
The closest SO question I've found related to this issue is this one but there's no answer. Or is JS really the best way to achieve this?
EDIT: Relationship clarification
Parent is "Assignment" and Child is "Task" (renamed all "Parent" and "Child" references above). I want users to be able to list all assignments and list all tasks, but only create Task (no Assignment should exist without a Task attached to it). Tasks also belongs to Users. So User will create a Task that belongs to himself, and an Assignment (existing or new).
Currently, my routes.rb looks like:
resources :assignments
resources :tasks

EDIT: Models
class Assignment < ActiveRecord::Base
  has_many :tasks
end

class Task < ActiveRecord::Base
  belongs_to :assignment
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :tasks
end


text:
Q: GNOME-Terminal: Create new terminal tab on remote machine Is there a way to open a new terminal tab in GNOME-Terminal when working on a remote machine that is connected via ssh?

A: tmux (or screen, the older alternative) are great for this.
tmux lets you do both horizontal and vertical splits.
You'll probably want to customize tmux, e.g. most people like cmd-a over cmd-b as the 'prefix' key.
I use the following ~/.tmuf.conf file settings to make it work better for me:
# mdd tmux settings
bind r source-file ~/.tmux.conf \; display "Reloaded!"  # Reload with ctrl-r
set -g prefix C-a         # prefix from ctrl-b to ctrl-a
unbind C-b                # allow ctrl-b for other things
set -sg escape-time 1     # quicker responses
bind C-a send-prefix      # Pass on ctrl-a for other apps
set -g base-index 1        # Numbering of windows
setw -g pane-base-index 1  # Numbering of Panes
# bind | split-window -h    # Split panes horizontal
bind \ split-window -h    # Split panes horizontal
bind - split-window -v    # Split panes vertically
bind h select-pane -L     # Switch to Pane Left
bind j select-pane -D     # Switch to Pane Down
bind k select-pane -U     # Switch to Pane Up
bind l select-pane -R     # Switch to Pane Right
bind -r C-h select-window -t :-  # Quick Pane Selection
bind -r C-l select-window -t :+  # Quick Pane Selection
bind -r H resize-pane -L 5       # Switch to Pane Left
bind -r J resize-pane -D 5       # Switch to Pane Down
bind -r K resize-pane -U 5       # Switch to Pane Up
bind -r L resize-pane -R 5       # Switch to Pane Right
setw -g mode-mouse off           # Mouse Off
set -g mouse-select-pane off     # Mouse Off
set -g mouse-resize-pane off     # Mouse Off
set -g mouse-select-window off   # Mouse Off
#set -g  default-terminal "screen-256color"
setw -g monitor-activity on      # Activity Alerts
set -g visual-activity on
set -g status-fg white           # Status line Colors
set -g status-bg black
setw -g window-status-fg cyan    # Window list color
setw -g window-status-bg default
setw -g window-status-attr dim
setw -g window-status-current-fg white     # Active Window Color
setw -g window-status-current-bg red
setw -g window-status-current-attr bright
set -g pane-border-fg green      # Pane colors
set -g pane-border-bg black
set -g pane-active-border-fg white
set -g pane-active-border-bg yellow
set -g message-fg white          # Command/Message Line.
set -g message-bg black
set -g message-attr bright
set -g status-left-length 40     # Status Line, left side
set -g status-left "#[fg=white]Session: #S #[fg=yellow]#I #[fg=cyan]#P"
set -g status-utf8 on            # Status Line, right side
set -g status-right "-------"
set -g status-interval 60        # frequency of status line updates
set -g status-justify centre     # center window list
setw -g mode-keys vi             # vi keys to move
unbind v                         # Open panes in same directory as tmux-panes script
unbind n
bind v send-keys " ~/tmux-panes -h" C-m
bind n send-keys " ~/tmux-panes -v" C-m
unbind Up                        # Maximizing and Minimizing...
bind Up new-window -d -n tmp \; swap-pane -s tmp.1 \; select-window -t tmp
unbind Down
bind Down last-window \; swap-pane -s tmp.1 \; kill-window -t tmp
bind P pipe-pane -o "cat >>~/#W.log" \; display "Toggled logging to ~/#W.log"
# Make keys for copy mode be like vi
unbind [
bind Escape copy-mode
unbind p
bind p paste-buffer
bind -t vi-copy 'v' begin-selection
bind -t vi-copy 'y' copy-selection

I also set the following aliases (in my ~/.bash_aliases file) to let me switch between scrolling and being able to copy text:
alias tof='tmux set -g mode-mouse off'
alias ton='tmux set -g mode-mouse on'


text:
Q: cannot resolve variable PIX_FMT_RGB24, ffmpeg source code install with the newest version i installed the ffmpeg from source code according https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu, and write a test file to save ppm file from a video, but the code cannot reslove PIX_FMT_RGB24, i write the code as below:
int main() {
    // Initalizing these to NULL prevents segfaults!
    AVFormatContext   *pFormatCtx = NULL;
    int               i, videoStream;
    AVCodecContext    *pCodecCtxOrig = NULL;
    AVCodecContext    *pCodecCtx = NULL;
    AVCodec           *pCodec = NULL;
    AVFrame           *pFrame = NULL;
    AVFrame           *pFrameRGB = NULL;
    AVPacket          packet;
    int               frameFinished;
    int               numBytes;
    uint8_t           *buffer = NULL;
    struct SwsContext *sws_ctx = NULL;

    const char* url = "/home/liulijuan/bin/test.mp4";

    // [1] Register all formats and codecs
    av_register_all();

    // [2] Open video file
    if(avformat_open_input(&pFormatCtx, url, NULL, NULL)!=0)
        return -1; // Couldn't open file

    // [3] Retrieve stream information
    if(avformat_find_stream_info(pFormatCtx, NULL)<0)
        return -1; // Couldn't find stream information

    // Dump information about file onto standard error
    av_dump_format(pFormatCtx, 0, url, 0);

    // Find the first video stream
    videoStream=-1;
    for(i=0; i<pFormatCtx->nb_streams; i++)
        if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO) {
            videoStream=i;
            break;
        }
    if(videoStream==-1)
        return -1; // Didn't find a video stream

    // Get a pointer to the codec context for the video stream
    pCodecCtxOrig=pFormatCtx->streams[videoStream]->codec;
    // Find the decoder for the video stream
    pCodec=avcodec_find_decoder(pCodecCtxOrig->codec_id);
    if(pCodec==NULL) {
        fprintf(stderr, "Unsupported codec!\n");
        return -1; // Codec not found
    }
    // Copy context
    pCodecCtx = avcodec_alloc_context3(pCodec);
    if(avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0) {
        fprintf(stderr, "Couldn't copy codec context");
        return -1; // Error copying codec context
    }

    // Open codec
    if(avcodec_open2(pCodecCtx, pCodec, NULL)<0)
        return -1; // Could not open codec

    // Allocate video frame
    pFrame=av_frame_alloc();

    // Allocate an AVFrame structure
    pFrameRGB=av_frame_alloc();
    if(pFrameRGB==NULL)
        return -1;

    // Determine required buffer size and allocate buffer
    numBytes=avpicture_get_size(PIX_FMT_RGB24, pCodecCtx->width,
                                pCodecCtx->height);
    buffer=(uint8_t *)av_malloc(numBytes*sizeof(uint8_t));

    // Assign appropriate parts of buffer to image planes in pFrameRGB
    // Note that pFrameRGB is an AVFrame, but AVFrame is a superset
    // of AVPicture
    avpicture_fill((AVPicture *)pFrameRGB, buffer, PIX_FMT_RGB24,
                   pCodecCtx->width, pCodecCtx->height);

    // initialize SWS context for software scaling
    sws_ctx = sws_getContext(pCodecCtx->width,
                             pCodecCtx->height,
                             pCodecCtx->pix_fmt,
                             pCodecCtx->width,
                             pCodecCtx->height,
                             PIX_FMT_RGB24,
                             SWS_BILINEAR,
                             NULL,
                             NULL,
                             NULL
    );

    // [4] Read frames and save first five frames to disk
    i=0;
    while(av_read_frame(pFormatCtx, &packet)>=0) {
        // Is this a packet from the video stream?
        if(packet.stream_index==videoStream) {
            // Decode video frame
            avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);

            // Did we get a video frame?
            if(frameFinished) {
                // Convert the image from its native format to RGB
                sws_scale(sws_ctx, (uint8_t const * const *)pFrame->data,
                          pFrame->linesize, 0, pCodecCtx->height,
                          pFrameRGB->data, pFrameRGB->linesize);

                // Save the frame to disk
                if(++i<=5)
                    SaveFrame(pFrameRGB, pCodecCtx->width, pCodecCtx->height,
                              i);
            }
        }

        // Free the packet that was allocated by av_read_frame
        av_free_packet(&packet);
    }

    // Free the RGB image
    av_free(buffer);
    av_frame_free(&pFrameRGB);

    // Free the YUV frame
    av_frame_free(&pFrame);

    // Close the codecs
    avcodec_close(pCodecCtx);
    avcodec_close(pCodecCtxOrig);

    // Close the video file
    avformat_close_input(&pFormatCtx);

    return 0;
}

so i replace PIX_FMT_RGB24 with AV_PIX_FMT_RGB24, but i cannot open the saved ppm file, the save code as below:
void SaveFrame(AVFrame *pFrame, int width, int height, int iFrame) {
    FILE *pFile;
    char szFilename[32];
    int  y;

    printf("start save frame ...\n");
    // Open file
    sprintf(szFilename, "/home/liulijuan/frame%d.ppm", iFrame);
    pFile=fopen(szFilename, "wb");
    if(pFile==NULL)
        return;

    printf("start write header ...\n");
    // Write header
    fprintf(pFile, "/P6\n%d %d\n255\n", width, height);

    // Write pixel data
    for(y=0; y<height; y++)
        fwrite(pFrame->data[0]+y*pFrame->linesize[0], 1, width*3, pFile);

    // Close file
    fclose(pFile);
    printf("close file ...\n");
}

so, what's wrong with this code?

A: As of commit 78071a14, pixel formats have been prefixed with AV_, and the PIX_FMT_* defines were moves to libavutil/old_pix_fmts.h (which was included by the original pixfmt.h). This file was then removed in the next major version.
The fix is to add this prefix (AV_) to any PIX_FMT_* statements which haven't been updated yet.


text:
Q: What can we learn from inactive assembly languages? There are still groups of programmers who support old microprocessors, e.g., Z80, 6510, 68000, etc. What can we learn from old assembly languages at a time when functional programming is becoming fashionable?
EDIT
I imagine that there would be more to learn for embedded systems. However, assembler styles apply to a more limited extent for web programming where caching is used and the size of routines does not really matter. The guideline for best practice for embedded and web styles differs massively (server and client styles being different). For example, the optimising a sprite multiplexer to run in say, under 30 bytes, is different to types of optimising we would make for code we intend to run on a web server. The types of optimisation are very different. The sprite multiplexer is written with memory usage as the main priority but regarding our web server routine, we want maximum performance which has little to do with efficient use of memory unless we are talking about shared resources.

A: The primary thing for these older platforms is essentially:
How to code efficiently when memory is tight and cpu cycles are few.

In an age where the typical response is "just upgrade the hardware" it is very interesting to see how to squeeze maximum performance out of what you have.
The Z80 and 6502/6510's are good starting points as they were very wide spread (CP/M-80 and C64 respectively) with a lot of code written.
See for instance the chess programs listed here - http://chessprogramming.wikispaces.com/Z80 - Sargon played a respectable game, and the ZX81 ran in 1 KB of RAM.

A: It's a very long time since I did any assembler... I remember learning on a 68k at college, the reason given was that the assembler was simpler on the older chips so easier to learn the fundamentals without any clever optimization getting in the way. So maybe they are still useful as teaching platforms?
I don't get the reference to functional programming - are you saying FP somehow replaces assembly programming?

A: It's a good way to get introduced to assembly language programming.  x86 has become a real mess over the decades, and it's used almost everywhere the average programmer would program that way.  Starting with something more coherent (like M68K, for example) has real advantages.

A: If you have an interest in computer history, how did we get to where we are now.  if you examine a lot of assembly today, much of the time most people are looking at compiler generated code, not hand written assembly.  The 6502 is a prime example if a processor to learn.  For one thing there are many roms from the classic standup arcade games like Asteroids.  You can learn the instruction set by writing a disassembler.  Writing a disassembler for a variable length instruction set is a educational programming challenge in and of itself, well worth the effort, or at least like a maze solving program, worth at least getting to the point where you figure out what you have to do to solve it.  Because these were hand coded assembler, they didnt have to, and didnt follow programming conventions like a compiler would.  Some of these roms either intentionally or on purpose have some traps in them that trip up a disassembler.  Back to the disassembler learning experience.  Then you can examine the programming style, how it might be similar to general programming in any language and the kinds of tricks and habits used by the programmer for that instruction set.  The 6502 holds an important position in computing history, despite the sales pitch leading many to think that Apple had anything to do with anything (they were an also ran behind commodore and tandy/radio shack in the personal computer movement) the 6502 was the common factor in the move from time share computers to ones you could afford to own.  As well as the video game world both atari vcs (a.k.a atari 2600) and stand up arcades.  Later the z80, and a number of others took over and carried us to where we are now.  the 6502 in particular has an addressing mode, which the msp430 can also take advantage of in its own way.  YOu may think of the 6502 being starved for registers, but consider the actual registers just temporary registers and the page zero memory being 256 registers.
I also highly recommend going backwards to the 8088/86 to get the history of where the current x86 family was born, compare it to the z80, 8080, and others that sprang from a common source/concept and evolved on their own. x86, even the modern one can be considered a dead instruction set it is so painful and archaic, it just wont die.  Why bother translating to some other instruction set inside, why not do what DEC did with the Alpha running windows and dynamically recompile converting the program to another instruction set, allowing legacy programs to run, the reason why microsoft and intel are still in business, but moving away from a poor intermediate interface between the source code and the execution unit(s).
Perhaps the most important lesson is that processors are as similar as they are different, load, store, the basic set of alu operations, xor, add, etc.  At the same time even with C, the programming languages never really clinched the features of the hardware, you still have to dive down into assembly to hand tune for performance.  core language libraries like memcpy for C are hand tuned asm per platform because the language just doesnt cut it.
You will also find out that many of the processors you claim to be obsolete are still available for sale, sure a small vendor or two with a small market share, but some markets or companies rely on the 8051 for example (have you used a network card lately, sent any TCP/IP packets to anyone?  how did you get this web page, there were a number of 8051 driven macs and phys that your packet flowed through, even reading the datasheets and programming those parts you dont realize they are 8051 based unless you have had the history or asked the right question to the vendor when programming those parts).  zilog still lives (z80) (and rabbit semiconductor is a modified z80), forms of the the 6502 are still for sale, the hc11, etc, etc.

A: You can learn what computing is all about: moving 0s and 1s from one location to the other, sometimes making them collide in an ALU.

A: I think you can learn a lot about a specific machine you need to do work on. For example if you want to emulate an old system such as the NES. You would need to learn about 6502.

A: I don't think the "assembly language" is obsolete, so much as the hardware is obsolete. There's no significant difference between old and new assembly languages, if you are able to ignore the vast changes in machine architecture they target, the syntax is nearly the same.
So uh, I'd say not much of anything.


text:
Q: Install the node-osc module in npm, in nodejs I'm trying to install the node-osc package in nodejs.
I run npm install node-osc and get this
I tried installing the dependencies on their own:
npm install python
npm install node-gyp

This did not work .. any ideas about what went wrong?

Update

I have set the environmemtal variable like this:
Variable name: PYTHON
Variable value: c:\Python33\
now I got rid of the python not found thingy and i get this:

Update
Now I installed the CORRECT verison of python (27) .. 33 is not supported by node-gyp
and I get this:

Update

Turns you I had to install some other stuff to get it working on a 64bit machine:
this guide was life-saving:  https://github.com/TooTallNate/node-gyp#installation

A: The error means you're missing Python from your executables, which node-gyp requires to build some modules. That means it either isn't installed, or you haven't set the PATH variable for python. To fix this, just install Python.
The installation guide states you will need version 2.6/2.7 or above of Python.


text:
Q: is.na() replacing all values instead of na ones I have dataframe tr which contins around 1700 rows. I am trying to replace Type column values wherever they are NA with string "None".
I do a quick count to check how many NAs I have in my Type column.
na_count = tr[which(is.na(tr$Type)), ]

na_count contains 8 records.
Now I replace all the NAs with "None" using
ifelse(is.na(tr$Type), tr$Type <- 'None', 0)

The above command is replacing all the 1700 rows with None instead of just the 8.
I'm not sure why that is happening.


text:
Q: C++17 - Modifying const values So, as of now, it seems to be impossible to actually modify a "const" value in C++ (tested in VS 2017).
const int a = 5;
int* ptr = (int*)&a; // Method 1
*((int*)(&a)) = 6; // Method 2
int* ptr = const_cast<int*>(&a); // Method 3
*ptr = 55;
cout << a << "\t" << &a << endl;
cout << *ptr << "\t" << ptr << endl;

Result:
5  SOMEMEMORYADDRESS
55 SOMEMEMORYADDRESS

Anyone got any idea what else can be tried to achieve the effect? Really curious how it is possible to have 1 memory address (at least according to the console) with 2 values.
Please note: there are topics like this for older C++ versions (and they used to work in the past - but they don't, anymore).

A:
Really curious how it is possible to have 1 memory address (at least according to the console) with 2 values.

It's because you invoked undefined behavior. The C++ standard, from C++98, has expressly forbidden you from modifying an object that is declared const. And the standard has a catch-all statement such that if you do anything which causes modification of a const object, you get undefined behavior.
Because modifying an object declared const is UB, the compiler is free to assume that this object will never be modified. So, since the compiler can see that a is const and it is initialed to 5, it is 100% valid for the compiler to at compile time replace everything which revers to this object with 5. So when you do cout << a, the compiler is free to not bother to access memory; it can just do cout << 5.
If you did something to modify the memory behind a, that's UB, so the compiler doesn't have to care about what happens in that case.

they used to work in the past - but they don't, anymore

No, they never "worked". They merely just so happened to do what you thought they should. But C++ never guaranteed that compilers would behave in this way, so you have no right to complain about compilers changing that behavior now.


text:
Q: C#: How do I create a WMP PositionChangeEvent I am relativly new to C# and also new in the Stackoverlow-community.
At the moment i am trying to create an audioplayer, which can loop an audiofile smoothly, by overlapping two playing instances of this file and fading between those.
I use the  WMPLib Windows Media Player. Until now I connected 2 WMPs with 2 Timers, which is not very precise and also buggy, when used with short Audiofiles.
While puzzling possible new solutions, i stumbled over the "PositionChangeEvent" from the WMP, which could be very useful for my Project. However i do not now how to use it.
For a timer i do it like this:
timer1.Tick += new EventHandler(timer1_Tick);

(...)
 private void timer1_Tick(object sender, EventArgs e){//...}

but an Event build like this, doesnt work for:
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.PositionChange += new _WMPOCXEvents_PositionChangeEventHandler(wplayer_PositionChange);

the error is
No overload for 'wplayer_PositionChange' matches delegate 'WMPLib._WMPOCXEvents_PositionChangeEventHandler
So, how do i create the correct event?
EDIT: Okay. I solved it by myself. apparently pressing tab in visual studio after typing the "wplayer.PositionChange +=" automaticly inserts the event handler, and pressing tab again, automaticly adds the new event.


text:
Q: In F#, how to break a list down into multiple subgroups and return all subgroups? (Newbie question). I have a database function in which I am downloading essentially an unordered set of records with the following record format (in C#):
public partial class view_rx
    {
        public int? rx_recid { get; set; }
        public DateTime? trx { get; set; }
        public string medname { get; set; }
        public string ssig { get; set; }
        public int disp { get; set; }
        public string form { get; set; }
        public int refills { get; set; }
        public DateTime? tstop { get; set; }
        public DateTime? tprinted { get; set; }
    }

All records will have either a trx or tstop time, or both.
How can these records be grouped by trx DATE or tstop DATE (when trx is null) in F#? That is, how can the returned database list be returned as multiple sub lists, with each list representing a single date?  All this in F#?  (I'm stumped on how to do groupings in F#).
(No code posted because I don't know where to start :( )
Thanks in advance for any help.

A: The function you want is groupBy. There are versions for each of the basic F# collection types (e.g. List.groupBy, Seq.groupBy, etc.).
Here's a quick example that does what you want:
// Simplified F# version of your record type
type view_rx =
    {
        rx_rec : Option<int>
        trx : Option<DateTime>
        tstop : Option<DateTime>
    }

// Group records by trx/tstop
let records = getRecords ()
let groups =
    records
        |> Seq.groupBy (fun record ->
            record.trx
                |> Option.orElse record.tstop)

// Display the results
for (date, records) in groups do
    printfn ""
    printfn "%A" date
    for record in records do
        printfn "   %A" record.rx_rec

With some made-up data:
let records =
    [|
        {
            rx_rec = Some 1
            trx = "7/1/2021" |> DateTime.Parse |> Some
            tstop = None
        }
        {
            rx_rec = Some 2
            trx = None
            tstop = "7/1/2021" |> DateTime.Parse |> Some
        }
        {
            rx_rec = Some 3
            trx = "7/2/2021" |> DateTime.Parse |> Some
            tstop = None
        }
        {
            rx_rec = Some 4
            trx = None
            tstop = "7/2/2021" |> DateTime.Parse |> Some
        }
    |]

Output is:
Some 7/1/2021 12:00:00 AM
   Some 1
   Some 2

Some 7/2/2021 12:00:00 AM
   Some 3
   Some 4


text:
Q: Make things available in any view file Laravel I have a question about making some elements available in any view file
Lets say im building a webshop and on every page i will be having my sidebar, shoppingcart, user greeting in the top.
How can i make these things available in all my view files?
I could make a class, lets say class Frontend
I could do something like this:
class Frontend {

    static $me;

    public function get(){
        if(!self::$me){
            self::$me = new self();
        }
        return self::$me;
    }

    private function getShoppingCart(){
        // do things
    }

    public function getData(){

        return array(
                'Username' => User::find(1)->UserName,
                'Cart' => $this->getShoppingCart()
        );

    }

}

Now in my controller i could pass this Frontend object into the view
View::make('file.view')->with(array('data' => Frontend::get()->getData()));

But this way i will end up with a god class containing way too much stuff and in every controller method i would have to pass these data, which is not relevant to the controller method
Is there a way in Laravel that makes specific data available across all view files?
Thanks!

A: Use share:
View::share('name', 'Steve');

as per http://laravel.com/docs/responses#views

A: You are close with your 'god class' idea.
Setting a $data variable in a basecontroller has helped me with similar issues
class BaseController extends Controller {

protected $data;

public function __construct() {

    $this->data['Username'] =  User::find(1)->UserName
    $this->data['Cart'] = $this->getShoppingCart()
 }
}

class Frontend extends BaseController {

   function someMethod(){
      View::make('file.view', $this->data)
   }
}

A: To keep everything clean, every part of the page should be its own *.blade.php file which would be put together using a master template of sorts.
master.blade.php
@yield('includes.sidebar')

@yield('users.greeting')

@yield('store.shoppingcart')

Then you can use view composers so that each time these views are loaded, the data you want is injected into them.  I would probably either create a new file which would get autoloaded, or if you have service providers for the separate portions of your app that these views would use, it would also go great in there.
View::composer('users.greeting', function($view)
{
    $view->with('user', Auth::user());
});

In this case, it would make the user model available inside your view.  This makes it very easy to manage which data gets injected into your views.


text:
Q: Как реализовать сортировку в doctrine? Всем привет. Есть запрос sql
http://sqlfiddle.com/#!9/af6428
SELECT * FROM `category`
  ORDER BY COALESCE(`orderNum`, `name`)

или
SELECT * FROM `category`
  ORDER BY `orderNum` IS NULL, `name`;

сам код
    $qb = $this->createQueryBuilder('s');
    $qb->join('s.category', 'c');
    $qb->where('c.code = :categoryCode')
        ->setParameter('categoryCode', self::MOBILE);
    $qb->andWhere('s.id <> c.primaryService');

    $qb->andWhere('s.isActive = true');
    $qb->andWhere('s.isVisible = true');

    $qb->orderBy('s.name', 'asc');

    return $qb->getQuery()->getResult();

как сделать их через doctrine orm?


text:
Q: Nav background image 100% height of page I'm trying to get the navigation background image to be the same height as my page and I can't figure out how. I have tried a bunch of different things found on this site to no avail. I'm very new to HTML5 and CSS so apologies if this is a stupid question. Here is my CSS:
body {
    background-color: #FF9933;
}
header {
    background-image: url(orangesquares.png);
}
h1 {
    background-color: #FFFFFF;
    opacity: 0.6;
    padding: 10px;
    width: 275px
}
h2 {
    color: #FF9933;
}
nav {
    background-image: url(orangesquares.png);
    float: left;
    width: 200px;
    margin-top: 0;
    Margin-bottom: 0;
    font-weight: bold;
}
nav ul {
    list-style-type: none;
    background-color: #FFFFFF;
    opacity: 0.6;
    padding: 10px;
}
#rightcolumn {
    margin-left: 205px;
    background-color: #ffffff;
    color: #000000;
    width: 80%;
}
.content {
    padding: 10px 20px 0 20px;
}
#footer {
    text-align: center;
    font-size: 11px;
}
a:link {
    color: #0033FF;
}
a:visited {
    color: #0033FF;
}
figure {
    width: 500px;
    border: 1px solid #FF9933;
    padding: 5px;
}
figcaption {
    text-align: center;
    font-size: 2em;
}

Here is my HTML code for the index page:
<!DOCTYPE html>

        <title>Sims 3 Open House</title>
        <meta charset="utf-8">
        <meta name="description" content="Sims 3 Open House provides information on houses included in the Sims 3 bin, such as what furniture is included and how many squares big the rooms are." />
        <meta name="keywords" content="Sims 3, the sims 3, the sims, sims, open house, house, houses, home, homes, lots and houses bin, bin, premade, premade houses, lot size, house size, furniture" />
        <link type="text/css" href="openhouse.css" rel="stylesheet" />

Sims 3 Open House

Home

One Bedroom Homes

Cabin Fever

Super Shack

Two Bedroom Homes

Ginger

Oak Grove Bungalow

Three Bedroom Homes

Cornucopia

Doubleday Lodge

Contact Us

Welcome

Ever want to use a house from the Sims 3 bin but you aren't sure which one? What do they look like inside? How big are they really? What kind of     furniture do they have? Well, here you can find all that information! I have split the bin houses into categories by number of bedrooms to make your search easier. On each house's page there is detailed information about the layout of each house, how big the rooms are, and what furniture is included, plus general info like lot size and price. All screenshots were taken in Sunset Valley 2.

One Bedroom Homes

                            Cabin Fever

                            Super Shack

Two Bedroom Homes

                            Ginger

                            Oak Grove Bungalow

Three Bedroom Homes

                            Cornucopia

                            Doubleday Lodge

                        Home | One Bedroom Homes | Cabin Fever | Super Shack | Two Bedroom Homes | Ginger | Oak Grove Bungalow | Three Bedroom homes | Cornucopia | Doubleday Lodge | Contact Us

                        Copyright © 2015 Natasha Schmidt

A: why putting your bg in nav?
either make it full height
nav
{
background-image: url(orangesquares.png);
background-size: cover;
float: left;
height:100%
width: 200px;
margin-top: 0;
Margin-bottom: 0;
font-weight: bold;

}

or I don't know, do it right like
html{
   padding:0; margin:0;background-image: url(orangesquares.png);
background-size: cover;
}

and remove the background from the nav.


text:
Q: Fast Circular buffer in python than the one using deque? I am implementing circular buffer in python using collections.deque to use it for some calculations. This is my original code:
clip=moviepy.editor.VideoFileClip('file.mp4')
clip_size= clip.size[::-1]
Depth=30
dc=5
TempKern = # some array of size Depth
RingBuffer=deque(np.zeros(clip_size, dtype=float),maxlen=NewDepth)
modified_clip = clip.fl_image(new_filtered_output)
modified_clip.write_videofile('output.mp4'))

def new_filtered_output(image):
   global RingBuffer
   inter_frame=somefunction(image)# inter_frame and image shape is same as clip_size
   RingBuffer.append(inter_frame)
   # Apply kernel
   Output =  dc + np.sum([np.asarray(RingBuffer)[j]*TempKern[j] for j in range(Depth)],axis=0)
   return Output

Is this the fastest way possible? I have heard that numpy roll is an option. But I don't know how to make it behave like the above code?

A: I noticed you changed the code above, but your original code was:
def one():
    TempKern=np.array([1,2,3,4,5])
    depth=len(TempKern)
    buf=deque(np.zeros((2,3)),maxlen=5)
    for i in range(10):
        buf.append([[i,i+1,i+2],[i+3,i+4,i+5]])
    total=  + np.sum([np.asarray(buf)[j]*TempKern[j] for j in range(depth)],axis=0)
    print('total')
    print(total)
    return total

You can simplify things greatly and make it run quite a bit faster if you first flatten the arrays for the computation.
def two():
    buf = np.zeros((5,6), dtype=np.int32)
    for idx, i in enumerate(range(5, 10)):
        buf[idx] = np.array([[i,i+1,i+2,i+3,i+4,i+5]], dtype=np.int32)
    return (buf.T * np.array([1, 2, 3, 4, 5])).sum(axis=1).reshape((2,3))

The second implementation returns the same values and runs about 4x faster on my machine
one()

>> [[115 130 145]
    [160 175 190]]   ~ 100µs / loop

two()

>> array([[115, 130, 145],
          [160, 175, 190]])    ~~ 26µs / loop

You can further simplify and parameterize this as such:
def three(n, array_shape):
    buf = np.zeros((n,array_shape[0]*array_shape[1]), dtype=np.int32)
    addit = np.arange(1, n+1, dtype=np.int32)
    for idx, i in enumerate(range(n, 2*n)):
        buf[idx] = np.arange(i, i+n+1)
    return (buf.T * addit).sum(axis=1).reshape(array_shape)

three(5, (2,3))
    >> array([[115, 130, 145],
             [160, 175, 190]])   ~ 17µs / loop

Note that the second and third version returns a numpy array. You can cast it to a list by using .tolist() if need be.
Based on your feedback - edit below:
def four(array_shape):
    n = array_shape[0] * array_shape[1] - 1
    buf = []
    addit = np.arange(1, n+1, dtype=np.int32)
    for idx, i in enumerate(range(n, 2*n)):
        buf.append(np.arange(i, i+n+1))
    buf = np.asarray(buf)
    summed = (buf.T * addit).sum(axis=1)
    return summed.reshape(array_shape)

A: You can have the ring buffer as a numpy array, by doubling the size and slicing:
clipsize = clip.size[::-1]
depth = 30
ringbuffer = np.zeros((2*depth,) + clipsize)

framecounter = 0

def new_filtered_output(image):
   global ringbuffer, framecounter
   inter_frame = somefunction(image)

   idx = framecounter % depth
   ringbuffer[idx] = ringbuffer[idx + depth] = inter_frame
   buffer = ringbuffer[idx + 1 : idx + 1 + depth]
   framecounter += 1

   # Apply kernel
   output =  dc + np.sum([buffer[j]*kernel[j] for j in range(depth)], axis=0)
   return output

Now you don't have convert the deque into a numpy array every frame (and every loop iteration..).
As mentioned in the comments, you can apply the kernel more effeciently:
output = dc + np.einsum('ijk,i->jk', buffer, kernel)

Or:
output = dc + np.tensordot(kernel, buffer, axes=1)


text:
Q: Oracle imp tables fail due to restraints I am using the Oracle imp utility to import data into a set of empty tables in Oracle 10g.  When I try to perform the import much of it fails due to referential integrity constraints.  E.g. Can't import data into table A because foreign key in table B does not exist yet.
Here is my import command:
imp C_PLUS/<password> rows=y file=db.dmp ignore=y FROMUSER=C_PLUS
TOUSER=C_PLUS tables=...

I could manually go through each table on import and when it fails import the missing table first, but I have over 400 tables that need imported and it would take far too long.
Is there a way around this or does anyone have any ideas?
Thanks

A: Since you want every table owned by C_PLUS, you can omit the TABLES clause.  Just specify the FROMUSER.  You can also omit the TOUSER parameter since you're not changing the schema name but that won't affect the behavior of the import.  Omitting the TABLES clause should fix the problem with constraints assuming that all the foreign key constraints reference other tables in the same schema and assuming that the data in the export file allows the constraints to be enabled (if the export was done without setting CONSISTENT=Y, there may be orphaned rows in the dump file that will prevent the constraints from being created for example).

A: For each table you can disable the primary key/foreign key constraints before import. Then enable each primary and foreign key constrains after the import.
Disable contraints
ALTER TABLE table_name DISABLE PRIMARY KEY CASCADE;

Enable constraint
ALTER TABLE table_name ENABLE CONSTRAINT constraint_name;

If the number of table and the number of constraints are too many to do it manually, you can write scripts to generate the ALTER TABLE commands using the data dictionary views.
Disable PK/FK contraints
SELECT 'ALTER TABLE '||table_name||' DISABLE PRIMARY KEY CASCADE' sql_statement
FROM USER_TABLES;

Enable PK constraint
SELECT 'ALTER TABLE '||table_name||' ENABLE CONSTRAINT '||constraint_name sql_statement
FROM USER_CONSTRAINTS
where constraint_type ='P';

Enable FK constraint
SELECT 'ALTER TABLE '||table_name||' ENABLE CONSTRAINT '||constraint_name sql_statement
FROM USER_CONSTRAINTS
where constraint_type ='R';


text:
Q: Identifying all files that have changed since my last commit *to that file* I'm working on a Git project where one of my roles is to be aware of and review/edit all changes to a part of a project, which is a bit scattered around the codebase.  The team is making lots of changes all over the codebase, and I'd like to focus my review to the parts I need, but not worry about reviewing the parts that haven't changed since my last commit there (since I'd obviously have reviewed that).
Now, I don't know all of git's commands, but I don't think there's one that will solve all of this itself.  So, I was planning to assemble a script that roughly did:

*

*Find all the files in the repository

*Find my last commit to that file

*

*Determine if the file changed since the identified commit

*If so, output the filename, date/time of my commit, and date/time/owner of the latest commit.

Any suggestions on how I should approach this?  Am I on the right track?  Am I missing a command or existing script that would handle this, or at least simplify it?
Note: I've made many commits to this project scattered across many files.  There's not a single commit I could compare to current that would cover all the files, and I've made unrelated commits to the same project, so I can't just check what has changed since my last commit to the repository :(


text:
Q: "Error:" "Unsupported_grant_type" Using OAuth 2.0, Owin. Password Grant and Authorization Grant I'm building a Web API Application using Framework NOT Core. I have a user Authorization which is Login/Logout/Register User Password Grant_Type, using Owin and OAuth2 Password Grant_Type.
To Access the NopCommerce protected resource I have to authorize my application using OAuth2, Authorization Grant_Type obtaining a token. [enter link description here][1]
The Problem is when I call the /Token endpoint using Authorization Grant. The moment NopCommerce API Redirects the user to callback url, I see the "Error:" "Unsopported_grant_type" message.
Startup.Auth.cs
// Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                ApplicationCanDisplayErrors = true,
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

And The Standard ApplicationOauthProvider.cs that comes with Owin.
How can i use the above /Token endpoint using OAuth2 Authorization Grant_Type?

A: So a while back i found a solution to my own problem. I did not have had the time to post my answer earlier. Any way.
First i thought the problem was in RouteConfig.cs, but it seems that the Standard ApplicationOauthProvider.cs is NOT ready for Authorization Grant, but is for Password grant. So to use multiple Grant-Types or Flow(s) the best practice is creating custom Startup Options.
In my Case i added the following:
NopOAuthOptions = new OAuthAuthorizationServerOptions
            {
                AuthorizeEndpointPath = new PathString("/NopAuthorize"),
                TokenEndpointPath = new PathString("/NopToken"),
                Provider = new NopOAuthProvider(),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(10),
                ApplicationCanDisplayErrors = true,
                //true only in development
                AllowInsecureHttp = true,
            };

            app.UseOAuthAuthorizationServer(NopOAuthOptions);

And then i created my custom provider like this:
public override Task MatchEndpoint(OAuthMatchEndpointContext context)
        {
            var endpointPath = new PathString("/NopAuthorize");

            if (context.Options.TokenEndpointPath == endpointPath)
            {
                context.MatchesAuthorizeEndpoint();
                Trace.WriteLine(context.OwinContext.Request.QueryString);
            }

            return base.MatchEndpoint(context);
        }

Ofcourse for security it is best to also configure:
public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)

 public override Task ValidateAuthorizeRequest(OAuthValidateAuthorizeRequestContext context)'

Etc....
Microsoft has a great Documentation page dedicated to Owin Oauth2 Authorization Server.
Microsoft Owin Oauth2 Authorization Server


text:
Q: nginx error "server" directive is not allowed here nginx -t results in the following error:

nginx: [emerg] "server" directive is not allowed here in /etc/nginx/sites-enabled/default:8

Below is the contents of the code in the / etc / nginx / sites-available / default file:
server {
        listen 27016;
        server_name 52.79.70.237;
        location / {
                proxy_pass http://127.0.0.1:27016;
}

server {
        listen 80 default_server;
        server_name 52.79.70.237;
        location / {
                proxy_redirect off;
                proxy_pass http://127.0.0.1:3001;
        }
}

I would appreciate it if you could tell me why the error occurred.

A: You can restart nginx. If you do not want to restart it, you can restart it by killing the process.
netstat -tnlp

The following table appears. Check the number next to the leftmost process name.
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:27017           0.0.0.0:*               LISTEN      1220/mongod
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      14263/mysqld
tcp6       0      0 :::80                   :::*                    LISTEN      2495/nginx: master

Enter the following command.
kill -2 2495

This will force the process to terminate. Now type nginx again and nginx will run.


text:
Q: Apple Push Notification Provider in own application I have some questions about apns in my own server-side application. I have a java application who should be able to send push notifications to apple.
The server and also the iphone app is working, my question aims to the distribution of the server application and the certificates.
Can I distribute all servers to the users with the same certificate? Or do I have to send every user their own certificate for their server?
Every server should be able to send their push messages to the apple servers for delivery, like:
Server-Application <--> Apple Push Notification Server <--> iPhone / iPad etc...
Is that possible?

A: Every server should be configure with certificate and should have SEND notification LOGIC coded in JAVA or any other language like PHP or C#.
You need one Certificate for every Server.
Every server should be preconfigure for APNS requirements. You need to build server with certificate and port enabled on that. Please check Ray wander linch' guide for APNS and you will find what it takes to do above.


text:
Q: How is this infinite list computed? The problem is the following:

Define a Haskell variable dollars that is the infinite list of amounts
  of money you have every year, assuming you start with $100 and get
  paid 5% interest, compounded yearly. (Ignore inflation, deflation,
  taxes, bailouts, the possibility of total economic collapse, and other
  such details.) So dollars should be equal to: [100.0, 105.0, 110.25,
  ...].

My solution is the following and it works:
 dollars::[Double]
 dollars = 100.0 : [1.05 * x | x<- dollars ]

The problem is that I have trouble understanding how the list is computed practically:
dollars= 100.0 : [1.05 * x | x<- dollars ]
= 100.0 : [1.05 * x | x<- 100.0 : [1.05 * x | x<- dollars ]   ]
= 100.0 : (1.05 * 100.0) : [1.05 * x | x<- [1.05 * x | x<- dollars ]    ]
= 100.0 : 105.0 : [1.05 * x | x<- [1.05 * x | x<- dollars ]   ]
= 100.0 : 105.0 : [1.05 * x | x<- [1.05 * x | x<-  100.0 : [1.05 * x | x<- dollars ]  ]  ]
= 100.0 : 105.0 : [1.05 * x | x<- 105.0:[1.05 * x | x<-[1.05 * x | x<- dollars ]  ]  ]
= 100.0 : 105.0 : 110.25 :[1.05 * x | x<-[1.05 * x | x<-[1.05 * x | x<- dollars ]  ]  ]

etc.
Is that how it is computed? If not then how? If yes, is there a simpler way to conceptualize these kinds of computations?

A: You are pretty much correct. It might help if you de-sugared the list comprehension into a function call. The equivalent is
dollars = 100.0 : map (* 1.05) dollars

This then evaluates to
= 100.0 : let dollars1 = 100 * 1.05 : map (*1.05) dollars1 in dollars1
= 100.0 : 105.0 : let dollars2 = 105 * 1.05 : map (*1.05) dollars2 in dollars2

and so on. I'm using dollars1, dollars2 as identifiers, even though they don't really exist.

A: That is more or less correct. In which order the substitutions happen depends on the code that prints out the results. The substitutions in the 2. and 3. line could be swapped.


text:
Q: How to apply k-means clustering on Network Graphs in R iGraph? The following code generates a Netwrok Graph and can separate the data into two groups, but I would like to apply k-means on it and see how the algorithm clusters the data into the same set of clusters.
library(igraphdata)  # library for the graph data
data(karate)
V(karate) %>% print()  # shows the list of the nodes

# Reproducible layout
set.seed(69)
l <- layout_with_kk(karate)   #sets the layout.

# Plot undecorated Graph Network First.
igraph_options(vertex.size=10)
par(mfrow=c(1,1))                               # sets plotting parameters
plot(karate, layout=l, vertex.label=V(karate),
     vertex.color=NA)                           # Plots a basic Graph

# Now decorate, starting with labels.
V(karate)$label <- sub("Actor ", "", V(karate)$name)
V(karate)
# Two Club Leaders get shapes different from other club members.
V(karate)$shape <- "circle"
V(karate)[c("Hi", "John")]$shape <- "rectangle"       # sets different shapes for these two only
# Differentiate two factions by color. (Similar to clustering & color-coded)
V(karate)[Faction == 1]$color <- "red"
V(karate)[Faction == 2]$color <- "dodgerblue"
# Vertex area proportional to vertex strength
# (i.e., total weight of incident edges).
V(karate)$size <- 4*sqrt(strength(karate))
V(karate)$size2 <- V(karate)$size * .5

# Weight edges by number of common activities
E(karate)$width <- E(karate)$weight
# Color edges by within/between faction.
F1 <- V(karate)[Faction==1]        # sets variable for first cluster (faction)
F2 <- V(karate)[Faction==2]        # similar to the above.
E(karate)[ F1 %--% F1 ]$color <- "pink"
E(karate)[ F2 %--% F2 ]$color <- "lightblue"
E(karate)[ F1 %--% F2 ]$color <- "green"
# Offset vertex labels for smaller points (size based, default is zero).
V(karate)$label.dist <-
  ifelse(V(karate)$size >= 9.0, 0, 1.0)
# Plot decorated graph, using same layout.
plot(karate, layout=l)

Final Output:

A: you can get the adjacency matrix of the resultant graph and apply k-means clustering on top of the matrix. It is equivalent to applying k-means to the graph.
Following is the sample code
adj.matrix = get.adjacency(graph, sparse=FALSE)
k <- 3 # no of desired clusters
km <- kmeans(matrix , centers = k, nstart = 25)


text:
Q: For given binary string find maximum sub-string with equal number of ones and zeroes I'm trying to solve this problem, let's say we have given string of length up to 100000 which consists only 0 and 1, now for this string we want to check which is the longest substring that contains equal number of zeroes and ones.
Example
Let's say we have string "1010110", the biggest substring that can be found in this string is with size 6 and that is the substring which is starting on position 1(if the string is zero-indexed), actually that is the string "010110".
What i tried
I tried to solve this with two nested loops such that the first one (i) goes from 0 to n-1, where n is length of the string and the second one(j) goes from i to n, I'm creating array of integers and instead of 0 I'm keeping -1, and now i just check if the sum of the elements from i to j is 0 if it is zero then we compare the size of that substring to the final result


text:
Q: I am getting the error "The requested resource isn't a valid image for /public/logoicon/logoOrange.png received text/html; charset=utf-8" I am getting an error while trying to add a PNG or SVG file to my code. What is my mistake is or what do I have to change to get it working?
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'

export default function Home() {
  return (

        <title>Maintenance</title>
        <meta name="description" content="This Website is in Maintenance Mode" />
        <link rel="icon" href="/favicon.ico" />

This website is currently in

     <break></break>

Maintenance Mode.

     <Image
            src="/public/logoicon/logoOrange.png"
            alt="server and database with broken cable"
            width={77}
            height={33}
        />

©2022 Karlo-Hosting.com

  )
}

My code is above.

A: If the server sends you a response thats say "received text/html; charset=utf-8", try to analyse the error. You can see that the server says "Here is your requested text/HTML content that has the UTF-8 format".
Check if the source of the image is correct. And if the image exists and try to check what text/HTML content the file server sends back to you.

A: Also just starting picking up Next.js and was baffled by why my images were not being displayed.
After changing the format multiple times and checking the source. It appear that the images are actually hosted in the public folder
The solution to my image problem:
So adding images in the following directory:
public/images/[place image file]
This is what my problem was. Hope this helps someone else.

A: Simply remove the /public portion before your image name.
The public folder is exposed, and automatically searched through and understood by NEXT.JS.
So make /public/test.jpg => /test.jpg

A: Solution 1.
this error is in terminal right, so
'public' folder is exposed at root level, so you need not specify the public folder
try this -
src="/logoicon/logoOrange.png"
instead of -
src="/public/logoicon/logoOrange.png"
Solution 2.still if you get 400 bad request error in console
then its a generic client error
check for->
a) URL string syntax
b) corrupted cache and cookie
c) check if image is too big
d) check for any whitespaces in naming folder

A: importing it like import img from '/public/[your image here]' seems to be working.

A: So the only thing that works since Next13's Image changes is a set up like this. Note that they have also opted to remove the objectFit props in favour for styles instead - I don't really get the rationale behind this as it feels a bit regressive!
But anyway, I hope this helps some of you. You dont have to call it 'imageAsset' this is just an example - call it what you like as long as it's in your public folder it'll work :)
I thought I would type out a bit of a example as I know some people that come here are new to Next/React and might not fully understand the implementation just yet.
NOTE: removing /public/ from the image src or import doesn't work for all cases as your images may not be directly in the public folder - like below my images are in a subfolder in that directory. Therefore removing /public/ will not work.
import Image from "next/image"
import imageAsset from '/public/images/your-image-asset.webp'

export default function Component() {
  return (
    <>
      <Image src={imageAsset} width={1920} height={1080} style={{objectFit: 'cover', objectPosition: 'center'}} />
    </>
  )
}

A: For me another process was running on port 3000. You can find the process by running the command below in your Mac Terminal.
$ lsof -i :3000

Afterwards, you can kill the process from Activity Monitor. In my case another instance of NodeJS was utilising port 3000.

A: Faced this issue today. Seems like a problem with next/dynamic which would not load the image properly. Not a ethical solution but not dynamically importing your component with the image in it seems to fix it for me.


text:
Q: How to verify the ACE-CORBA service local windows machine I'm able to create docker container for ACE-TAO service , and able to  access  it  from parent windows machine using port-forwarding  concept.
From  browser i try  to hit  the localhost:forward-port and getting "ERR_EMPTY_RESPONSE" and TAO service is running in  docker container.
If I want to  verify in local, whether its connected properly or  not.
How can I write Java code to verify?

A: The following java code connects to localhost:17500 and prints out a message saying whether or not it could create a tcp connection.
import java.io.*;
import java.net.*;

class TCPClient
{
 public static void main(String argv[]) throws Exception
 {
   try {
    Socket clientSocket = new Socket("localhost", 17500);
    System.out.println("Could connect");
   }
   catch (ConnectException e) {
    System.out.println("Cannot connect");
   }
 }
}


text:
Q: jQuery $.inArray returns -1 when it should be 0 Hell All,
I have an odd problem:
//dataText hold current language data that's gathered from another function
//pick one to test it out
//if english data gathered
var dataText = ["Data uploads"];
//if french data gathered
var dataText = ["Envois de données"];

function lang_lib(lang) {
    var data_fre = [13, 'Envois de données'];
    var data_eng = [14, 'Data uploads'];
    var data_lang, rep_lang;

    switch(lang) {
        case "English":
            data_lang = data_eng;
            data_rep = rep_eng;
            break;
        case "Français":
            data_lang = data_fre;
            data_rep = rep_fre;
            break;
        default:
            $('table.infobox tbody').append('

User language is not available

');
    };

    this.data_uploads = data_lang[1];
}
_lang = new lang_lib($('#toplinks-language').text());

//if lang_lib("English")
alert($.inArray(_lang.data_uploads, dataText)); // 0

//if lang_lib("Français")
alert($.inArray(_lang.data_uploads, dataText)); // -1

I shortened the code but it should give a general idea of what I'm trying to achieve.
I know it seems weird why I would be using the same data in two arrays but the data_fre and data_eng have language specific dataText info plus other language specific data as well. dataText will have non-specific language data which is why I'm testing it agains data_fre or data_eng to find which language to use.
I can't figure out why it would return -1 because I have other languages set (with special character too like Russian text) and they all return 0.
Appreciate the help :)

A: -1 means false.  0 means 'at position 0'.  Without knowing more about the data coming in, I expect it is working properly.

A: Strings do not match numbers.
Simple Test
var arr = [13, 'Envois de données'];
console.log($.inArray(13,arr));    // 0 - matches as a number
console.log($.inArray("13",arr));  // -1 - matches as a string

A: Ok I figured out what it was.
I used $.trim() in the function that collects data for dataText. Since I couldn't see any leading or trailing spaces when I would alert() it was confusing me why it wouldn't work.
This explains why $.inArray() wouldn't match "Envois de données" with "Envois de données ".
Thanks again everybody for taking a look :)


text:
Q: Converting KML coordinates to Leaflet I am trying to convert a Google Map KML file to a csv, to map the longitude and latitude points on Leaflet. But the coordinates keep mis-projecting and some end up off the land mass.
The steps I have done are:
- Download KML file
- Import into a GIS package (both MapInfo 12 and QGIS), and used the projections of WGS84 EPSG 3857, WGS84 EPSG 4326 and Google Mercator EPSG 900913, to create long/lat points
- Save this table as csv
- Upload to Leaflet using the Recline.js in DKAN to allow users to preview the map data.
Screenshot 1 is the original google map, and then screenshot 2 is the csv on Leaflet

Have looked around the rest of the forum and cannot find an answer. Any help?


text:
Q: Should I use useMemo in hooks? I created useBanner hooks
const useBanner = (array, yardage) => {
  const [bannArr, setBannArr] = useState(array.slice(0, yardage));
  const [bannListIndex, setBannIndex] = useState(1);

  return {
   ....
  };
};

Am I doing the right thing and the props throw in useState.
It's permissible to use useBanner.
const Banner= ({
  array,
  yardage
}) => {
  const { bannForth, bannBeck, bannArr } = useBanner(array, yardage);
  return (
    ...
  );
};

when props will change here.
Will change the state in useBanner.
or is it considered anti-patterns I have to write all this in useMemo
const useBanner = (array, yardage) => {
  const [bannArr, setBannArr] = useState([]);
  const [bannListIndex, setBannIndex] = useState(1);

 useMemo(() => {
    setBannArr(array.slice(0, yardage));
    setBannIndex(1);
  }, [array, yardage]);

  return {
   ....
  };
};

A: Yes, custom hooks are possible in React. Here is separate document discussing custom hooks.
But exactly you sample may require additional code depending on what is your final goal.

*

*If you want initialize state only once, when component Banner is first created, you can just do as in your first sample
const Banner= ({
    array,
    yardage
}) => {
    const { bannForth, bannBeck, bannArr } = useBanner(array, yardage);
    return (
      ...
    );
};

This will work perfectly. But if props array and yardage will change, this will not be reflected in component. So props will be used only once as initial values and then will not be used in useBanner even if changed (And it doesn't matter whether you'll use useBanner or useState directly). This answer highlight this.

*If you want to update inital values on each props change, you can go with useEffect like below
const Banner= ({
    array,
    yardage
}) => {
    const { bannForth, bannBeck, bannArr, setBannArr } = useBanner(array, yardage);
    useEffect (() => {
        // setBannArr should also be returned from useBanner. Or bannArr should be changed with any other suitable function returned from useBanner.
        setBannArr(array.slice(0, yardage));
    }, [array, yardage, setBannArr])
    return (
      ...
    );
};

In this case Banner component can control state itself and when parent component change props, state in Banner component will be reset to new props.
Here is small sample to showcase second option.


text:
Q: Convert date type in do loop? I am trying to write a SAS macro, in which I need to loop a date range and use the date in the where condition in PROC SQL step. At the same time, I have to use a path through in the PROC SQL step.
The start_date field in table1 is in the datetime format, i.e. '15mar2021:00:00:00'.
I tried to convert the date format for &i in the where clause to match the format of start_date field in table1. I tried below query but got this error: ERROR: CLI describe error: [Oracle][ODBC][Ora]ORA-00923: FROM keyword not found where expected
%macro date_delq(start,end);
%let start=%sysfunc(inputn(&start,anydtdte9.));
%let end=%sysfunc(inputn(&end,anydtdte9.));
%do i= &start %to &end;
  proc sql;
     connect using admin as server;
          create table delq_&i as
                select * from connection to server(
     select *
     from table1
     where start_date= CONVERT(datetime,&i,106)
);
run;
%end;
%mend date_delq;
%date_delq(01mar2021,02mar2021);

Thank you for your help!

A: I don't use SAS.
However, as it looks that you use an Oracle database, I presume that start_date column's datatype is date (as it should be; if it is varchar2, table designer has made a HUGE mistake).
In Oracle, dates are stored in its internal format, unreadable to us, humans. That's why we use functions (like TO_CHAR) or alter session to set NLS_DATE_FORMAT or apply desired format mask in our front-end applications to display those date datatype values as we want.
Therefore, there's no use in "converting" column contents from e.g. 15Mar2021 00:00:00 to 21mar2021 because you won't achieve anything, data will still be stored in the same internal format and - unless you do something about presenting those values, you won't see any difference.
What you could / should do is to use desired format mask, e.g.
SQL> with test (start_date) as
  2    (select to_date('24.03.2021 08:14:23', 'dd.mm.yyyy hh24:mi:ss') from dual)
  3  select to_char(start_date, 'fmdd Month yyyy, hh24:mi') example_1,
  4         to_char(start_date, 'Mon dd, yyyy') example_2,
  5         to_char(start_date, 'hh24:mi:ss') example_3
  6  from test;

EXAMPLE_1           EXAMPLE_2    EXAMPLE_
------------------- ------------ --------
24 March 2021, 8:14 Mar 24, 2021 08:14:23

SQL>

or
SQL> alter session set nls_date_format = 'dd Mon yyyy, hh24:mi';

Session altered.

SQL> select sysdate from dual;

SYSDATE
------------------
24 Mar 2021, 08:16

SQL>

and so forth.


text:
Q: CodeIgniter: Using Composer libraries without composer I have a project where I can't install or use composer.
However, I want to use the OmniPay library, which is a composer package. So I want to just take the libraries out and use them as standard libraries in Code Igniter.
This is what I get from the Composer install (below). If I take them into my application/libraries/ folder, how can i load them into my controller?

A: I think the easiest way would be to actually USE Composer on the machine you are developing on, and then commit the vendor folder to the repository.
If you don't want to do this, you'd have to manually do the steps Composer does. And this is more complicated than you think:
The last steps would be to extract the source from the package, put it somewhere suitable, and recreate the autoloading for it. This is the easy step, because the autoloading usually is PSR-0 or PSR-4. "Onmipay/Common" has one addtional class that doesn't fit into this and is loaded as classmap by Composer, so this class has to be handled extra.
The more complicated step before this: Omnipay is also using "guzzle/http" as a HTTP client, and "symfony/http-foundation". These packages also need to be included both as a file and then with their respective autoloading. And these also have dependencies with autoloading and dependencies...
Let Composer do the error-prone work, and commit the vendor folder if you can't provide the infrastructure to add the dependencies later during deployment.