text:
Q: Impossible to connect to VSFTPD from distant server My FTP server is a CentOS 5.4 with VSFTPD.
When I try to ls after connecting to my server using FTP I get this :
ftp> ls
229 Entering Extended Passive Mode (|||12206|)
ftp: Can't connect to `000.000.000.000': Connection refused
500 Illegal PORT command.
425 Use PORT or PASV first.

I can do mkdir without any problem.
When I connect from the same server to my ftp server I have no problem.
Port 20 and 21 are open in my iptable.
How can I fix that?
Thanks!!
UPDATE :
telnet myftpserver.com 20
Trying 000.000.000.000...
telnet: connect to address 000.000.000.000: Connection refused
telnet: Unable to connect to remote host

and
[root@internal vsftpd]# /sbin/iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
RH-Firewall-1-INPUT  all  --  0.0.0.0/0            0.0.0.0/0
SSH_CHECK  tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:22 state NEW

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
RH-Firewall-1-INPUT  all  --  0.0.0.0/0            0.0.0.0/0

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain RH-Firewall-1-INPUT (2 references)
target     prot opt source               destination
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:33988
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:3306
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:20
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:21
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:80
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0           icmp type 255
ACCEPT     esp  --  0.0.0.0/0            0.0.0.0/0
ACCEPT     ah   --  0.0.0.0/0            0.0.0.0/0
ACCEPT     udp  --  0.0.0.0/0            224.0.0.251         udp dpt:5353
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0           udp dpt:631
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           tcp dpt:631
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0           state RELATED,ESTABLISHED
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0           state NEW tcp dpt:22
REJECT     all  --  0.0.0.0/0            0.0.0.0/0           reject-with icmp-host-prohibited

Chain SSH_CHECK (1 references)
target     prot opt source               destination
           all  --  0.0.0.0/0            0.0.0.0/0           recent: SET name: SSH side: source
DROP       all  --  0.0.0.0/0            0.0.0.0/0           recent: UPDATE seconds: 60 hit_count: 4 name: SSH side: source

A: The problem is related to the fact that Passive FTP uses ports other than 20 and 21. Read about it here: http://slacksite.com/other/ftp.html
Usually I will setup a port range in the vsftpd.conf file for the Passive FTP and then open these ports on the firewall.
Also, I'm mostly a freebsd guy but I'm pretty sure there is a way on linux to dynamically open the FTP PASV ports but someone else will have to chime in on that one. I'll look and see what I can find.
In Linux, running the command:
modprobe ip_conntrack_ftp

should correct the connection issue when 'Entering Extended Passive Mode'.
EDIT:
First hit on google:
http://www.cyberciti.biz/faq/iptables-passive-ftp-is-not-working/
Better explanation:
http://www.sns.ias.edu/~jns/wp/2006/01/12/iptables-connection-tracking-ftp/


text:
Q: $_FILES["file"]["tmp_name"] return blank value I hosted my website with 000webhost and I run the following code during upload but it returned me blank value. I suspect something must be wrong with the temp folder but I not sure how to check this.
<?php
echo "Upload: " . $_FILES["file"]["name"] . "
";
echo "Type: " . $_FILES["file"]["type"] . "
";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
";
?>

A: Your error is: UPLOAD_ERR_NO_TMP_DIR
Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.

Please refer this http://us.php.net/manual/en/features.file-upload.errors.php
to resolve this error
To resolve this check your php.ini file and check upload_tmp_dir location
upload_tmp_dir = "c:/wamp/tmp"  // or whataver desired location you want

A: It seems there is no value in your php.ini for "upload_tmp_dir".
The value for upload_tmp_dir needs to be set in php.ini
You cannot set this value by using ini_set().  So, you may want to run phpinfo() to check, and if you confirm it is missing (and if you are not allowed to edit your php.ini) you need to speak to the web host and ask them to set a value in your php.ini.  They may decline to do so if they wish to disallow file uploads.

redpajama_set_name: RedPajamaStackExchange


text:
Q: windows 10 constantly getting default gateway is not available (2 routers are connected together) This issue has been occurring for the last couple of days, my internet (wire connection) just stops working, i troubleshoot the problem and after ~30 seconds it said it fixed the :
default gateway is not available
and sometimes i get :
The connection between your access point, routers, or cable modem and the internet is broken

this 2nd error don't get fixed when it appears, it have a yellow triangle, but the internet works.
I tried :

*

*reinstalling the driver (latest version of the intel network drivier for the MSI Z270 sli)

*

*those ipconfig steps (flushdns, release, etc..)

*removed VmWare adapters (i use virtual machine sometimes)

*installed "Complete Internet repair" ticked all the boxes and apply.
And the issue is still occurring, knowing that all of my other devices (phones, ps4, switch, other computers) all work fine.
any idea how i can identify the issue please ?
The only clue that i have is that this have started occurring after i tried using DNS4ME to watch Netflix outside the U.S, but i made sure to reverse all the steps they asked to do here
EDIT
i can't believe i forget to mention this...
I am using 2 Routers,

*

*ZTE provided by my ISP (ZXHN H367N)

*Asus RT-N12+

The computer with the problem is connected to the ZTE with a cable, ZTE is also having its own Wifi so my other devices can connect to it.
The Asus router is connected to the ZTE via cable into to the available 4 ports that you use to connect any other device (i have a red port in the ZTE called WLAN but i never used that).
The reason i use the Asus router is because it allows me to control the bandwidth for those connected to it, so am using it as a "guest wifi access point"
Could this be the issue ?
EDIT 2
yeah its definetly the 2nd router, i just unplugged it from the main one while the internet got cut again, and the net is coming back immediately without the need to run the windows troubleshooting, i am not sure what i should be looking for but is this normal :

The 1st client is the Asus router, 2nd is this computer, is it okay that the router doesn't have an IpV6 address ?
Edit 3:
Internet got cut while the Asus router is completely unplugged, and after troubleshooting am getting this :

Edit 4:
yeah the Issue (default gateway is not available) is still happening even when the Asus router is disconnecting ...
Edit 5:
Ipconfig/all result :
    C:\WINDOWS\system32>ipconfig/all

Windows IP Configuration

   Host Name . . . . . . . . . . . . : MegaMonster
   Primary Dns Suffix  . . . . . . . :
   Node Type . . . . . . . . . . . . : Hybrid
   IP Routing Enabled. . . . . . . . : No
   WINS Proxy Enabled. . . . . . . . : No

Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Intel(R) Ethernet Connection (2) I219-V
   Physical Address. . . . . . . . . : 4C-CC-6A-AE-15-4D
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes
   Link-local IPv6 Address . . . . . : fe80::b9b3:9aeb:f92f:7b61%17(Preferred)
   IPv4 Address. . . . . . . . . . . : 192.168.100.21(Preferred)
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Lease Obtained. . . . . . . . . . : Friday, January 12, 2018 23:30:55
   Lease Expires . . . . . . . . . . : Saturday, January 13, 2018 23:30:55
   Default Gateway . . . . . . . . . : 192.168.100.1
   DHCP Server . . . . . . . . . . . : 192.168.100.1
   DHCPv6 IAID . . . . . . . . . . . : 323800170
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-20-9B-07-38-4C-CC-6A-AE-15-4D
   DNS Servers . . . . . . . . . . . : fe80::1%17
                                       192.168.100.1
   NetBIOS over Tcpip. . . . . . . . : Enabled

Ethernet adapter Connexion réseau Bluetooth 4:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Bluetooth Device (Personal Area Network) #4
   Physical Address. . . . . . . . . : 00-1F-81-00-08-30
   DHCP Enabled. . . . . . . . . . . : Yes
   Autoconfiguration Enabled . . . . : Yes

Tunnel adapter Teredo Tunneling Pseudo-Interface:

   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes
   IPv6 Address. . . . . . . . . . . : 2001:0:9d38:6abd:3819:36c6:d61d:82e(Preferred)
   Link-local IPv6 Address . . . . . : fe80::3819:36c6:d61d:82e%6(Preferred)
   Default Gateway . . . . . . . . . : ::
   DHCPv6 IAID . . . . . . . . . . . : 419430400
   DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-20-9B-07-38-4C-CC-6A-AE-15-4D
   NetBIOS over Tcpip. . . . . . . . : Disabled

C:\WINDOWS\system32>

Edit 6:
could this help ? running ipconfig/all when the net is broken give a different result for the Tunnel adapter Teredo Tunneling Pseudo-interface, it has less more values than the "normal one"
Tunnel adapter Teredo Tunneling Pseudo-Interface:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
   Description . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface
   Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
   DHCP Enabled. . . . . . . . . . . : No
   Autoconfiguration Enabled . . . . : Yes

A: In Device Manager, you should find your network device under 'Network adapters'. First uninstall your device driver, make sure you select the checkbox to 'Delete the driver software for this device'. This should ensure that Windows removes the device and its settings from the registry. Then restart your computer, then reinstall your driver again.
If this doesn't work, check if you have a system restore point that was created before you made changes for DNS4ME.
In the future, before you make any configuration changes... create a system restore point.


text:
Q: How is the Ruby safe navigation (&.) implemented? I was trying to figure out how the safe navigation operator is implemented but didn't find the source for it, would love to know how it works and how efficient it is.

A: The safe navigation operator was implemented following Feature #11537.
It is part of Ruby's core langiage, i.e. is implemented in the language parser, has an op code in the virtual machine. Thus, there is no single place where the operator is implemented. The first version of it was added in commit a356fe1c but it has seen multiple extensions since then.
As for how efficient it is, the answer is probably: quite. You might want to run your own benchmarks however to confirm whether it suits your requirements.

A: Before the safe navigation operator was implemented into the core language using C, there used to be a gem with similar functionality called andand. If you want to research how something like this could be implemented using Ruby, then the andand source is a good place to start:
https://github.com/raganwald/andand
require 'andand'

nil.andand.some_method
=> nil


text:
Q: Numbers, Units, and Measurements When it comes to measuring quantities, we say 1 L of water, 1 gallon of gasoline, or 1 kW of power.
Is it correct if I rearrange the words by exchanging the position of the unit and their quantities?
For example, is "water of 1 L" the same as "1 L of water"?
Is "power of 1 kW" the same as "1 kW of power"?

A: In the case of kilowatt (kW), three forms appear:
The device dissipates 1 kW of power.
The device dissipates a power of 1 kW.
The device dissipates 1 kW. (power is implied by the name of the unit)
You can verify that all three forms appear by searching for them, in the Google search bar and at Google books.  The same forms appear for current (ampere or A), and to some degree for EMF (voltage or V).
In the case of (water of 1 L) or (gasoline of 1 gallon), those forms are very rare, and should not be used.
The safest form to use is the one that appears in a textbook.


