text:
Q: Hyper-V core NIC speeds and registry changes On a Dell PE T610 I have Hyper-V core running, with 2 x Broadcom BCM5709C NetXtreme II GigE installed. I have noticed that copying large files 17GB for example, from a network physical server to the Hyper-V host local drive [not vm guest] is very slow in comparison to copying from Physical to Physical servers.

*

*Copying a 17GB file physical to Hyper-V host takes 30 minutes

*Copying a 17GB file physical to physical host takes 15 minutes

Can someone tell me exactly what registry nodes I should disable on Hyper-V NICs to improve performance. So far I have gone to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4 D36E972-E325-11CE-BFC1-08002BE10318} and set the following to 0 on both physical NICs:

*

*LSOv1IPv4

*LSOv2IPv6

*TCPUDPChecksumOffloadIPv4

*TCPUDPChecksumOffloadIPv6

Should I also disable *TCPConnectionOffloadIPv4 & *TCPConnectionOffloadIPv6?

A: Are you copying files from one VM to another VM on the same Hyper-V host?
If you're doing a physical to physical transfer, one disk/LUN is reading at full speed, and one is writing at full speed. If you are doing VM to VM transfers on the same storage, you can expect half the throughput because the same set of disks are doing both the reads and the writes.
If the VMs are using independent storage, are you using dynamic disks or pass-through? Dynamic disks have a lot lower overhead in Hyper-V R2, but it's not zero. I wouldn't expect a 50% drop in throughput though.

A: I assume your only copying host to host, not into a VM like Aaron correctly put the concerns around VM's.
I have tested these scenarios and just by installing Hyper-V role you won't slow a server down.   To prove this theory you could remove the role, or reload the box and test throughput before adding role.  I suspect something not Hyper-V related is to blame.  If you have to regedit after a fresh install then you're likely going down the wrong path.
If it's not drivers then are they the same OS version?  SMB is the protocol of file copying from/to Windows and was updated big time in 2008 and again in 2008 R2.  You need to ensure your testing is valid based on what OS's are involved.  If Win2000/2003 is involved in a file copy transfers will be much slower.
Are you taking disk spindles into account?  Newer SAS drivers are faster at I/O then older SCSI or SATA.  The number of disks and RAID config matter in file copy as well.  Fragmentation can also play a part if using servers that have been around awhile.
You may have formatted disks on the new server with mis-aligned disks.  Google can help you find out how to check if your disk formatting is aligned, which if it isn't, can affect performance like you are seeing.


text:
Q: Access denied for user 'root'@'localhost' (using password: YES) I am following the Moodle 3.0 dev installation.
In the database setting process there is an error:
Error: Database connection failed

It is possible that the database is overloaded or otherwise not running properly.
The site administrator should also check that the database details have been correctly specified in config.php
Warning: mysqli::mysqli(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES) inC:\Apache24\htdocs\moodle\lib\dml\mysqli_native_moodle_database.php on line 79

There is somebody who can tell me what to do in order to proceed.
Thanks

A: You must allow remote login on MySQL server to root user using the command below
To allow from localhost
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*root_user_password' WITH GRANT OPTION

To allow from anywhere
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY PASSWORD '*root_user_password' WITH GRANT OPTION

To allow from some host X.X.X.X
GRANT ALL PRIVILEGES ON *.* TO 'root'@'X.X.X.X' IDENTIFIED BY PASSWORD '*root_user_password' WITH GRANT OPTION

Note : Above command must be followed by FLUSH PRIVILEGES;& restart on MySQL service

A: At the Linux or DOS prompt type

mysql -u root -p

Then the following will create a new root user id which can be logged in from anywhere. It also drops already created root to remove the possibility of problems. Warning: this is not the best solution in a production environment.
CREATE USER 'root'@'%' IDENTIFIED BY 'P@ssw0rd';
grant all privileges on *.* to 'root'@'%' WITH GRANT OPTION;
flush privileges;
drop user 'root'@'localhost';
drop user 'root'@'127.0.0.1';
drop user 'root'@'::1';
flush privileges;

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert string to unicode using PostgreSQL? Here I want to convert my string to unicode. I am using PostgreSQL 9.3 version. In SQL Server its much more easy:
Example:
   sql = N'select * from tabletest'; /* For nvarchar/nchar/ntext */

OR
   sql = U'select * from tabletest'; /* For varchar/char/text */

Question: How can I do the above conversion in PostgreSQL?

A: PostgreSQL databases have a native character type, the "server encoding". It is usually utf-8.
All text is in this encoding. Mixed encoding text is not supported, except if stored as bytea (i.e. as opaque byte sequences).
You can't store "unicode" or "non-unicode" strings, and PostgreSQL has no concept of "varchar" vs "nvarchar". With utf-8, characters that fall in the 7-bit ASCII range (and some others) are stored as a single byte, and wider chars require more storage, so it's just automatic. utf-8 requires more storage than ucs-2 or utf-16 for text that is all "wide" characters, but less for text that's a mixture.
PostgreSQL automatically converts to/from the client's text encoding, using the client_encoding setting. There is no need to convert explicitly.
If your client is "Unicode" (which Microsoft products tend to say when they mean UCS-2 or UTF-16), then most client drivers take care of any utf-8 <--> utf-16 conversion for you.
So you should not need to care, so long as your client does I/O with correct charset options and sets a correct client_encoding that matches the data its actually sends on the wire. (This is automatic with most client drivers like PgJDBC, nPgSQL, or the Unicode psqlODBC driver).
See:

*

*character set support


text:
Q: In what situations should I use Entity SQL? I was wondering whether there are situation that's more advisable to use ESQL?
Generally, I find ESQL frustrating (specially with all the special cases where you need to fully qualify an entity type) & probably anything done using ESQL can be done through SQL or LINQ.
But I was wondering of situations where ESQL is a better fit for a solution or would have a competitive edge over using SQL or LINQ (either easier/faster to code, or better performance, etc.)
So, what's the compromise here? When is it better to use each one of the three approaches in querying over EF4?

A: I came across these pretty similar questions (which didn't show up when I typed mine, earlier) on stack over flow, I guess they have deeper discussions (though T-SQL is not mentioned a lot, but it's kinda pretty obvious though):

*

*Linq to Entities vs ESQL - Stack
Overflow

*Entity framework entity sql vs linq
to entities
Note that the two questions are a bit "old" so you might validate some of data based on your current understanding of EF4

A: I find that ESQL to be good for edge cases, for example:

*

*Where it's just really hard to express something in LINQ.

*For building very dynamic searches.

*If you want to use a database specific function that is exposed by the provider you are using.

Also, if you know Entity SQL, you will be able to express QueryViews and Model-Defined Queries.

A: Just as what julie mentioned. Esql is required to write model defined functions which in return can be used through LINQ to Entities Queries.
Most cased you'll be using LINQ to Entities. One another case where you can't use LINQ TO Entities us when you want to build queries with store functions, either buit in or UDF. In this case esql is your only way in EF1 but in EF4 you can use its features to expose those functions to be used in LINQ.
About performance, esql is performing better. but you might prefer productivity using Linq over performance gain using esql.


text:
Q: RTK Query "merge-patch+json" content type ruins request body I am using RTK Query mutation to update my entities. There is api-platform on the backend that accepts only "application/merge-patch+json" Content-Type with PATCH requests.
If I try to put this in my mutation's return statement:
method: 'PATCH',
headers: {
  "Content-Type": 'application/merge-patch+json'
},

I get only [object Object] in my request body instead of json. However, if i change my method to "PUT" or Content-Type to "application/json", my request body is as expected and contains valid json.

A: fetchBaseQuery does not know that content-type by default. In that case instead of passing
  body: something

from your query,
you need to pass
  body: JSON.stringify(something)


text:
Q: Clean way of generating custom warnings in cross platform C code?
Possible Duplicate:
user warnings on msvc AND gcc?

I am trying to come up with a relatively clean way of using the preprocessor to generate a custom warning message in C code that works for multiple compilers (MS VC, gcc, AIX, sun, etc).
I am mostly interested in warning about deprecated items, but also just for general use.
I know the Microsoft compiler supports "#pragma deprecated" and "#pragma message", and I've used "#warning" on gcc before. I know "#error" is in the C standard, but I just want a warning I don't want the compile process to stop.
I'm starting to get the feeling that every platform has a different way of doing this, but does anyone have any better ideas or tips?


text:
Q: Potential mistake in a textbook? Is $y=x^{1/2}$ the same as $y=±\sqrt{x}$? So I was consulting a textbook (Stroud, K. A., & Booth, D. J. (2009). Foundation mathematics) for some definitions and noticed the following statement on p. 275:

$y=x^{1/2}$ which is the same as $y=±\sqrt{x}$

I am confused as I have always thought that $f(x)=y=x^{1/2} = \sqrt{x}$. Am I wrong or is that a mistake in the textbook?


text:
Q: How to hash a CAN message? I want to Hash a CAN message received from a vehicle. The following code written in Python is used to receive the CAN message(dev.recv()) from the vehicle and print the received message (dev.send()).I want to hash the CAN message present in dev.recv()function before sending the message using dev.send().Is this possible? If so how can it be done?
from canard.hw import socketcan

dev = socketcan.SocketCanDev('can0')
dev.start()
while True:
    f = dev.recv()
    dev.send(f)

