text:
Q: Getting error when trying to delete a file in asp.net I have a an html data in a literal and i make a pdf file say scan.pdf from that html using iTextsharp .But when i try to delete the created pdf file using File.Delete() method,it shows an error like
D:\Hosting\filepath\scan.pdf' because it is being used by another process
How can i solve it?
this is the code for creating pdf file from html and send it to some mailid as attachment
   string MailFormat = searchDt.Rows[0][1].ToString();
            EmalBody.Append(MailFormat);
            EmalBody.Replace("[Date]", DateTime.Today.ToString());
            string emailbody = EmalBody.ToString();
            message.Body = EmalBody.ToString();
            ***HTMLToPdf(emailbody, "scan.pdf");***
            System.Net.Mail.Attachment attachment;
            attachment = new System.Net.Mail.Attachment(Server.MapPath("scan.pdf"));
            message.Attachments.Add(attachment);
            message.IsBodyHtml = true;
            message.Subject = "";
            smtpClient.Send(message);
            File.Delete("D://filepath//scan.pdf");

   public void HTMLToPdf(string HTML, string FilePath)
   {
   Document document = new Document();
   PdfWriter.GetInstance(document, new FileStream("D:\\filepath\\scan.pdf",FileMode.Create));
    document.Open();

    iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
    iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
    hw.Parse(new StringReader(HTML));
    document.Close();
    }