text:
Q: Chess AI with alpha beta algorithm I have implemented the alpha beta algorithm for my chess game, however it takes a lot of time (minutes for 4-ply) to finally make a rather stupid move.
I've been trying to find the mistake (I assume I made one) for 2 days now, I would very much appreciate some outside input on my code.
getMove function: is called for the root node, it calls alphaBeta function for all it's child nodes (possible moves) and then chooses the move with the highest score.
Move AIPlayer::getMove(Board b, MoveGenerator& gen)
{
    // defined constants: ALPHA=-20000 and BETA= 20000
    int alpha = ALPHA;
    Board bTemp(false); // test Board
    Move BestMov;
    int i = -1; int temp;
    int len = gen.moves.getLength();  // moves is a linked list holding all legal moves
    BoardCounter++; // private attribute of AIPlayer object, counts analyzed boards
    Move mTemp;     // mTemp is used to apply the nextmove in the list to the temporary test Board
    gen.mouvements.Begin();   // sets the list counter to the first element in the list
    while (++i < len && alpha < BETA){
        mTemp = gen.moves.nextElement();
        bTemp.cloneBoard(b);
        bTemp.applyMove(mTemp);
        temp = MAX(alpha, alphaBeta(bTemp, alpha, BETA, depth, MIN_NODE));
        if (temp > alpha){
            alpha = temp;
            BestMov = mTemp;
        }
    }
    return BestMov;
}

alphaBeta function:
int AIPlayer::alphaBeta(Board b, int alpha, int beta, char depth, bool nodeType)
{
    Move m;
    b.changeSide();
    compteurBoards++;
    MoveGenerator genMoves(b); // when the constructor is given a board, it automatically generates possible moves
    // the Board object has a player attribute that holds the current player
    if (genMoves.checkMate(b, b.getSide(), moves)){ // if the current player is in checkmate
        return 100000;
    }
    else if (genMoves.checkMate(b, ((b.getSide() == BLACK) ? BLACK : WHITE), moves)){ // if the other player is in checkmate
        return -100000;
    }
    else if (!depth){
        return b.evaluateBoard(nodeType);

    }
    else{
        int scoreMove = alpha;
        int best;
        genMoves.moves.Begin();
        short i = -1, len = genMoves.moves.getLength();
        Board bTemp(false);

        if (nodeType == MAX_NODE){
            best = ALPHA;
            while (++i < len){
                bTemp.cloneBoard(b);
                if (bTemp.applyMove(genMoves.moves.nextElement())){
                    scoreMove = alphaBeta(bTemp, alpha, beta, depth - 1, !nodeType);
                    best = MAX(best, scoreMove);
                    alpha = MAX(alpha, best);

                    if (beta <= alpha){
                        std::cout << "max cutoff" << std::endl;
                        break;
                    }
                }
            }
            return scoreMove;
        //return alpha;
        }
        else{
            best = BETA;
            while (++i < len){
                bTemp.cloneBoard(b);
                if (bTemp.applyMove(genMoves.moves.nextElement())){
                    scoreMove = alphaBeta(bTemp, alpha, beta, depth - 1, !nodeType);
                    best = MIN(best, scoreMove);
                    beta = MIN(beta, best);
                    if (beta <= alpha){
                        std::cout << "min cutoff" << std::endl;
                        break;
                    }
                }
            }
            return scoreMove;
            //return beta;
        }
        return meilleur;
    }
}

EDIT: I should note that the evaluateBoard only evaluates the mobility of pieces (number of possible moves, capture moves get a higher score depending on the piece captured)
Thank you.

A: I can see that you're trying to implement a mini-max algorithm. However, there is something in the code that makes me suspicious. We'll compare the code with the open-source Stockfish chess engine. Please refer to the search algorithm at https://github.com/mcostalba/Stockfish/blob/master/src/search.cpp
1.  Passing Board b by value
You have this in your code:

alphaBeta(Board b, int alpha, int beta, char depth, bool nodeType)

I don't know what exactly "Board" is. But it doesn't look right to me. Let's look at Stockfish:

Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth
  depth, bool cutNode)

The position object is passed by reference in Stockfish. If "Board" is a class, the program will need to make a new copy everytime the alpha-beta function is called. In chess, when we have to evaluate many number of nodes, this is obviously unacceptable.
2. No hashing
Hashing is done in Stockfish as:

ttValue = ttHit ? value_from_tt(tte->value(), ss->ply) : VALUE_NONE;

Without hashing, you'll need to evaluate the same position again and again and again and again. You won't go anywhere without hashing implemented.
3. Checking for checkmate
Probably not the most significant slow-down, but we should never check for checkmate in every single node. In Stockfish:
// All legal moves have been searched. A special case: If we're in check
// and no legal moves were found, it is checkmate.
if (InCheck && bestValue == -VALUE_INFINITE)
    return mated_in(ss->ply); // Plies to mate from the root

This is done AFTER all possible moves are searched. We do it because we usually have many more non-checkmates node than checkmate-nodes.
4. Board bTemp(false);
This looks like a major slow-down. Let's take at Stockfish:

  // Step 14. Make the move
  pos.do_move(move, st, ci, givesCheck);

You should not create a temporary object in every node (creating an object of bTemp). The machine would need to allocate some stack space to save bTemp. This could be a serious performance penalty in particular if bTemp is not a primary variable (ie, not likely be cached by the processor). Stockfish simply modifies the internal data-structure without creating a new one.
5. bTemp.cloneBoard(b);
Similar to 4, even worse, this is done for every move in the node.
6. std::cout << "max cutoff" << std::endl;
Maybe it's hard to believe, printing to a terminal is much slower than processing. Here you're creating a potential slow-down that the string would need to be saved to an IO buffer. The function might (I'm not 100% sure) even block your program until the text is shown on the terminal. Stockfish only does it for statistic summary, definitely not everytime when you have a fail-high or fail-low.
7. Not sorting the PV move
Probably not something that you want to do before addressing the other issues. In Stockfish, they have:

std::stable_sort(RootMoves.begin() + PVIdx, RootMoves.end());

This is done for every iteration in an iterative-deepening framework.

A: I am only going to address the runtime cost problem of your algorithm, because I don't know the implementation details of your board evaluation function.
In order to keep things as simple as possible, I will assume the worst case for the algorithm.
The getMove function makes len1 calls to the alphaBeta function, which in turn makes len2 calls to itself, which in turn makes len3 calls to itself and so on until depth reaches 0 and the recursion stops.
Because of the worst case assumption, let's say n = max(len1, len2, ...), so you have
n * n * n * ... * n calls to alphaBeta with number of multiplications depending on depth d, which leads to n^d calls to alphaBeta which means that you have an exponential runtime behavior. This is ultra slow and only beaten by factorial runtime behavior.
I think you should take a look at the Big O notation for that purpose and try to optimize your algorithm accordingly to get much faster results.
Best regards,
OPM


text:
Q: Shadow Properties to access related entity with Table-Per-Hierarchy inheritance model I'm building a menu system for a website in ASP.Net Core. Let's assume I have a couple of database tables, one for Pages and one for Articles, although it only really matters that they are different entities. Each of them have a Name and Permalink property.
In my menu, which I want to also store in the database, I want to refer to the Name and Permalink of each entity. I have devised a simple menu class/model structure as follows:
Abstract MenuItem
public abstract class MenuItem
{
    [Key]
    public int MenuItemId { get; set; }
    public int MenuPosition { get; set; }
    public abstract string Name { get; }
    public abstract string Permalink { get; }
}

Concrete ArticleMenuItem
public class ArticleMenuItem : MenuItem
{
    public ArticleMenuItem() {}
    public ArticleMenuItem(Article article)
    {
        Article = article;
    }

    public string Name => Article.Name;
    public string Permalink => Article.Permalink;

    [Required]
    public int ArticleId { get; set; }
    [ForeignKey("ArticleId")]
    public Article Article { get; set; }
}

Concrete PageMenuItem
public class PageMenuItem : MenuItem
{
    public PageMenuItem() {}
    public PageMenuItem(Page page)
    {
        Page = page;
    }

    public string Name => Page.Name;
    public string Permalink => Page.Permalink;

    [Required]
    public int PageId { get; set; }
    [ForeignKey("PageId")]
    public Page Page{ get; set; }
}

I then override onModelCreating(ModelBuilder modelBuilder) for the relevant DbContext as I don't want to make the individual DbSet<T>'s available:
modelBuilder.Entity<PageMenuItem>();
modelBuilder.Entity<ArticleMenuItem>();

As well as add the relevant DbSet<T> for the menu:
public virtual DbSet<MenuItem> MenuItems { get; set; }

Add a couple of sample records to the database when the app loads (assume I've got some articles and pages initialised too):
List<MenuItem> items = new List<MenuItem>()
{
    new PageMenuItem(pages[0]) { MenuPosition = 1 },
    new ArticleMenuItem(articles[0]) { MenuPosition = 2 }
};
items.ForEach(item => context.MenuItems.Add(item));

A simple repository method to get the menu items from the database:
public IEnumerable<MenuItem> GetAllMenuItems() => _context.MenuItems;

With all this in place I was hoping that I could get the Name and Permalink for each item as follows (in a view, for instance):
@foreach (MenuItem item in Model)
{
    @item.Name
}

Sadly, this results in a null object exception, and then I remembered EF Core doesn't support lazy loading. So I want to eagerly load the shadow properties, specifically the related entities, when I get the menu items in the repository.
There are two approaches to accessing shadow properties. The first approach I took updating my repository method looked like this:
public IEnumerable<MenuItem> GetAllMenuItems() => _context.MenuItems
    .Include(item => context.Entry(item).Property("Page").CurrentValue)
    .Include(item => context.Entry(item).Property("Article").CurrentValue)

This results in:

InvalidCastException: Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpression1' to type 'System.Linq.Expressions.MemberExpression'.

Casting to (Page) and (Aticle) respectively results in:

InvalidOperationException: The property expression 'item => Convert(value(InfoSecipediaWeb.Infrastructure.EntityFramework.ApplicationDbContext).Entry(item).Property("Page").CurrentValue)' is not valid. The expression should represent a property access: 't => t.MyProperty'.

The second method for accessing shadow properties only seems to enable accessing a single property value:
public static TProperty Property<TProperty>([NotNullAttribute] object entity, [NotNullAttribute][NotParameterized] string propertyName);
However, giving it a try:
public IEnumerable<MenuItem> GetAllMenuItems() => _context.MenuItems
    .Include(item => EF.Property<Page>(item, "Page"))
    .Include(item => EF.Property
(item, "Article"));

Results in:

InvalidOperationException: The property expression 'item => Property(item, "Page")' is not valid. The expression should represent a property access: 't => t.MyProperty'.

I'd like to know whether it is possible to use shadow properties for navigation with an inheritance model? If so, how do I include the related entities so that it is accessible in my concrete MenuItem classes? e.g. for public string Name => Page.Name.

A: Unfortunately currently there is no syntax for eager loading derived class  properties (note that they are different from shadow properties). This along with the lack of lazy loading leaves the explicit loading to be the only option. See for instance ef-core load collection property of nested tph inherited member how you can use it for a single item, for collection of items I'm afraid you have to materialize the result into a list, then using explicit loading of the concrete types and rely on EF navigation property fix up.
For your example it could be something like this:
public IEnumerable<MenuItem> GetAllMenuItems()
{
    var menuItems = _context.MenuItems.ToList();
    _context.MenuItems.OfType<ArticleMenuItem>().Include(e => e.Article).Load();
    _context.MenuItems.OfType<PageMenuItem>().Include(e => e.Page).Load();
    return menuItems;
}

Another workaround (did I say only one) is to use manual union query, which basically kills the TPH idea:
public IEnumerable<MenuItem> GetAllMenuItems() =>
    _context.MenuItems.OfType<ArticleMenuItem>().Include(e => e.Article)
    .AsEnumerable() // to avoid runtime exception (EF Core bug)
    .Concat<MenuItem>(
    _context.MenuItems.OfType<PageMenuItem>().Include(e => e.Page));


text:
Q: Javascript get css height propriety I have this CSS transition effect menu that is activated with a Javascript function through the click event on a button. However, I need the same button to hide the menu if it is visible.
I tried doing this by getting the same property that is changed by the function, as follows:
if (menu01.style.maxHeight == '0px')
menu01.style.maxHeight = '600px';
else
menu01.style.maxHeight = '0px';

However, as it may seem perfectly logical, IT DOES NOT WORK, and in addition it locks the function.
A GLOBAL variable could solve the problem, but they say we should avoid globals because of security.

Meus Dados

Alterar Senha

Agenda

Calendario

Sair

<button onclick="showmenu()">Menu(show/hide)</button>

I need a solution in Javascript Vanilla. I do not use jQuery.

A: Its very simple, since you are adding 600px max height property, on button click add logic to check height and toggle it between 0px and 600px.
checkout the snippet

function showmenu(){
    var menu01 = document.getElementById('menu01');
    menu01.style.maxHeight = menu01.style.maxHeight == '600px' ? '0px': '600px';
}
#menu01{
display: block;
position: absolute;
top:0px;
left: 130px;
width: 120px;
border-top: none;
background: white;
border-radius: 0px 0px 4px 4px;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2), 0 2px 4px 0 rgba(0,0,0,0.1);
max-height: 0px;
overflow: hidden;
transition-property: max-height;
transition: all 1s ease-in-out;
}