`

A: *

*I am not sure what the data type is for "f", the data you receive from the function recv.

*I am guessing that SocketCanDev is just a wrapper for the device, and recv acts very similar to the function, read().

*So, "f" in your code might be interpreted as an array of bytes, or chars.

Hashing is done to an array of bytes, regardless of the format of the
  string.

And, the result of the hashing does not depend on the input format or data type.
Therefore, in your case,
while True:
    f = dev.recv()
    result = (hashFunction)(f)
    dev.send(result) // result should in the data type that the function send can accept as a parameter

(hashFunction) can be replaced with an actual function from a hashing library, such as "hashlib".

A: If you are interested in cryptographic hashing, you should take a look at hashlib
With it you should be able to hash the message and send the hash like this
H = hashlib.new('sha256', message)
dev.send(H.digest())

If you want to still send the original message besides the hash, you could make two calls to send.


text:
Q: code for a PHP form that connects with a database I am having problems with creating a PHP form for a web site that popluates a MySQL database.
Here is the error message I am getting at the following URL: http://www.laboro.biz/employer.php:

Parse error: syntax error, unexpected $end in /hermes/bosoraweb013/b1108/ywh.tsarge83/laboro/employer-FormToEmail.php on line 228

The other file that is the action file is http://www.laboro.biz/employer-FormToEmail.php.
I need help with scripting to make this work.
Can anyone please help?

A: You're missing a curly brace somewhere in your script.
You're missing a { or have one more } or ; than needed. Look it over.


text:
Q: How can I combine two PDF pages show up on the same page? I am looking for a free tool that allows re-arranging pages of a PDF document and combining multiple pages per sheet. The first part (re-arranging) is easily solved by many tools (I use PyPDF).
The problem is with the second requirement: to combine two (or more) pages into single page. For example, take two pages (A and B), rotate them, scale and combine into a single page like this
------       ------            ------
|     |      |      |          |     |
|  A  |      |  B   |          | a   |
|     |      |      |          |     |
|     |      |      |  --->    ------
|     |      |      |          |     |
|     |      |      |          | b   |
|     |      |      |          |     |
------       ------            ------

The solution needs to work on Linux and preferably on Windows too. I'm looking for either console application or library with Python or Perl bindings.
Edit there is pdfnup library that is supposed to perform exactly this kind of transformation, and is cross-platform, however I cannot use it due to a bug similar to this.

A: On Linux, you can convert the PDF files to Postscript and use psnup. The exact way to invoke it depends on exactly how you want the pages to be put together, whether you want them rotated, what paper size(s) you want to use, etc. but it'll be something like this:
pdf2ps infile.pdf infile.ps
psnup -2 infile.ps outfile.ps
ps2pdf outfile.ps outfile.pdf

Depending on what tools you have available, you might have a more efficient way to do this - psnup is certainly not the only way, but it's a relatively well-known program (on Linux anyway).

A: This is a summary of the tools I found for PDF (I wanted to find the equivalent of psup and psbook)

*

*Create booklets: pdfbook, pdf-tools (command: pdfbklt)

*Merge PDF files: pdfmerge, pdfjam (command: pdfjoin)

*Rotate pages: pdfjam (command: pdf90)

*Multiple pages per sheet: pdfjam (command: pdfnup)

*Create posters (multiple sheets per page): pdfposter

From my package manager:

*

*pdf-tools: http://search.cpan.org/dist/Text-PDF

*pdfbook: http://www.ctan.org/tex-archive/support/pdfbook/

*pdfmerge: https://github.com/dmaphy/pdfmerge

*pdfjam: http://go.warwick.ac.uk/pdfjam

*pdfposter: http://pdfposter.origo.ethz.ch/
Create an A6 booklet:
pdfbook -2 -p a5 infile.pdf outfile.pdf

pdf-tools contains:

*

*pdfbklt: create booklets

*pdfrevert: Removes one layer of changes to a PDF file, trying to maximise the size of the output file (to account for linearised PDF).

*pdfstamp: Adds the given string to the infile .pdf file at the given location, font and size.

There is also multivalent: http://multivalent.sourceforge.net/Tools/index.html

A: If you use Linux, you can use BookletImposer for putting multiple PDF pages on one single page.
For Ubuntu users, this tool is available at Ubuntu Software Center.

A: Check out this answer that uses Multivalent to impose PDF pages

A: In answer to your question, you'll need a PDF 'Imposition' tool, which is a fancy way of saying a tool that arranges PDF page images onto a particular array to create a NEW single PDF page.  Imagine it's something like typesetting a newspaper.  You define an array of slots a certain number of columns wide, by a certain number of rows deep, on a page of a certain fixed dimensions (in cm).  Then you fill those empty slots top to bottom, left to right with pages from a pdf source-file.  In the case of the OP, they want to create a single page, composed of two 8.5x11 pages arranged in a 1x2 array (1 column, 2 rows).  Their pages will be dropped into the array in the following order: 1,2.  So you are dropping the first page (page 1 of the pdf) into the first slot of your array (Column 1, row 1), and you are dropping the second page (page 2) into the second slot (Column 1, row 2).
How to use the tool to make this happen:
Download the old version of Multivalent.  Note the author removed the good tool classes from the latest edition without explanation, so you have to use an older one. Here's a working link as of 02/12:
http://code.google.com/p/pdfsizeopt/downloads/detail?name=Multivalent20060102.jar
For simplicity, I renamed the jar file to m.jar.
It sort of goes without saying that you need to install JRE for this to work, but I'll put it out there.
Add m.jar to your Java Class Path Environment variables (for scripting) or run the command line syntax with the -cp option and the relative path (shown below).  Note, I ran it FROM the command-line at the install directory in my example below.  Provide an absolute path from root otherwise (like c:\1\bin\m.jar).
Here is an example that will accomplish exactly what OP posted about:
C:\1\bin>java -cp m.jar tool.pdf.Impose -dim 1x2 -verbose -papersize "21.59x55.88cm" -layout "1,2" yourfilename.pdf
Note, the -dim option creates the array in Columns x Rows.  The -papersize is specified in centimeters here, but if you need inches, just multiply inches by 2.54 to get cm.  The -layout option gives you the order you want to fill the empty slots in your array, filling from top to bottom and left to right.  In this case, we want page one of the pdf on top and page two on the bottom, so our argument is "1,2".  The final argument is your actual source file.  The tool will output a file called yourfilename-up.pdf when you are done.
Hope that helps.
-Matt Zweil

A: Check the source code of PyPDF, especially the rotateClockwise() method. There must be a place where the content of a page is written. Insert a "q" operator (save state) and "cm" (with the correct parameters for a scaling matrix) before the content and a "Q" operator (restore state) afterwards.
See the PDF documentation for an explanation of operators and the structure of a page (scroll to the bottom for some useful links).
Don't forget to send a patch to PyPDF :)
[EDIT] You might also want to check the pdfjam sources which include a pdfnup command.

A: This is a perl function I use to grab a directory full of prn files from a 3rd party app and create a single merged pdf.
sub runMerged($)
{
    my($path) = @_;

    print "Generating merged PDFs for $path\n";

    my @files = sort(getFiles($path, ".prn\$"));
    if (scalar(@files))
    {
        open(MERGE, ">$path/merged.prn");
        for (my $i = 0; $i < scalar(@files); $i++)
        {
            print MERGE "^L\n" if ($i > 0);

            open(FN, "$path/" . $files[$i]);
            while (my $line = <FN>)
            {
                print MERGE $line;
            }
            close(FN);
        }

        chdir("$BASE_PATH/txt2pdf");
        print `./txt2pdf.pl $path/merged.prn`;
    }
}

A: I Had a similar need this week.
But I needed to repeat each A4 page (landscape) "twice" in the A3 sheet (portrait), to later cut then in half.
I found a Acrobat Plugin with tons of imposition features that worked great for my needs, and with a fully functional 30 days trial.
Hope It could be helpfull for someone else.
http://www.pdfsnake.com/

A: I had the same issue as you and this is what I did:

*

*Extracted all the pages in the pdf file as a separate file each

*In irfanView (with plugins) I created a Vertical "Panoramic" image

*Dragged the pdf files over to the images section

*Clicked created

*The "image" is created with all the pages following each other as one very long vertical image

*You can export to PDF with almost no loss in quality.

*Enjoy

A: Here's a script for repeating pages (like A5, landscape) twice on a sheet double this size (A4, portrait):
#!/bin/bash
INPUTFILE=$*
PAGENUM=`pdftk ${INPUTFILE} dump_data | grep NumberOfPages | cut -d : -f 2  | cut -d " " -f 2`
PAGES=`seq 1 ${PAGENUM}`
DUPAGES=`for i in ${PAGES} ; do echo $i $i | tr "\n" " " ; done`
OUTPUT1=`basename ${INPUTFILE} .pdf`.dup.pdf
OUTPUT2=`basename ${INPUTFILE} .pdf`.double.pdf
pdftk ${INPUTFILE} cat ${DUPAGES} output ${OUTPUT1}
pdfjam --nup 1x2 ${OUTPUT1} --outfile ${OUTPUT2}

It's not really elegant; it could be done without the second pdftk call, and it does not work with files containing spaces. But it works with multi-page pdfs.

A: Using Adobe Acrobat XI Pro, open the 1st document.
Edit, select "take a snapshot", then click at the top corner of what you want to copy and drag to the opposite corner.
Have an open clean sheet in Paint.
Click over to the clean sheet in paint and control V to paste the 1st document into the clean sheet.
Repeat for the 2nd item that you want to combine on the same page except position the 2nd item UNDER the 1st item temporarily in your Paint sheet.
Then drag the 2nd item to position it where you need it in the Paint Sheet.
Save the paint sheet file and you are done!


text:
Q: Why the Functions aren't defined ? PHP What do I have to do so that I can use the standard php functions without creating an instance of a Math_functions Class ?
<?php

    class Math_functions {

        public static function evenNumber($number) {
            return !($number & 1);
        }

        public static function natual_sum($n) {
            while ($n) {
                if (evenNumber($n)) {
                    $sum = $sum + $n;
                }
                $n--;
            }
            return $sum;
        }

    }

    echo natual_sum(4);
?>

A: This is a static function. You have to access it using class name. Use  like this
Math_functions::natual_sum(4);

A: Just put the functions into a PHP File.
You don't NEED the class
Example:
<?php
        function evenNumber($number) {
            return !($number & 1);
        }

        function natual_sum($n) {
            while ($n) {
                if (evenNumber($n)) {
                    $sum = $sum + $n;
                }
                $n--;
            }
            return $sum;
        }

    echo natual_sum(4);
?>


text:
Q: List or ArrayList?(lots of items) which one is more memory efficient?
which one works faster with 1000000 items?
is there anything better?

A: List<T> is better than ArrayList:

An Array of a specific type (other than Object) has better performance than an ArrayList because the elements of ArrayList are of type Object and, therefore, boxing and unboxing typically occur when storing or retrieving a value type. However, a List can have similar performance to an array of the same type if no reallocations are required; that is, if the initial capacity is a good approximation of the maximum size of the list.

From ArrayList and List Collection Types

A: A List<T> is generally preferable to using an ArrayList because it is a type safe collection. This means that you get build time type safety. It is also more memory efficient for value types because entries in an ArrayList will be boxed because its a list of type object:
eg: Adding an integer to a List<int> will put the data on the heap using an int[] as the underlying data structure. Adding an integer to an ArrayList will put the data on the heap, but because the underlying data structure is an object[], the data has to be boxed which means a pointer also has to be stored on the heap which requires more memory to be allocated.
The memory allocation for an ArrayList and a List<T> : class (a list of reference types) is exactly the same.


text:
Q: How to change the font of the legend? I want to be able to change the font of the legend from the default to Times New Roman. I have managed to change the font of the axis labels and ticks but I am unsure of what to do. Bellow is what I have tried so far:
tnrfont = {'fontname':'Times New Roman'}

plt.figure(figsize=(12,6))
plt.scatter(N,R0_Top[:,0],s=20,marker='x',color='#0000ff',label='Top DBR')
plt.scatter(N,R0_Bottom[:,0],s=20,marker='x',color='#e60000',label='Bottom DBR (100%)')

plt.xlabel('Percentage of Aluminium',**tnrfont)
plt.ylabel('Reflectance',**tnrfont)
plt.xlim(-2,102)
plt.ylim(-0.05,1.05)
plt.minorticks_on()
plt.grid(which='both')
plt.legend(loc=0,**tnrfont)
plt.xticks(**tnrfont)
plt.yticks(**tnrfont)
plt.rcParams.update({'font.size': 28})

How can I change the font of the legend?

A: To set the font of the legend labels you can use the prop argument to plt.legend. It will accept any FontProperty in form of a dictionary.
plt.legend(... , prop={"family":"Times New Roman"})

If you want to change the font of all of the figure's text, you may be better off by setting the font in the rcParams at the beginning of the script:
plt.rcParams["font.family"] = "Times New Roman"


text:
Q: How to use smartglass in context of Windows 8? In the context of Windows-8, I keep seeing mentions of SmartGlass feature.
What is SmartGlass, How do we go about using it or is there any good blog post detailing about this?

A: SmartGlass app will essentially enable people to use their phones, tablets and PCs as "second screens" and remote controllers for the Xbox 360.

*

*Microsoft posts SmartGlass walkthrough, launching alongside Windows 8

*Xbox SmartGlass

A: SmartGlass is an XBOX Companion application, run on various devices (Phone, Tablet, or PC) to remotely control an XBOX.
The best description of it is actually at the XBOX SmartGlass site: http://www.xbox.com/en-US/smartglass


text:
Q: Play Java, How to read a local JSON file and show as list on a body? I am starting learning Play Java, and found many different samples (often without imports etc.) about how to do what explained on subject.
I am using Play 2.5 and JDK 8, and configured my own controller. The file is in a directory that I can access from the controller Java class, but not clear to me what is the best practice to read the JSON file: through Jackson? or java.io.* functions?
Is it possible to obtain a working minimal sample from an expert?
I tried following this guide, but the code goes always in error (sample code does't neither have the final comma!):
https://www.playframework.com/documentation/2.5.x/JavaJsonActions
Basically my json items.json is under ..workspace\play-java\app\data\items.json .
The JSON file is something like this:
[
  {
    "id": 10000000,
    "name": "name1",
    "starttime": "2015-06-18T06:26:56-07:00",
    "endtime": "2015-07-08T12:47:16-07:00"
  }, etc.
]
and I guess that in the function to read the file I need to specify the path 'app/data/items.json' or 'data/items.json'
Thanks in advance!

A: If you want to deliver JSON to the client, you can use the Json class to convert an input stream (or string) into a JsonNode and pass that directly back in the response.  Because you're using a JsonNode, the content type of the will be response will be set automatically.
(For this example, I created a file in /conf called foo.json.)
package controllers;

import java.io.IOException;
import java.io.InputStream;
import javax.inject.Inject;
import com.fasterxml.jackson.databind.JsonNode;
import play.Environment;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;

public class SomeController extends Controller {

    private final Environment env;

    @Inject
    public SomeController(final Environment env) {
        // the environment is used to access local files
        this.env = env;
    }

    public Result index() {
        try (InputStream is = env.resourceAsStream("/foo.json")) {
            final JsonNode json = Json.parse(is);
            return ok(json);
        } catch (IOException e) {
            return internalServerError("Something went wrong");
        }
    }
}

A: I solved by myself with this basic code:
package controllers;

import com.fasterxml.jackson.databind.JsonNode;
import play.Environment;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;

import javax.inject.Inject;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class CustomersController extends Controller {

    private final Environment env;

    @Inject
    public CustomersController(final Environment env) {
        // the environment is used to access local files
        this.env = env;
    }

    public Result index() {
        File file = new File("absolute path/items.json");

        try (
                FileInputStream is =new FileInputStream(file);
        ){
            final JsonNode json = Json.parse(is);
            return ok(json);
        } catch(IOException e){
            return internalServerError("Something went wrong");
        }
    }
}


text:
Q: Override the initialization of a ChoiceField in django I am trying to initialize a form containing a ChoiceField in django. I have the following code:
# in file models.py
class Locality(models.Model):
    locality = models.CharField(primary_key=True, unique=True, max_length=36)
    def __unicode__(self):
        return self.locality

# in file forms.py
class RegisterForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.username = forms.CharField(required=True)
        self.email = forms.EmailField(required=True)
        self.locality = forms.ChoiceField(widget=forms.Select())
        self.fields['locality'].choices = [l.locality for l in Locality.objects.all()]

but oon the shell, once I try to instanciate:

r = RegisterForm(username="toto", email="a@b.com")

I receive 'RegisterForm' object has no attribute 'fields' error. Is this happening as the object is not already formed? How can I access to the ChoiceField?
Any help appreciated.

A: You're not using the Form object in the good way. The fields attribute is initialize by the __init__ method of BaseForm (see the source code) (a parent class of forms.Form), but you have redefine it, so you broke the process.
So, you should call the parent __init__ in your __init__ method, something like this:
class RegisterForm(forms.Form):
    username = forms.CharField(required=True)
    email = forms.EmailField(required=True)
    locality = forms.ChoiceField(widget=forms.Select())

    def __init__(self, *args, **kwargs):
         super(forms.Form, self).__init__(*args, **kwargs)
         self.fields['locality'].choices = [(l.id, l.locality) for l in Locality.objects.all()]

I have moved every *Field declaration outside the __init__, because it's the common way. It's question is very similar to a previous one: Override defaults attributes of a Django form

A: try:
def __init__(self, *args, **kwargs):
     super(forms.Form, self).__init__(*args, **kwargs)
     self.fields['locality'].choices = [(l.id, l.locality) for l in Locality.objects.all()]


text:
Q: Validations in form_tag In my online shop I want to have validation before adding a product to the cart
my order_item form is in the product show
I want to force the user to select  a size, and display an error message if no size chosen ?
Size is a nested attributes of products
How I am supposed to write it?
<%= form_tag clients_order_items_path, input_html: {id: "orderform"} do %>
    <%= hidden_field_tag :product_id, @product.id %>
    <%= hidden_field_tag :user_id, @token %>
    <%= hidden_field_tag :quantity, 1 %>
    <%= select_tag :size_id, options_from_collection_for_select(@product.sizes.where('quantity >=1'), :id, :size_name), prompt: "Your Size", class: 'form-control custom-select'%>
<%= submit_tag "Add to cart", class: "btn-main", id: "add_to_cart" %>

here is the OrderItemsController with the create method:
 def create
    @item = current_cart
    @size = Size.find(params[:size_id])

    if @size.quantity >= params[:quantity].to_i

      current_cart.add_item(
        product_id: params[:product_id],
        quantity: params[:quantity],
        size_id: params[:size_id],
      )

      redirect_to clients_cart_path
    else
      redirect_to clients_product_path(Product.find(params[:product_id]))

    end
  end

A: To force user to select one size:
<%= select_tag :size_id, options_from_collection_for_select(@product.sizes.where('quantity >=1'), :id, :size_name), {include_blank: 'Your Size'}, required: true, class: 'form-control custom-select'%>

This will make the select required, and the browser custom message will appears if size not selected.
If you want to customize the message, and shows before the request are made, consider use JS, i recommends https://jqueryvalidation.org/
OBS: Its a good pratice, don't perform databases queries on your view, consider to make @product.sizes.where('quantity >=1') in your controller like:
# Inside your controller
def show
    ...
    @product_size_options = @product.sizes.where('quantity >=1')
    ...
end

and your  select_tag:
<%= select_tag :size_id, options_from_collection_for_select(@product_size_options, :id, :size_name), {include_blank: 'Your Size'}, required: true, class: 'form-control custom-select'%>


text:
Q: Можно ли сделать в Visual Studio 2019 поведение похожее на Resharper? 1)Автоматическая подстановка даже если пространства нет с последующем его добавлением
При использовании Resharper самое главное, что бы необходимые сборка была подцеплена к проекту. А далее выбираешь из выпадающего списка необходимый тип и он появляется в using'ах. Т.е автоподстановка работает даже тогда, когда в пространство не указано.
В Visual Studio 2019, вроде, завезли фичи автоматического добавления пространства, но работают они неудобно:
Сначала вводится название класса без каких-либо подсказок, а далее нужно нажать на лампочку и лишь тогда добавится пространство имен...
2)При форматировании развертывание анонимного типа из одной строки в несколько:
было так:
new { IsComplete=row.IsComplete,Error=row.Error, Id=row.Id }

Хочу так:
        new
    {
        IsComplete=row.IsComplete,
        Error=row.Error,
        Id=row.Id
     }

Resharper умел такое делать.
Нет ли в новой VS какой-нибудь настройки, которая бы добавила поведение похожее на Resharper?

A: Отвечу на первый вопрос, раз никто не ответил:
В Visual Studio 2019 добавили экспериментальную фичу IntelliSense completion for unimported types и включается она тут:

В итоге, если раньше было так:

Стало так:

При выборе типа произойдет автоматический импорт пространства имен.
Однако, на скриншоте видно, что работает он не удобно:

*

*Он ищет с середины слова, а не с начала, что на мой взгляд не есть
гуд.

*Не импортируются классы с методами-расширения.
Возможно, в будущем это поправят, а пока для себя я открыл вот такое бесплатное расширение - IntelliSense Extender 2019, который методы расширения отображает, а так же в селекторе подсвечивается наиболее похожий по названию тип. Например, если есть объект с названием File, то он будет первым подсвечен в выпадающем списке.


text:
Q: Unable to set Local time zone in Terraform IAC on AWS Event Bridge rule Terraform has aws_cloudwatch_event_target
see docs:
https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_event_target
I have a schedule pattern for a cron event to run currently in GMT time.
I want to edit this in IAC (Terraform) to be "Local Time Zone" instead. There is an option for it in the AWS console but I cannot find anyway to change this value in Terraform! Any ideas?


text:
Q: Qml window with transparent mask I write some app and need to create window with transparency mask.
How I can create QtQuick 2.0 top level window with masked transparency?

A: For mask, you can use setMask function of QWindow, it's work for QQuickView. But you need to launch QML UI with QQuickView and not with qmlscene application (cf http://qt-project.org/doc/qt-5.1/qtgui/qwindow.html#setMask)


text:
Q: htaccess redirecting to query URL I am using following rule for pages e.g. domain.com/item means get item page and URL should be visible as domain.com/item only.
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?page=$1 [QSA,L]
domain.com/item was working fine until few days back but now it redirects to domain.com/item/?page=item.
When I try to open some other page e.g. domain.com/otherpage it is working fine and it is showing domain.com/otherpage only and not redirecting.
The issue is happening only with item page.
When I am using domain.com/item/ it is not redirecting and working correctly and showing domain.com/item/ (though I will not be using /, this I used for testing purpose only).
How to correct this issue?


text:
Q: Is there a way to implement custom files that work like the 'files' in the /proc file system? I'm looking for something like a persistent named pipe... something that I can cat or grep multiple times, and always get the current state of whatever process is feeding into the pipe.
For example, let's say that I create a named pipe called /tmp/timestamp, and then use date to write to it:
mkfifo /tmp/timestamp
date --iso-8601=seconds > /tmp/timestamp

At this point, the call to date will block, waiting for /tmp/timestamp to be read ...
cat `/tmp/timestamp`

Will un-block date, I'll see something like 2017-03-18T16:11:54-04:00 written to stdout, and date will terminate.
... but what if I want an updated date every time I cat /tmp/timestamp?
I guess that
while :; date --iso-8601=seconds > /tmp/timestamp; done

will work, but I'd like to know if a) there are any non-obvious issues with this approach and b) if there's a way to do it which doesn't require a loop.
I would also like to set this up so that it launches automatically, making the fifo always available.
In terms of why I want this to be in pipes -- the information in question is stored in a database backing a web application. Most of our tech support folks are entirely comfortable logging into the servers via ssh and running queries against the database, but there are certain vital statistics that would be really handy to simply grep from files. Being able to ls the directory containing the named pipes would make all of this discoverable... essentially, I'm not doing this because I have to, I'm doing it because it's a metaphor that I think will work well.

A: Here's a "non-obvious issue" with the loop: if a reading process holds the fifo open (because, say, it blocks on opening another file or is suspended), the write loop will run continuously (until it fills the fifo buffer).  There are also issues with multiple concurrent readers, but perhaps you can reasonably eliminate that possibility.
As for a non-loop solution, you can use a socket instead of a fifo, but then you have to write a (trivial) reader program (and use pipes if you want to run something other than cat) since you can't just open those.

A: You could implement a custom filesystem either as a kernel module or by using fuse. Within that custom filesystem you can then have whatever virtual files you want.


text:
Q: Can Hive support Primary keys functionality I am on hive 1.2 version.
We have a requirement where we would like to store data in HIve tables 3-4 times a day and the tables should have primary keys capability so that the delta's are taken care of and we can avoid duplicate records.
Has anyone face similar situation and have any workarounds, as i am finding hive doesnot support primary keys functionality until 2.1 version.
Thank you


text:
Q: Read CSV file in PHP and Validate if its first row contains title and date I have to upload a csv file using php. but before uploading i need to validate it for two things.

*

*if its headers are Title and Date (there are only Colomns).

*first two rows title should not be same.
here is the strucure of expected file.
Title   Date
"The Forest: Season 1: Episode 1",  "7/7/2018"
"Forgive Us Our Debts", "7/7/2018"
"Mr. Sunshine: Season 1: Episode 1",    "7/7/2018"

code so far
$rows   = array_map('str_getcsv', file($_FILES["file"]["tmp_name"]));
    $header = array_shift($rows);
    $csv    = array();
    foreach($rows as $row) {
        $csv[] = array_combine($header, $row);
    }

i have a csv file in associative array but unable to read the first row.
How to read CSV rows with row indexes?

A: Try this
$csv = array_map('str_getcsv', file('data.csv'));
if(isset($csv[0])){
    if($csv[0][0] != 'Title' || $csv[0][1] != 'Date'){
        return "Heading(Title and/or Date) is missing.";
    }else{
        foreach ($csv as $key => $value) {
            //Process further
        }
    }
}

A: str_getcsv has a comma as default delimiter. And you can only convert one line of CSV. If you want to convert a whole file you should use fgetcsv [https://secure.php.net/manual/en/function.fgetcsv.php]
This code example will work:
<?php

$csv = "Title\tDate
\"The Forest: Season 1: Episode 1\"\t\"7/7/2018\"
\"Forgive Us Our Debts\",\t\"7/7/2018\"
\"Mr. Sunshine: Season 1: Episode 1\",\t\"7/7/2018\"";

$rows   = array_map(function ($csv){
    return str_getcsv($csv, "\t");
}, explode("\n",$csv));

$header = array_shift($rows);
$result    = array();
foreach($rows as $row) {
   $result[] = array_combine($header,$row);
}

var_dump($result);

A: You can do something like this:
$file = new SplFileObject("file.csv");
$file->setFlags(SplFileObject::READ_CSV);

$valid = true;
foreach ($file as $i => $row) {

     if ($i > 1) break;

     list($title, $date) = $row;

     if ($i === 0 && ($title !== 'Title' || $date !== 'Date')) {
          $valid = false;
     } else {
          $second_row = $file[2];

          if ($title === $second_row[0]) {
              $valid = false;
          }
     }
}


text:
Q: How to overload an iterator function without losing the advantages of the iterator Since I usually use VB.net as my language of choice I didn't cope with yielding yet. Now I read, that they introduced yielding to VB.net as well, so I tried to learn about it, and now I have a question.
Let's say I have an Iterator function that uses yielding. For the sake of this question I created this rather useless function:
Public Iterator Function Test(ByVal gap As Integer) As IEnumerable(Of Integer)
    Dim running As Integer

    Do While running < (Integer.MaxValue - gap)
        Yield running
        running += gap
    Loop
End Function

If I understood yielding correctly, than the code stops after the yielding and only continues, when the next item is asked for.
So, in my example... if getting the next value for the running variable would need 1 second, then my code would only run 1 second if I only need the first number and it would run 5 seconds if I'd need 5 numbers.
So far, so good, but now I want to overload my function:
Public Function Test() As IEnumerable(Of Integer)
    Return Test(1)
End Function

It's not an Iterator function anymore, so did I lose the advantage of only needing as much time as I need numbers?

A:
It's not an Iterator function anymore, so did I lose the advantage of only needing as much time as I need numbers?

You did not. Iterator functions are not magic, all they do is give you a convenient way of implementing the IEnumerable(Of T) interface. So, to get the advantage of producing only the values you require, all you need is a method that returns a good implementation of that interface. And that could be any of:

*

*An iterator method, like your Test(ByVal gap As Integer).

*A method that calls an iterator method and returns the object it produces, like your Test().

*A method that returns an instance of a type that implements the IEnumerable(Of T) interface by hand.


text:
Q: The synchronous form of require throws errors when resolving a circular dependency, unless I rename require I have a strange behaviour in require, that I dont know how to avoid (or maybe I have my basics wrong?).
Consider the following code:
define (require) ->

  potoo = require "potoo"
  service = require "communication.data"

  downloadIfNeeded = ->
    # ...
    service.download()

  new potoo.App
    pageContainer: potoo.UI.NGStylePage
    userRequired:  true
    stdRoute:      "overview"
    onLogin:       downloadIfNeeded

This is not going to work, because 'communication.data' itself requires 'app' (the code shown). so we obviously have a circular dependency. That fails with a 'Uncaught Error: Module name "app" has not been loaded yet for context: _'
Since the downloadIfNeeded function doesn't get called until after the user actually clicks something, I figured, that something like the following should work:
define (require) ->

  potoo = require "potoo"

  downloadIfNeeded = ->
    service = require "communication.data"
    service.download()

  ...

But that actually throws the same error as above. To make it work, i have to use a little hack. I alias the require function with some other name:
define (require) ->

  potoo = require "potoo"
  reqs = require

  downloadIfNeeded = ->
    service = reqs "communication.data"
    service.download()

  ...

Is this the best way to do so? Or would you recommend the CommonJS Style (module.export) that is also supported by requirejs.

A: I've done a test here and was able to find a solution. What you have is equivalent to this JavaScript:
define(function (require) {

This is enough to be able to use the (fake) synchronous form of require. However, RequireJS will give you the error you got when you try to use a synchronous require and you have circular dependencies. What you need is this:
define(function (require, exports, module) {

This is so that your module uses exports to export its values and consequently RequireJS has an object that can be updated when the module has finished initialized.


text:
Q: ASP.NET Framework can't get reference to another model I have Two Models that are relevant to my situation:
ApplicationUser ( Identity Framework ) and Room,
That's the Properties of Room.cs in the Model folder:
   public class Room
   {
        public int RoomId { get; set; }
        public string Name { get; set; }
        public int EnterPrice { get; set; }
        public int UserDecisionTime { get; set; }
        public virtual ICollection<Card> CardsDeck { get; set; }
        public virtual ICollection<Card> CardsOnTable { get; set; }
        public int WhosTurnChairNumber { get; set; }
        public string Chair0_Id { get; set; }
        public string Chair1_Id { get; set; }
        public string Chair2_Id { get; set; }
        public string Chair3_Id { get; set; }
        public string Chair4_Id { get; set; }
        public virtual ApplicationUser Chair0 { get; set; }
        public virtual ApplicationUser Chair1 { get; set; }
        public virtual ApplicationUser Chair2 { get; set; }
        public virtual ApplicationUser Chair3 { get; set; }
        public virtual ApplicationUser Chair4 { get; set; }
        public int Round { get; set; }
        public int PotOfChair0 { get; set; }
        public int PotOfChair1 { get; set; }
        public int PotOfChair2 { get; set; }
        public int PotOfChair3 { get; set; }
        public int PotOfChair4 { get; set; }
}

That's how Room looks like as a table:
CREATE TABLE [dbo].[Rooms] (
    [RoomId]              INT            IDENTITY (1, 1) NOT NULL,
    [Name]                NVARCHAR (MAX) NOT NULL,
    [EnterPrice]          INT            NOT NULL,
    [UserDecisionTime]    INT            NOT NULL,
    [WhosTurnChairNumber] INT            NOT NULL,
    [Round]               INT            NOT NULL,
    [PotOfChair0]         INT            NULL,
    [PotOfChair1]         INT            NULL,
    [PotOfChair2]         INT            NULL,
    [PotOfChair3]         INT            NULL,
    [PotOfChair4]         INT            NULL,
    [Chair0_Id]           NVARCHAR (MAX) NULL,
    [Chair1_Id]           NVARCHAR (MAX) NULL,
    [Chair2_Id]           NVARCHAR (MAX) NULL,
    [Chair3_Id]           NVARCHAR (MAX) NULL,
    [Chair4_Id]           NVARCHAR (MAX) NULL,
    [Chair0_Id1]          NVARCHAR (128) NULL,
    [Chair1_Id1]          NVARCHAR (128) NULL,
    [Chair2_Id1]          NVARCHAR (128) NULL,
    [Chair3_Id1]          NVARCHAR (128) NULL,
    [Chair4_Id1]          NVARCHAR (128) NULL,
    CONSTRAINT [PK_dbo.Rooms] PRIMARY KEY CLUSTERED ([RoomId] ASC),
    CONSTRAINT [FK_dbo.Rooms_dbo.AspNetUsers_Chair0_Id1] FOREIGN KEY ([Chair0_Id1]) REFERENCES [dbo].[AspNetUsers] ([Id]),
    CONSTRAINT [FK_dbo.Rooms_dbo.AspNetUsers_Chair1_Id1] FOREIGN KEY ([Chair1_Id1]) REFERENCES [dbo].[AspNetUsers] ([Id]),
    CONSTRAINT [FK_dbo.Rooms_dbo.AspNetUsers_Chair2_Id1] FOREIGN KEY ([Chair2_Id1]) REFERENCES [dbo].[AspNetUsers] ([Id]),
    CONSTRAINT [FK_dbo.Rooms_dbo.AspNetUsers_Chair3_Id1] FOREIGN KEY ([Chair3_Id1]) REFERENCES [dbo].[AspNetUsers] ([Id]),
    CONSTRAINT [FK_dbo.Rooms_dbo.AspNetUsers_Chair4_Id1] FOREIGN KEY ([Chair4_Id1]) REFERENCES [dbo].[AspNetUsers] ([Id]) );

GO CREATE NONCLUSTERED INDEX [IX_Chair0_Id1]
    ON [dbo].[Rooms]([Chair0_Id1] ASC);

GO CREATE NONCLUSTERED INDEX [IX_Chair1_Id1]
    ON [dbo].[Rooms]([Chair1_Id1] ASC);

GO CREATE NONCLUSTERED INDEX [IX_Chair2_Id1]
    ON [dbo].[Rooms]([Chair2_Id1] ASC);

GO CREATE NONCLUSTERED INDEX [IX_Chair3_Id1]
    ON [dbo].[Rooms]([Chair3_Id1] ASC);

GO CREATE NONCLUSTERED INDEX [IX_Chair4_Id1]
    ON [dbo].[Rooms]([Chair4_Id1] ASC);

Now, in the Room, I have a method that add users to a chair, for example I can:
SomeMethod(ApplicationUser user) {
    this.Chair0 = user;
}

(I also do db.SaveChanges() )
And when I look into View -> SQL Server Object Explorer, it really saves in Chair0_Id the user, but when I'm doing:
Room = db.Rooms.Find(id);

It doesn't show in Room.Chair0 the first ApplicationUser, why's that?


text: Q: SSAS Design 2 Fact tables (1 Weekly, 1 Monthly) I am currently busy building a sales cube for a customer. However they would also like to see their current stock count in the same cube. The Sales Fact table is on a daily grain, where as the Stock Fact is aggregated on a weekly grain. They would like to see their stock as at sales date. I know i will need to add a calculated field, i am just not sure how to create this. For instance, they close business on a Sunday, so as from Monday, I need to subtract total sales from the Closed Sunday Stock and so forth for each day until Sunday again.


text:
Q: Using the PHP spl_autoload_register() with Codeigniter Please how can I use spl_autoload_register() with Codeigniter? I need to do this because Im using Codeigniter with another framework which also uses autoload.
I saw something here
PHP spl_autoload_register
but I dont know how to target the CodeIgniter autoload. Im new to OOP and Codeigniter. Thanks a lot!
The above link has this:

function autoload_services($class_name){
    $file = 'services/' . $class_name. '.php';
    if (file_exists($file)){
        require_once($file);
    }
}

function autoload_vos($class_name){
    $file = 'vos/' . $class_name. '.php';
    if (file_exists($file)){
        require_once($file);
    }
}

function autoload_printers($class_name){
    $file = 'printers' . $class_name. '.php';
    if (file_exists($file)){
        require_once($file);
    }
}

spl_autoload_register('autoload_services');
spl_autoload_register('autoload_vos');
spl_autoload_register('autoload_printers');

A: Thanks to http://codeigniter.com/forums/viewthread/73804/#366081 and some bits of information from some CI folk that I follow on twitter (I asked em): Eric Barnes, Dan Horrigan, Phil Sturgeon and Zack Kitzmiller, I found a solution. If you are a CodeIgniter n00b like me, you may like to follow these guys.
I deleted init.php and config.php, then jammed the following into the bottom of my CI's config.php (I am also autoloading from a custom library called mylibrary).
function multi_auto_require($class) {
if(stripos($class, 'CI') === FALSE && stripos($class, 'PEAR') === FALSE) {
    foreach (array('flourish', 'mylibrary') as $folder){
        if (is_file(APPPATH."../auxengines/{$folder}/{$class}.php")){
            include_once APPPATH."../auxengines/{$folder}/{$class}.php";
        }
    }
}
}

spl_autoload_register('multi_auto_require');

Works brilliantly. Thanks, people!

A: Ahhh, I see now (after looking at a prior question you asked)...  You're having a problem because there are 2 defined __autoload functions (and hence result in a parse error)...
To fix it, simply rename one of them to something else, and then right after definition call spl_autoload_register('yournewfunctionname');...
That should be all there is to it, so long as I understand your problem...


text:
Q: Trying to use egrep to pull only matched hexadecimal chars from a database The hex chars are in the form of <9F>. There's lots of data around them, but I am only interested in getting the regex right so I can remove these from a table with sed and then re-import the database.
Here's what I've tried so far:
egrep -io '\<[0-9A-Fa-f]{2}\>' /root/database.sql

And several variations. I can't seem to get it to work, and I'm not sure why. I've tried double/triple escaping and grouping as well. It finds the character pair, but doesn't find the < >'s
So it gives output like this:
39
48
69
6F
B9

but I need it to get the full
<39>
<48>
<69>
<6F>
<B9>

A: I'm betting that these are bytes outside the range your terminal can display (either control characters or multibyte strings).
First I have to ask if you are absolutely certain that you want to clean this out of the data abase (after all someone might have rally wanted to insert a record with the word 'über' or something). Also, I have seen some databases use control characters as separaters in DB dump files, as well (Ingres comes to mind)
If you still want to scrub the data then maybe try this:
perl -npe 'tr/\001-\177/cd'
I'm typing this on a tablet so I can't double check, but that should delete any characters outside the 7-bit ASCII range.

A: This works for me:
$cat testfile
<39> <48>
<60><6F><a4>

$egrep -io '<[0-9A-Fa-f]{2}>' testfile

<39>
<48>
<60>
<6F>
<a4>

A: Escaping the less than and greater than signs makes the match look for beginning of word and end of word boundaries. If you want to match those literal characters then use them unescaped.
Also, you can simplify your regex by using a character class.
grep -E '<[[:xdigit:]]{2}>'

It's possible that you have other non-printing characters that aren't being matched. As Adam suggested, use od or hexdump to see what else may be hiding. Binary files are sometimes represented for output using, e.g.,  <EF> without those characters actually being there. What is there would be a byte having the value 0xEF. Binary data like that won't work well with sed or grep.


text:
Q: Edição de dados em PHP Olá, estou com um problema em meu código que não encontrei o problema.
Ao tentar editar o ID 1750 ele executa mas salva no ID 0, gostaria de saber se meu código possui algum erro neste sentido, por que ao clicar em editar na linha que desejo ele acessa e puxa os dados dela mas quando tento salvar ele sempre vai no ID 0.
Erro que apresenta Warning:  Trying to access array offset on value of type null in C:\xampp\htdocs\eletrictel\painel\projetos_editar.php on line 244
// Classe Projeto Editar.php
<?php
include('../class/classe_verifica_login.php');
include_once('../class/classe_conexao.php');
$id = filter_input(INPUT_GET, "id", FILTER_SANITIZE_NUMBER_INT);
$result_empresa = "SELECT * FROM empresa WHERE id='$id' LIMIT 1";
$resultado_empresa = mysqli_query($conexao, $result_empresa);
$row_empresa = mysqli_fetch_assoc($resultado_empresa);
?>

<form method="POST" action="projeto_editar.php">

                        ID ( Desabilitado )
              //linha 244          <input type="text" name="id" id="id" class="form-control" value="<?php echo $row_empresa['id']; ?>" disabled>

                        Empresa
                        <input name="nm_empresa" type="text" value="<?php echo $row_empresa['nm_empresa']; ?>" class="form-control">

                        Status
                        <input name="pj_status" type="text" value="<?php echo $row_empresa['pj_status']; ?>" class="form-control">

                        Nome do projeto
                        <input name="nm_projeto" type="text" value="<?php echo $row_empresa['nm_projeto']; ?>" class="form-control">

                        Número de EI
                        <input name="nm_ei" type="text" value="<?php echo $row_empresa['nm_ei']; ?>" class="form-control">

                        Nome da concessionária
                        <input name="nm_concessionaria" type="text" value="<?php echo $row_empresa['nm_concessionaria']; ?>" class="form-control">

                        Cidade
                        <input name="nm_cidade" type="text" value="<?php echo $row_empresa['nm_cidade']; ?>" class="form-control">

                        Kilometragem
                        <input name="qnt_kilometragem" type="text" value="<?php echo $row_empresa['qnt_kilometragem']; ?>" class="form-control">

                        Quantidade de postes
                        <input name="qnt_postes" type="text" value="<?php echo $row_empresa['qnt_postes']; ?>" class="form-control">

<button type="submit" class="btn btn-primary pull-right">Atualizar</button>

```