A: You're probably not disposing resources after you produce the PDF file. Usually it's done by calling "Close" and/or "Dispose" methods on the corresponding objects.
If the object implements IDisposable, you can just use the using construct. This way resources will be freed once the execution passes the using block (this also guarantees that the resources are freed even if there's an exception inside the using block).

A: After saving the file in Textsharp you still have the file in use, because you haven't cleaned all handles to the file. Your writer is probably not within a using block, see which other classes should be disposed by checking if they are disposable. If you find them, make sure you dispose them, so all handles will be released.
some sample code:
using (FileStream stream = new FileStream(temp_filename, FileMode.Create))
{
    iTextSharp.text.Document document = new iTextSharp.text.Document();
    PdfWriter writer = PdfWriter.GetInstance(document, stream);
    ...
}

//    Do the delete after using block

The delete must be outside your using block. If you still have the error check the code where you are using the file (send it to the client etc).

A: actually i forgot to free the mail attachment object,and thats why i got the error.When i put this code attachment.Dispose(); the error got cleared.

A: I have never used this Textsharp library before but I would guess you can solve this by just either creating the file in a using block:
using(PdfWriter MyWriter=PdfWriter.GetInstance(Document,Stream))
{
...
}

or by simply calling .dispose() on it:
MyWriter.Dispose()

If you could show your code it would help to debug the exact location of your problem.


text:
Q: When would I use std::integral_constant over constexpr? #include <iostream>
#include <type_traits>

int main(){

    //creating an integral constant with constexpr
    constexpr unsigned int speed_of_light{299792458};

    //creating an integral constant with std::integral_constant
    typedef std::integral_constant<unsigned int, 299792458> speed_of_light_2;

    //using them
    std::cout << speed_of_light/2 << '\n';
    std::cout << speed_of_light_2::value/2 << '\n';

}

What's special about std::integral_constant that I would choose to use it over constexpr?
Their behaviour and use cases look identical to me.  I'm trying to think of some kind of template scenario, where constexpr may not suffice.

A: Template integral_constant defines a type, keyword constexpr defines a constant.
For example std::true_type is std::integral_constant<bool, true>.
One of the usage examples is tag-dispatching.
template<typename T>
void use_impl(const T&, std::false_type)
{
}

template<typename T>
void use_impl(const T&, std::true_type)
{
}

template<typename T>
void use(const T& v)
{
   use_impl(v, typename std::is_integral<T>::type());
}

Live example

A: It can be used  with the ternary operator
eg
void gotoN_impl(std::integral_constant<int,0>::type)
{
    std::cout << "GoTo 0" << '\n';
}

void gotoN_impl(std::integral_constant<int,1>::type)
{
    std::cout << "GoTo 1" << '\n';
}

void gotoN_impl(std::integral_constant<int,2>::type)
{
    std::cout << "GoTo 2" << '\n';
}

void gotoN_impl(std::integral_constant<int,3>::type)
{
    std::cout << "GoTo 3" << '\n';
}

template<int N>
void gotoN()
{
    gotoN_impl(typename std::integral_constant<int, N>::type());
}

int main()
{
    gotoN<0>();
    gotoN<1>();
    gotoN<2>();
    gotoN<3>();

    constexpr auto x = 99;

    gotoN<x<4?x:3>(); // with a ternary operator
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sending email automatically I want to send an email automatically without any user intervention to a particular id. To send mail,username and password of the device from which I am sending,has to be authenticated. I am able to get the registered  account name from my phone using
Account[] accounts = AccountManager.get(this).getAccounts();
for (Account account : accounts) {
       String  possibleEmail = account.name;
}

I know my password,so I am sending hardcoded password to authenticate.Is it possible to get password programatically?

A: Nope. You can't get a password from the AccountManager. Look at the docs to see how it works.
http://developer.android.com/reference/android/accounts/AccountManager.html

A: No its not possible get the password


text:
Q: Not quite grasping goroutines and channels, please break this code down I'm following a quick intro to Go and one of the examples is:
package main

import (
    "fmt"
    "time"
)

func worker(done chan bool) {
    fmt.Print("working...")
    time.Sleep(time.Second)
    fmt.Println("done")
    done <- true
}

func main() {
    done := make(chan bool, 1)
    go worker(done)
    <-done
}

I understand whats occuring but I guess I'm not grasping the sequence of events or the limitations?

*

*A channel is created called done with a buffer size of 1.

*The channel is passed into a function

*After the timer is complete it adds a true boolean to the channel

*I'm not sure what the final <-done is doing though

from: https://gobyexample.com/channel-synchronization

A: Receiver operator <- followed by channel name (done in this case) is  used to wait for a value written to channel from worker goroutine. (i.e this read operation will be blocking. If you omit <-done, main goroutine will exit immediately even before worker's goroutine start and you won't be able to see results)
You can do whatever you want with <-done as value: assign it to another variable, pass it as a parameter to another function or just ignore it as in your case... etc.


text:
Q: How to dynamically format string representation of float number in python? Hi I would like to dynamically adjust the displayed decimal places of a string representation of a floating point number, but i couldn't find any information on how to do it.
E.g:
precision = 8
n = 7.12345678911
str_n = '{0:.{precision}}'.format(n)
print(str_n) should display -> 7.12345678
But instead i'm getting a "KeyError". What am i missing?

A: You need to specify where precision in your format string comes from:
precision = 8
n = 7.12345678911
print('{0:.{precision}}'.format(n, precision=precision))

The first time, you specified which argument you'd like to be the number using an index ({0}), so the formatting function knows where to get the argument from, but when you specify a placeholder by some key, you have to explicitly specify that key.
It's a little unusual to mix these two systems, i'd recommend staying with one:
print('{number:.{precision}}'.format(number=n, precision=precision))  # most readable
print('{0:.{1}}'.format(n, precision))
print('{:.{}}'.format(n, precision))  # automatic indexing, least obvious

It is notable that these precision values will include the numbers before the point, so
>>> f"{123.45:.3}"
'1.23e+02'

will give drop drop the decimals and only give the first three digits of the number.
Instead, the f can be supplied to the type of the format (See the documentation) to get fixed-point formatting with precision decimal digits.
print('{number:.{precision}f}'.format(number=n, precision=precision))  # most readable
print('{0:.{1}f}'.format(n, precision))
print('{:.{}f}'.format(n, precision))  # automatic indexing, least obvious

A: In addition to @Talon, for those interested in f-strings, this also works.
precision = 8
n = 7.12345678911

print(f'{n:.{precision}f}')


text:
Q: No bash in /usr/bin Я новичок в Oracle 10, пытаюсь его выучить. Поэтому простите за глупый вопрос. Я пытаюсь переключится на bash в OracleSolaris 10 Комманда which bash показывает no bash is /usr/sbin /usr/bin Как:
no bash is /usr/sbin /usr/bin

Как я могу переключится на bash Заранее спасибо за помощь?

A: судя по всему, имеется в виду операционная система solaris, а не база данных oracle.
установить пакет в этой операционной системе можно так:
$ pkgadd -a имя-пакета

скорее всего, программа bash присутствует в одноимённом пакете.

A: по умолчанию bash в системе solaris находится в другом месте:
/usr/bin/bash

попробуй поискать:
find / -name bash

для того, чтобы не менять путь в готовых скриптах лучше сделать симлинк:
ln -s /usr/bin/bash /bin/bash


text:
Q: How wcf catch exception before exe user code How WCF catch exception before exe user code?
There are a lot of topic about how to solve the misconfig in the config file, like:
The maximum string content length quota (8192) has been exceeded while reading XML data.. If developer doesn't config the configuration correctly, the client will get a error.
I send a very large request to WCF service, before the WCF engine exe my code, WCF engine has returned a message to client. I think this is not an unhandle exception, because on server side, there is no exception throw.
Now I want to catch this kind of exception before wcf return the result to client.
I set a breakpoint at the first line of my code, but it didn't hit the breakpoint, and the client got the error message. Before exe the user code, wcf engine return a error message to client.
I don't wish to hide the .net Exception, but I hope to do something before the WCF engine return.
It seems like WCF return a HTTP code of 500 (not 200).


text:
Q: Use AppDomain.Load(byte[]) without loading from file? I crack my mind... I trying to manually load and unload domain with one assembly:
        var domainInfo = new AppDomainSetup
                            {
                               PrivateBinPath = baseDir
                            };

        _hostedDomain = AppDomain.CreateDomain("Domain", null, domainInfo);
        _hostedDomain.UnhandledException += HostedDomainUnhandledException;
        _hostedDomain.DomainUnload += _hostedDomain_DomainUnload;

        var bytes = File.ReadAllBytes("Facade.dll"); // Loads facade from hosts location.
        _hostedDomain.Load(bytes);

        string asmName = Path.Combine(baseDir, Properties.Settings.Default.AssemblyName);
        bytes = File.ReadAllBytes(asmName);
        var entryPoint = _hostedDomain.Load(bytes); // exception here!

And what I see:
When I tryed to load assembly I see that system load it from CurrentDir/assemblyname.dll (and fails).
Exception: System.IO.FileNotFoundException:
Could not load file or assembly Worker, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
LOG: This bind starts in default load context.
LOG: Using application configuration file: D:#Development!test\trunk\bin\Debug\Bootstrapper.vshost.exe.Config
LOG: Using host configuration file:
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///D:/#Development/!test/trunk/bin/Debug/Worker.DLL.
LOG: Attempting download of new URL file:///D:/#Development/!test/trunk/bin/Debug/Worker/Worker.DLL.
LOG: Attempting download of new URL file:///D:/#Development/!test/trunk/bin/Debug/Worker.EXE.
LOG: Attempting download of new URL file:///D:/#Development/!test/trunk/bin/Debug/Worker/Worker.EXE.
BTW. It is impossible to use LoadFrom due to limitations (I've got the problem with XML serialization....).
Wat the hell .NET doing in this routines?
Why it is so hard to load and unload domain?
Thanks for the help!


text:
Q: How to Add UDID to Xcode Managed Provisioning Profile A couple months ago, I used crashlytics to distribute beta versions of my app and all was well. Recently, I was asked to add another beta tester. This appears to be a simple thing in crashlytics, I clicked "distribute" added an email address, and all seemed fine except for a confounding message along the lines of...

You'll need to distribute again to make a build that will work for this tester. We'll walk you through adding any missing devices to the correct provisioning profile

Unfortunately, Crashlytics didn't "walk me through" adding missing devices. I did however login to Apple Developer, went to Devices > iOS, and manually added the tester's UDID. I'm pretty sure this is correct, but I'm unsure how to "distribute again". See the screenshot below for a walk through of what I tried.
The target beta tester is (Bryan). The phone also shows up under Wayne's profile because he attempted to add the phone as well to help troubleshoot. In any case, you'll notice on the last page that it reports that the UDID is missing from the"iOSTeam Provisioning Profile: *".
The iOSTeam Provisioning Profile only contains the original 3 devices and I'm unable to edit from Apple Developer since this profile is apparently managed in Xcode. I created a new profile which includes the added device, but I'm unsure how to get Crashlytics to recognize and use it.
I found this article titled "Fabric for Enterprise Beta Distribution" on Twitter Community which suggested the user run this command...
rm -rf ~/Library/Caches/com.crashlytics.mac

Which I did (after shutting down Fabric), but it had zero affect.
Any suggestion as to what my next steps ought to be? After much head scratching, I'm at a loss.

A: After adding the UDID into provisioning profile, you should do the following.

*

*Go to Xcode->Settings->Accounts.

*Select your team-> View Details...-> Download All.

*After download finishes, select updated provisioning profile in the Build Settings ( old should become invalid ).

*Press Cmd+Shift+K, Cmd+Alt+Shift+K to clean the project and build folder.

*Archive your project and distribute again.

A: For me only works:
Go to folder

~/Library/MobileDevice/Provisioning Profiles/

Delete all the Provisioning Profiles
Press CMD + K
Archive again.
Tested it in Xcode 10


text:
Q: Is it possible to convert a c++ string into actual code? Is it possible to take a string like this:
 string code = "std::cout<<"Hello World";"

And somehow make the code within the string run?

A:
Is it possible to take a string like this:  string code = "std::cout<<"Hello World";"
And somehow make the code within the string run?

Certainly.
First, output the string and pipe the output as input into another program. This other program should take the input and interpret it as a C++ and produce an executable. Such program is called a compiler (technically, assembler and linker are also needed but let's assume that they are invoked by the compiler automatically). Lastly, run the executable produced by the compiler.


text:
Q: Google Charts - Adding trend line option breaks chart Trying to add a trend line to a line chart in Google Charts but every time I add the trend line option the chart will not display. My understanding is that the "date" column type is a continuous axis so I don't understand why it won't add the trend line.

 var data4 = new google.visualization.DataTable();
        data4.addColumn('date', 'Date');
        data4.addColumn('number', 'Average Price');

        data4.addRows([
          [new Date('12/19/2017'), 10.75],[new Date('12/20/2017'), 6.30],[new Date('12/21/2017'), 8.00],[new Date('12/22/2017'), 9.21],[new Date('12/24/2017'), 5.68]         ]);

          var options = {
           hAxis: {
             title: 'Day'
           },
           vAxis: {
             title: 'Average Price'
           }
              trendlines: { 0: {} }
       };

        var chart4 = new google.visualization.LineChart(document.getElementById('chart_div4'));

        chart4.draw(data4, options);


text:
Q: normally distributed Sample data generation I have 10 sample data (array of int) and now I want to make it 100 and mean while I don't want to just copy it 10 times.
Data = [0, 1,2,3,4,5,6,7,8,9]
So I want to create 90 more data and if I copy it 9 times than each frequency will be 10 or evenly distributed. Which I don't want but some other way where frequency randomly or at least not evenly  distributed.

A: If I understand the question correctly (which I am not sure I do) then you should look at using the numpy module which has easy built in ways of generating data with a normal distribution using numpy.random.normal
You can look at the documentation and tweak it by adding the mean SD and number of values you need - 90 arranged into groups of 10?
import numpy as np

mu, sigma = 0, 0.1 # mean and standard deviation
s = np.random.normal(mu, sigma, [10,9]) # [10,9] is the shape of data.

This leaves you with a numpy array (s) of the data, which is easy to access in the list format that you seem to be after.


text:
Q: How to run .mp4 videos on firefox When play mp4 videos on chrome it works fine.But same videos not playing on firefox. After some search I found this

Firefox does not support .mp4 playback. Try conveting the video to .ogg format which is fast becoming a standard format for html 5 applications.

Now how I convert this to ogg for firefox.
My model code is
has_attached_file :videod, :styles => {
  :medium => { :geometry => "640x480", :format => 'mp4' },
  :thumb => { :geometry => "100x100#", :format => 'jpg', :time => 10 }
}, :processors => [:ffmpeg]
validates_attachment_size :videod, :less_than => 100.megabytes
    validates_attachment_presence :videod
    validates_attachment_content_type :videod, :content_type => /\Avideo\/.*\Z/


text:
Q: why am I not seeing traffic using TCPDUMP while sniffing on wireless interface with the station in WDS mode I've 2 wireless interfaces one has the type of AP and the other has the type monitor.
the AP is attached to a bridge br-lan.
When I run for example:
tcpdump port 5201 -s 0 -ni wlan0

TCPdump is not able to capture any traffic, while if I run it without the "port 5201" filter it captures everything. The same situation if I filter only on "udp", it was not able to capture any single packet.
and when I run it on the br-lan interface using the exact filter:
tcpdump port 5201 -s 0 -ni br-lan

it works perfectly as I want, but the problem I'm not able to get the radiotap header in this case since it considers the bridge as Ethernet interface.
What's the solution in this case ?
Is there any format to specify to filter in link type : IEEE802_11_Radio ??
Is there any specific tool to do that with wireless adapters?
Thanks in advance.

Update

What caused this issue is the WDS (Wireless Distributed System) enabled on the station device (My scenario is: two devices with openwrt in infrastructure mode). As soon as I reconfigured my station device not to use WDS, tcpdump worked correctly as I wanted. Still the real explanation why this happened is unknown.
if someone knows the reason or knows how to filter the traffic in WDS mode, please mention it in the answers since I've lost a feature because of disabling WDS.

A: I'm thinking that your traffic didn't have any traffic on port 5201 or UDP traffic. As for the header, tcpdump does have a "--monitor-mode" switch.  Try that.  It's supposed to drive a wireless interface into monitor mode, which is what you'll want to "see" the wireless info.
Whether or not --monitor-mode will work depends on a number of things: your wireless NIC will need to support monitor mode, tcpdump needs to be of a recent version, and your kernel drivers need to support the NIC properly (i.e., sometimes you need to build a specific driver which isn't part of a standard install).
Also, depending on the version of tcpdump, you might be able to drop the "-s 0" portion of your command.  If you leave it off, tcpdump defaults to a snap length of 262144 bytes (okay, I had to look that up).  Setting the snaplength to "0" accomplishes the same thing.


text:
Q: Find and replace only if it matches a string in vi editor I have a large file:
.
..
...
        {
        "term": "Allow A to B",
        "to_zone" : ["inside"],
        "from_zone" : ["sys"],
        "source" : ["10.10.10.10/32"],
        "destination": ["20.20.20.20/32","30.30.30.30/32"],
        "source_user" : ["any"],
        "category" : ["any"],
        "application" : ["any"],
        "service" : ["application-default"],
        "source_hip" : ["any"],
        "destination_hip" : ["any"],
        "tag" : ["con"],
        "action" : "allow",
        "rule_type" : ["universal"],
        "group_tag" : ["con"],
        "profile_setting" : "alert-only"
        },
...
..
.

I would like to delete only the square brackets '[,]' and leave the quotes quotes ONLY if it matches the line, 'group_tag'.
The expected result would be:
.
..
...
        {
        "term": "Allow A to B",
        "to_zone" : ["inside"],
        "from_zone" : ["bdd"],
        "source" : ["10.10.10.10/32"],
        "destination": ["20.20.20.20/32","30.30.30.30/32"],
        "source_user" : ["any"],
        "category" : ["any"],
        "application" : ["any"],
        "service" : ["application-default"],
        "source_hip" : ["any"],
        "destination_hip" : ["any"],
        "tag" : ["con"],
        "action" : "allow",
        "rule_type" : ["universal"],
        "group_tag" : "con",
        "profile_setting" : "alert-only"
        },
...
..
.

How do I accomplish this in vi editor?

A: You can apply a substitution to lines matching a pattern:
:/group_tag/s/[\[\]]//g

The [\[\]] matches a literal open or closing square bracket.
To get all such lines in one go, I think you'd have to use this approach:
:%s/\(^.*group_tag" : \)\[\(.*\)\]\(.*\)/\1\2\3/g

This is matching the whole line, but remembering (using capture groups: \(
and \)) everything except the square brackets. Then we replace the line with
only the remembered capture groups.
But also see the approaches in this
question.


text:
Q: I need to get svn_deff out put between two revisions in php I tried using this svn diff -r BEGIN_REVISION:END_REVISION  in terminal, I get results , But I need a solution in php. I tried this code
$svn_blame_array=exec("svn diff -r 125:126 --username abc --password abc753 ",$ret);
print_r ( $ret );

in php. Below error is occurred ,
"You can avoid future appearances of this warning by setting the value of the 'store-plaintext-passwords' option to either 'yes' or 'no' in /var/www/.subversion/servers.
Store password unencrypted (yes/no)? svn: Can't read stdin: End of file found"

Can anyone help me ?

A: This error appears, because the svn command is run as the user who runs the webserver process (often called www-data). By default subversion will try to cache authentication data into the ~/.subversion directory of a user (which is /var/www for the webserver user on your machine).
If you don't want that, you can try to add the --no-auth-cache option to your command.
You may also want to add --non-interactive.


text:
Q: ERROR 1005 (HY000): Can't create table 'db.POSTS' (errno: 150) Hi I'm having issues creating my post database. I'm trying to make a forenge key to link to my users database. Can someone please help?
Here's the code for my tables :
CREATE TABLE USERS(

UserID int NOT NULL AUTO_INCREMENT,
UserName varchar(255),
UserPassword varchar(255) NOT NULL,
UserEmailAddress varchar(255) NOT NULL,
Admin int DEFAULT 0,
PRIMARY KEY (userID,UserName)
)ENGINE=InnoDB;

CREATE TABLE POSTS(

postID int NOT NULL AUTO_INCREMENT,
postTitle varchar(255) NOT NULL,
postContent varchar(255) NOT NULL,
category varchar(255) NOT NULL,
postDate Date NOT NULL,
postAuthor varchar(255),
tag varchar(255),

PRIMARY KEY(postID),
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB;

Here's the last InnoDB error message:
Error in foreign key constraint of table db/POSTS:
FOREIGN KEY(postAuthor) REFERENCES USERS(UserName)
)ENGINE=InnoDB:
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
for correct foreign key definition.

A: There really should not be a good reason to have a compound primary key on the first table.  So, I think you intend:
CREATE TABLE USERS (
    UserID int NOT NULL AUTO_INCREMENT,
    UserName varchar(255),
    UserPassword varchar(255) NOT NULL,
    UserEmailAddress varchar(255) NOT NULL,
    Admin int DEFAULT 0,
    PRIMARY KEY (userID),
    UNIQUE (UserName)
);

CREATE TABLE POSTS (
    postID int NOT NULL AUTO_INCREMENT,
    postTitle varchar(255) NOT NULL,
    postContent varchar(255) NOT NULL,
    category varchar(255) NOT NULL,
    postDate Date NOT NULL,
    postAuthor int,
    tag varchar(255),

    PRIMARY KEY(postID),
    FOREIGN KEY(postAuthor) REFERENCES USERS(UserId)
);

Some notes:

*

*An auto-incremented id is unique on every row.  It makes a good primary key.

*A primary key can consist of multiple columns (called a composite primary key).  However, an auto-incremented id doesn't make much sense as one of the columns.  Just use such an id itself.

*If you use a composite primary key, then the foreign key references need to include all columns.

*I chose UserId for the foreign key reference.  You could also use UserName (because it is unique).

*UserName is a bad choice for foreign keys, because -- conceivably -- a user could change his or her name.

A: The error is caused by incorrect foreign key definition. In the concrete case you are missing a complete column in your foreign key definition.
In the USERS table you have defined primary key as composite key of UserID and UserName columns.
CREATE TABLE USERS (
  UserID int NOT NULL AUTO_INCREMENT,
  UserName varchar(255),
  UserPassword varchar(255) NOT NULL,
  UserEmailAddress varchar(255) NOT NULL,
  Admin int DEFAULT 0,
  PRIMARY KEY (UserID,UserName)
) ENGINE=InnoDB;

note that it is good practice to respect case of the identifiers (column names)
In the POSTS table you declared your foreign key to reference only one column in the USERS table, the UserName column. This is incorrect as you need to reference entire primary key of the USERS table which is (UserID, UserName). So to fix the error you need to add one additional column to the POSTS table and change your foreign key definition like this:
CREATE TABLE POSTS(
  postID int NOT NULL AUTO_INCREMENT,
  postTitle varchar(255) NOT NULL,
  postContent varchar(255) NOT NULL,
  category varchar(255) NOT NULL,
  postDate Date NOT NULL,

  authorId int,
  postAuthor varchar(255),

  tag varchar(255),
  PRIMARY KEY(postID),
  FOREIGN KEY(authorId, postAuthor) REFERENCES USERS(UserID, UserName)
) ENGINE=InnoDB;

Please look at following fiddle: http://sqlfiddle.com/#!9/92ff1/1
NOTE: If you can you should re-architect this to not use the composite primary key in the USERS table as it does not make sense from what I can see in the displayed code. You can change the tables like this:
CREATE TABLE USERS (
  UserID int NOT NULL AUTO_INCREMENT,
  UserName varchar(255),
  UserPassword varchar(255) NOT NULL,
  UserEmailAddress varchar(255) NOT NULL,
  Admin int DEFAULT 0,
  PRIMARY KEY (UserID)
) ENGINE=InnoDB;

CREATE TABLE POSTS (
    postID int NOT NULL AUTO_INCREMENT,
    postTitle varchar(255) NOT NULL,
    postContent varchar(255) NOT NULL,
    category varchar(255) NOT NULL,
    postDate Date NOT NULL,

    postAuthorID int,

    tag varchar(255),
    PRIMARY KEY(postID),
    FOREIGN KEY(postAuthorID) REFERENCES USERS(UserID)
) ENGINE=InnoDB;;


text:
Q: How do you run EF migrations from a custom NuGet package? I have a c# class libary that has its own database context and Entity Framework migrations.
My solution contains a web site that references the class library as a Project Reference.
I can apply the EF migrations for the Class Library in Visual Studio from Package Manager Console by setting the default project to my Class Library and using the following command:
update-database -StartupProject MyMainWebProj -Context MyClassLibDbContext

I have created a private NuGet package for the class libary and updated the Web Site to reference the NuGet package rather than a project reference.
I cannot figure out how to run the EF migrations now that the class library is referenced via NuGet package.

A: You may use the builder object of the Use*() method during service configuration like mentioned here: https://github.com/jasontaylordev/CleanArchitecture/blob/d0f133ee026aec5cd5856c5592c307b5f20fa8e4/src/Infrastructure/DependencyInjection.cs#L28
services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(
        configuration.GetConnectionString("DefaultConnection"),
        b => b.MigrationsAssembly(typeof(SomeClassInTheOtherAssembly).Assembly.FullName)));


text:
Q: Zebra ZPL code mixed mode QR data This is my complete ZPL code for labels I will be printing. This contains mock data, as the finished code will be concatenated in to Excel for over 1000 labels.
^XA
^FO50,30
^ADN,60,50
^FD300957^FS
^FO50,170
^ADN,40,25
^FDGUIDE PIN PANELBOARD^FS
^FO50,240
^ADN,25,15
^FDPOU Location^FS
^FO50,280
^ADN,40,25
^FDD2P^FS
^FO50,370
^ADN,25,15
^FDSupply Location^FS
^FO50,410
^ADN,40,25
^FDW7E02^FS
^FO50,490
^ADN,40,25
^FDBin Qty^FS
^FO50,540
^ADN,50,25
^FD50^FS
^FO650,30
^ADN,25,15
^FDSTORES^FS
^FO650,70
^ADN,25,15
^FDKBLINE^FS
^FO650,110
^ADN,28,15
^FDD2P^FS
^FO450,250^BQ,2,10
^FDD03048F,LA,N300957,ACAGE,AW7E02,ASTORES,AKBLINE,N50^FS
^XZ

The line in question is
^FDD03048F,LA,N300957,ACAGE,AW7E02,ASTORES,AKBLINE,N50^FS

What I need my QR code to do is be in mixed mode with automatic input and take the 6 field entries found in the part "N300957,ACAGE,AW7E02,ASTORES,AKBLINE,N50" and plug them in to separate fields when scanned. The data is in the order the fields are in when tabbed through on the inventory form. At this time, when scanned, the QR sends all the data to only the first field in a long string. Does anyone know how to get this working?

A: Use \09 for Horizontal Tab and \0D for Carriage Return like this:
^FDD03048F,LA,N300957\09ACAGE\09AW7E02\09ASTORES\09AKBLINE\09N50\0D^FS

You also might need to specify ^FH\, here is full example that I have used in the past:
^XA
^FO343,295
^BQN,2,4^FH\^FDLA,Field1\09Field2\09Field3\0D^FS
^PQ1,0,1,Y
^XZ

A: _0D_0A to get to next line in QR Code.


text:
Q: C# Reflection test if member is an interface implementation Suppose I have the following interface and implementing class:
public interface IInterface
{
    string AMember { get; }
    string OtherMember { get; }
}

public class Class : IInterface
{

    public string OtherMember { get { return "other"; } }

    public string AMember { get { return "class"; }}

    string IInterface.AMember { get { return "explicit"; } }

}

Now I get the members via reflection and want to test if they are an interface implementation.
public class Program
{
    public static void Main()
    {
        var inst = new Class();
        var members = typeof(Class).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
        foreach(var member in members)
        {
            object val;
            try
            {
                val = member.GetValue(inst);
            }
            catch(MethodAccessException e)
            {
                val = "EXPLICIT";
            }

            Console.Out.WriteLine(string.Format("{0}: {1} is interface implementation? {2}", member.Name, val, false /*member.IsInterfaceImplementation*/));
        }
    }
}

How can I test if the member is the implementation of an interface?

A: In case you really just want to check whether a member of a certain class comes from any interface, you could do the following:
bool myMemberComesFromInterface = typeof(Class).GetInterfaces()
    .SelectMany(i => i.GetMember("MyMember")).Any();

There is an edge case though: explicit interface implementation; consider:
public interface IInterface
{
    int MyMember { get; }
}

public class Class : IInterface
{
    public string MyMember => "foo";
    int IInterface.MyMember => 2;
}

The above code would yield true in this case and I can't be sure if that's what you want in your use case. If you don't want this, I think you'd have to do comparisons of the members you found with the SelectMany(...) on a per-interface basis. Perhaps InterfaceMapping (see here) could be of use as well here.
Edit: Since it is now clarified that this case is of interest, I tried fiddling something that would work for your case:
var interfaces = typeof(Class).GetInterfaces()
    .ToDictionary(i => i.FullName, i => i.GetProperties().Select(p => p.Name).ToList());
var properties = typeof(Class).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance);

// explicitly implemented properties
foreach (var pi in properties.Where(pi => pi.Name.Contains(".")))
{
    Console.WriteLine($"Explicitly implemented property {pi.Name} found.");
    var parts = pi.Name.Split('.');
    string interfaceName = string.Join(".", parts.Take(parts.Length - 1));
    string propertyName = parts[parts.Length - 1];
    interfaces[interfaceName].Remove(propertyName);
}

// rest
foreach (var pi in properties.Where(pi => !pi.Name.Contains(".")))
{
    // instead of this, you could also use LINQ and SelectMany
    // on the Values to check for containment
    bool found = false;
    foreach (var interfaceName in interfaces.Keys)
    {
        if (interfaces[interfaceName].Contains(pi.Name))
        {
            found = true;
            Console.WriteLine($"Found property {pi.Name} in interface {interfaceName}.");
        }
    }

    if (!found)
    {
        Console.WriteLine($"Property {pi.Name} is self-defined.");
    }
}

For your example, this give me the following output:
Explicitly implemented property Fiddle.IInterface.AMember found.
Found property OtherMember in interface Fiddle.IInterface.
Property AMember is self-defined.

A: You can use the following code:
var interfaceType = typeof(IInterface);
var interfaceVar = typeof(Class).GetInterface(interfaceType.Name);
var returnMethod = interfaceVar.GetMethods().FirstOrDefault(m
         =>m.ReturnType.IsSubclassOf("MyMember") || m.ReturnType == "MyMember");
 if(returnMethod != null){
  // your member is implementation of interface
   }


text:
Q: Metric equivalence I have that $E=[0,1]$ and $d'(x,y)=|\sqrt{x}-\sqrt{y}|$ and i want to prove that $d'$ and the usual metric $d(x,y)=|x-y|$ are not equivalent in the metric sense.
I proved easely that $d(x,y)\leq 2 d'(x,y)$ but i don't find an example witch give me that we can't prove  for a positive $\alpha,$ that $$\alpha~ d'(x,y)\leq d(x,y) $$ Pease help me
Thank you.

A: Let $y = 0$. Assume there is $\alpha$ so that
$$
\alpha \sqrt x \leq x
$$
for all $x$. This would mean that $\alpha \leq \sqrt x$ for all $x \in [0,1]$.

A: Set $y=0$, then you want to prove
$$\alpha\sqrt x=\alpha\,d'(x,0)\le d(x,0)=x\iff \sqrt x(\sqrt x-\alpha)\ge 0,$$
which clearly fails for $\sqrt x<\alpha$.

A more advanced way of seeing it is that for $f(x)=\sqrt x$ we have $f'_+(x)=+\infty$, so $f$ can't be Lipschitz from the right at $0$.


text:
Q: Linq Cascade Select with object generation in ef core I have an api that has the following model keep in my that this's just an exemple to get the whole idea of my problem
namespace Models{
    public class A
    {
        public int Id{get;set;}
        public List<B> Bs{get;set;}
        .
        .
    }

    public class B
    {
        public int Id{get;set;}
        public List<C> Cs{get;set;}
        .
        .
    }

    public class C
    {
        public int Id{get;set;}
        .
        .
    }
}
namespace Api{
    public class Aprime
    {
        public int Id{get;set;}
        public List<BPrime> BPrimes{get;set;}
        public int Calculation{get;set;}
        .
        .
    }

    public class Bprime
    {
        public int Id{get;set;}
        public List<CPrime> CPrimes{get;set;}
        .
        .
    }

    public class CPrime
    {
        public int Id{get;set;}
        .
        .
    }
}

I have a method that do some work and give me the result and this method work percetly in this case
public ICollection<Api.Aprime> Foo(){
    var result = query.TableA.something().Select(dataFromA=>
        new Api.Aprime
        {
            Id = dataFromA.Id,
            BPrimes = dataFromA.Bs.Where(dataFromB=> Condition).Select(dataFromB
                new Api.BPrime
                {
                    Id=dataFromB.Id,
                    CPrimes=dataFromB.Cs.Where(dataFromC=> Condition).Select(
                        new Api.CPrime()
                        {
                            Id = dataFromC.Id,
                        })
                }
            )
        }
    );
}

Everthing that exist before this work perfectly.
My problem is that, If have a method that create for exemple Bprime objectto simplify the reading of the query and code.
Thus doing so generate a NullReferenceException however it work in one case when the transformation is made in one lvl and there's no query that need a navigation inside it like the following
public ICollection<Api.Aprime> FooWithTransformation(){
    var result = query.TableA.something().Select(dataFromA=>
        new Api.Aprime
        {
            Id = dataFromA.Id,
            BPrimes = dataFromA.Bs.Where(dataFromB=> Condition).Select(dataFromB
                new Api.BPrime
                {
                    Id=dataFromB.Id,
                    CPrimes=dataFromB.Cs.Where(dataFromC=> Condition).Select(dataFromC=>dataFromC.ToCprimes()) //lvl 1
                }
            )
        }
    );
}

but I want to do is this kind of writing but it wont work in this following case because there's a navigation
public ICollection<Api.Aprime> FooWithNullExceptionInTransformation(){
    var result = query.TableA.something().Select(dataFromA=>
        new Api.Aprime
        {
            Id = dataFromA.Id,
            // Won't work because the C collection in this case is null and I got an exception
            Bs = dataFromA.Bs.Where(dataFromB=> Condition).Select(dataFromB=>dataFromB.ToBprimes())
        }
    );
}

I use ef core with an azure database


text:
Q: Plotting rows corresponding to a given y-value separately Suppose I have a table of data-
No. 200 400 600 800

1    13 14 17 18

2    16 18 20 21

3    20 15 18 19

and so on...
where each column represents a y-value for a given x-value. The first line is the x-value and the first column is the number of each dataset.
How can I read in and plot each row seperately?
For an idea of how I would like my results to be for the table I have quoted above see the following images. I have plotted each plot individually.
http://postimg.org/image/yw46zw7er/92d01c08/
http://postimg.org/image/c1kf2nqwp/29a8b1c8/

A: Matplotlib plots 2d arrays by plotting each column, so here you just need to transpose your data. Assuming the data is in a text file called data.csv.
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('data.csv')
x = [200, 400, 600, 800]
plt.plot(x, data.T)
plt.legend((1,2,3))
plt.show()


text:
Q: ASP.NET Site crashes when uploading "large" files I've got the Fileupload and I set this in my WebConfig:
 <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <customErrors mode="Off"/>
    <httpRuntime
 executionTimeout="110"
 maxRequestLength="102400"
 requestLengthDiskThreshold="80"
 useFullyQualifiedRedirectUrl="false"
 minFreeThreads="8"
 minLocalRequestFreeThreads="4"
 appRequestQueueLimit="5000"
 enableKernelOutputCache="true"
 enableVersionHeader="true"
 requireRootedSaveAsPath="true"
 enable="true"
 shutdownTimeout="90"
 delayNotificationTimeout="5"
 waitChangeNotification="0"
 maxWaitChangeNotification="0"
 enableHeaderChecking="true"
 sendCacheControlHeader="true"
 apartmentThreading="false" />
  </system.web>

that allows me, to upload 100MB files.. maxRequestLength="102400"
Now the problem is, that the site crashes, when uploading b.E a 85MB File..
It stops working on about 70% and I get an Error.. How can I solve this Problem?

A: Have you checked if the executionTimeout="110" is causing the issue? If you upload the file multiple times, will it fail at almost the same time? Try updating the executionTimeout to a higher value.


text:
Q: Split string into pair What would be the best/easiest way to split a string into pair of word ?
Ex:
string = "This is a string"
Output:
["This is", "is a", "a string"]

A: >>> import itertools
>>> a, b = itertools.tee('this is a string'.split());
>>> next(b, None)
>>> [' '.join(words) for words in zip(a, b)]
['this is', 'is a', 'a string']

A: string_list = string.split()
result = [f'{string_list[i] string_list[i+1]}' for i in range(len(string_list) - 1)]

A: words = str.split()
output = []

i = 1
while i < len(words):
    cur_word = words[i]
    prev_word = words[i - 1]

    output.append(f"{prev_word} {cur_word}")

    i += 1

A: You can use the zip function, with its first argument the whole list of words and its second the list of words without the first word. Since zip aggregates elements from each of the iterables, this will connect each word with its next in the list:
string = "This is a string"
zipped_lst = zip(string.split(), string.split()[1:])
print(list(zipped_lst))

This outputs
[('This', 'is'), ('is', 'a'), ('a', 'string')]


text:
Q: SYN packet getting no replies (Python) raw sockets Whenever I send a SYN packet using my program, I get no reply.I know the server is working because I can connect to it using the normal socket connect() method but when I try using RAW sockets to do it I get no reply, not even an RST.
Here is my packet according to Wireshark
    Transmission Control Protocol, Src Port: 5173 (5173), Dst Port: 5005 n (5005), Seq: 0, Len: 0
    Source Port: 5173
    Destination Port: 5005
    [Stream index: 15]
    [TCP Segment Len: 0]
    Sequence number: 0    (relative sequence number)
    Acknowledgment number: 0
    Header Length: 40 bytes
    Flags: 0x002 (SYN)
        000. .... .... = Reserved: Not set
        ...0 .... .... = Nonce: Not set
        .... 0... .... = Congestion Window Reduced (CWR): Not set
        .... .0.. .... = ECN-Echo: Not set
        .... ..0. .... = Urgent: Not set
        .... ...0 .... = Acknowledgment: Not set
        .... .... 0... = Push: Not set
        .... .... .0.. = Reset: Not set
        .... .... ..1. = Syn: Set
        .... .... ...0 = Fin: Not set
        [TCP Flags: **********S*]
    Window size value: 53270
    [Calculated window size: 53270]
    Checksum: 0x9f18 [incorrect, should be 0x90ae (maybe caused by "TCP checksum offload"?)]
    Urgent pointer: 0
    Options: (20 bytes), Maximum segment size, SACK permitted, Timestamps, No-Operation (NOP), Window scale
        Maximum segment size: 65495 bytes
            Kind: Maximum Segment Size (2)
            Length: 4
            MSS Value: 65495
        TCP SACK Permitted Option: True
            Kind: SACK Permitted (4)
            Length: 2
        Timestamps: TSval 378701, TSecr 0
            Kind: Time Stamp Option (8)
            Length: 10
            Timestamp value: 378701
            Timestamp echo reply: 0
        No-Operation (NOP)
            Type: 1
                0... .... = Copy on fragmentation: No
                .00. .... = Class: Control (0)
                ...0 0001 = Number: No-Operation (NOP) (1)
        Window scale: 7 (multiply by 128)
   [SEQ/ACK analysis]

And here is my Python code
#!/usr/bin/python

import socket
from struct import *
import random

s = socket.socket()
host = "127.0.0.1"
destination = "127.0.0.1"

CLRF = '\r\n'
#socket.gethostname()
print destination
port = 5173

#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#s.connect((host, 5005))

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW)
except socket.error , msg:
    print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

ipSource = '192.168.0.106'

#IP header

ipIHL = 5 # Header Length
ipVersion = 4 # ipv4/v6
ipTOS = 0 # type of service
ipTotalLen = 0 ## Kernel will fill correct length apparently
ipPackID = random.randint(1,1000)

#Flags
ipReserved = 0
ipNoFrag = 1
ipMoreFrags = 0

ipFragOffset = 0 #Fragment offset
ipTTL = 64
ipProtocol = socket.IPPROTO_TCP
ipChecksum = 0 # Magic kernel filling in at work again
ipSource = socket.inet_aton (host)
ipDest = socket.inet_aton (destination)

#Packing IP flags
ipFlags = ipMoreFrags + (ipNoFrag << 1) + (ipReserved << 2)
ipFragOffset = (ipFlags << 13) + ipFragOffset

ipIHLVersion  = (ipVersion << 4) + ipIHL

headerIP = pack('!BBHHHBBH4s4s',ipIHLVersion, ipTOS, ipTotalLen, ipPackID, ipFragOffset,  ipTTL, ipProtocol, ipChecksum, ipSource, ipDest)

#Checksum function
def carry_around_add(a, b):
    c = a + b
    return (c & 0xffff) + (c >> 16)

def checksum(msg):
    s = 0
    for i in range(0, len(msg), 2):
        w = ord(msg[i]) + (ord(msg[i+1]) << 8)
        s = carry_around_add(s, w)
    return ~s & 0xffff

#TCP Header
tcpSourcePort = port #Source Port
tcpDestPort = 5005 #Destination Port
tcpSeqNum = 0 #Packet sequence
tcpAckNum = 0 #Ackknowledge Number
tcpOffset = 10 #Size of tcp header 20 bytes
#tcpReserved = 0
#tcpECN = 0
#Control Flags
tcpURG = 0
tcpACK = 0
tcpPSH = 0
tcpRST = 0
tcpSYN = 1
tcpFIN = 0
tcpWindow = socket.htons (5840) #Dunno how this works
tcpChecksum = 0
tcpUrgentPointer = 0
#TCP Options
tcpMaxSegmentSize = (2 << 24) + (4 << 16) + 65495 # Kind + Length + Max Segment Size
tcpSACKPermitted  = (4 << 8) + 2#Kind + Length
#Split TCP TImestamps into 2 because too large

tcpTimestampPartOne = (8 << 8) + (10) #Kind + Length
tcpTimestampPartTwo = (378701 << 32) + 0 #Timestamp Value + Timestamp echo reply
tcpNoOp = (0 << 7) + (0 << 5) + 1 #Copy on fragmentation + Class + Number
tcpWindowScale = (3 << 16)+ (3 << 8) + 7 #Kind + Length(Bytes) +Shift CountS

#Combine both due to length issues
tcpNoOpAndWindowScale = (tcpNoOp << 24) + tcpWindowScale

tcpOffsetResult = (tcpOffset << 4) + 0 #Shift 4 bytes to left

#Putting together all the TCP Control Flags
tcpFlags = tcpFIN + (tcpSYN << 1) + (tcpRST << 2) + (tcpPSH << 3) + (tcpACK << 4) + (tcpURG << 5)

#Packing the pseudo TCP header
headerTCP = pack('!HHLLBBHHHLHHQL', tcpSourcePort, tcpDestPort, tcpSeqNum, tcpAckNum, tcpOffsetResult, tcpFlags, tcpWindow, tcpChecksum, tcpUrgentPointer, tcpMaxSegmentSize, tcpSACKPermitted, tcpTimestampPartOne, tcpTimestampPartTwo, tcpNoOpAndWindowScale)

#headerTCP = pack('!HHLLBBHHH', tcpSourcePort, tcpDestPort, tcpSeqNum, tcpAckNum, tcpOffsetResult, tcpFlags, tcpWindow, tcpChecksum, tcpUrgentPointer)

#data = 'GET ./asd HTTP/1.1'
data = ''

#Checksum Calculation
#Pseudo Header Fields
sourceAddr = socket.inet_aton(host)
destAddr = socket.inet_aton(destination)
placeholder = 0
protocol = socket.IPPROTO_TCP
tcpLen = len(headerTCP) + len(data)

psh = pack('!4s4sBBH', sourceAddr, destAddr, placeholder, protocol, tcpLen);
psh = psh + headerTCP + data;

#Calc checksum
tcpChecksumReal = (checksum(psh) << 1)

print(tcpChecksumReal)

#Pack actual tcp header with checksum
headerTCP = pack('!HHLLBBH', tcpSourcePort, tcpDestPort, tcpSeqNum, tcpAckNum, tcpOffsetResult, tcpFlags, tcpWindow) + pack('!H', 40728) + pack ('!H', tcpUrgentPointer) + pack('!LHHQL', tcpMaxSegmentSize, tcpSACKPermitted, tcpTimestampPartOne, tcpTimestampPartTwo, tcpNoOpAndWindowScale)

#Build full packet / ip with tcp with data
packet = headerIP + headerTCP + data
#print [hex(ord(c)) for c in packet]
s.sendto(packet, (destination,0))

Any help would be appreciated, thanks in advance.

A: Credits to @KenCheung for the answer
Turns out it was the checksum, the checksum from the headers I used as reference also were incorrect but the network card was offloading them.


text:
Q: Run Jasmine tests after initial function calls I'm writing Jasmine tests for a Node.js API.  I'm trying to test the create a user functionality.  The test would look like this:
describe('User test', function() {
  describe('Post /api/saveUser'), function() {
    it('saves a new user', function(done) {
      request.post({url: 'http://website/api/saveUser', form:{email:testU.email, password:testU.password}, headers: {'authorization': adminU.jwt}}, function(err, res, body) {
        expect(res.statusCode).toBe(200);
      });
    });
  });
});

So I need to authenticate the admin user (adminU) in the spec to get the valid token to pass in the request.  This is done using another endpoint.
request.post({url: 'http://website/api/authenticate', form:{email:adminU.email, password: adminU.password}}, function(err, res, body) {
  adminUser.jwt = JSON.parse(res.body).token;
});

But how do I combine these.  If I slot the authentication code above the User test block, the user tests are run before the response from the authentication endpoint is received.  The obvious choice is to wrap the user tests in the callback from the authenticate api, but then when I run the tests Jasmine doesn't actually run them.
What's the best way to use the results of a callback in the Jasmine specs?

A: You need to wait until the request of the auth call is finished.
it('saves a new user', function(done) {
    request.post({
        url: 'http://website/api/authenticate',
        form: {
            email: adminU.email,
            password: adminU.password
        }
    }, function(err, res, body) {
        adminUser.jwt = JSON.parse(res.body).token;
        request.post({
            url: 'http://website/api/saveUser',
            form: {
                email: testU.email,
                password: testU.password
            },
            headers: {
                'authorization': adminU.jwt
            }
        }, function(err, res, body) {
            expect(res.statusCode).toBe(200);
            done();
        });
    });
});

If you need the token in more then one test, i would recommend to put it in the before block. If you do this, jasmine runs this once before starting the test and you don't have to make the auth call in every test case.
before(function(done){
    request.post({
        url: 'http://website/api/authenticate',
        form: {
            email: adminU.email,
            password: adminU.password
        }
    }, function(err, res, body) {
        if(err) done(err);
        adminUser.jwt = JSON.parse(res.body).token;
        done();
    });
});

Also, i recommend supertest for testing apis. See https://www.npmjs.com/package/supertest


text:
Q: calling a base class method in the child class python What is going on. I have looked at other solutions on stack overflow but non seem to work from what I have seen. I have a base object with a method that changes the value of the base attribute. When I call the base function in a child class (Inheritance) I get that the child class does not have the attribute "baseAttribute"
class GameObject(object):
 #This is the base class for gameObjects
 def __init__(self):
     self.components = {}

 def addComponent(self, comp):
     self.components[0] = comp #ignore the index. Placed 0 just for illustration

class Circle(GameObject):
 #circle game object
 def __init__(self):
     super(GameObject,self).__init__()
     #PROBLEM STATEMENT
     self.addComponent(AComponentObject())
     #or super(GameObject,self).addComponent(self,AComponentObject())
     #or GameObject.addComponent(self, AComponentObject())

EDIT:
Apologies, I never originally passed in a self.

A: Simple - leave out the second self:
self.addComponent(AComponentObject())

You see, the above actually translates to
addComponent(self, AComponentObject())

In other words: in essence "OO" works on functions that have an implicit this/self pointer (however you name that) as  argument.

A: You are using incorrect arguments for .addComponent() method.
# ...

class Circle(GameObject):

 def __init__(self):
     super(GameObject,self).__init__()
     # NOT A PROBLEM STATEMENT ANYMORE
     self.addComponent(AComponentObject())
     # ...


text:
Q: Are there 1:M Recursive relationships in the StackExchange Database? I'm looking for a 1 to many recursive relationship in the Stack Exchange Database. I'm querying it here https://data.stackexchange.com/math/queries. I don't see any 1 to many recursive relationships. The closest I've found is the relationship between posts and the parent of posts (both columns in the Posts table). I suppose that's still a 1:M recursive relationship, but it only goes 1 level deep, because there are no posts that are parents of one post, but children of a different post.
Can anyone point me to a 1 to many recursive relationship in this database?
Thanks,
ET


text:
Q: Why my Graph API / cancel outlook meetings call returns always 404 error I am trying to get all events associated with a user (in order to cancel them). Here is the API doc
I am able through Powershell and Graph API to see a user, and also to sign out this user with the API.
I am using a token got from oauth2 protocol, with grant type client_credentials. I put the permission "Calendars.ReadWrite".
But I only get 404 errors when trying to get the events with :
Invoke-WebRequest 'https://graph.microsoft.com/v1.0/users/864abe35-a43f-44c3-9d24-ea7d2ce53907/events' -ContentType 'application/json' -Method Get -Headers @{Authorization = "Bearer $token"}

This strange thing is that I can get the user array, or revoke his session...
Do this endpoint not working ?
Thank you
EDIT : Answer was that when a user does not have mailboxes, events URL does not exist, and lead to a 404. It works with user having mailbox.

A: Please provide the full response (with error message etc.).

*

*Have you granted admin consent to Calendars.Write?
In the azure portal, go to Home > App registrations > your app registration and then click on "API permissions". I don't think this is the issue but better to be safe than not. I would rather expect a 403 Forbidden if this is the problem.

*Are you sure that the guid of the user is correct? Check if the user with this Id exists in your tenant.

*Has the user a valid licence?

*Check if the user has a calendar. Use Get calendar.

*Maybe the user has only group calendar(s). If this is the case, you need Group.Read.All or Group.ReadWrite.All.

*Try to get oulook meetings from a user where you are sure that he has a calendar.

A: Finally, it appeared that the accounts who do not have any exchange mailbox will not result with an empty return, but with an unexisting URL (that's explains the 404).
It works with an account which holds a mailbox.


text:
Q: Active Directory scanning and role mapping I am running JBPM in JBoss Wildfly 8 and this is configured to use Active Directory Authentication. The configuration is as follows:
<security-domain name="jbpm_ldap_domain">
    <authentication>
        <login-module code="LdapExtended" flag="required">
            <module-option name="java.naming.factory.initial" value="com.sun.jndi.ldap.LdapCtxFactory"/>
            <module-option name="java.naming.provider.url" value="ldap://serverIP"/>
            <module-option name="java.naming.security.authentication" value="simple" />
            <module-option name="bindDN" value="CN=Administrator,CN=Users,DC=domain,DC=com"/>
            <module-option name="bindCredential" value="secretpass"/>
            <module-option name="baseCtxDN" value="OU=MYOU,DC=domain,DC=com"/>
            <module-option name="baseFilter" value="(sAMAccountName={0})"/>
            <module-option name="rolesCtxDN" value="ou=MYOU,dc=domain,dc=com"/>
            <module-option name="roleFilter" value="(member={1})"/>
            <module-option name="roleAttributeID" value="memberOf"/>
            <module-option name="roleAttributeIsDN" value="true"/>
            <module-option name="roleNameAttributeID" value="cn"/>
            <module-option name="allowEmptyPasswords" value="false"/>
            <module-option name="throwValidateError" value="true"/>
        </login-module>
        <login-module code="RoleMapping" flag="optional">
            <module-option name="rolesProperties" value="file:${jboss.home.dir}/standalone/configuration/jbpm-roles.properties"/>
            <module-option name="replaceRole" value="true"/>
        </login-module>
    </authentication>
</security-domain>

jbpm-roles.properties:
BPM_ADMIN=admin
BPM_ANALYST=analyst
BPM_DEVELOPER=developer
BPM_USER=user
BPM_MANAGER=manager

So as of now I am scanning a specific OU for roles and user scanning.
I want to do it the following way:

*

*Scan complete domain for users.

*scan role group in an OU.

*user with specific group membership should get admin rights (BPM_ADMIN=admin)

*rest all users should have 'user' role.

I do not want to add all users to a group to give them the user role in JBPM. Instead I want to set the default role as user and if I need to grant admin role I will add the user to the group I have defined for admin users in Active Directory (BPM_ADMIN=admin)
How can this be achieved?


text:
Q: A paper of Jean Bourgain accessible to an undergraduate? The title is pretty much the question : the acclaimed mathematician Jean Bourgain recently passed away, there is a tribute on the blog of Terry Tao.
Apparently, most of his papers are deep and technical, but :

what are some of his  most accessible ones, say in the broad area of real analysis/functional analysis (after following an advanced course like Brezis' book) ?
[edit:] or indeed in any other area, if it is more suitable.

Many thanks!


text:
Q: How to recover journal superblock on mdadm RAID5 array Yesterday my raid5 array with 3 disks was suddenly unmounted. After examining it, it seemed it had become degraded and one of the disks had a much lower event count than the rest.
I started running: sudo mdadm --assemble --force /dev/md0 /dev/sd[bcd]1 - however, I made a mistake: at the time I ran the command, the /dev/sdb disk was named /dev/sde, so the command was run against /dev/sdc1 and /dev/sdd1 only. The command reset the lowest event count disk to the highest count of the two (it was a diff of 600 events, I think). Which surprised me, as in the past IIRC, --force would not reset the event count for large diffs.
In the end, I ended up syncing the remaining disk (which was not the one with the lowest event count) with sudo mdadm /dev/md0 --add /dev/sdb1, as I've had to do a few of times in the past. The syncing finished after a couple of hours as expected, without errors. But ever since then, I've not been able to mount the array.
Here are the details of this system:
OS:
lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 19.10
Release:    19.10
Codename:   eoan

RAID array
sudo mdadm --detail /dev/md0
/dev/md0:
           Version : 1.2
     Creation Time : Thu Apr  4 23:46:03 2019
        Raid Level : raid5
        Array Size : 1953257472 (1862.77 GiB 2000.14 GB)
     Used Dev Size : 976628736 (931.39 GiB 1000.07 GB)
      Raid Devices : 3
     Total Devices : 3
       Persistence : Superblock is persistent

     Intent Bitmap : Internal

       Update Time : Thu Feb  6 13:16:05 2020
             State : clean
    Active Devices : 3
   Working Devices : 3
    Failed Devices : 0
     Spare Devices : 0

            Layout : left-symmetric
        Chunk Size : 64K

Consistency Policy : bitmap

              Name : pc:0  (local to host pc)
              UUID : 96c2bb9a:8318792c:843e1e85:820cd123
            Events : 21280

    Number   Major   Minor   RaidDevice State
       5       8       17        0      active sync   /dev/sdb1
       4       8       33        1      active sync   /dev/sdc1
       3       8       49        2      active sync   /dev/sdd1

cat /proc/mdstat
Personalities : [raid6] [raid5] [raid4] [linear] [multipath] [raid0] [raid1] [raid10]
md0 : active raid5 sdc1[4] sdd1[3] sdb1[5]
      1953257472 blocks super 1.2 level 5, 64k chunk, algorithm 2 [3/3] [UUU]
      bitmap: 0/8 pages [0KB], 65536KB chunk

Relevant part of lsblk -f:
sdb
└─sdb1                  linux_raid_member pc:0 96c2bb9a-8318-792c-843e-1e85820cd123
  └─md0                 ext4              RaidData 88936c12-1664-4d4d-9d33-8aabd1efe0ab
sdc
└─sdc1                  linux_raid_member pc:0 96c2bb9a-8318-792c-843e-1e85820cd123
  └─md0                 ext4              RaidData 88936c12-1664-4d4d-9d33-8aabd1efe0ab
sdd
└─sdd1                  linux_raid_member pc:0 96c2bb9a-8318-792c-843e-1e85820cd123
  └─md0                 ext4              RaidData 88936c12-1664-4d4d-9d33-8aabd1efe0ab

Relevant output from the lsdrv tool:
PCI [ahci] 00:1f.2 SATA controller: Intel Corporation 7 Series/C210 Series Chipset Family 6-port SATA Controller [AHCI mode] (rev 04)
│
├scsi 1:0:0:0 ATA      WDC WD10EZEX-08W
│└sdb 931.51g [8:16] Empty/Unknown
│ └sdb1 931.51g [8:17] Empty/Unknown
│  └md0 1.82t [9:0] MD v1.2 raid5 (3) clean, 64k Chunk {None}
│                   Empty/Unknown
├scsi 2:0:0:0 ATA      WDC WD10EZRZ-22H
│└sdc 931.51g [8:32] Empty/Unknown
│ └sdc1 931.51g [8:33] Empty/Unknown
│  └md0 1.82t [9:0] MD v1.2 raid5 (3) clean, 64k Chunk {None}
│                   Empty/Unknown
└scsi 3:0:0:0 ATA      WDC WD10EZEX-00K
 └sdd 931.51g [8:48] Empty/Unknown
  └sdd1 931.51g [8:49] Empty/Unknown
   └md0 1.82t [9:0] MD v1.2 raid5 (3) clean, 64k Chunk {None}
                    Empty/Unknown

RAID member status:
sudo mdadm --examine /dev/sd[bcd]
/dev/sdb:
   MBR Magic : aa55
Partition[0] :   1953521664 sectors at         2048 (type 83)
/dev/sdc:
   MBR Magic : aa55
Partition[0] :   1953521664 sectors at         2048 (type 83)
/dev/sdd:
   MBR Magic : aa55
Partition[0] :   1953521664 sectors at         2048 (type 83)

Error while trying to mount, not sure what the error means:
sudo mount /dev/md0
mount: /media/dpm/Dades: mount(2) system call failed: Structure needs cleaning.

Superblock seems to be corrupted?:
sudo e2fsck -v /dev/md0
e2fsck 1.45.3 (14-Jul-2019)
Journal superblock is corrupt.
Fix<y>? cancelled!
e2fsck: The journal superblock is corrupt while checking journal for RaidData
e2fsck: Cannot proceed with file system check

RaidData: ********** WARNING: Filesystem still has errors **********

I'm not too sure what fsck will do or if it's safe to run it at this point. Any advice will be greatly appreciated, thanks!


text:
Q: Unable to connect to Windows 8 created network When hosting a WPA2 infrastructure network on my Windows 8 PC (though this happened on XP for me too, but I do not have that computer anymore), I am only able to connect the first device (iPhone) attempted. When trying to connect a different device or the same one after disconnecting from the network, it will not assign any IP or fill any other forms (router, DNS, so on...) through DHCP and displays unable to join network.
Originally, I was using the program Connectify, but this was not the problem because when trying to do the same thing through the command line, I got the same results.
I was hoping not to have to assign static IP addresses to each device as a alternative, but (any?) alternative suggested I'll attempt.
Thank you for the help!

A: You do not provide enough information about your current setup, so I have to go on a few assumptions, namely a standard setup with a LAN and WLAN adapter, a reasonably up-to-date- MS Windows 8 PC and no 3rd party firewalls, etc. I would ask, but I'm not allowed to post comments yet ;)
First off, you should run netsh wlan show driver to see if your driver supports SoftAPs. If not, hunt for a more recent driver.
Second, you need to enable ICS on the hardware NIC connected to your (W)LAN and you need to select the "virtual wifi adapter" provided by MS for the "home networking connection". I don't know why the screenshot in the how-to is missing this option.
Third, if you are missing the virtual wifi NIC, check if it is disabled. If so, enable it. If the virtual wifi adapter is missing completely you need to remove and reinstall your wifi NIC drivers. MS Windows should then automatically also install the virtual wifi NIC.
Here is what MS has to say about this issue: http://msdn.microsoft.com/en-us/library/dd815243%28v=VS.85%29.aspx

A: Have you tried Virtual WiFi Hotspot?

Virtual Wifi Hotspot turns any Windows 7 and Windows 8 computer into a Wifi Hotspot using Wireless hosted network technology.
Virtual Wifi Hotspot is a free, open source software based router for PCs running Windows 7, Windows 8, Windows Server 2008 R2 and Windows Server 2012. Using Virtual Wifi Hotspot, users can wirelessly share any internet connection (Wifi, LAN, Cable Modem, Dial-up, Cellular, etc.) with any Wifi device (Laptop, Smart Phone, iPod Touch, iPhone, Android Phone, Zune, Netbook, wireless printer, etc.) These devices connect to Virtual Wifi Hotspot just like any other access point, and the connection is completely secured using WPA2 (the most secure wireless encryption.)


text:
Q: Refresh div content after OnGet method in Razor Pages I've got 1 data in view which is assign in OnGet method as a ViewData.
OnGet method:
public void OnGet(string parameter = "default")
{
    ViewData["SelectedParam"] = parameter;
}

My View:
@{
    var selectedParam= ViewData["SelectedParam"];
}

Some Page

            @await Component.InvokeAsync("MyComponent")

            @selectedParam

            @if (string.IsNullOrEmpty(selectedParam.ToString()))
            {

No param selected

            }
            else
            {

@selectedParam selected

            }

My component is sending parameter, View is changing value of ViewData["SelectedParam"] and now I want to refresh the content of a div.
JQuery:
$(document).on('click', 'componentElement', function () {
    var parameterResult = "test";
    $.ajax({
        url: '/Index',
        type: 'get',
        data: {
            parameter: parameterResult
        },
        success: function () {

        }
    });
});

I tried to do location.reload(), but I must refresh only this div, not the whole page, tried also with $('#mainDiv').load(' #mainDiv'), but still nothing

A: Razor evaluates the View and creates the HTML the client sees. If you examine the source code on Chrome for example, you'll notice all your Razor code was replaced with standard HTML.
If you want to modify the HTML after the page already loaded, you have 2 options. Reload page with new data, so new HTML will be created and the new conditions will be reevaluated, or use JS / JQuery to modify the page on the client side. JQuery won't have access to the ViewData though, this is pure HTML / JS. Since you don't want to reload the page, that's the only way.
Example of JQuery function that removes and adds stuff from the HTML:
$(document).on('click', 'componentElement', function () {
    var parameterResult = "test";
    $.ajax({
        url: '/Home/OnGet/', //assuming controller would be Home
        type: 'POST', //if you are sending data, it's a POST
        dataType: "Json", //specify the datatype you are sending
        data: {
            parameter: parameterResult
        },
        success: function (obj) { //notice I'm expecting an object back here
            $( "#mainDiv" ).empty(); //this will clear all the children inside the mainDiv
            $( "#mainDiv" ).append("<h5<" + obj + " selected
"); //this will add back the string you get your OnGet
        }
    });
});

And here is how your OnGet should be to respond to the ajax request:
public JsonResult OnGet(string parameter = "default") //I'll return a Json, so class needs to be JsonResult
{
    return Json(parameter);
}


text:
Q: incorporate user messaging using firebase and swift So I am trying to find a way to incorporate a messaging feature within an app. I cannot find any up to date information on the web, so I figured I'll ask on this platform. Can someone guide me in the right direction?
I am currently using firebase and swift as building tool for my app. I am looking to build a simple chat/messaging function where users can message each other like instagram, facebook and airbnb allows users to do.

A: Firebase provides realtime database for chatting feature and many other features where you need data updates in realtime.
You can refer to https://firebase.google.com/docs/database/ios/lists-of-data where it shows you can handle child-added, child-changed event for realtime updates.
You will have to design your database to incorporate chats in it though and then write business logics to handle it through firebase realtime apis.


text:
Q: YOLOv5: Basic Architecture - Where to find? Has anybody come across a legit figure of the basic architecture of YOLOv5 (Ultralytics)? I found the below image in one study, but don't seem to be able to verify whether it's a valid depiction of the base architecture of the model.

A: This one looks correct for YOLOv5 release v4.0.
https://github.com/ultralytics/yolov5/issues/280#issuecomment-774578839


text:
Q: Rails Administrate - How to Customize Navigation Link Text In administrate if I have a model called parentequipmenttype how to I customize the Navigation link to display as "Parent Equipment Type" instead of listing as parentequipmenttype?

A: You will need to customize app/dashboards/parentequipmenttype_dashboard.rb file.
require "administrate/custom_dashboard"

class ParentequipmenttypeDashboard < Administrate::CustomDashboard
  resource "Parent Equipment Type"
end


text:
Q: Using Now() for Foreign Countries I'm trying to convert different date formats into an appropriate SQL DateTime format and am getting errors.
I have a client's machine that is setup with the following date format, "dd-mm-yyyy" (Localization is India)
When using Now() within VB.Net it parses the month and days backwards. I've tried the following code but get conversion errors.
    Dim Month As String = Nothing
    Dim Year As String = Nothing
    Dim Day As String = Nothing
    Dim Hour As String = Nothing
    Dim Minute As String = Nothing
    Dim Second As String = Nothing
    Dim strDate As String = Nothing
    Dim Date_to_SQL_DateTime As Date

    Month = DatePart(DateInterval.Month, Now()).ToString
    Year = DatePart(DateInterval.Year, Now())
    Day = DatePart(DateInterval.Day, Now())
    Hour = DatePart(DateInterval.Hour, Now())
    Minute = DatePart(DateInterval.Minute, Now())
    Second = DatePart(DateInterval.Second, Now())

    strDate = Month & "/" & Day & "/" & Year & " " & Hour & ":" & Minute & ":" & Second

    Date_to_SQL_DateTime = Date.ParseExact(strDate, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture)

strDate returns
1/24/2017 23:17

Error I'm receiving is
String was not recognized as a valid Datetime

A: Try below. Need to make sure parameters are of same format as specified in the ParseExact function.
Dim Month As String = Nothing
Dim Year As String = Nothing
Dim Day As String = Nothing
Dim Hour As String = Nothing
Dim Minute As String = Nothing
Dim Second As String = Nothing
Dim strDate As String = Nothing
Dim Date_to_SQL_DateTime As Date

Month = DatePart(DateInterval.Month, Now()).ToString("00")
Year = DatePart(DateInterval.Year, Now()).ToString("0000")
Day = DatePart(DateInterval.Day, Now()).ToString("00")
Hour = DatePart(DateInterval.Hour, Now()).ToString("00")
Minute = DatePart(DateInterval.Minute, Now()).ToString("00")
Second = DatePart(DateInterval.Second, Now()).ToString("00")

strDate = Month & "/" & Day & "/" & Year & " " & Hour & ":" & Minute & ":" & Second
Date_to_SQL_DateTime = DateTime.ParseExact(strDate, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture)


text:
Q: Automatically generating table of IP addresses? I currently have a directory on my website of all possible IP addresses.  Over the past year it's been pulling the information from a MySQL database, but obviously it's an enormous database to be pulling information from.
I was thinking that since all IP addresses are between 0.0.0.0 to 255.255.255.255 there should be a way to have the database automatically generated without using a database and just based on the page that the person is on.
Each page shows 1002 IP addresses, so the first page would should the first 1-1002 possible IP addresses, the second page would show 1003-2004 IP addresses.
Here's the code I'm currently using for the site:
<?php
    /*
        Place code to connect to your DB here.
    */

 mysql_connect("localhost", "user_name", "password") or die(mysql_error());
 mysql_select_db("data_base") or die(mysql_error());

    $tbl_name="domain_names";       //your table name
    // How many adjacent pages should be shown on each side?
    $adjacents = 5;

    /*
       First get total number of rows in data table.
       If you have a WHERE clause in your query, make sure you mirror it here.
    */
    $query = "SELECT COUNT(*) as num FROM $tbl_name";
    $total_pages = mysql_fetch_array(mysql_query($query));
    $total_pages = $total_pages[num];

    /* Setup vars for query. */
    $targetpage = "ip.php";   //your file name  (the name of this file)
    $limit = 1002;                              //how many items to show per page
    $page = $_GET['page'];
    if($page)
        $start = ($page - 1) * $limit;          //first item to display on this page
    else
        $start = 0;                             //if no page var is given, set start to 0

    /* Get data. */
    $sql = "SELECT domains FROM $tbl_name LIMIT $start, $limit";
    $result = mysql_query($sql);

    /* Setup page vars for display. */
    if ($page == 0) $page = 1;                  //if no page var is given, default to 1.
    $prev = $page - 1;                          //previous page is page - 1
    $next = $page + 1;                          //next page is page + 1
    $lastpage = ceil($total_pages/$limit);      //lastpage is = total pages / items per page, rounded up.
    $lpm1 = $lastpage - 1;                      //last page minus 1

    /*
        Now we apply our rules and draw the pagination object.
        We're actually saving the code to a variable in case we want to draw it more than once.
    */
    $pagination = "";
    if($lastpage > 1)
    {
        $pagination .= "
";
        //previous button
        if ($page > 1)
            $pagination.= "< previous";
        else
            $pagination.= "< previous";

        //pages
        if ($lastpage < 7 + ($adjacents * 2))   //not enough pages to bother breaking it up
        {
            for ($counter = 1; $counter <= $lastpage; $counter++)
            {
                if ($counter == $page)
                    $pagination.= "$counter";
                else
                    $pagination.= "$counter";
            }
        }
        elseif($lastpage > 5 + ($adjacents * 2))    //enough pages to hide some
        {
            //close to beginning; only hide later pages
            if($page < 1 + ($adjacents * 2))
            {
                for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "$counter";
                    else
                        $pagination.= "$counter";
                }
                $pagination.= "...";
                $pagination.= "$lpm1";
                $pagination.= "$lastpage";
            }
            //in middle; hide some front and some back
            elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
            {
                $pagination.= "1";
                $pagination.= "2";
                $pagination.= "...";
                for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "$counter";
                    else
                        $pagination.= "$counter";
                }
                $pagination.= "...";
                $pagination.= "$lpm1";
                $pagination.= "$lastpage";
            }
            //close to end; only hide early pages
            else
            {
                $pagination.= "1";
                $pagination.= "2";
                $pagination.= "...";
                for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
                {
                    if ($counter == $page)
                        $pagination.= "$counter";
                    else
                        $pagination.= "$counter";
                }
            }
        }

        //next button
        if ($page < $counter - 1)
            $pagination.= "next >";
        else
            $pagination.= "next >";
        $pagination.= "
\n";
    }
?>

    <?php
$i = 0;
echo '

';
        while($row = mysql_fetch_array($result))
{
    $i ++;
    if ($i<=3)
    {
      echo '

'.strtolower($row[domains]).'

       	';
    }

    else
    {
      echo '

';
      echo '
'.strtolower($row[domains]).'
	';
      $i = 0;
    $i++;
   }
}
echo '

';
    ?>

<?=$pagination?>

Is what I'm thinking possible to do and is there an easy way that someone can think to do it?  It seems like it should be as simple as removing any code related to the database and then basing the numbers off which page that someone is on...
Any help with this would be really appreciated.

A: IPv4 addresses are actually just 32bit integers. You could work with integers and use long2ip to convert them in 'ip format'.
You begin the page at number ([pagenumber] * [pagesize]), iterate over [pagesize] numbers and print them with long2ip.
Possible pitfalls:
You should be ok on a 64bit system - on a 32bit system, you would have to handle 'negative' numbers.
Depending on your use case, please also consider that not ALL possible addresses might actually be legit. There are the so-called private ranges (unrouted), multicast etc.

A: Something along these lines would make this easier.
$perPage = 1002;

$i = ($page - 1 ) * $perPage;
$end = $page * $perPage;

while($i < $end ) {

    $dotIP = long2ip((float)$i);

    // Do something with $dotIP;
}


text:
Q: easy tcp socket no receive Ok, I want to communicate to a python script to send data and receive an answer, but my script doesn't work. Here is the code:
Socket socket = new Socket("192.168.178.25",5005);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DataInputStream DIS = new DataInputStream(socket.getInputStream());
DOS.writeUTF("Dies ist ein Test");
String text = DIS.readUTF().toString();
Toast.makeText(getApplicationContext(), text, 0).show();socket.close();

Send Text are alright...but I cannot receive the data.

A: writeUTF() and readUTF() can't 'communicate to a Python script': only with each other. See the Javadoc.
You may need to read and write lines.


text:
Q: Deserializing XML into objects I have the following XML which I need to deserialize:
<?xml version="1.0" encoding="UTF-8" ?>
<event code="2wuj0ticofhzt" self="/events/2wuj0ticofhzt" revision="1260234836">
  <name>Test Event 2013</name>
  <partner-settings>
    <partner-setting>
      <registration-type code="1yfopbwhk" link="/registration-types/1yfopbwhk" />
        <personnel code="3eclag1dsrjfi">
          <free-badges>unlimited</free-badges>
        </personnel>
        <personnel code="0nxgc6mfec8yh">
          <free-badges>3</free-badges>
       </personnel>
     </partner-setting>
     <partner-setting>
       <registration-type code="1ygg67prw" link="/registration-types/1ygg67prw" />
     </partner-setting>
   </partner-settings>
</event>

Here are my classes that I have created. (I only need to deserialize the fields I have in my classes.):
[XmlRoot("event")]
public class Event
{
    [XmlAttribute("code")]
    public string Code { get; set; }

    [XmlAttribute("name")]
    public string EventName { get; set; }

    [XmlArray("partner-settings")]
    public List<PartnerSetting> PartnerSettings { get; set; }
}

[XmlType("partner-setting")]
public class PartnerSetting
{
    [XmlElement("registration-type")]
    public RegistrationType RegistrationType { get; set; }

    [XmlArray("personnel")]
    public List<Personnel> Personnel { get; set; }
}

[XmlRoot("registration-type")]
public class RegistrationType
{
    [XmlAttribute("code")]
    public string Code { get; set; }

    [XmlAttribute("name")]
    public string RegistrationTypeName { get; set; }

    [XmlElement("type")]
    public string Type { get; set; }
}

[XmlType("personnel")]
public class Personnel
{
    [XmlAttribute("code")]
    public string Code { get; set; }

    [XmlElement("free-badges")]
    public int FreeBadges { get; set; }
}

When I currently deserialize the above XML it all works except from the Personnel object where I get 0 returned when I'm expecting to see 2.
I'm not doing anything differently when I'm trying to return a personnel list (i.e. XMLArray attribute, return a List) to a partner setting list but for some reason it won't deserialize.

A: You need to change the attribute into XmlElement to force each element in the list to be rendered as a single XML element:
[XmlElement("personnel")]
public List<Personnel> Personnel { get; set; }


text:
Q: Selecting specific rows based on values in 2 columns in R I have a large data set of GPS collar locations that have a varying number of locations each day. I want to separate out only the days that have a single location collected and make a new data frame containing all their information.
month    day    easting    northing    time    ID
  6       1     #######    ########    0:00    ##
  6       2     #######    ########    6:00    ##
  6       2     #######    ########    0:00    ##
  6       3     #######    ########    18:00   ##
  6       3     #######    ########    12:00   ##
  6       4     #######    ########    0:00    ##
  6       5     #######    ########    6:00    ##

Currently I have hashed together something, but can't quite get to the next step.
library(plyr)
dog<-count(data1,vars=c("MONTH","day"))
datasub1<-subset(dog,freq==1)

This gives me a readout that looks like
    MONTH day freq
1       6  29    1
7       7   5    1
8       7   6    1
10      7   8    1
12      7  10    1

I am trying to use the values of the Month and day to pull out the rows that contain them from the main dataset so that I can make a data frame containing only the points with a frequency of 1 but that contains all the associated data. I've got to this point:
sis<-c(datasub1$MONTH)
bro<-c(datasub1$day)
datasub2<-subset(data1,MONTH==sis&day==bro)

... but that doesn't give me anything, personally it makes intuitive sense (R beginner) that it should subset out the rows that contain both the values of bro and sis.
Any help would be greatly appreciated.

A: Revised:
datasub2<-subset(data1, paste(month,day,sep=".") %in% paste(datasub1$MONTH, datasub1$day,sep=".") )

It's not very likely (and quite possibly impossible) that any particular MONTH item will exactly equal that subset. You are presumably more interested in whether a combo of "Month.Day" is  in the combo sets of "Month.Day" in the datasub1. You have mixed up the capitalization that returns from the count() function if the headers were as you illustrated.
> dog
  month day freq
1     6   1    1
2     6   2    2
3     6   3    2
4     6   4    1
5     6   5    1
> datasub1
  month day freq
1     6   1    1
4     6   4    1
5     6   5    1
> datasub2
  month day easting northing time ID
1     6   1 ####### ######## 0:00 ##
6     6   4 ####### ######## 0:00 ##
7     6   5 ####### ######## 6:00 ##

A: After this:
library(plyr)
dog<-count(data1,vars=c("MONTH","day"))

try this:
indx = which(dog$freq==1)
data1[indx,]

A: data1[rownames(datasub1), ]

This is an extension of the OP's original thinking but may not be what they're after and is really just what Wesley suggested but carrying the OP's original steps one more forward (minus the bro sis part which confused me a bit because...well for the same reason DWin said :)).  You're after the rownames not really the values in those columns.  You've already got that information.  The row names carry that information back to the original data set.
n <- 100
data1 <- data.frame(
    Accuracy = round(runif(n, 0, 5), 1),
    MONTH    = sample(1:5, n, replace=TRUE),
    day      = sample(1:28, n, replace=TRUE),
    Easting  = rnorm(n),
    Northing = rnorm(n),
    Etc      = rnorm(n)
)

library(plyr)
dog<-count(data1,vars=c("MONTH","day"))
datasub1<-subset(dog,freq==1)

data1[rownames(datasub1), ]


text:
Q: Inheriting XML files and modifying values This is a question about concept.
I have an XML file, let's call it base:
<base id="default">
    <tags>
        <tag>tag_one</tag>
        <tag>tag_two</tag>
        <tag>tag_three</tag>
    </tags>
    <data>
        <data_a>blue</data_a>
        <data_b>3</data_b>
    </data>
</base>

What I want to do is to be able to extend this XML in another file, modifying individual properties. For example, I want to inherit that file and make a new one with a different data/data_a node:
<base id="green" import="default">
    <data>
        <data_a>green</data_a>
    </data>
</base>

So far it's pretty simple, it replaces the old data/data_a with the new one. I even can add a new node:
<base id="ext" import="default">
    <moredata>
        <data>extended version</data>
    </moredata>
</base>

And still it's pretty simple. The problem comes when I want to delete a node or deal with XML Lists (like the tags node).
How should I reference a particular index on a list? I was thinking doing something like:
<base id="diffList" import="default">
    <tags>
        <tag index="1">this is not anymore tag_two</tag>
    </tags>
</base>

And for deleting a node / array index:
<base id="deleting" import="default">
    <tags>
        <tag index="2"/>
    </tags>
    <data/>
</base>

<!-- This will result in an XML containing these values: -->

<base>
    <tag>tag_one</tag>
    <tag>tag_two</tag>
</base>

But I'm not happy with my solutions. I don't know anything about XSLT or other XML transformation tools, but I think someone must have done this before.
The key goal I'm looking for is ease to write the XML by hand (both the base and the "extended").
I'm open to new solutions besides XML, if they are easy to write manually.
Thanks for reading.

A: The below may guide you. XSLT may transform one XML into another.
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="data_a">
        <data_a>green</data_a>
    </xsl:template>

    <xsl:template match="tags/tag[1]"/>

</xsl:stylesheet>

Explanation of the three templates above:
(1) copy all nodes and attributes
(2) but change data_a node
(3) and do nothing for the first tag element within (any) tags element.
I hope this will help you transforming your XML.


text:
Q: MongoDB "_id" is null when saving via Camel-MongoDB component We are using MongoDB 2.6.12 and have recently upgraded Camel to 2.18.1 and the "mongo-java-driver" to 3.4.1.
We are using the Camel component "camel-mongodb" and have a route:
    <camel:route id="save">
        <from uri="direct:save"/>
        <camel:process ref="myProcessor"/>
        <camel:to uri="mongodb:mongoDBConnectionBean?database=abc&collection=xyz&operation=save"/>
    </camel:route>

The "MyProcessor" basically looks like this:
   public void process(Exchange exchange) {
       Object body = exchange.getIn().getBody();
       if (body instanceof DBObject) {
           DBObject newObject = (DBObject) body;

          //some more logic here manipulating "newObject"
          //but "newObject" does not have a field "_id"

           exchange.getIn().setBody(newObject);
       } else {
           exchange.setProperty(Exchange.ROUTE_STOP, Boolean.TRUE);
       }
    }

The result is that the object gets stored in MongoDB but for some reason the "_id" field is set to "null". This did not happen before.

UPDATE:
I took a closer look at org.apache.camel.component.mongodb.MongoDbProducer.createDoSave where this code does the "upsert":
MongoCollection e = this.calculateCollection(exchange1);
BasicDBObject saveObj = (BasicDBObject)exchange1.getIn().getMandatoryBody(BasicDBObject.class);
UpdateOptions options = (new UpdateOptions()).upsert(true);
BasicDBObject queryObject = new BasicDBObject("_id", saveObj.get("_id"));
UpdateResult result = e.replaceOne(queryObject, saveObj, options);

Now in my opinion the problem is that MongoDB on a "replaceOne" takes the "_id" of the "queryObject" (which is null in my case") and inserts "saveObj" with this "_id". (See: MongoDB Java Client stores "_id" as null on "replaceOne")
This behaviour can also be seen in the mongo shell:
> db.abc.replaceOne({"_id":null}, {"test":"1"}, {"upsert": true})
> db.abc.find()
{ "_id" : null, "test" : "1" }

Therefore on the one hand I think this is a problem in the mongo-camel component code on the other hand I think I must be missing something because else a lot of people would be having this problem.


text:
Q: How to display polish characters in python I have in my database varchar column containing text with polish characters.
I already changed format in DB to utf8
Now I am pulling data from DB using Django raw SQL creator and receiving an error:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xd3 in position 9:
  invalid continuation byte

I have no idea how to repair it. There is # -- coding: utf-8 -- at the beginning of view file.
Will be thankful for each support,
Thanks in advance,


text:
Q: Supply information automatically to simple form I'm working on a simple little Rails social network and right now I am trying to automatically fill in the name of the currently signed in user when creating a new status update. My original code let them select their user name from a drop down which is silly - when you go on Facebook, you fill out the box and it automatically knows that it belongs to you. Here is my original code:
<%= simple_form_for(@status, html: {:class => "form-horizontal"}) do |f| %>
  <% if @status.errors.any? %>

<%= pluralize(@status.errors.count, "error") %> prohibited this status from being saved:

      <% @status.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>
  <%= f.input :user_id, collection: User.all, label_method: :full_name %>
  <%= f.input :content %>

    <%= f.button :submit %>

<% end %>

And here is what I am trying to replace it with:
<%= simple_form_for(@status, html: {:class => "form-horizontal"}) do |f| %>
  <% if @status.errors.any? %>

<%= pluralize(@status.errors.count, "error") %> prohibited this status from being saved:

      <% @status.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>
  <%= f.input :user_id, current_user.full_name %>
  <%= f.input :content %>

    <%= f.button :submit %>

<% end %>

It doesn't like this and says "can't convert Symbol into Integer"
How can I supply it with the logged in user's full name without ever giving them the option to chose another user?

A: Your first input of the form is specified as an input for the :user_id which is an integer in your table of users.  Putting a full name there is creating a mismatch in data types.  Does this help?
Now that you want the username to be displayed without the user being able to change what is displayed, is there really a need to have this as an input?  Can you just display the username in a normal

, so to speak?

A: user_id is the forreign key to User, it holds something like current_user.id not it's name.
It seems, that the user is already signed in, so you just need to show the name and provide the id to the create action:
<%= f.input :user_id, as: :hidden %>
<%= current_user.name %> <%# just for information %>

and set it in the new @status in the controller:
def new
  @status = Status.new(user: current_user)
  ...
end


text:
Q: How to create a SQL report so that if a date is prior to reporting start date, then I would use the Report Start date I'm trying to create a sql report that captures the length of a patient stay. Basically what I'm doing is if a patient is admitted on 12-12-2013 and discharged on 1-31-2014 I'm going to run a report that will count the length of stay starting on the report date range which is 1-1-2014 to 1-31-2014. I want the datediff to only start on 1-1-2014 not 12-12-2013.
This is how I have my sql for now, but I know it is incorrect
 declare @from_date date, @to_date date

 set @from_date = '07/01/14'
 set @to_date = '07/31/14'

 SELECT
   datediff(dd, @from_date, @to_date) LOS,
   PT_ADMISSION.ADMIT_DATE,
   pt_admission.TERMINATION_DATE

 FROM O_DATASET O_DATASET
    INNER JOIN PT_ADMISSION PT_ADMISSION ON
    (PT_ADMISSION.CLINICAL_SET_ID = O_DATASET.CLINICAL_SET_ID)
     where admit_date <= @from_date

A: You can use the CASE statement to set the @from_date variable.  Here's your sample adjusted with the @from_date set based on the value of the report start date.
declare @report_start_date date
declare @from_date date, @to_date date

SET @report_start_date = '7/15/14'

set @from_date = '07/01/14'
set @to_date = '07/31/14'

-- adjust for report start date
SET @from_date = CASE WHEN @report_start_date > @from_date
                THEN @report_start_date ELSE @from_date END

SELECT
  datediff(dd, @from_date, @to_date) LOS,
  PT_ADMISSION.ADMIT_DATE,
  pt_admission.TERMINATION_DATE

FROM O_DATASET O_DATASET
   INNER JOIN PT_ADMISSION PT_ADMISSION ON
   (PT_ADMISSION.CLINICAL_SET_ID = O_DATASET.CLINICAL_SET_ID)
    where admit_date <= @from_date


text:
Q: Is it possible to add "aria-hidden" for css content property? I have a decorative element in the header that separates links "|". It is added as a CSS content element:
::after {
    content: "|";
    .....
}

In HTML it is presented inside of the span along with the header link:

        Link

In some screen readers, "|" separator is being displayed and I want to make it invisible for the screen readers by adding "aria-hidden". Is there any way to add it to the CSS file? Or is there any other way to make a CSS content property invisible for screen readers?
I saw an example of adding ARIA property in square brackets like so:
::after[aria-hidden] {
    content: "|";
    .....
}

However, it would remove the visibility of the whole element completely, not only for screen readers.

A: No, it's impossible. This is one of the drawback of CSS generated content, and why it's quite discouraged from accessibility point of view.
You can't add HTML attributes to an element using CSS.
If you want to control ARIA attributes like aria-hidden, you have to add the content in the HTML code.
Just for your information, most screen readers render CSS generated contents as normal, but some don't at all with some browsers. So, CSS content isn't recommended either for conveying important information.
Note that your proposition, ::after[aria-hidden] don't add the attribute to the generated element, but tries to match a generated element having the attribute. As it isn't possible to add any attribute to CSS generated elements, it won't ever match anything. It doesn't make any sense, and is in fact invalid according to CSS specification.

A: As noted, you can't add ARIA attributes via CSS.  However, the way I usually do this is have a separate  element that uses the CSS content attribute and specify aria-hidden on the .

some link

another link

A: It is not possible. There are two great answer already, I'd like to explore some other options, though.
A solution would be to not use content.
`

a {
  display: inline-block;
}
a::after {
  content: "";
  display: inline-block;
  height: 1em;
  margin-left: .3em;
  border-right: .12em solid black;
}
Link
Link
Link

CSS selectors
In CSS you can only select an element for styling, you cannot add attributes. Some elements allow to define generated content, for example the ::before and ::after pseudo-elements.
You can select elements based on attributes, for example [aria-hidden].
Note that

Pseudo-elements are featureless, and so can't be matched by any other selector.

so you cannot select a pseudo-element based on its attributes. It has none!
The selector from the example ::after[aria-hidden] is invalid and will be discarded.
You could match an element that has aria-hidden and add a pseudo-element to it. Beware though, that aria-hidden is not a regular boolean attribute, it expects a string true|false.
[aria-hidden="true"]::after {
  content: …

Defining accessible names for generated content
As discussed in the related question How to hide CSS generated content from screen readers without HTML markup?, the CSS standard allows to define alternative text (an accessible name) for generated content.

If the pseudo-element is purely decorative and its function is covered elsewhere, setting alt to the empty string can avoid reading out the decorative element.

content: "|" / "";

Unfortunately, alternative text for content is not well supported.
Speech module
There is the standard CSS Speech Module which intends to allow control of how contents are announced by screen readers.
/* not supported anywhere – yet? */
::after {
  speak: never;
}

This is purely theoretical, though, and would probably only apply to screen readers, not to assistive technology in general. Braille displays would still output the content of the pseudo-element.