Meus Dados

Alterar Senha

Agenda

Calendario

Sair

<button onclick="showmenu()">Menu(show/hide)</button>

A: Proposing another methods based on Akhil Aravind's answer :)
Prefer using addEventListener for future use so you can use the function for another DOM elements.

*

*delete the onclick attached to 'button' element

*get the get the Elements for the button and menu01

*add event listener for each elements. (I tried Akhil Aravind's answer code, and when you click the list item, all the elements disappear. Maybe bug)

*I just save the elements into an array and use for each to make it shorter(no need for writing twice)


text:
Q: Sprintf floating a 18,16 float with right padding zeros I'm trying to get float (18,16) with padding zeros to the right, but this isn't working because it always ends with a 1 instead of a zero. My guess it's because I've specified it wrong but I'm not sure how to do it correct.
Sample:
12.12234 must become 12.122340000000000 and 1.01 must become 1.01000000000000.
To achieve this I'm using sprintf('%18.016f', $fMyFloat); but this always ends with a 1 instead of a 0. Obviously I'm overseeing something, I just don't know what. Any help is greatly appreciated.

A: This test code:
$data = array(
    12.12234,
    1.01
);
foreach($data as $fMyFloat){
    echo sprintf('%18.016f', $fMyFloat) . PHP_EOL;
}

... prints this in my 64-bit computer:
12.1223399999999994
1.0100000000000000

You are facing the well-known problem of floating point precision. Converting integers from base 10 to base 2 is pretty straightforward (and exact) but base 10 floating point numbers cannot always be represented exactly in base 2. This issue isn't specific to PHP but there's a warning in the PHP manual:

Floating point numbers have limited precision. Although it depends on
  the system, PHP typically uses the IEEE 754 double precision format,
  which will give a maximum relative error due to rounding in the order
  of 1.11e-16. Non elementary arithmetic operations may give larger
  errors, and, of course, error propagation must be considered when
  several operations are compounded.
Additionally, rational numbers that are exactly representable as
  floating point numbers in base 10, like 0.1 or 0.7, do not have an
  exact representation as floating point numbers in base 2, which is
  used internally, no matter the size of the mantissa. Hence, they
  cannot be converted into their internal binary counterparts without a
  small loss of precision

Your only chance to achieve such precision is to manipulate numbers as strings. PHP bundles two arbitrary precision libraries that can help you when you need to do match with strings: GNU Multiple Precision and BC Math. Here's a little hack with bcmath:
$data = array(
    '12.12234',
    '1.01'
);
bcscale(16);
foreach($data as $fMyFloat){
    echo bcdiv($fMyFloat, 1) . PHP_EOL;
}

It this case, though, you can probably use simple string functions:
$data = array(
    '12.12234',
    '1.01'
);
foreach($data as $fMyFloat){
    list($a, $b) = explode('.', $fMyFloat);
    echo $a . '.' . str_pad($b, 16, 0) . PHP_EOL;
}


text:
Q: Share a dict with multiple Python scripts I'd like a unique dict (key/value) database to be accessible from multiple Python scripts running at the same time.
If script1.py updates d[2839], then script2.py should see the modified value when querying d[2839] a few seconds after.

*

*I thought about using SQLite but it seems that concurrent write/read from multiple processes is not SQLite's strength (let's say script1.py has just modified d[2839], how would script2.py's SQLite connection know it has to reload this specific part of the database?)

*I also thought about locking the file when I want to flush the modifications (but it's rather tricky to do), and use json.dump to serialize, then trying to detect the modifications, use json.load to reload if any modification, etc. ... oh no I'm reinventing the wheel, and reinventing a particularly inefficient key/value database!

*redis looked like a solution but it does not officially support Windows, the same applies for leveldb.

*multiple scripts might want to write at exactly the same time (even if this is a very rare event), is there a way to let the DB system handle this (thanks to a locking parameter? it seems that by default SQLite can't do this because "SQLite supports an unlimited number of simultaneous readers, but it will only allow one writer at any instant in time.")
What would be a Pythonic solution for this?
Note: I'm on Windows, and the dict should have maximum 1M items (key and value both integers).

A: Before there was redis there was Memcached (which works on windows).
 Here is a tutorial.  https://realpython.com/blog/python/python-memcache-efficient-caching/

A: I'd consider 2 options, both are embedded databases
SQlite
As answered here and here it should be fine
BerkeleyDB
link

Berkeley DB (BDB) is a software library intended to provide a high-performance embedded database for key/value data

It has been designed exactly for your purpose

BDB can support thousands of simultaneous threads of control or
  concurrent processes manipulating databases as large as 256
  terabytes,3 on a wide variety of operating systems including most
  Unix-like and Windows systems, and real-time operating systems.

It is robust and has been around for years if not decades
Bringing up redis/memcached/ whatever else full-fledged socket-based server that requires sysops involvement IMO is an overhead for the task to exchange data between 2 scripts located on the same box

A: You can use python dictionary for this purpose.

Create a generic class or script named as G, that initializes a dictionary in it. The G will run the script1.py & script2.py and passes the dictionary to both scripts file, in python dictionary is passed by reference by default. In this way, a single dictionary will be used to store data and both scripts can modify dictionary values, changes can be seen in both of the scripts. I hope script1.py and script2.py are class based. It doesn't guarantee the persistence of data. For persistence, you can store the data in the database after x intervals.

Example
script1.py
class SCRIPT1:

    def __init__(self, dictionary):
        self.dictionary = dictionary
        self.dictionary.update({"a":"a"})
        print("SCRIPT1 : ", self.dictionary)

    def update(self):
        self.dictionary.update({"c":"c"})

script2.py
class SCRIPT2:
    def __init__(self, dictionary):
        self.dictionary = dictionary
        self.dictionary.update({"b":"b"})
        print("SCRIPT 2 : " , self.dictionary)

main_script.py
import script1
import script2

x = {}

obj1 = script1.SCRIPT1(x) # output: SCRIPT1 :  {'a': 'a'}
obj2 = script2.SCRIPT2(x) # output: SCRIPT 2 :  {'a': 'a', 'b': 'b'}
obj1.update()
print("SCRIPT 1 dict: ", obj1.dictionary) # output: SCRIPT 1 dict:  {'c': 'c', 'a': 'a', 'b': 'b'}

print("SCRIPT 2 dict: ", obj2.dictionary) # output: SCRIPT 2 dict:  {'c': 'c', 'a': 'a', 'b': 'b'}

Also create an empty _ init _.py file in the directory where you will run the scripts.
Another option is:

Redis

A: Mose of embedded datastore other than SQLite doesn't have optimization for concurrent access, I was also curious about SQLite concurrent performance too, so I did a benchmark:
import time
import sqlite3
import os
import random
import sys
import multiprocessing

class Store():

    def __init__(self, filename='kv.db'):
        self.conn = sqlite3.connect(filename, timeout=60)
        self.conn.execute('pragma journal_mode=wal')
        self.conn.execute('create table if not exists "kv" (key integer primary key, value integer) without rowid')
        self.conn.commit()

    def get(self, key):
        item = self.conn.execute('select value from "kv" where key=?', (key,))
        if item:
            return next(item)[0]

    def set(self, key, value):
        self.conn.execute('replace into "kv" (key, value) values (?,?)', (key, value))
        self.conn.commit()

def worker(n):
    d = [random.randint(0, 1<<31) for _ in range(n)]
    s = Store()
    for i in d:
        s.set(i, i)
    random.shuffle(d)
    for i in d:
        s.get(i)

def test(c):
    n = 5000
    start = time.time()
    ps = []
    for _ in range(c):
        p = multiprocessing.Process(target=worker, args=(n,))
        p.start()
        ps.append(p)
    while any(p.is_alive() for p in ps):
        time.sleep(0.01)
    cost = time.time() - start
    print(f'{c:<10d}\t{cost:<7.2f}\t{n/cost:<20.2f}\t{n*c/cost:<14.2f}')

def main():
    print(f'concurrency\ttime(s)\tpre process TPS(r/s)\ttotal TPS(r/s)')
    for c in range(1, 9):
        test(c)

if __name__ == '__main__':
    main()

result on my 4 cores macOS box, SSD volume:
concurrency time(s) pre process TPS(r/s)    total TPS(r/s)
1           0.65    7638.43                 7638.43
2           1.30    3854.69                 7709.38
3           1.83    2729.32                 8187.97
4           2.43    2055.25                 8221.01
5           3.07    1629.35                 8146.74
6           3.87    1290.63                 7743.78
7           4.80    1041.73                 7292.13
8           5.37    931.27                  7450.15

result on an 8 cores windows server 2012 cloud server, SSD volume:
concurrency     time(s) pre process TPS(r/s)    total TPS(r/s)
1               4.12    1212.14                 1212.14
2               7.87    634.93                  1269.87
3               14.06   355.56                  1066.69
4               15.84   315.59                  1262.35
5               20.19   247.68                  1238.41
6               24.52   203.96                  1223.73
7               29.94   167.02                  1169.12
8               34.98   142.92                  1143.39

turns out overall throughput is consistent regardless of concurrency, and SQLite is slower on windows than macOS, hope this is helpful.

As SQLite write lock is database wise,  in order to get more TPS, you could partition data to multi-database files:
class MultiDBStore():

    def __init__(self, buckets=5):
        self.buckets = buckets
        self.conns = []
        for n in range(buckets):
            conn = sqlite3.connect(f'kv_{n}.db', timeout=60)
            conn.execute('pragma journal_mode=wal')
            conn.execute('create table if not exists "kv" (key integer primary key, value integer) without rowid')
            conn.commit()
            self.conns.append(conn)

    def _get_conn(self, key):
        assert isinstance(key, int)
        return self.conns[key % self.buckets]

    def get(self, key):
        item = self._get_conn(key).execute('select value from "kv" where key=?', (key,))
        if item:
            return next(item)[0]

    def set(self, key, value):
        conn = self._get_conn(key)
        conn.execute('replace into "kv" (key, value) values (?,?)', (key, value))
        conn.commit()

result on my mac with 20 partitions:
concurrency time(s) pre process TPS(r/s)    total TPS(r/s)
1           2.07    4837.17                 4837.17
2           2.51    3980.58                 7961.17
3           3.28    3047.68                 9143.03
4           4.02    2486.76                 9947.04
5           4.44    2249.94                 11249.71
6           4.76    2101.26                 12607.58
7           5.25    1903.69                 13325.82
8           5.71    1752.46                 14019.70

total TPS is higher than single database file.

A: You could use a document-based database manager. Maybe is too heavy for your system to do so, but concurrent access is typically one of the reasons DB management systems and API to connect to them are in place.
I have used MongoDB with Python and it works fine. The Python API documentation is quite good and each document (element of the database) is a dictionary that can be loaded to python as such.

A: I would use a pub/sub websocket-framework, like Autobahn/Python, with one script as a "server" and it handles all the file communication but it depends on scale maybe this could be Overkill.

A: CodernintyDB could be worth exploring, using the server version.
http://labs.codernity.com/codernitydb/
Server version:
http://labs.codernity.com/codernitydb/server.html

A: It sounds like you really need is a database of some kind.
If redis won't work for windows, then I would look at MongoDB.
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/
MongoDB works great with python and can function similar to redis. Here are the install docs for PyMongo:
http://api.mongodb.com/python/current/installation.html?_ga=2.78008212.1422709185.1517530606-587126476.1517530605
Also, many people have brought up SQlite. I think you were concerned that it only allows one writer at a time, but this is not really a problem for you to worry about. I think what it is saying is that, if there are two writers, the second will be blocked until the first is finished. This is probably fine for your situation.


text:
Q: Matrix error in code converted from Matlab to R To cross validation for CCLE (Cancer Cell Line Encyclopedia) drug data I tried to convert the following codes from matlab to R. However, I was unsuccessful. Matlab codes work fine and can create both a *cross.mat that is a group of 10 fold CV data for each data set and a *data.mat that is the grouped data of 10 times of CV of each data set.
I will be appreciate if you can help me find my mistake.
#This function is about 10-fold cross-validation data grouping
getcrossMatrixs <- function(MM){
  library(pracma)
  N <- nnz(MM)
  zeroM <- matrix(0L, nrow = dim(MM)[1], ncol = dim(MM)[2])
  D <- randperm(N)
  first <- floor(N/10)

  w = which(MM != 0, arr.ind=TRUE);
  nrows=w[,1]; ncols=w[,2]
  crossdata  <-  list()

  for (i in 1:10) {
    crossdata[[i]] <- zeroM
  }

  for (i in 1:10){
    for (j in (1+(i-1)*first):(i*first)){
      crossdata[[i]][c(nrows[D[j]]),c(ncols[D[j]]) ] <- MM[c(nrows[D[j]]),c(ncols[D[j]])]

    }
  }
  k <- (N-(10*first))
  i <- 10*first+1
  for (j in 1:k){
    crossdata[[j]][c(nrows[D[i]]),c(ncols[D[i]]) ] <- MM[c(nrows[D[i]]),c(ncols[D[i]])]

    i <- i+1
  }
}

#The following lines is the main for calling above function.
library(foreach)
n.cores <- parallel::detectCores()
my.cluster <- parallel::makeCluster(
  n.cores,
  type = "PSOCK"
)
print(my.cluster)
#> socket cluster with 16 nodes on host 'localhost'
doParallel::registerDoParallel(cl = my.cluster)
foreach::getDoParRegistered()
#> [1] TRUE
CCLEdata <- list()
#MM<-matrix(read_csv("MM.csv", col_names = FALSE, show_col_types = FALSE), rownames.force = NA)
MM <- matrix(seq(0, 4.5, length.out = 11784), nrow = 491) #datamatrix like CCLE drug activity area sensitivity matrrix(491*24)
foreach(i = 1:10) %dopar% {
  CCLEcross <- getcrossMatrixs(MM)
  CCLEdata[[i]] <- CCLEcross
}
#> [[1]]
#> NULL
#>
#> [[2]]
#> NULL
#>
#> [[3]]
#> NULL
#>
#> [[4]]
#> NULL
#>
#> [[5]]
#> NULL
#>
#> [[6]]
#> NULL
#>
#> [[7]]
#> NULL
#>
#> [[8]]
#> NULL
#>
#> [[9]]
#> NULL
#>
#> [[10]]
#> NULL

Created on 2022-08-29 with reprex v2.0.2
Actually when I use the original CCLE dataset the error is changing in the main.R:
Error in { : task 1 failed - "is.numeric(x) || is.complex(x) is not TRUE"
or
Error in { :
  task 1 failed - "attempt to select less than one element in integerOneIndex"

%These are from Matlab
function [crossdata] = getcrossMatrixs(MM)
N = nnz(MM(:));
zeroM = zeros(size(MM));
D = randperm(N);
first = floor(N/10);
[nrows,ncols] = find(MM);
crossdata = {};
for i = 1:10
    crossdata{i} = zeroM;
end
for i = 1:10
    for j = 1+(i-1)*first:i*first
        crossdata{i}(nrows(D(j)),ncols(D(j))) = MM(nrows(D(j)),ncols(D(j)));
    end
end
 k=N -10*first ;
 i=10*first+1;
  for j=1:k
 crossdata{j}(nrows(D(i)),ncols(D(i))) = MM(nrows(D(i)),ncols(D(i)));
  i=i+1;
  end
end

load('MM.mat')
parfor i=1:10
    [CCLEcross] = getcrossMatrixs(MM);
    CCLEdata{i}=CCLEcross;
end

A: I didn't look too closely to figure out what was wrong. I based this function on the Matlab function supplied. Note that for this particular example, going parallel is more expensive due to overhead. Parallel will provide performance with large enough matrices and/or more samples.
library(parallel)

MM <- matrix(seq(0, 4.5, length.out = 11784), nrow = 491)

getcrossMatrixs <- function(MM, parts = 10L) {
  D <- sample(which(MM != 0))
  first <- length(D) %/% parts
  last <- length(D) %% parts
  idx <- c(0L, cumsum(c(rep(first + 1L, last), rep(first, parts - last))))
  mZero <- matrix(0, nrow(MM), ncol(MM))
  lapply(1:parts, function(i, m) {m[D[(idx[i] + 1L):idx[i + 1L]]] <- MM[D[(idx[i] + 1L):idx[i + 1L]]]; m}, mZero)
}

reps <- 10L
clust <- makeCluster(min(detectCores() - 1L, reps))
clusterExport(clust, c("getcrossMatrixs", "MM"))
CCLEdata <- parLapply(clust, 1:reps, function(x) getcrossMatrixs(MM))
stopCluster(clust)

# check that each set of matrices returned has all elements of MM
identical(rep(list(MM), reps), lapply(1:reps, function(i) Reduce("+", CCLEdata[[i]], matrix(0, nrow(MM), ncol(MM)))))
#> [1] TRUE

And here's a cleaned-up version of the Matlab function:
function [crossdata] = getcrossMatrixs(MM)
    idx = find(MM);
    N = length(nrows);
    zeroM = zeros(size(MM));
    idx = idx(randperm(N));
    first = floor(N/10);
    crossdata = cell(10, 1);
    for i = 1:10
        crossdata{i} = zeroM;
    end
    for i = 1:10
        j = 1 + (i - 1)*first:i*first;
        crossdata{i}(idx(j)) = MM(idx(j));
    end
    k = N - 10*first;
    j = 10*first + 1;
    for i = 1:k
        crossdata{i}(idx(j)) = MM(idx(j));
        j = j + 1;
    end
end


text:
Q: Call method from another composents I have two child components and I would like to call a function that is in child component 1 from child component 2, I have tested several methods but I haven't found anything that works.
Do I have to go through the parent to use the function? Otherwise here is my code
Tools - parent
<template>

        <VariablesChanger/>
        <Console/>

</template>

Sender - Child 1
<template>
    <v-btn color="primary" @click="sendMessageConsole()">Change</v-btn>
</template>

Console - Child 2
<template>
    <v-card>
        <v-toolbar color="light-blue" dark>
            <v-toolbar-title>Console</v-toolbar-title>
        </v-toolbar>
        <v-list>
            <v-list-item v-for="message in messages" :key="message">
                <v-list-item v-text="message"/>
            </v-list-item>
        </v-list>
    </v-card>
</template>

Thank you in advance for your help.

A: you can use refs and events to call functions in child component 1 from child component 2 if 2 components have same parent
Tools - parent
<template>

        <VariablesChanger @addMessage="showMessage($event)" />
        <Console ref="console" />

</template>

Sender - Child 1
<template>
    <v-btn color="primary" @click="sendMessageConsole()">Change</v-btn>
</template>

Console - Child 2
<template>
    <v-card>
        <v-toolbar color="light-blue" dark>
            <v-toolbar-title>Console</v-toolbar-title>
        </v-toolbar>
        <v-list>
            <v-list-item v-for="message in messages" :key="message">
                <v-list-item v-text="message"/>
            </v-list-item>
        </v-list>
    </v-card>
</template>

if 2 child components not in same parent, use EventBus to communicate between 2 components
https://medium.com/@andrejsabrickis/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860


text:
Q: Structuring Output Folders in Buck I am working on a project that uses Buck for its build system, and I want to have buck build a set of shaders. It is my understanding that I would use genrule to generate these shaders. The problem that I run into is that I need to specify the location of the shaders output relative to the main binary so that I can run them later. Is there a way to structure this with buck?

A: It's generally not possible to do that directly. The standard way to access the output a genrule is to use location macro.
If your binary requires input data to be in a fixed location relative to the binary or current directory, you can work around that limitation by creating symlinks to the output of genrule. To do that you need to add a wrapper script which would create a link to the output of a genrule and then call the main binary.


text:
Q: Perl : Join function and arrays I combined 2 sequence file, so I have 1 file with 2 sequences. I have split these 2 sequences into an @char array- because I later have to compare them character by character. 1 of the sequences, however is on two lines. I want to use the join function to combine the 2 lines but I don't know how to.
Ex:
seq 1
ACGTATATATTATATCTGGCGCTATCGATGCTATCGAT
CGATGCGCG

seq 2
AGTGAGCGTAGCTAGCGGCGCGATCTAGCTA

my code so far
#!usr/bin/perl
use strict;
use warnings;

# open file 1
open (my $seq1, "<", "file1.fa") or die $!;
# open file 2
open (my $seq2, "<", "file2.fa") or die $!;
# open combined file
open (my $combined, ">", "combined.txt") or die $!;

# read file 1, skip header line, write to combined file
while (my $line = <$seq1>) {
        if($line =~ />/) {
                next;
}

        else {
        print $combined "$line\n";
}
}
# read file 2, skip header line, write to combined file on new line
while (my $line2 = <$seq2>) {
        if ($line2 =~ />/) {
                next;
}
        else {
        print $combined "$line2\n";
}
}
# need to open combined file for reading
open (my $combined2, "<", "combined.txt") or die $!;
# read through combined file line by line
while (my $seqs = <$combined2>) {
        chomp($seqs);
# split sequences into characters
        my @chars = split(//, $seqs);
# the sequence from file1 is on 2 separate lines. Need to join these
# lines together

A: Consider using Bio::SeqIO to read your fasta files, as it can handle a sequence that's on multiple lines:
use strict;
use warnings;
use Bio::SeqIO;

my $in = Bio::SeqIO->new( -file => "file1.fa", '-format' => 'Fasta' );

while ( my $seq = $in->next_seq ) {
    my $sequence = $seq->seq;
    print $sequence, "\n";
}

Contents of file1.fa:
>seq0
FQTWEEFSRAAEKLYLADPMKVRVVLKYRHVDGNLCIKVTDDLVCLVYRTDQAQDVKKIEKF
>seq1
KYRTWEEFTRAAEKLYQADPMKVRVVLKYRHCDGNLCIKVTDDVVCLLYRTDQAQDVKKIEKFHSQLMRLME
LKVTDNKECLKFKTDQAQEAKKMEKLNNIFFTLM
>seq2
EEYQTWEEFARAAEKLYLTDPMKVRVVLKYRHCDGNLCMKVTDDAVCLQYKTDQAQDVKKVEKLHGK
>seq3
MYQVWEEFSRAVEKLYLTDPMKVRVVLKYRHCDGNLCIKVTDNSVCLQYKTDQAQDVK

Output:
FQTWEEFSRAAEKLYLADPMKVRVVLKYRHVDGNLCIKVTDDLVCLVYRTDQAQDVKKIEKF
KYRTWEEFTRAAEKLYQADPMKVRVVLKYRHCDGNLCIKVTDDVVCLLYRTDQAQDVKKIEKFHSQLMRLMELKVTDNKECLKFKTDQAQEAKKMEKLNNIFFTLM
EEYQTWEEFARAAEKLYLTDPMKVRVVLKYRHCDGNLCMKVTDDAVCLQYKTDQAQDVKKVEKLHGK
MYQVWEEFSRAVEKLYLTDPMKVRVVLKYRHCDGNLCIKVTDNSVCLQYKTDQAQDVK

A: I am assuming that your sequences are separated by a ">" sign, and that is why you have used the if($_ =~ />/) as a skipper. If it is not, comment back and I'll change the code. Here try the following:
open (fil1, "<", "file1.fa") or die $!;
# open file 2
open (fil2, "<", "file2.fa") or die $!;
# open combined file
open (combined, ">", "combined.txt") or die $!;

# read file 1, skip header line, write to combined file
while (<fil1>) {
        if($_ =~ />/) {
                print $combined "\n";
}

        else {
        print $combined "$line";
}
}
# read file 2, skip header line, write to combined file on new line
while (<fil2>) {
        if ($_ =~ />/) {
                print $combined "\n";
}
        else {
        print $combined "$line2";
}
}

Just check out combined.txt, if there are sequences on different lines.


text:
Q: adding navigation bar to detailview and tableview i am developing an iPhone app in which there is a uitableview and a when any of the rows in the table view is selected, a new viewcontroller will be loaded which shows details about the selected row in the tableview . My problem is that i need a navigation bar in the tableview and the details view,the navigation bar should have back button ie the navigation bar on detail view should have a back button to tableview should have a back button to earlier view controller.How can i do this programatically??

A: The viewcontroller with the tableview should be the root view controller of a navigation controller (which you can create programatically). Then you just push (pushviewcontroller:animated:) the detail view controller.

A: @implementation UINavigationBar (CustomImage)

  - (void)drawRect:(CGRect)rect
  {
     NSLog(@"self.topItem.title = %@", self.topItem.title);
     CGRect frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
     UIImage *image = [UIImage imageNamed: @"background.png"];
     [image drawInRect:frame];
     UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
     [label setBackgroundColor:[UIColor clearColor]];
     label.font = [UIFont boldSystemFontOfSize: 20.0];
     //label.shadowColor = [UIColor colorWithWhite:1.0 alpha:1];
     label.textAlignment = UITextAlignmentCenter;
     label.textColor = RGBCOLOR(73, 81, 85);
     label.text = self.topItem.title;
     self.topItem.titleView = label;
    self.tintColor = RGBCOLOR(229, 239, 246);
  }
 @end

also add UIButton and it's Action event to Navigate between View Controlllers


text:
Q: Show that the upper envelope of a bounded function is upper semi continuous directly Definition 1:

A real valued function $f$ is said to be upper semicontinuous at a point $p$ if:
$$f(p) \geq \limsup_{x \rightarrow p} f(x) $$

Definition 2:

Let $f$ be a bounded real valued function on $[a,b]$. Define the upper envelope $h$ of $f$ as:
$$ h(y) = \inf_{\delta >0} \sup_{|x-y|<\delta} f(x)$$

The question: If $f$ is a real valued bounded function on $[a,b]$, show that the upper envelope of $f$ is upper semicontinuous.
Background:
This is a sample qualifying exam question. In the past, this question is sometimes asked with a part a which says that a function is upper semicontinuous iff the sets $\{x: f(x) < \lambda\}$ are open for each $\lambda \in \mathbb{R}$. This characterization is not too difficult to prove. Also, the desired result is not too difficult to deduce from this characterization. For example, see:
Upper semi-continuity and lower semi-continuity of particular functions
However, this approach is unsatisfactory. In particular, this problem has shown up sans part a before on the qualifying exam. I'm looking for a proof that takes a bounded real valued function $f$, and from Definition 2 deduces Definition 1 directly. Every attempt I make, I get lost in chasing infs and sups through inequalities. Any help would be much appreciated.

A: Looks like this question has been resolved here:
Upper semi continuity of Lim sup
calling the function in question the limsup instead of the upper envelope.


text:
Q: matrices such that $A^2B+BA^2=2ABA$ Let be $A$, $B$ two matrices $3 \times 3$ with complex entries.
Prove that if $$A^2B+BA^2=2ABA$$
THEN
$$B^2A+AB^2=2BAB$$
I tried it and do not know how to continue.
If $A$ is invertible then
$$AB^2+A^{-1}BA^2B=2BAB$$
so I have to prove that
$$B^2A=A^{-1}BA^2B$$
How to continue and also have to discuss the case when $A$ is not invertible

A: The statement in question is equivalent to $[A,[A,B]]=0\rightarrow[[A,B],B]=0$ and it is false. Here is a counterexample taken from the last section of Irving Kaplansky, Jacobson's Lemma Revisited, Journal of Algebra, 62, 473-476 (1980):
\begin{aligned}
A&=\pmatrix{1&1&0\\ 0&1&0\\ 0&0&1},\quad B=\pmatrix{0&0&0\\ 0&0&1\\ 1&0&0},\\
[A,B]&=\pmatrix{1&1&0\\ 0&1&0\\ 0&0&1}\pmatrix{0&0&0\\ 0&0&1\\ 1&0&0}-\pmatrix{0&0&0\\ 0&0&1\\ 1&0&0}\pmatrix{1&1&0\\ 0&1&0\\ 0&0&1}\\
&=\pmatrix{0&0&1\\ 0&0&1\\ 1&0&0}-\pmatrix{0&0&0\\ 0&0&1\\ 1&1&0}
=\pmatrix{0&0&1\\ 0&0&0\\ 0&-1&0},\\
[A,[A,B]]&=A[A,B]-[A,B]A=[A,B]-[A,B]=0,\\
[[A,B],B]&=\pmatrix{0&0&1\\ 0&0&0\\ 0&-1&0}\pmatrix{0&0&0\\ 0&0&1\\ 1&0&0}-\pmatrix{0&0&0\\ 0&0&1\\ 1&0&0}\pmatrix{0&0&1\\ 0&0&0\\ 0&-1&0}\\
&=\pmatrix{1&0&0\\ 0&0&0\\ 0&0&-1}-\pmatrix{0&0&0\\ 0&-1&0\\ 0&0&1}
=\pmatrix{1&0&0\\ 0&1&0\\ 0&0&-2}\ne0.
\end{aligned}

A: If $A$ and $B$ commute, the result is immediate.
Note that $(A+B)^3 = A^3 + (A^2B + BA^2) + ABA + (B^2A + AB^2) + BAB + B^3$.
If the result holds, that turns into $(A+B)^3 = A^3 + A^2B + AB^2 + B^3$.  This suggests that $A$ and $B$ might have to commute for the given to hold.
If $A$ and $B$ do not commute, let $AB-BA = C$.
Rewrite that as $BA = AB - C$ and as $AB = BA + C$.
Plugging in, we get
$$B^2A = B(AB-C) = BAB-BC$$and
$$AB^2 = (C+BA)B = CB + BAB$$
so
$$B^2A + A^2B = 2BAB - BC + CB$$ without even using the given.  Turning to that, we get
$$A^2B + BA^2 = 2ABA + AC-CA$$ by the same reasoning.
This implies $AC-CA = 0$.  So now our goal is to get from $AC=CA to BC=CB.$. But according to the other answer by @user1551, the claim isn't true in the first place!

A: We'll work with commutators, $[X,\,Y]:=XY-YX$. Given $[A,\,[A,\,B]]=O$, we want to prove $[[A,\,B],\,B]=O$. Since $A,\,[A,\,B]$ are simultaneously diagonalisable, we need only show any base diagonalising both - we'll work hereafter in such a base - also diagonalises $B$. The easiest case is one in which $A$ has no repeated eigenvalues: if $i\ne j$,$$0=[A,\,B]_{ij}=(\underbrace{A_{ii}-A_{jj})}_{\ne0}B_{ij}\implies B_{ij}=0.$$The general case follows by such "nondegenerate" $A$ being dense in $\Bbb C^{3\times3}$.


text:
Q: Opencv 3.2.0 .dll missing despite static linking I am trying to use a program utilizing OpenCV on a PC that does not have OpenCV installed. Trying to start the program results in the following error:
"This program can't start because opencv_world320.dll is missing from your computer. Try reinstalling the program to fix the problem."
Now I know this normally happens if the correct libraries are not linked or linking was not static but as pre-built OpenCV 3.2 only uses a single library and after double checking that runtime library is set to /MT in VS2015 I have no idea why this error is still present.
Looking at the built .exe file in a PE Analyzer also shows that opencv_world320.dll is still listed as an import.
How to fix this?

A: OpenCV 3.2 prebuild only provides x64 dynamic libraries for vc14.
The .lib you're trying to link (in subfolder x64\vc14\lib) is a import library, that contains the symbols to allow the linker to link to the dll. See here and here for further details on the matter.
In practice, if you want to static link to OpenCV, you need to rebuild it. You'll find the static libraries in subfolder x64\vc14\staticlib.


text:
Q: Is there a disadvantage to not using text file extensions? I recently learned that file extensions (at least for plain text) in a Unix-like environment generally don't have meaning. Whether a bash script has a .sh,.log,.txt, or .hgfjgfdjgd, it can still run if you make it executable with chmod +x scriptname.
Upon figuring this out, I've slowly been starting the (perhaps bad) practice of the not using file extensions anymore. Any general text file or script I write nowadays doesn't have an extension, and everything still works just like before.
The one and only advantage I can think of for using file extensions in this situation is organization, for both yourself and others (ie. people recognize a .sh file as being a script). But other than that, they just seem useless at this point, as they add extra "complexity" for no reason.
Is what I'm doing a bad practice? Are files without extensions generally frowned upon? What other uses do extensions have for plain text files that I'm not seeing?

A: File system extensions don't have any meaning inside the Linux kernel.
However, several applications (web servers, compilers, editors, linkers) tend to use file extension on purpose. You could get the gcc compiler to accept some file name source-file (or even bizarre.o or strange.sh) as some C source file, but you'll need some tricks (the -x option). Also, you will unpleasantly surprise other people.
BTW you could also name all your files as 0001, 0002, etc... but this is not very user friendly.

A: I use file extensions for a number of reasons.  In many cases, this is to save me working around the issues resulting from not using an extension.  There are few cases were not using an extension provides an advantage, mainly when running a program.
In Unix/Linux file extensions don't have meaning when it comes to executing a file.  This is controlled by the executable bit.  The interpreter for scripting languages is specified in the first line using a bang path such as #!/bin/bash.
For executable files in standard directories, it is standard practice to omit the extension.  However, it is also common to use extensions for locally written scripts.  This is helpful when searching for an example or common practice in a particular scripting language.
For non-executable files the extension provides valuable type information both user and programs that read them.  Web servers use the file extension extensively in determining the file type, and thus what headers to apply.  Compilers and programmers rely on the extensions to determine the file types.
Some tools will use magic files to determine the file type based on the file contents.  Many file types contain magic values at known locations, and these can be used to reliably guess the file type in many cases.  Other tools will just open a file assuming it is an appropriate file.  This allows you to play text files or text edit pictures, although neither are recommended.
Within classifications of files there are often incompatible types which are normally indicated by the extension:

*

*Pictures: bmp, jpeg, gif, png, tiff...

*Videos: mpg, rm, flv, wmv...

*Sound: mp3, ogg, wav...

*Documents: html, txt, pdf, rtf, doc...

While some tools can handle multiple formats, others will fail with one or more types.  Omitting the file extension will likely lead you to use the wrong tool to open some files.
There are also cases where there are multiple related files are differentiated by the extension.  For example a program foobar written in c may result from the files foobar.c, foobar.h, and foobar.o.


text:
Q: Laravel eloquent relationship return empty array I want to show one link, one page, one tag, and many comments with user name from "users", but, the comments return one empty array. All tables have "id" as primary key and auto increment.
Controller:
$link = Link::with('page', 'tag', 'comments.user')->where('friendly_url', $id)->first();
return view('site.link', compact('link'));

Model (link)
class Link extends Model
{
public function page()
{
    return $this->belongsTo(Page::class);
}

public function tag()
{
    return $this->belongsTo(Tag::class);
}

public function comments()
{
    return $this->hasMany(Comment::class);
}
}

Model (comments)
class Comment extends Model
{

    public function user(){
        return $this->belongsTo(User::class);
    }
    }

View:
    @foreach($link->comments as $comment)

{{ $comment->user->name . $comment->user->lastname }}

{{ $comment->content }}

    @endforeach

dd($link);

0 => Link {#291 ▼
      #relations: array:3 [▼
        "page" => Page {#295 ▶}
        "tag" => Tag {#289 ▶}
        "comments" => Collection {#292 ▼
          #items: array:2 [▼
            0 => Comment {#299 ▶}
            1 => Comment {#301 ▶}
          ]
        }
      ]

SOLVED:
$link->getRelation('comments');

But I want to show the userProfile too, but return 0...
CONTROLLER:
$link = Link::where('friendly_url', $id)->with('page', 'tag', 'comments.user', 'comments.userProfile')->first();

        dd($link);

#relations: array:3 [▼
"page" => Page {#296 ▶}
"tag" => Tag {#290 ▶}
"comments" => Collection {#293 ▼
  #items: array:2 [▼
    0 => Comment {#300 ▶}
    1 => Comment {#302 ▼
      #relations: array:2 [▼
        "user" => User {#305 ▶}
        "userProfile" => null
      ]

A: 1, Database: You must have link_id and user_id in the comments table
2, Controller : You should use with() function to get comments and user
    $link = Link::with(['page', 'tag', 'comments' => function($query){
           $query->with('user')
    }])->where('friendly_url', $id)->first();

    return view('site.link', compact('link'));

You can use dd($link) to check relationship data
You can try them.
You can comment below for me to support you


text:
Q: Java Process InputStream bug? Hey guys. So here is the deal. I have a Java program run a C++ program. The C++ process sends some doubles to the Java program by simply calling write on std::cout with some pointer casting. The Java program uses Process's getInputStream(), reads in 8 bytes and converts them into a double using some byte shifting and Double.longBitsToDouble(). I have made sure that the type sizes as well as byte orders match up between the 2 applications. Now, while this works most of the time, every so often an error occurs.
I have isolated one of the errors to a simple sequence of bytes that I seem to be unable to transfer correctly. Check out the following snippets:
#include <iostream>

int main(int argc, char** argv) {
  long long l = 0x4048e398b90ae1b6;
  char* ptr = (char*) &l;
  std::cout.write(ptr, 8);
  std::cout.flush();

  //  for (int i = 0; i < 8; ++i)
  //    std::cout.put(ptr[i]);
  //  std::cout.flush()
}

And the Java app:
public static void main(String[] argv) throws IOException {
  Process p = Runtime.getRuntime().exec("prog.exe");
  InputStream is = p.getInputStream();

  for (int i = 0 ; i < 8; ++i) {
    System.err.print(Long.toHexString(is.read()) + " ");
  }
}

These are pretty simple examples but they server to demonstrate my problem. When I run this on my Windows 7 machine. I get the following Java output:
b6 e1 d a b9 98 e3 48

The expected output is
b6 e1 a b9 98 e3 48 40

Somehow, an extra 0x0d byte is inserted. However, what is really weird is that if inside the java app we read one more byte (change the 8 to a 9), we get
b6 e1 d a b9 98 e3 48 40

This means that the InputStream actually contained 9 bytes of data and once that extra 0x0d is removed it contains the correct data.
What do you guys think? As I mentioned before, this doesn't happen often but when it does, it is disastrous.
Thanks in advance,
zienkikk

A: cout is by default opened in text mode, what I would say is happening is that the 0xa (linefeed) character is getting converted to a <CRLF> sequence during output preprocessing.
I don't think it's possible to reliably write binary data to cout (see here for example), so I would convert your desired output into text, and then deserialize on the input side (Java).

A: C++ is translating 0x0A, which is \n, to 0x0d0a, which is \r\n. There's a method to stop it doing that, can't help you with what it is. I wouldn't use iostreams for binary data myself, I would probably just use write() or fwrite().

A: Looks to me like your Windows shell converts UNIX style line terminator LF ( 0xA ) to Windows Line Terminator CRLF( 0xD OxA ).
Generally it is not advisable to write binary data to the program output stream for this particular reason.  Convert your long data to text and then parse it on a Java side.


text:
Q: How do I use AVAssetWriter? I'd like to take some video frames and encode them into a video. It looks like that's exactly what AVAssetWriter was meant for, but no matter how I eyeball the docs and Google I can't find any way to actually use it. From the docs it looks like I need an input (AVAssetWriterInput) to feed the writer from. Fine. But the AVAssetWriterInput class is abstract and the only subclass that I know of in 4.1 is AVAssetWriterInputPixelBufferAdaptor that requires a AVAssetWriterInput in its initializer…? Am I missing something obvious here?

A: Ah yes, I have to acquire an instance using +[AVAssetWriterInput assetWriterInputWithMediaType:outputSettings:], see my post under a different question for a detailed code sample.


text:
Q: What different kinds of dragons are there in Skyrim? I've encountered regular dragons of different color and skill, such as ice or fire breath, but I've also encountered Blood Dragons. Are new types appearing as i gain levels? Or does it relate to the main quest?

A: Not including story dragons (usually only a single fight, they are named. Can't recall them all):

*

*Dragon

*Ice Dragon

*Blood Dragaon

*Elder Dragon

*Ancient Dragon

*Serpentine Dragon (DragonBorn DLC)

*Revered Dragon (DawnGuard DLC)

*Legendary Dragon (DawnGuard DLC)

Thats in order of their strengths weakest->strongest. The appear based on your level. Higher level will encounter more elders.
more information on dragons here


text:
Q: ASP.NET Core 2.0 Identity with custom tables configuration I am trying to build an authentication functionality using Identity Core 2.0 with my own custom tables and EF Core 2.0.
I am using this for reference: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-custom-storage-providers?view=aspnetcore-2.1.
The thing is I'm not using Roles, nor Claims so I have a single Table/DbSet containing the user information. I've implemented the required interfaces and everything looks fine. I am also using JWT authentication. The problem is I am not sure how to configure the services in the Startup. Here is my current code:
public void ConfigureServices(IServiceCollection services)
{
    services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,

                ValidIssuer = Configuration["JwtIssuer"],
                ValidAudience = Configuration["JwtAudience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"]))
            };
        });

    services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<User, IdentityRole>()
        //.AddEntityFrameworkStores<MyDbContext>()
        .AddDefaultTokenProviders();

    services.AddTransient<IUserRepository, UserRepository>();
    services.AddTransient<IUserStore<User>, UserStore>();
    services.AddTransient<IEmailSender, EmailSender>();

    services.AddMvc();
}

where User is my custom implementation of the user class. Same goes for UserStore.
However, I am not sure how to configure the specific Identity services. I am supposed to call services.AddIdentity, but it requires a parameter of type TRole which I am not implementing and there isn't any variation without providing a role type. I either have to implement dummy/use the IdentityRole or I have to extract the contents of the extension method and add them manually, which doesn't seem like a good idea to me. Furthermore, it adds Cookie Auth by default, so it won't cut it for me. Here is the body of the extension method I've found: ASP.NET Identity Ref-1 / ASP.NET Identity Ref-2.
How should I register the services? Also, am I missing something else in the configuration in general given the circumstances(JWT, Identity with custom tables).


text:
Q: Trouble verifying md5 checksums created on Windows with Linux Verifiying checksums inside a file usually works like this using Linux and md5sum.
    md5sum -c file.md5

However, using it like this on a Windows file reveals errors, that took me a long while to figure out. The first error was easy: Windows uses backslash instead of slash and different line endings. This can be fixed!
    sed 's/\r$//' file.md5 | sed 's_\\_/_g' | md5sum -c

The first sed takes care of the line endings and the second one of the backslashes.
And while this does solve the major issue, it always ignores the first line of the file, saying unhelpfully at the very end:

md5sum: WARNING: 1 line is improperly formatted

Switching lines around doesn't change this. The first line of the file is always ignored.

A: I finally found the answer after noticing that copying the entire content into a new file does not produce this error.
So it turns out that in Windows the file has some binary characters in front that are not shown in a text editor, but are interpreted by md5sum.
So the solution is then to get rid of these:
 sed 's/\r$//' file.md5 | sed 's_\\_/_g' | sed -e '1s/^.//' | md5sum -c

The third sed removes the first binary blob, finally enabling me to check md5 files generated on Windows!
And because this has been a major ordeal that I didn't find much help online for, I've decided to share it with the world.


text:
Q: How to update/modify existing 'aws_route53_record' CNAME to ALIAS with Terraform I want to update the existing 'aws_route53_record' from CNAME to Alias. What would be the proper process? It is even possible to make such update at once, or it needs to be done in two steps, like create a new ALIAS record and then delete CNAME record?
For example let's assume this it is the existing resource code.
resource "aws_route53_record" "record" {
  count.  = var.rds_enabled
  zone_id = data.aws_route53_zone.zone.zone_id
  name    = var.record_name.data.aws_route53_zone.zone.name
  type    = "CNAME"
  ttl     = "300"
  records = module.rds_aurora_postgress.rdscluster_endpoint
  provider = "aws.dns"
}

A: You don't have to create a new alias record. What you would want to do is to change the existing aws_route53_record resource to alias, so:
resource "aws_route53_record" "record" {
  count  = var.rds_enabled
  zone_id = data.aws_route53_zone.zone.zone_id
  name    = var.record_name.data.aws_route53_zone.zone.name
  type    = "A"

  alias {
    name      = module.rds_aurora_postgress.endpoint
    zone_id   = module.rds_aurora_postgress.hosted_zone_id
    evaluate_target_health = true
  }
}

Note: for the endpoint and hosted_zone_id, see aws_db_instance` resource docs.
If you do the changes on the resource, Terraform will detect it as tainted. This means that it will automatically destroy it and recreate it with a single apply.


text:
Q: Grunt read/write files. Race Condition? I am wiring up an automated release script for my application with several grunt tasks. Basically, I use
grunt.file.readJSON('package.son', {encoding: 'utf8'});
... to extract the version and increment it, and then I use
fs.writeFileSync('package.json', JSON.stringify(packageJson, null, 2), 'utf8');
to write it back. Straight forward.
Another task has to tag the git-commit with the new, incremented, version number and reads the file again. At this point the task still reads the old version. (if I take a look into the file manually later then there is the new version, so increment and write works)
Whats going wrong here? Is that a race condition or are grunt tasks executed asynchronously somehow?


text:
Q: How to reset input value after clicking submit button? import React, { useState } from 'react';
import './StockQuotes.css';
import { createMuiTheme, withStyles, makeStyles, ThemeProvider } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import stockData from '../util/stockData';
import { useDispatch } from 'react-redux';
import { getStocksOwned } from '../slices/stocksOwnedSlice';

const StockQuotes = () => {

    const [sharesToBuy, setSharesToBuy] = useState(stockData);
    const dispatch = useDispatch();

    const handleChange = (event, index) => {
        stockData[index].owned = parseInt(event.target.value);
        setSharesToBuy(stockData);
    }

    const handleClick = (event, index) => {
        event.preventDefault();
        dispatch(getStocksOwned(sharesToBuy));
        stockData[index].owned = 0;
    }

    const StyledTableCell = withStyles((theme) => ({
        head: {
            backgroundColor: theme.palette.common.black,
            color: theme.palette.common.white,
        },
        body: {
            fontSize: 14,
        },
    }))(TableCell);

    const StyledTableRow = withStyles((theme) => ({
        root: {
            '&:nth-of-type(odd)': {
            backgroundColor: theme.palette.action.hover,
            },
        },
    }))(TableRow);

    const useStyles = makeStyles((theme) => ({
        margin: {
            margin: theme.spacing(1),
        },
        table: {
            minWidth: 700,
            },
    }));

    const classes = useStyles();

    const theme = createMuiTheme({
            palette: {
                primary: {main: '#00e676'},
            },
        });

    return(
        <TableContainer component={Paper}>
            <Table className={classes.table} aria-label="customized table">
                <TableHead>
                    <TableRow>
                        <StyledTableCell>Stock Name</StyledTableCell>
                        <StyledTableCell align="right">Current Price</StyledTableCell>
                        <StyledTableCell align="right">Shares</StyledTableCell>
                        <StyledTableCell align="right">Order</StyledTableCell>
                    </TableRow>
                </TableHead>
                <TableBody>
                {stockData.map((stock, index) => (
                    <StyledTableRow key = {index} >
                        <StyledTableCell component="th" scope="row">
                            {stock.name}
                        </StyledTableCell>
                        <StyledTableCell align="right">${stock.price}</StyledTableCell>
                        <StyledTableCell align="right"><input type="number" onChange={event => handleChange(event, index)}></input></StyledTableCell>
                        <StyledTableCell align="right">
                            <ThemeProvider theme={theme}>
                                <Button variant="contained" color="primary" className={classes.margin} onClick={event => handleClick(event, index)}>
                                    BUY
                                </Button>
                            </ThemeProvider>
                        </StyledTableCell>
                    </StyledTableRow>
                    ))}
                </TableBody>
            </Table>
        </TableContainer>
    )
}

export default StockQuotes;

I'm trying to get stockData[index].owned to 0 after I click submit button. Usually straight forward, but this time 8 input fields are created through mapping stockData json file which contains 8 objects. So if I put value property by input tag then type, entire 8 input field changes. So I coded this way except after I click, I get "TypeError: Cannot assign to read only property 'owned' of object '#'". What can I do?

A: A few things going on here:

*

*stockData appears to just be an initial value for setting the component state. Once state is initialized, update and read from sharesToBuy so those changes flow to your component tree.

*Don't mutate objects/state. That can cause bugs and prevent your component from updating properly. Instead, create a new copy with updated values.

*Make your input controlled and update the value based on state changes.

// Convenience function for updating state.
const updateOwnedValue = (index, owned) => {
  // Instead of mutating the array/object, create a copy with the updated values
  // and then update state so the changes flow down to your components.
  const newState = sharesToBuy.map((stock, idx) => (
    idx === index ? { ...stock, owned } : stock
  ));

  setSharesToBuy(newState);
};

const handleChange = (event, index) => {
  updateOwnedValue(index, parseInt(event.target.value));
}

const handleClick = (event, index) => {
  event.preventDefault();
  dispatch(getStocksOwned(sharesToBuy));
  updateOwnedValue(index, 0);
}

...
// Iterate over component state instead of the imported value.
{sharesToBuy.map((stock, index) => (
  ...
  <input
    type="number"
    onChange={event => handleChange(event, index)}
    value={
      // This makes your input a controlled component.
      // The value will respond to state changes.
      stock.owned
    }
  />
  ...
))}

A: Clearing an Input
In order to reset the input upon hitting submit, you want the input to be a controlled component.  This means that is gets its value from you passing it a value prop rather than storing it locally.  Your handler for the submit event is then tasked with setting that value to 0.
Material UI supports both controlled and uncontrolled components so this should be an easy change, but it's made complicated by the messy control of data in your app.  Where does the this entered value come from?  Which value needs to change in order to set it to 0?
Data Structure
You need to think about what data exists and where it is stored.  Data from from your json file should be used once to populate the initialState of your app or its redux store and that's it.
Right now you are actually mutating the stockData value which you imported from the json file.  This is really bad design.
You can have some information which is stored in redux and some which is stored in the local component state, but it shouldn't be the same data in both places.  The local state would be for local changes, like the number entered in the form before hitting the "Buy" button.  While the current price for each stock should be stored in redux and accessed via useSelector.
This Revision isn't perfect, but hopefully it puts you on the right track.
Nested Components
In the demo that I linked to above you might notice that the input component loses focus when you type a character.  The reason that this happens is that you have defined the components StyledTableCell and StyledTableRow inside of your StockQuotes component.  That means that these components will get recreated every time that the state changes.  The input is not seen as the same input because the table cell that it's inside of is a different table cell and that's why it loses focus.
You want to define your styled components as top level components outside of your StockQuotes component.  (I tried just copy and pasting them outside but this introduced other errors.  As a temporary hack solution you could useMemo to avoid re-creation, but this is not ideal.)

A: in handleClick function, at last reset your setSharesToBuy
as like, setSharesToBuy('');


text:
Q: Find minimal edge set to remove such that each remaining component is spanned by one node Suppose I have a weighted undirected graph $G$. I want to find a set of edges $E_{rem}$ to remove from $G$ and create $G'$ such that

*

*in every component of $G'$, there is at least one node connected to all others (or the minimum spanning tree of each component contains just one node)

*$\sum_{e \in E_{rem}} w(e)$ is minimal, where $w(e)$ denotes the edge weight

Is there existing work like this / a nice connection to other problems? I can envision some greedy algorithms but am wondering if a deterministic/exhaustive solution exists in reasonable complexity?


text:
Q: Eclipse: Adding a jars folder to lib I was trying to add a directory full of jars to the lib folder in my dynamic web project in eclipse. I am adding a directory because I want to maintain the new jars separate from the existing ones.
I added the new jars to the class path by selecting and adding all of them to the build path. When I run the web-application, I get class not found for the classes residing in the new jars directory.
However, the same procedure when implemented in a plain Java project works just fine. What am I doing wrong?
Thanks
EDIT - 1: This has something to do with Deployment Assembly, I guess.
I added the jar path in that and it worked. Now, trying to apply for the complete directory.

A: Reconfigure your build path. Remove web libraries and add web libraries again.

A: I found the solution. When you deploy an application on tomcat (through eclipse or otherwise), all the jars have to be present in the lib folder.
If you are using a separate directory for some jars then you need to add an entry in the Deployment Assembly of your project to copy the jars in the lib folder. So, when you will actually run the application, the directory jars will be copied to lib.


text:
Q: Char array printing extra garbage memory This program is supposed to ouput VYGHBUTMDE, but it appends some garbage characters on the end.  Why is this?
#include <stdio.h>
#include <string.h>

int
encrpypt(char ciphertext_buffer[], char plaintext[], char key[]) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
  return 0;
}

int
main() {
  char ciphertext_buffer[10];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT");
  printf("%s\n", ciphertext_buffer);
  return 0;
}

A: Since you are only allocating a 10 byte array for a 10 byte string, there is "nowhere" for the terminating null character to go.  Consider increasing the buffer size to at least one character greater than the length of the string in "visible" characters.

A: You are not null terminating the string. Here is a slightly modified version: (although there are still problems)
#include <stdio.h>
#include <string.h>

int
encrpypt(char ciphertext_buffer[], char plaintext[], char key[]) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
  ciphertext_buffer[i] = 0;
  return 0;
}

int
main() {
  char ciphertext_buffer[11];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT");
  printf("%s\n", ciphertext_buffer);
  return 0;
}

A larger problem is that you are not doing any bounds checking. Here is a better version:
#include <stdio.h>
#include <string.h>

int
encrpypt(char ciphertext_buffer[], char plaintext[], char key[], int size) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    if (i > size - 1) break;
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
  ciphertext_buffer[i] = 0;
  return 0;
}

int
main() {
  char ciphertext_buffer[11];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT", sizeof(ciphertext_buffer));
  printf("%s\n", ciphertext_buffer);
  return 0;
}

A: Char array has to be terminated with '/0'. So always u need to allocate char array as max string size + 1.
try with below corrections.
#include <stdio.h>
#include <string.h>

int encrpypt(char ciphertext_buffer[], char plaintext[], char key[]) {
  int i;
  for (i=0; i<strlen(plaintext); i++) {
    ciphertext_buffer[i] = (char) ( ( ((int)plaintext[i] - 65 + (int)key[i%(strlen(key))] - 65) % 26 ) + 65 );
  }
 ciphertext_buffer[i] = '\0';
  return 0;
}

int
main() {
  char ciphertext_buffer[11];
  encrpypt(ciphertext_buffer, "THISISCOOL", "CRYPT");
  printf("%s\n", ciphertext_buffer);
  return 0;
}


text:
Q: Php API json_encode coding not responding to MySQL query I am trying to get a response from my api coding but it does not return any results even when the code is true
Here is my code
<?php
include "connect.php";
function api($id, $token, $to) {
    $result=$conn->prepare('select * from users where id=:user');
    $result->bindParam(':user', $id);
    $result->execute();
    while($row = $result->fetch(PDO::FETCH_BOTH))
    {
        $username=$row['username'];
        $credit=$row['balance'];
        $pin=$row['pin'];
    }
    $sj = $conn->prepare("SELECT number FROM users WHERE number = :number");
    $sj->bindParam(":number", $to);
    $sj->execute();
    if($sj->rowCount()<1){
        $a=array('code'=>'0', 'text'=>'not working');
        return json_encode($a);
    }
    elseif($token ==$pin)
    {
        $a=array('code'=>'10', 'text'=>'not working');
        return json_encode($a);
    }
    else {
        $a=array('code'=>'1', 'text'=>'ok');
        return json_encode($a);
    }
}
$id=$_GET['id'];
$token=$_GET['token'];
$to=$_GET['to'];
$a=api($id, $token, $to);

echo $a;
?>


text:
Q: C# Send email using Office 365 SMTP doesn't change given email display name I am using C# MailMessage for sending Email through office 365, and I want to change the display name of the sender in the email.
I have tried using mailMessage MailAddress Constructor like this
mailMessage.From = new MailAddress("email","display name");

but it doesn't solve the problem
But when I tried to use Gmail instead, the display name is changed.

A: This is our generic SMTP email function.  It includes the sender's email address and name.
 public static bool EmailReport(
               String Subject,
               String Body,
               String FromAddress,
               String FromName
               String[] To,
               String[] CC,
               out String sError)
        {
            MailMessage m = new MailMessage();
            SmtpClient smtp = new SmtpClient("<insert your email server name here i.e.: mail.Mycompany.com>");
            smtp.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            m.Subject = Subject;
            m.Body = Body;
            m.From = new MailAddress(FromAddress, FromName);
            foreach (String sTo in To)
            {
                m.To.Add(sTo);
            }
            if (CC != null)
            {
                foreach (String sCC in CC)
                {
                    m.CC.Add(sCC);
                }
            }
            try
            {
                smtp.Send(m);
                sError = "";
                return true;
            }
            catch (Exception ex)
            {
                sError = ex.Message + "\r\n\r\n" + ex.StackTrace;
                return false;
            }
        }


text:
Q: How to toggle ng class by clicking a checkbox button? Through webservice i used ngrepeat to show the check box.
It contains 10 check box. Check box was produced in div tag not used html input tag.
In Html,

{{showproduct.productName}}

In controller,
$http({
method  : 'POST',
url     : '///',
headers : {'Content-Type': 'application/x-www-form-urlencoded'},
data:$.param({
userId:$localStorage.loginUserDet.LoginStatus.user.userId,
sessionId:$localStorage.loginUserDet.LoginStatus.sessionId,
authToken:$localStorage.loginUserDet.LoginStatus.user.authToken
})
})
.success(function(data)
{
alert("success");
$scope.showproducts= data;
console.log($scope.showproducts);
});

JSon, to view the check box list
{
"ProductList": {
"code": 0,
"products": [
  {
"productId": 1,
"productName": "Credit Card",
"productStatus": 1
},
  {
"productId": 2,
"productName": "Net Banking",
"productStatus": 1
},
  {
"productId": 3,
"productName": "Saving Account",
"productStatus": 1
},
  {
"productId": 4,
"productName": "Loan",
"productStatus": 1
},
  {
"productId": 5,
"productName": "Insurance",
"productStatus": 1
},
  {
"productId": 6,
"productName": "Certificate Of Deposit",
"productStatus": 1
},
  {
"productId": 7,
"productName": "Prepaid Card",
"productStatus": 1
},
  {
"productId": 8,
"productName": "Investment",
"productStatus": 1
},
  {
"productId": 9,
"productName": "All Products",
"productStatus": 1
},
  {
"productId": 10,
"productName": "Demo",
"productStatus": 1
},
  {
"productId": 11,
"productName": "Remittance",
"productStatus": 1
}
],
"uploadStatus": 1
}
}

I need to toggle the ngclass when i click the check obx.
Can anyone please help on this.

A: So, you want to div behave like toggle, on click you the selectTog() will be called and adds ClassName because of $scope.mSlected varibale will become true in the same way it removes the class

{{showproduct.productName}}

now in controller
$scope.mSelected = false; // setting it false by default
$scope.selectTog = function(){
    $scope.mSelected = !$scope.mSelected;
}

What if there is ng-repeat?
remove ng-class from
 and add class in the function.
<div ng-repeat="x in [1,2,3,4]"

{{x}}

now in controller
$scope.selectTog = function(){
    $event.target.addClass("ClassName");
}

A: Do like this:

{{showproduct.productName}}

controller:
$scope.data = true;
$scope.toggle = function() {
    $scope.data = !$scope.data;
}

When ever you click the div it will toggle the class.
All the best.

A: ng-class evaluates an expression like ng-class="productSaleTrue ? onSale : notOnSale"

    {{showproduct.productName}}

This would evaluate to true and add the css class onSale to the element with that ng-class, if the expression would evaluate to false, the other css class notOnSale would be added to the element, in your case the checkbox.
There is a lot of documentation and codepen examples that you can take from! Have a nice day! A link, just for the sake of knowledge: https://appendto.com/2016/03/ng-class-use-cases-action/
A practical example taken from treehouse:

      <input ng-model="todo.completed" type="checkbox"/>

        {{todo.name}}
      <input ng-change="todo.edited = true" ng-blur="editing = false;" ng-show="editing" ng-model="todo.name" class="editing-label" type="text"/>

        Edit
        Save
        delete

    {{todos}}

A: In your html:

{{showproduct.productName}}

In your controller:
$scope.myFunc = function(event) {
    $(event.target).toggleClass("your_css_class");
}