```
// Classe Projeto Editar.php

<?php
include('../class/classe_verifica_login.php');
include_once('../class/classe_conexao.php');

$id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_NUMBER_INT);
$nm_empresa = filter_input(INPUT_POST, 'nm_empresa', FILTER_SANITIZE_STRING);
$pj_status = filter_input(INPUT_POST, 'pj_status', FILTER_SANITIZE_STRING);
$nm_projeto = filter_input(INPUT_POST, 'nm_projeto', FILTER_SANITIZE_STRING);
$nm_ei = filter_input(INPUT_POST, 'nm_ei', FILTER_SANITIZE_STRING);
$nm_concessionaria = filter_input(INPUT_POST, 'nm_concessionaria', FILTER_SANITIZE_STRING);
$nm_cidade = filter_input(INPUT_POST, 'nm_cidade', FILTER_SANITIZE_STRING);
$qnt_kilometragem = filter_input(INPUT_POST, 'qnt_kilometragem', FILTER_SANITIZE_STRING);
$qnt_postes = filter_input(INPUT_POST, 'qnt_postes', FILTER_SANITIZE_STRING);

$conexao->query("UPDATE empresa SET
                nm_empresa = '$nm_empresa',
                pj_status = '$pj_status',
                nm_projeto = '$nm_projeto',
                nm_projeto = '$nm_projeto',
                nm_ei = '$nm_ei',
                nm_concessionaria = '$nm_concessionaria',
                nm_cidade = '$nm_cidade',
                qnt_kilometragem = '$qnt_kilometragem',
                qnt_postes = '$qnt_postes',
                modificado = NOW()
                WHERE users.id = $id");

if(mysqli_affected_rows($conexao)) {
    $_SESSION['sucesso'] = true;
    header("Location: projetos_editar.php?id=$id");
} else {
    $_SESSION['negado'] = true;
    header("Location: projetos_editar.php?id=$id");
}
?>
```

A: Olá, já verificou o fechamento da tag " "?  Pergunto por que já tive o mesmo problema e há princícipio não enconrei o fechamento da tag no seu código.

A: O erro ao meu ver se encontra nessa parte do código

  ID ( Desabilitado )
  <input type="text" name="id" id="id" class="form-control" value="<?php echo
  $row_empresa['id']; ?>" disabled>

Até onde sei formulários desabilitados não são enviados no post, o que voce pode usar é a tag type="hidden" no lugar do disabled, porem não vai aparecer na tela


text:
Q: How to create a function to generate a matrix where numbers progessivley get smaller columnwise? Basically I have been trying to come up with a 2D array loop in Matlab. It will create a 5 column array for example that starts of with full 100's and removes the 5th column by an interval of 10 until it hits zero and then moves onto the 4th column and starts at 90, then the 5th column (starting at 90) goes down to zero. This repeats until all the numbers have become zero. Im looking for some sort of loop that creates something like this:
100 100 100 100 90

100 100 100 100 80

100 100 100 100 70 .....

100 100 100 90 90 .....

100 100 100 90 80

100 0   0   0  0 ....

0   0   0   0  0

But I am really struggling to come up with a simple loop for it.
If anyone has an ideas on how to create this I would really appreciate it.

A: The following should get you started. Its a very nice application possibility of the Kronecker Tensor Product to get a fully vectorized solution without loop.
Parameters:
step = 20;
nrows = 3;
nsteps = 5;

As one-liner:
A = cumsum(kron(fliplr(eye(nrows)),step*ones(nsteps,1)),1,'reverse');

with explanation:
basepattern = fliplr(eye(nrows));  % general matrix design
subpattern = step*ones(nsteps,1);  % pattern to repeat
a = kron(basepattern, subpattern); % kronecker delta to repeat pattern
A = cumsum(a,1,'reverse');         % cumulative sum upwards

% optional: filter out lines:
A(nsteps+1:nsteps:end,:) = [];
% optional: pad zeros at the end
A(end+1,:) = 0

Result
A =

   100   100   100
   100   100    80
   100   100    60
   100   100    40
   100   100    20
   100    80     0
   100    60     0
   100    40     0
   100    20     0
    80     0     0
    60     0     0
    40     0     0
    20     0     0
     0     0     0

A: Here's a simple loop-approach that does what you want. You have to make minor adjustments for it to work with the steps you want, but that should be simple:
c = 4; % number of columns
n = 3; % starting number
x = zeros(n*c+1, c); % Initial matrix of zeros
for ii = 1:c
    last_idx(ii) = ((n*c+1)-n)-(ii-1)*n;
    x(1:last_idx(ii),ii) = n;
    x(last_idx(ii)+[1:n-1], ii) = [n-1:-1:1];
end

x =
   3   3   3   3
   3   3   3   2
   3   3   3   1
   3   3   3   0
   3   3   2   0
   3   3   1   0
   3   3   0   0
   3   2   0   0
   3   1   0   0
   3   0   0   0
   2   0   0   0
   1   0   0   0
   0   0   0   0


text:
Q: Python - How do I make a dictionary inside of a text file? I'm writing a program that allows the user to create a username and password. How do I write this as a dictionary into a text file, and then retrieve it when I need it? Also, if there is an easier way to do this I'm welcome to any new ideas.

A: Use Python serialization mechanism - pickle.
Small example:
>>> import pickle
>>> s = pickle.dumps({'username': 'admin', 'password': '123'})
>>> s
"(dp0\nS'username'\np1\nS'admin'\np2\nsS'password'\np3\nS'123'\np4\ns."

Now you can easily save content of s to some file.  After that you can read it and decode:
>>> pickle.loads(s)
{'username': 'admin', 'password': '123'}

But this approach is not quite safe.  Don't use it for dangerous data or data that you rely on.
Check out "Why Python Pickle is Insecure" by Nadia Alramli.

A: I'd use json. It's pretty great for that sort of thing, and in the standard library since 2.6.
import json

# write settings
with open('settings.json', 'w') as f:
    f.write(json.dumps(settings))

# load settings1
with open('settings.json', 'r') as f:
    settings = json.load(f)

A: Check out pickle. It is a way to serialize your objects to a file, then retrieve it.
Also check out shelve, which will give you a more abstract feeling to the serialization.

A: >>> f = open('pass_file','w')
>>> d = {"name":"my_name", "pass":"my_pass"}
>>> import pickle
>>> pickle.dump(d, f)
>>> f.close()

>>> import pickle
>>> f = open('pass_file', 'r')
>>> d = pickle.load(f)
>>> d
{'name': 'my_name', 'pass': 'my_pass'}
>>>

And there is a faster version called cPickle.


text:
Q: How to get the checkbox value of a list in asp mvc I use the below code to have a list with dynamic count. when I get the model in my action the checkbox values are null(even when i check them).
my model:
public partial class Job_SharhVazife
{
    public int ID { get; set; }
    public Nullable<int> Job_Id { get; set; }
    public string Name { get; set; }
    public Nullable<bool> Asli { get; set; }
    public Nullable<bool> Mostamar { get; set; }
    public Nullable<int> Dore { get; set; }
    public Nullable<bool> Tafviz { get; set; }

    public virtual Job_MainJob Job_MainJob { get; set; }
    public virtual Job_SharhVazife_Dore Job_SharhVazife_Dore { get; set; }
}
public class AllDataOfMainJob
{
     public IEnumerable<Job_SharhVazife> Job_SharhVazife { get; set; }
}

my html code:
@model JobWebApplication.Models.AllDataOfMainJob
...

        @Html.LabelFor(model => model.Job_SharhVazife, htmlAttributes: new { @class = "control-label col-md-2" })

                                @Html.Label("Row")
                                @Html.Label("Header1-text")
                                @Html.Label("Header2-checkbox")
                                @Html.Label("Header3-checkbox")
                                @Html.Label("Header4-dropdown")
                                @Html.Label("Header5-checkbox")

                            @if (Model.Job_SharhVazife != null)
                            {
                                for (int i = 0; i < Model.Job_SharhVazife.Count(); i++)
                                {

                                    @((i + 1).ToString())
                                    <input class="form-control text-box single-line valid" id=@("Job_SharhVazife_" + @i + "__Name") name="Job_SharhVazife[@i].Name" type="text" value="@Model.Job_SharhVazife.ToList()[i].Name">

                                                <input type="checkbox" id=@("Job_SharhVazife_" + @i + "__Asli") name="Job_SharhVazife[@i].Asli" value="" @if (!string.IsNullOrEmpty(Model.Job_SharhVazife.ToList()[i].Asli.ToString()) && bool.Parse(Model.Job_SharhVazife.ToList()[i].Asli.ToString()))
                                                { <text> checked="checked" </text> } />

                                                <input type="checkbox" id=@("Job_SharhVazife_" + @i + "__Mostamar") name="Job_SharhVazife[@i].Mostamar" value="" @if (!string.IsNullOrEmpty(Model.Job_SharhVazife.ToList()[i].Mostamar.ToString()) && bool.Parse(Model.Job_SharhVazife.ToList()[i].Mostamar.ToString()))
                                                { <text> checked="checked" </text> } />

                                        <select id=@("Job_SharhVazife_" + @i + "__Dore") name="Job_SharhVazife[@i].Dore" width="100% !important" class="valid">
                                                @Html.Raw(GetSharheVazifeDoreDDL(Model.Job_SharhVazife.ToList()[i].Dore.ToString()))
                                            </select>

                                                    <input type="checkbox" id=@("Job_SharhVazife_" + @i + "__Tafviz") name="Job_SharhVazife[@i].Tafviz" value="" @if (!string.IsNullOrEmpty(Model.Job_SharhVazife.ToList()[i].Tafviz.ToString()) && bool.Parse(Model.Job_SharhVazife.ToList()[i].Tafviz.ToString()))
                                                    { <text> checked="checked" </text> } />

                                    }
                                }

                    <input id="btnAddSharhVazife" type="button" value="+" onclick="AddSharhVazife();" />
                    @Html.ValidationMessageFor(model => model.Job_SharhVazife, "", new { @class = "text-danger" })

...

A: I test the code and I replace HTML with MVC razor html Helper
@Html.CheckBoxFor(x => Model.Job_SharhVazife[i].Asli)

and for all properties and It working now, But you have to change Job_SharhVazife to be List not IEnumerable and all bool? to bool and you can add false as a default value.


text:
Q: Mapstruct 1.3.0.Final version is generating wrong code generation for optional collection getter fields We have a POJO class with Optional getter fields. The mapstruct 1.3.0.Final generating wrong code for the Optional collection field.
We have ProgramAggregate POJO which contains Collection of Program (Collection) and it is an Optional getter type.
When we run with mapstruct 1.2.0.Final, we are seeing proper code generation.
But the same code with 1.3.0.Final generating wrong code. It is not generating the Collection mapping method for Optional Collection getter methods.
Generated code image
@Data
@NoArgsConstructor
@ToString(callSuper = true)
@FieldDefaults(makeFinal = false, level = AccessLevel.PRIVATE)
public class ProgramAggregate {
    public static final long serialVersionUID = 1L;

    Collection<Program> programs;

    public Optional<Collection<Program>> getPrograms() {
        return Optional.ofNullable(programs);
    }

}

@Data
@NoArgsConstructor
@FieldDefaults(makeFinal = false, level = AccessLevel.PRIVATE)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "_type")
public class Program {
    String name;
    String number;

    public Optional<String> getName() {
        return Optional.ofNullable(name);
    }

    public Optional<String> getNumber() {
        return Optional.ofNullable(number);
    }

}

@Data
@NoArgsConstructor
@FieldDefaults(makeFinal = false, level = AccessLevel.PRIVATE)
public class ProgramResponseDto {
    Collection<ProgramDto> programs;

    public Optional<Collection<ProgramDto>> getPrograms() {
        return Optional.ofNullable(programs);
    }

}

@Data
@NoArgsConstructor
@FieldDefaults(makeFinal = false, level = AccessLevel.PRIVATE)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "_type")
public class ProgramDto {
    String name;
    String number;
    String oldNumber;

    public Optional<String> getName() {
        return Optional.ofNullable(name);
    }

    public Optional<String> getNumber() {
        return Optional.ofNullable(number);
    }

    public Optional<String> getOldNumber() {
        return Optional.ofNullable(oldNumber);
    }

}

@Mapper(nullValueCheckStrategy = NullValueCheckStrategy.ALWAYS, unmappedTargetPolicy = ReportingPolicy.WARN,
        collectionMappingStrategy = CollectionMappingStrategy.TARGET_IMMUTABLE)
public interface IProgramMapper extends IOptionalMapper, IDefaultMapper {
    ProgramResponseDto map(ProgramAggregate programAggregate);

    ProgramDto map(Program sourceProgramDto);

    Collection<ProgramDto> mapPrograms(Collection<Program> sourcePrograms);

}

Result:
@Generated(
    value = "org.mapstruct.ap.MappingProcessor",
    date = "2020-10-12T13:10:32+0530",
    comments = "version: 1.3.0.Final, compiler: javac, environment: Java 1.8.0_231 (Oracle Corporation)"
)
public class IProgramMapperImpl implements IProgramMapper {

    @Override
    public ProgramResponseDto map(ProgramAggregate programAggregate) {
        if ( programAggregate == null ) {
            return null;
        }

        ProgramResponseDto programResponseDto = new ProgramResponseDto();

        **Collection<ProgramDto> collection = fromOptional( programAggregate.getPrograms() );**
        if ( collection != null ) {
            programResponseDto.setPrograms( collection );
        }

        return programResponseDto;
    }

    @Override
    public ProgramDto map(Program sourceProgramDto) {
        if ( sourceProgramDto == null ) {
            return null;
        }

        ProgramDto programDto = new ProgramDto();

        if ( sourceProgramDto.getName() != null ) {
            programDto.setName( fromOptional( sourceProgramDto.getName() ) );
        }
        if ( sourceProgramDto.getNumber() != null ) {
            programDto.setNumber( fromOptional( sourceProgramDto.getNumber() ) );
        }

        return programDto;
    }

    @Override
    public Collection<ProgramDto> mapPrograms(Collection<Program> sourcePrograms) {
        if ( sourcePrograms == null ) {
            return null;
        }

        Collection<ProgramDto> collection = new ArrayList<ProgramDto>( sourcePrograms.size() );
        for ( Program program : sourcePrograms ) {
            collection.add( map( program ) );
        }

        return collection;
    }
}

Below is the error after maven build.
Error:
[ERROR] //mapstruct_latest_example/target/generated-sources/annotations/IProgramMapperImpl.java:[21,57] incompatible types: inference variable T has incompatible bounds
[ERROR]     equality constraints: java.util.Collection
[ERROR]     upper bounds: java.util.Collection,java.lang.Object

A: Issue:
Allow generic of generics in types when matching
e.g. method signature such as
<T> T fromOptional(Optional<T> optional)

when T resolves to another generic class such as Collection
This might be resolved in mapstruct 1.4.2. version.


text:
Q: When should I select openid or email as scope in msal.js executin in browser I have an entirely client side web page that makes ajax calls to Microsft ASP.NET Core client REST services. Both this UI application and the web service are registered in Azure ActiveDirectory tenants. I have successfully used another ASP.NET Core app registered in the directory to do user authentication and then request a JWT token for the web service and authenticate against that. Nowhere is the ASP.NET Core Authentication code did I have to specify scopes anywhere. If I wanted to call the graph API, I requested a token for https://graph.windows.net and used that.
Looking at this sample, which I made work in my AD, requesting a token for 'user.read' seems to be necessary. However, other samples just use ['openid'] or ['openid', 'email']?
I know that user.read is the AzureAd pernmission to read my entire user profile with the graph api. Does that imply whatever openid and email gives me?

A: The openid and email scopes are used in Azure AD v2 applications to get access to different info. They are not needed in v1 applications.
Quoting from documentation:

If an app performs sign-in by using OpenID Connect, it must request the openid scope. The openid scope shows on the work account consent page as the "Sign you in" permission, and on the personal Microsoft account consent page as the "View your profile and connect to apps and services using your Microsoft account" permission. With this permission, an app can receive a unique identifier for the user in the form of the sub claim. It also gives the app access to the UserInfo endpoint.

And about the email scope:

The email scope can be used with the openid scope and any others. It gives the app access to the user's primary email address in the form of the email claim.

User.Read is a scope for the Microsoft Graph API. Actually the fully qualified form is https://graph.microsoft.com/User.Read. But MS Graph API is a special case :)


text:
Q: select non-existing pairs of ids in one MySQL statement I have a set of ids in a table (column id), lets say from 1-10, I want to couple.
I have an existing set of completely randomly generated couples in a table (columns id1, id2).
I want to find the set of remaining couples on a single SQL statement.
It's very easy for permutations, my problem is with combinations without repetition. That means when considering (id1,id2) == (id2,id1) or in other words I don't know how to do to find a set which doesn't include the existing couples with the order changed.
Any ideas?
E.g. If i have table myids
|id|
|1 |
|2 |
|3 |
|4 |
|5 |
|6 |
|7 |
|8 |
|9 |
|10|

and table mycouples
|id1|id2|
|1  |2  |
|9  |1  |
|7  |8  |

I should get 10*9 - 6 = 84 different couples with my statement, that is all posible permutations of 10 elements not including (id1=1,id2=2),(id1=2,id2=1),(id1=9,id2=1),(id1=1,id2=9),(id1=7,id2=8),(id1=8,id2=7).

A: SELECT
    m1.id AS id1
  , m2.id AS id2
FROM myids AS m1
  JOIN myids AS m2
    ON m1.id <> m2.id
WHERE NOT EXISTS
      ( SELECT *
        FROM mycouples AS c
        WHERE (c.id1, c.id2) = (m1.id, m2.id)
      )
  AND NOT EXISTS
      ( SELECT *
        FROM mycouples AS c
        WHERE (c.id2, c.id1) = (m1.id, m2.id)
      )

A: SELECT perids.* FROM (SELECT myids1.id AS id1, myids2.id AS id2
            FROM (SELECT DISTINCT id FROM myids) AS myids1
            INNER JOIN (SELECT DISTINCT id FROM myids) AS myids2
            ON myids1.id <> myids2.id) AS perids
        LEFT OUTER JOIN ((SELECT id1,id2 FROM mycouples)UNION ALL(SELECT id2,id1 FROM mycouples))
        AS assoc USING (id1,id2)
        WHERE assoc.id1 is NULL;

seems to do the trick... (wasn't easy to think of it though ^^')


text:
Q: Would like to understand this error message. Typescript: Cannot read properties of undefined (reading 'length') js:6 I am writing some code that will generate a random option from an array as a computer selection, but I keep getting an error code. The error code is this: Typescript: Cannot read properties of undefined (reading 'length'). Below is the code that I have written. Thank you in advance. I'm fairly new to coding so please let me know if there is anything that I can improve.
let x = ['Rock','Paper','Scissors'];
function getComputerChoice(x){
const random = Math.floor(Math.random()* x.length);
  console.log(x[random]);
}


text:
Q: dockerfile inheritance and RUN commands I'm trying to create a dockerfile to build a LAMP server for development using the alpine-lamp base.
FROM glats/alpine-lamp
ENV MYSQL_ROOT_PASSWORD=password
RUN apk add wget && \
    apk add php7-simplexml && \
    mysql -u root -ppassword -e "CREATE DATABASE IF NOT EXISTS mydb"

When I run the docker image build -t testing . command to build my image I get an error:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2)

Is my mysql command being run before the "parent" dockerfile has completed running? I've been able to remove these lines and start the container, and then run the identical mysql command from the cli, so I'm thinking the mysql server part of the parent lamp stack just didn't get completely run. Is there a way to ensure my commands run after the parent?

A: At image build time, mysql will not be running. That is why you see the error message about not being able to connect.
This type of thing isn't something that should be run at build-time. Put the database initialization into an entrypoint script instead.


text:
Q: Does CodeIgniter's $this->image_lib->resize() function return the new image size? CodeIgniter has a nice image manipulation class. I'm setting an image to be resized to a max of 200x200 pixels, with "master_dim" enabled to keep the aspect ratio the same. However, I don't see a way to get the new size of the image after it's done so that I can store it in the  database. Does it not do this? Or do I have to use PHP's getimagesize() to do this?
Thanks.

A: $this->image_lib->resize() returns TRUE or FALSE.
You will need to use getimagesize on the new image to get its size after the resize.


text:
Q: How to check accessToken valid if facebook has been logout? Here's my scenario,

*

*log in facebook in android app, and store the access token to be used next time.

*change my facebook password.

*use my app again --> test facebook.isSessionValid() --> it should return "false", but returns "true".

I looked into the "isSessionValid" implementation, but it just tests "accessExpries".
With this scenario, how do I check if the access token is really valid before I proceed to call the Graph API ?
thanks a lot.

A: The only way to do that is to make a graph request (for "/me" for example), and check that the request succeeds. There's no other guaranteed method that's strictly client-side.


text:
Q: Using only base python count student per course from a csv file (no other dictionaries except python) Initial CSV file has these columns and rows

enroll_code,student_id
10030,55000
10030,55804
10250,55804
10510,55000

After reading the csv file the data list becomes a list of sublists
import csv
data=[]
with open('C:/Users/Taha/Downloads/Data.csv','r') as csvFile:
    reader = csv.reader(csvFile)
    data=list(reader)
    print(data)

csvFile.close()

Output of the above code gives this as data.
data=[['enroll_code', 'student_id'], ['10030', '55000'], ['10030', '55804'], ['10250', '55804'], ['10510', '55000']]

The result I need is

10030: 2
10250: 1
10510: 1

How do I convert it into a dictionary and have the key 10030 represent and count both student_id
When I do:
import csv
data={}
with open('C:/Users/Taha/Downloads/Data.csv','r') as csvFile:
    reader = csv.DictReader(csvFile)
    data=dict(reader)
    print(data)

csvFile.close()

It only gives output: {'enroll_code': 'student_id'}
What I need is a way for python to count of number of occurences on the enroll_code, lets say if there were a thausand entries in the CSV file and enroll_code and student_id were repeated throughout the CSV file, how do I code it to get the required result.
Basically I want to code it in base python what the Code below would yield
import pandas as pd

df=pd.read_csv('data.csv')
df.gourpby('enroll_code').count()

A: the most straightforward way that comes to mind is simply going over your items and "counting" them into a dictionary
assuming you already did
data=list(reader)

you can then do:
result = {}
for item in data[1:]:
    if item[0] not in result :
        result [item[0]] = 1
    else:
        result [item[0]] += 1

we are going over your data item by item, skipping the header (thats why we have the data[1:] part), checking if the item is in the dictionary and if it isnt we add it with the count of 1, otherwise we increment the current count

A: If you don't want to use any external library, you can achieve the desired result using .get:
data=[['enroll_code', 'student_id'], ['10030', '55000'], ['10030', '55804'], ['10250', '55804'], ['10510', '55000']]

dct = {}

for x in data[1:]:
    dct[x[0]] = dct.get(x[0], 0) + 1

print(dct)

output:

{'10030': 2, '10250': 1, '10510': 1}

.get returns the value of key (x[0]) if the key is in the dictionary, otherwise returns 0. Then we sum 1 to this value (x[0]'s value or 0) and assign the new value to the same key.
Here's a link to the official documentation on .get and other dictionary's methods

A: You can use collections.defaultdict
Ex:
import csv
from collections import defaultdict

result = defaultdict(int)
with open('C:/Users/Taha/Downloads/Data.csv') as csvFile:
    reader = csv.reader(csvFile)
    next(reader)   #Skip Header.
    for row in reader:
        result[row[0]] += 1
print(result)

Output:
defaultdict(<type 'int'>, {
    '10250': 1,
    '10510': 1,
    '10030': 2
    })

A: This would work:
import csv

with open('C:/Users/Taha/Downloads/Data.csv') as f:
    enroll_count = {}
    reader = csv.reader(f)
    next(reader)
    for row in reader:
        code = row[0]
        if code in enroll_count:
            enroll_count[code] += 1
        else:
            enroll_count[code] = 1
    print(enroll_count)

A: try below:
data=pd.DataFrame([['10030', '55000'], ['10030', '55804'], ['10250', '55804'], ['10510', '55000']],columns=['enroll_code', 'student_id'])
dict(data.groupby('enroll_code').count())


text:
Q: watir webdriver browser will not goto url When I run the .rb file, the browser opens, but doesn't go to the desired url. Screen stays blank white. When I hit control c in the terminal to quit, I get:
/Users/xxx/.rvm/gems/ruby-2.2.1/gems/selenium-webdriver-2.49.0/lib/selenium/webdriver/firefox/launcher.rb:90:in 'connect_until_stable': unable to obtain stable firefox connection in 60 seconds (xxx.x.x.x:xxxx) (Selenium::WebDriver::Error::WebDriverError)
I used simple code to test and still no luck:
require "rubygems"
require "watir-webdriver"

browser = Watir::Browser.new :firefox #:profile => profile
browser.goto('http://google.com')

A: There seems to be an open issue on this for Selenium:     https://github.com/seleniumhq/selenium/issues/835
Most often proposed solution:
Downgrade to Firefox 45.


text:
Q: How to migrate from SQLite database to Room about "String" field? I am trying to migrate a database from SQLite to Room in Android.
But I got an error:

Migration didn't properly handle:
  staff_message(db.entity.StaffMessage).
       Expected:
      TableInfo{message=Column{name='message', type='TEXT', affinity='2', notNull=true, primaryKeyPosition=0,
  defaultValue='null'}}
       Found:
      TableInfo{message=Column{name='message', type='String', affinity='1', notNull=true, primaryKeyPosition=0,
  defaultValue='null'}}

Origin table was written like:
db.execSQL("CREATE TABLE IF NOT EXISTS staff_message( " +
                    "message String NOT NULL");");

And new table scheme is like:
@Entity(tableName = "staff_message")
data class StaffMessage(
        @ColumnInfo(name = "message") val message: String
)

The only difference is the type.

String VS. TEXT

How can I migrate this table to the Room?

A: There is no data type in SQLite like String. You have to use TEXT
db.execSQL("CREATE TABLE IF NOT EXISTS staff_message( " + "message TEXT NOT NULL");");

A: I should have migrated by myself.
static final Migration MIGRATION_3_4 = new Migration(3, 4) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        // Create the new table
        database.execSQL(
                "CREATE TABLE users_new (userid TEXT, username TEXT, last_update INTEGER, PRIMARY KEY(userid))");
// Copy the data
        database.execSQL(
                "INSERT INTO users_new (userid, username, last_update) SELECT userid, username, last_update FROM users");
// Remove the old table
        database.execSQL("DROP TABLE users");
// Change the table name to the correct one
        database.execSQL("ALTER TABLE users_new RENAME TO users");
    }
};

Thanks to @Raghunandan


text:
Q: Converting Windows 2012 R2 from Hyper-V to KVM (qemu) I have a Windows Server 2012 R2 running SharePoint 2013 which I am trying to migrate from Hyper-V to KVM (qemu). I have converted the vhdx file to qcow2 format
and copied it across to the KVM server (RHEL 7.3)
The Hyper-V VM was configured as Generation 2 and I have create a new VM in KVM with a UEFI firmware (OVMF).
When I boot up the machine goes in to Automatic Repair mode but will not boot. I can open the Cmd Prompt and to do so I need to authenticate with the local Administrator password.
I have run the following:

*

*Type BOOTREC /FIXMBR, and then press ENTER.

*Type BOOTREC /FIXBOOT, and then press ENTER.

*Type Drive:\boot\Bootsect.exe /NT60 All, and then press ENTER.

However the VM is unable to boot always enters Repair mode.
Any suggestions on what I might need to check or any 3rd party utilities I might be able to use or buy to help me easily get past this ?
If I login to command prompt I can run Diskpart / sel disk 0 / list vol to see :
Volume 0    D          CDROM          0 B   No Media
Volume 1    C NTFS     Partition    126GB   Healthy
Volume 2    E Recovery Partition    300MB   Healthy   Hidden
Volume 3               Partition     99MB   Healthy   Hidden

VM on KVM was configured as:
*Emulator:/usr/libexec/qemu-kvm
*Firmware:UEFI x86_64:
*/usr/share/edk2.git/ovmf-x64/OVMF_CODE-pure-efi.fd
*CPUs 8
*Memory 8192MB
*IDE DISK- Disk Bus IDE
*Storage format qcow2
What I have done so far:

*

*Opened Hyper-V and Exported the VM to a new directory on Windows

*Use Hyper-V Inspect Disk to merge the difference avhdx and vhdx disks into one vhdx

*Used StarWind v2v Converter to create a qcow2 file

*Copied the qcows file to KVM machine

*Create new VM of same spec:

6. When starting the new machine I see this:

A: What's your tool for converting? MVMC? You can also try StarWind v2v converter: https://www.starwindsoftware.com/converter It was a big help at my time. And besides, it makes identical hard drive when converts from Hyper-v. Conversion itself is performing at the block level, so all the blocks should be copied unchanged.

A: This this
yum install qemu-img

First, check the file, make sure it's ok.
qemu-img check -r all rmcjmc01.vhdx

If ok, convert the file
qemu-img convert -O qcow2 rmcgmc01.vhdx rmcgmc01.qcow2


text:
Q: problems with building project after update to sdk28 After updating Android Studio to SDK 28, my app doesn't build anymore. I always get this error, which I don't know what I can do with it:
Android resource linking failed
C:\SDK\projects\EngineersWizard\app\src\main\res\layout\activity_form_beleuchtung.xml:18: error: attribute layout_scrollFlags (aka com.example.ren.engineerswizard:layout_scrollFlags) not found.
C:\SDK\projects\EngineersWizard\app\src\main\res\layout\activity_form_beleuchtung.xml:35: error: resource string/appbar_scrolling_view_behavior (aka com.example.ren.engineerswizard:string/appbar_scrolling_view_behavior) not found.
error: failed linking file resources.

Maybe anybody has an idea?

A: Android SDK Build-Tools is a component of the Android SDK required for building Android apps. It's installed in the /build-tools/ directory.
You should always keep your Build Tools component updated by downloading the latest version using the Android SDK Manager. If you're using Android plugin for Gradle 3.0.0 or higher, your project automatically uses a default version of the build tools that the plugin specifies. To use a different version of the build tools, specify it using buildToolsVersion in your module's build.gradle, as follows:
android {
    buildToolsVersion "29.0.0"
...
}


text:
Q: Unable to change the column width dynamically in flex datagrid It's very very frustrating. I am using a singleton class (popup, which means it doesn't forget the last used variables) which contains a datagrid. I am making various columns visible/invisible, setting the widths and headers in accordance to data received from a database call. Everything works fine except that when I put the breakpoints before and after the point where I change width of columns, I do not see the change in width of datagrid at all! Instead I see some values totally out of sync as widths of datagrid column! However, since it is a singleton class, the next time I call this popup, I see widths which I did set up in last call.
I must be messing up in calling the setWidth() function (which is my custom function which changes the width of datagrid in action script). What should be the point where I should call this function? I tried in creationComplete, show and in the setter of dataprovider. Doesn't help...
I have kept horizontal scroll policy as 'off' (turning it on totally messes it up).
If I do datagrid.validateNow(), it doesn't help! And why the hell I don't see the width change reflected immediately if I put the breakpoints before and after the change. Somebody please advise me about what I am doing wrong here.
Thanks.

A: First of all you are indicating yourself what might be wrong here.
1) When you update the width when the component is visible => no change
2) When you close the popup and reopen this it is ok, this also means that the item has been re-rendered whereas it was not the first time. This means that you indeed have to try and trigger this yourself.
Here are some usefull links concerning flex component lifecycle. These should help you figure out which methods to call and / or override.
http://weblog.mrinalwadhwa.com/2009/06/21/flex-4-component-lifecycle/
http://www.slideshare.net/rjowen/adobe-flex-component-lifecycle-presentation
Furthermore, you should never call validateNow() directly, but use invalidation methods instead.
I guess in this case you need to trigger the measurement of your component so a call to
invalidateSize() should do just fine.
Cheers

A: The key is to set the horizontalScrollPolicy="on" before you set the widths. See
fixed row width in DataGrid quirk
or Flex 3 DataGrid Column Width Problem


text:
Q: Why does appending a list to itself show [...] when printed? When I appended the list in itself using the following code.
a = [1, 2, 3, 4]
print a

a.append(a)
print a

I was expecting the output to be...
[1, 2, 3, 4]
[1, 2, 3, 4, [1, 2, 3, 4]]

But it was something like this...
[1, 2, 3, 4]
[1, 2, 3, 4, [...]]

WHY?

A: You are adding a to a itself. The second element of a is a only. So, if it tries to print a, as you wanted

*

*it would print the first element [1, 2, 3, 4]

*it would print the second element, which is actually a

*

*it would print the first element [1, 2, 3, 4]

*it would print the second element, which is actually a

*

*it would print the first element [1, 2, 3, 4]

*it would print the second element, which is actually a ...

you see how it is going, right? It will be doing it infinitely. So when there is a circular reference like this, Python will represent that as an ellipsis within a pair of square brackets, [...], only.
If you want to insert a copy of a as it is, then you can use slicing to create a new list, like this
>>> a = [1, 2, 3, 4]
>>> a.append(a[:])
>>> a
[1, 2, 3, 4, [1, 2, 3, 4]]

A: You could also add them using a for loop, But you end up with one big list.
a = [1, 2, 3, 4]

lengthOfA = len(a)

for x in range(0, lengthOfA):
    item = a[x]
    a.append(item)

print a #Answer is [1, 2, 3, 4, 1, 2, 3, 4]

I like this answer because it dosent create a nested list, But if that's not what you want please discard this answer.
If you want a list inside a list, You can use thefourtheye's awnser.
a = [1, 2, 3, 4]

a.append(a[:])

print a #Answer is [1, 2, 3, 4 [1, 2, 3, 4]]


text:
Q: как передать "тяжелую" строку? В переменной - свёрстанная страница письма. При компиляции ошибка:

Error:(138, 17) java: constant string too long

Как мне передать эту переменную в метод? Разрезать-забить массив-передать массивом? Потоком?

A: По спецификации виртуальной машины Java максимальная длина строкового литерала — 65535. Определить в коде строковую константу большей длины не получится.
Обойти это можно несколькими способами.

*

*Загружать строку из текстового файла/базы данных/конфигурации приложения и т.п.

*Разбить строку на подстроки допустимой длины и определить ее так, чтобы компилятор не считал ее константой.
Например:
 String tmp = "";
 String value = tmp+
        "длинная подстрока 1 ... (еще 60000 символов)"+
        "длинная подстрока 2 ... (еще 60000 символов)"+
        ....
        "длинная подстрока n ... (еще 60000 символов)";

Рекоммендую первый способ, т.к. хранить такие строки в коде неудобно как для строк (сверстанную страницу нужно будет изменять), так и для кода (переписывать код посреди которого гигантский блок текста неудобно).
Полезные ссылки:

*

*Вопрос по ошибке «constant string too long» на StackOverflow с альтернативными вариантами решения проблемы.

*Вопрос на StackOverflow по максимальной длине строкового литерала.

*Java Tutorial. Основы чтения/записи.

*Java Tutorial. Файлы конфигурации.


text:
Q: What's the easiest way to have a script run at boot time in OS X? I want a script (bash/zsh/ruby/...) to run at boot time in OS X. What's the most simple way to do this, without messing with xml/plist files, and preferably not needing to make a meta AppleScript.

A: MacOS X uses Vixie cron, which has special meta tags for launching at reboot time. See the man page for the file format.
something like:
@reboot /path/to/script.sh

in your crontab would work. I'm not sure that this a better solution than launchd, you probably have more meta tools that look at launchd than cron.

A: In case you change your opinion:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.superuser.245713</string>
    <key>ProgramArguments</key>
    <array>
        <string>/path/to/script.sh</string>
    </array>
    <key>UserName</key>
    <string>someuser</string>
</dict>
</plist>

Store as com.superuser.245713.plist in /Library/LaunchAgents/ and make root:wheel the owner/group.

A: There are also Login Hooks if you would prefer the script to run (as root) when a user logs in rather than when the machine is booted.
Here is an example which provides a briefer explanation about them:
How to run a script at login/logout in OS X?


text:
Q: Broken category pagination For some reason the below code works until I hit the third page and gives 404. Is it possible to fix it without using any plugins?
<?php
    $temp = $wp_query;
    $wp_query = null;
    $wp_query = new WP_Query('cat='. $id .'&posts_per_page=4&paged='.$paged);
    while ($wp_query->have_posts()) : $wp_query->the_post();
?>

<?php get_the_content() ?>

<?php endwhile; ?>

<?php if (  $wp_query->max_num_pages > 1 ) : ?>
    <?php previous_posts_link( __( 'Previous', 'themename' ) ); ?>
    <?php next_posts_link( __( 'Next', 'themename' ) ); ?>
<?php endif; ?>

<?php $wp_query = null; $wp_query = $temp;?>

A: Here is some working code i use:
    <?php $temp_query = $wp_query;
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    query_posts("category_name=".$cat."&showposts=20&paged=".$paged."");

    while (have_posts()) : the_post(); ?>

        the_content();

    endwhile; ?>

<?php next_posts_link('Older Entries') ?>

<?php previous_posts_link('Newer Entries') ?>

    <?php $wp_query = $temp_query; ?>

A: Try creating a new instance of WP_Query and at the end use wp_reset_query(); like this:
<?php
    $my_query = new WP_Query();
    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $my_query->query('cat='. $id .'&posts_per_page=4&paged='.$paged);
    while ($my_query->have_posts()) : $my_query->the_post();
?>

<?php get_the_content() ?>

<?php endwhile; ?>

<?php if (  $my_query->max_num_pages > 1 ) : ?>
    <?php previous_posts_link( __( 'Previous', 'themename' ) ); ?>
    <?php next_posts_link( __( 'Next', 'themename' ) ); ?>
<?php endif; ?>

<?php wp_reset_query(); ?>


text:
Q: AJAX inserting a row at any position in a table I am building a rails app and I use AJAX to populate the newly created entry in the table(in views folder).
$("#table tr:first").after('<%= @record.priority %>')

A: $("#career_objective_table tr:nth-child(4)").after('<%= @career_objective.priority %>')

Replace 4 with any number


text:
Q: Represent algebraic expressions in an OOP language like C# I am trying to represent algebra expressions such as polynomials and non-polynomials in C#. At the moment I have the following classes
class Variable {
    public char Var {get; set;}
    public int Exponent {get; set;}
...
}

class Term {
    public IList<Variable> {get; set;}
    public int CoEfficient {get; set;}
...
}

class Expression {
    public IList<Term> {get; set;}
...
}

This allows me to represent simple polynomials such as x^2+3x-8 but I want to be able to represent such expressions as (x+3)(x-2) and 3x(y+2). I have been trying to find out the terminology for this and I think the first is an expression '(x+3)(x-2)' containing two expressions 'x+3' and 'x-2' each containing two terms 'x', '3' and 'x', '-2'. The second is an expression '3x(y+2)' containing an expression 'y+2' multiplied by the term '3x' I was thinking that instead of a list of Terms in the Expression class it was a list of objects which are base classes of both Expression and Term and using recursion of some sort
How could I go about representing this in my classes?
I also want to be able to represent fractions and other non-polynomials
How would this fit into the picture?

A: Having a base class for expressions lets you build expressions out of other expressions.
public abstract class BaseExpression
{
}

public class VariableExpression : BaseExpression
{
   public string Var {get; set;}
   public int Exponent {get; set;}
}

public class ConstExpression : BaseExpression
{
   public object Val {get; set;}
}

public class BinExpression : BaseExpression
{
   public BaseExpression Left { get; set; }
   public BaseExpression Right { get; set; }
   public string Operator { get; set; }
}

For example x(y-1) would be
var xy_1 = new BinExpression()
{
   Left  = new VariableExpression() { Var = "x" },
   Right = new BinExpression()
   {
       Left     = new VariableExpression() { Var = "y" },
       Right    = new ConstExpression() { Val = "1" },
       Operator = "-"
   },
   Operator = "*"
}