text:
Q: make client wait for input, client - server I'm trying to write a very simple client-server program.
Basically as soon as the client connects to the server he gets a login screen where he has to enter a username password and a filename.
My problems are:

*

*The client continues with the flow of the code without actually waiting for the input.

*The server side seems to be stuck at some line and i get a connection reset.

This is the code at the clients side:
public static void main(java.lang.String[] args) throws JsonIOException, JsonSyntaxException, ClassNotFoundException, IOException
{
    try
    {
        Socket socket = new Socket(InetAddress.getLocalHost(), 12345);
        LoginScreen login = new LoginScreen();
        login.open();
        String name = login.getUsername();
        String pass = login.getPassword();
        String log = login.getLogname();
        System.out.println(name + " " + pass + " " + log);
    }

this is the LoginScreen
@SuppressWarnings("serial")
public class LoginScreen extends JFrame implements ActionListener
{
    private JTextField userText;
    private JTextField passText;
    private JTextField logText;
    private JLabel userLabel;
    private JLabel passLabel;
    private JLabel logLabel;
    private JButton loginButton;

    private String username;
    private String password;
    private String logname;

    public String getUsername()
    {
        return username;
    }

    public String getPassword()
    {
        return password;
    }

    public String getLogname()
    {
        return logname;
    }

    public LoginScreen()
    {
        super("Login");

        userLabel = new JLabel("username: ");
        passLabel = new JLabel("password: ");
        logLabel = new JLabel("File name: ");

        Dimension preferredSize = new Dimension(80,20);
        userText = new JTextField("");
        userText.setPreferredSize(preferredSize);
        passText = new JTextField("");
        passText.setPreferredSize(preferredSize);
        logText = new JTextField("");
        logText.setPreferredSize(preferredSize);

        loginButton = new JButton("Login");
        loginButton.addActionListener(this);
    }
    public void open()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500,500);
        setLayout(new BorderLayout());

        JPanel userPanel = new JPanel();
        userPanel.setLayout(new FlowLayout());
        add(userPanel,BorderLayout.NORTH);

        JPanel passPanel = new JPanel();
        passPanel.setLayout(new FlowLayout());
        add(passPanel,BorderLayout.CENTER);

        JPanel logPanel = new JPanel();
        logPanel.setLayout(new FlowLayout());
        add(logPanel,BorderLayout.SOUTH);

        JPanel loginPanel = new JPanel();
        loginPanel.setLayout(new FlowLayout());
        add(loginPanel,BorderLayout.EAST);

        userPanel.add(userLabel);
        userPanel.add(userText);
        passPanel.add(passLabel);
        passPanel.add(passText);
        logPanel.add(logLabel);
        logPanel.add(logText);
        loginPanel.add(loginButton);

        pack();

        this.setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent arg0)
    {
        username = new String(userText.getText());
        password = new String(passText.getText());
        logname = new String(logText.getText());
    }
}

And this is the server
try
{
    Socket client = socket.accept();
    ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
    ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
    String userPassFile = (String)ois.readObject();
    String[] parts = userPassFile.split("");
    if(AuthenticationManager.Authenticate(parts[0], parts[1]))
    {
        new MMULogService(client,parts[2]);
    }
    else
    {
        oos.writeObject("Incorrect Username / Password");
    }
    client.close();
}

it should be noted that before executing the client side, i open the server.
Currently the output is null null null IE - the client side reaches the login.getUsername methods before i clicked "login" on the login screen itself.
And once I close the login screen, I get the error -
java.net.SocketException: Connection reset at the line ObjectInputStream ois = new ObjectInputStream(client.getInputStream()); in the server.
How do I make the client wait for me to actually hit the login button before doing the get methods? how do i fix the connection reset error?

A: Here is how you can fix your first issue (for the second I don't see your code so I can't help), you need a way to synchronize the main thread and your UI.
So first let the AWT event dispatching thread launch your UI as next:
SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        login.open();
    }
});

Or If your use Java 8, simply:
SwingUtilities.invokeLater(() -> login.open());

Then make your main thread wait before the get methods by making it call a new method like this:
login.waitForInputs();
String name = login.getUsername();
...

Then in your class LoginScreen, the new method will simply make the calling thread wait by doing this:
public void waitForInputs() throws InterruptedException {
    synchronized (this) {
        // Make the current thread waits until a notify or an interrupt
        wait();
    }
}

Finally you need to modify the method actionPerformed in order to release the main thread when it is ok, by doing something like this:
public void actionPerformed(ActionEvent arg0)
{
    username = userText.getText();
    password = passText.getText();
    logname = logText.getText();
    // Here you should test if the input values are OK if it is KO do a
    // return to prevent calling the following code
    synchronized (this) {
        // Release the waiting threads
        notifyAll();
    }
}

And it is done we have implemented a simple wait/notify mechanism to get the input values from the UI before calling the get methods.


text:
Q: Count number of objects by date in daterange In a Django project, I have these simplified models defined:
class People(models.Model):
    name = models.CharField(max_length=96)

class Event(models.Model):

    name = models.CharField(verbose_name='Nom', max_length=96)

    date_start = models.DateField()
    date_end = models.DateField()

    participants = models.ManyToManyField(to='People', through='Participation')

class Participation(models.Model):
    """Represent the participation of 1 people to 1 event, with information about arrival date and departure date"""

    people = models.ForeignKey(to=People, on_delete=models.CASCADE)
    event = models.ForeignKey(to=Event, on_delete=models.CASCADE)

    arrival_d = models.DateField(blank=True, null=True)
    departure_d = models.DateField(blank=True, null=True)

Now, I need generate a participation graph: for each single event day, I want the corresponding total number of participations.
Currently, I use this awful code:
def daterange(start, end, include_last_day=False):
    """Return a generator for each date between start and end"""
    days = int((end - start).days)
    if include_last_day:
        days += 1
    for n in range(days):
        yield start + timedelta(n)

class ParticipationGraph(DetailView):

    template_name = 'events/participation_graph.html'
    model = Event

    def get_context_data(self, **kwargs):

        labels = []
        data = []

        for d in daterange(self.object.date_start, self.object.date_end):
            labels.append(formats.date_format(d, 'd/m/Y'))
            total_participation = self.object.participation_set
                .filter(arrival_d__lte=d, departure_d__gte=d).count()
            data.append(total_participation)

        kwargs.update({
            'labels': labels,
            'data': data,
        })
        return super(ParticipationGraph, self).get_context_data(**kwargs)

Obviously, I run a new SQL query for each day between Event.date_start and Event.date_end. Is there a way to get the same result with a reduced number of SQL query (ideally, only one)?
I tried many aggregation tools from Django orm (values(), distinct(), etc.) but I always fall to the same issue: I don't have a field with a simple date value, I only have start and end date (in Event) and departure and arrival date (in Participation), so I can't find a way to group my results by date.

A: I agree that the current approach is expensive because, for each day, you are re-querying the DB for participants that you already retrieved earlier. I would instead approach this by doing a one-time query to the DB to get the participants and then use that data to populate your result data structure.
One structural change I would make to your solution is that instead of tracking two lists where each index corresponds to a day and the participation, aggregate the data in a dictionary mapping the day to the number of participants. If we aggregate results this way, we can always convert this to the two-lists at the end if needed.
Here is what my general (pseudo-codeish) approach is:
def formatDate(d):
    return formats.date_format(d, 'd/m/Y')

def get_context_data(self, **kwargs):

    # initialize the results with dates in question
    result = {}
    for d in daterange(self.object.date_start, self.object.date_end):
        result[formatDate(d)] = 0

    # for each participant, add 1 to each date that they are there
    for participant in self.object.participation_set:
        for d in daterange(participant.arrival_d, participant.departure_d):
            result[formatDate(d)] += 1

    # if needed, convert result to appropriate two-list format here

    kwargs.update({
        'participation_amounts': result
    })
    return super(ParticipationGraph, self).get_context_data(**kwargs)

In terms of performance, both approaches do the same number of operations. In your approach, for every day, d, you filter over every participant, p. Thus, the number of operations is O(dp). In my approach, for each participant I go through every day they attended (worse cast every day, d). Thus, it is also O(dp).
The reason to prefer my approach is what you pointed out. It only hits the database once to retrieve the participant list. Thus, it is less dependent on network latency. It does sacrifice some of the perf benefits that you get from SQL queries over python code. However, the python code is not too complex and should be fairly easy to process for events that even have hundreds of thousands of people.

A: I saw this question few days ago and honoured it with an upvote, since it is really well written and the problematics is very interesting. Finally I found some time to dedicate to its solution.
Django is a variation of a Model-View-Controller called Model-Template-View. My approach would follow thus the paradigm "fat model and thin controllers" (or translated to conform with Django "fat model and thin views").
Here is how I would rewrite the models:
import pandas

from django.db import models
from django.utils.functional import cached_property

class Person(models.Model):
    name = models.CharField(max_length=96)

class Event(models.Model):
    name = models.CharField(verbose_name='Nom', max_length=96)
    date_start = models.DateField()
    date_end = models.DateField()
    participants = models.ManyToManyField(to='Person', through='Participation')

    @cached_property
    def days(self):
        days = pandas.date_range(self.date_start, self.date_end).tolist()
        return [day.date() for day in days]

    @cached_property
    def number_of_participants_per_day(self):
        number_of_participants = []
        participations = self.participation_set.all()
        for day in self.days:
            count = len([par for par in participations if day in par.days])
            number_of_participants.append((day, count))
        return number_of_participants

class Participation(models.Model):
    people = models.ForeignKey(to=Person, on_delete=models.CASCADE)
    event = models.ForeignKey(to=Event, on_delete=models.CASCADE)
    arrival_d = models.DateField(blank=True, null=True)
    departure_d = models.DateField(blank=True, null=True)

    @cached_property
    def days(self):
        days = pandas.date_range(self.arrival_d, self.departure_d).tolist()
        return [day.date() for day in days]

All calculations are placed in the models. Information that depends on the data stored in the database is made available as cached_property.
Let's see an example for Event:
djangocon = Event.objects.create(
    name='DjangoCon Europe 2018',
    date_start=date(2018,5,23),
    date_end=date(2018,5,28)
)
djangocon.days
>>> [datetime.date(2018, 5, 23),
     datetime.date(2018, 5, 24),
     datetime.date(2018, 5, 25),
     datetime.date(2018, 5, 26),
     datetime.date(2018, 5, 27),
     datetime.date(2018, 5, 28)]

I used pandas for generating the date range, which is probably an overkill for your application, but it has nice syntax and is good for demonstrational purposes. You can generate the date range in your own way.
To get this result there was only one query. The days is available as any other field.
The same thing I made in Participation, here are some examples:
antwane = Person.objects.create(name='Antwane')
rohan = Person.objects.create(name='Rohan Varma')
cezar = Person.objects.create(name='cezar')

They all want to visit DjangoCon Europe in 2018, but not all of them are attending all days:
p1 = Participation.objects.create(
    people=antwane,
    event=djangocon,
    arrival_d=date(2018,5,23),
    departure_d=date(2018,5,28)
)
p2 = Participation.objects.create(
    people=rohan,
    event=djangocon,
    arrival_d=date(2018,5,23),
    departure_d=date(2018,5,26)
)
p3 = Participation.objects.create(
    people=cezar,
    event=djangocon,
    arrival_d=date(2018,5,25),
    departure_d=date(2018,5,28)
)

Now we want to see how many participants there are for every day the event is going on. We track the number of SQL queries too.
from django.db import connection
djangocon = Event.objects.get(pk=1)
djangocon.number_of_participants_per_day
>>> [(datetime.date(2018, 5, 23), 2),
     (datetime.date(2018, 5, 24), 2),
     (datetime.date(2018, 5, 25), 3),
     (datetime.date(2018, 5, 26), 3),
     (datetime.date(2018, 5, 27), 2),
     (datetime.date(2018, 5, 28), 2)]

connection.queries
>>>[{'time': '0.000', 'sql': 'SELECT "participants_event"."id", "participants_event"."name", "participants_event"."date_start", "participants_event"."date_end" FROM "participants_event" WHERE "participants_event"."id" = 1'},
    {'time': '0.000', 'sql': 'SELECT "participants_participation"."id", "participants_participation"."people_id", "participants_participation"."event_id", "participants_participation"."arrival_d", "participants_participation"."departure_d" FROM "participants_participation" WHERE "participants_participation"."event_id" = 1'}]

There are two queries. The first one fetches the object Event and the second gets the number of participants per day for the event.
Now it's up to you to use it in your views as you please. And thanks to the cached properties you won't need to repeat the database query to get the result.
You can follow the same principle and maybe add property to list all participants for each day of an event. It could look like:
class Event(models.Model):
    # ... snip ...
    @cached_property
    def participants_per_day(self):
        participants  = []
        participations = self.participation_set.all().select_related('people')
        for day in self.days:
            people = [par.people for par in participations if day in par.days]
            participants.append((day, people))
        return participants

    # refactor the number of participants per day
    @cached_property
    def number_of_participants_per_day(self):
        return [(day, len(people)) for day, people in self.participants_per_day]

I hope you like this solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating two Column layout using CSS for ASP.NET MVC3 create view I am new to CSS. I have a create records page and it has html elements like textboxes, dropdown lists, multiselect lists.  The View create.html is as follows :
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>

            @Html.LabelFor(model => model.SDate)

            @Html.EditorFor(model => model.SDate)
            @Html.ValidationMessageFor(model => model.SDate)
             @Html.EditorFor(model => model.STime)
            @Html.ValidationMessageFor(model => model.STime)

            @Html.LabelFor(model => model.EDate)

            @Html.EditorFor(model => model.EDate)
            @Html.ValidationMessageFor(model => model.EDate)
            @Html.EditorFor(model => model.ETime)
            @Html.ValidationMessageFor(model => model.ETime)

            @Html.LabelFor(model => model.SitID)

            @Html.DropDownList("SiteID", new SelectList(ViewBag.Sit as System.Collections.IEnumerable, "SitID", "SitName"), "Select a Sit", new { id = "ddlSit" })

            @Html.ValidationMessageFor(model => model.SitID)

            @Html.LabelFor(model => model.UnitID)

            @Html.ListBoxFor(Model => Model.SelectedUnits, new SelectList(ViewBag.Unit as System.Collections.IEnumerable, "UnitID", "UnitName"), new { id = "ddlUnit", size="4", style = "width: 150px"  })
            @Html.ValidationMessageFor(model => model.UnitID)

            @Html.LabelFor(model => model.DestID)

            @Html.DropDownList("DestID", "--Select One--")
            @Html.ValidationMessageFor(model => model.DestID)

            @Html.LabelFor(model => model.RestID)

            @Html.DropDownList("RestID", "--Select One--")
            @Html.ValidationMessageFor(model => model.RestID)

            @Html.LabelFor(model => model.Desc)

            @Html.TextAreaFor(model => model.Desc, 10, 55, null)
            @Html.ValidationMessageFor(model => model.Desc)

            <input type="submit" value="Save" />

    </fieldset>
}

The CSS style defined is as follows:
fieldset
{

    border: 1px solid #ddd;
    padding: 0 1.4em 1.4em 1.4em;
    margin: 0 0 1.5em 0;
}

.display-label,
.editor-label
{

    margin: 1em 0 0 0;
}

.display-field,
.editor-field
{
    margin: 0.5em 0 0 0;
}

Now, the view is displayed everything as left aligned and below each label the textbox is displayed.
I would like to have nice two colmn layout in the view so that I do not have to scroll down in that page and also it will look nicer if I have few fileds in a same row (e.g. startdate, enddate).
Please help me. Thank you!

A: If you doing divs, every div is (by default) in one row.
One way is to do the following 3 steps.
1) set the height of you label
2) set the position of you fields to relative
3) set the top of your fields to -LABEL_HEIGHT
.display-label,
.editor-label
{
    height:24px;
    margin: 1em 0 0 0;
}

.display-field,
.editor-field
{
    position:relative;
    top: -24px;
    float:right;
    margin: 0.5em 0 0 0;
}

hope that helps


text:
Q: What does the spread operator in ES6 convert to in older JavaScript? Is it costlier than array.concat? I wanted to concat two arrays in JavaScript so I wanted to know if the ES6 spread operator ... is costlier than array.concat?
Does that mean we should use the ... syntax wisely and only when utmost needed?

A: let arrayVar = [1, 2, 3];
let array2 = [...arrayVar, 4];

is equivalent to
var arrayVar = [1, 2, 3];
var array2 = [].concat(arrayVar, [4]);

per https://babeljs.io/


text:
Q: How to store two different cache "tables" in Redis under the same database/index? Trying to build a data set of two cache tables (which are currently stored in SQL Server) - one is the actual cache table (CacheTBL); the other is the staging table (CacheTBL_Staging).
The table structure has two columns - "key", "value"
So I'm wondering how to implement this in Redis as I'm a total noob to this NoSQL stuff.  Should I use a SET or LIST?  Or something else?
Thank you so much in advance!

A: You need to decide whether you want separate REDIS keys for all entries using SET and GET, or put them into hashes with HSET and HGET. If you use the first approach, your keys should include a prefix to distinguish between main and staging. If you use hashes, this is not necessary, because the hash name can also be used to distinguish these. You probably also need to decide how you want to check for cache validity, and what your cache flushing strategy should be. This normally requires some additional data structures in REDIS.


text:
Q: R: Undefined column error when using mediate in a user made function I am running a series of mediation analyses using R's mediation package. Because the models are extremely similar to each other I wrote a function where all
that would change would be the mediating variable, the outcome variable, and the data set.  The function is below:
    library(mediation)
    data("framing", package = "mediation")
    covList <- list("age", "educ", "gender", "income")

    meBrokenFunction <- function(MEDIATOR, OUTCOME, DATA) {

      treatOnMed <- lm(DATA[[MEDIATOR]] ~ treat + age + educ + gender + income, data = DATA)

      medOnOut <- glm(DATA[[OUTCOME]] ~ DATA[[MEDIATOR]] + treat + age + educ + gender + income, data = DATA, family = binomial("probit"))

      expt <- mediate(treatOnMed, medOnOut, sims = 100,
                      treat = "treat", mediator = MEDIATOR,
                      covariates = covList, robustSE = TRUE)
      expt
    }
    set.seed(2019)
    test_first <- meBrokenFunction("emo", "cong_mesg", framing)

When I run this function I get the following error:
Error in `[.data.frame`(y.data, , mediator) : undefined columns selected

However if I run the code without using the function I wrote, everything works as intended.
test_treatOnMed <- lm(emo ~ treat + age + educ + gender + income,
                        data = framing)
test_treatOnOut <- glm(cong_mesg ~ treat + age + educ + gender + income,
                        data = framing, family = binomial("probit"))
test_medOnOut <- glm(cong_mesg ~ emo + treat + age + educ + gender + income,
                        data = framing, family = binomial("probit"))

test_second <- mediate(test_treatOnMed, test_medOnOut, sims = 100,
                  treat = "treat", mediator = "emo",
                  covariates = covList, robustSE = TRUE)

The error appears to be in the mediate function, specifically at mediator = MEDIATOR but I do not understand why it is not working or if I am approaching the problem incorrectly.

A: In the formula, we may need paste instead of DATA[[MEDIATOR]]
lm(paste(MEDIATOR,  "~ treat + age + educ + gender + income"), data = DATA)

Similarly for the glm
-fullcode
meFixedFunction <- function(MEDIATOR, OUTCOME, DATA) {

      treatOnMed <- lm(paste(MEDIATOR,
          "~ treat + age + educ + gender + income"), data = DATA)

      medOnOut <- glm(paste(OUTCOME, "~", MEDIATOR,
         "+ treat + age + educ + gender + income"), data = DATA,
             family = binomial("probit"))

      expt <- mediate(treatOnMed, medOnOut, sims = 100,
                      treat = "treat", mediator = MEDIATOR,
                      covariates = covList, robustSE = TRUE)
      expt
    }

-testing
set.seed(2019)
test_first <- meFixedFunction("emo", "cong_mesg", framing)


text:
Q: Boostrap Navigation for Kendo Angular components In my existing projects I have angular components with using kendo style. Now I need to create the navigation as shown in below image

Currently "Home","Profile","Contact" are different components and are working based on the routing.
How can I use the Bootstrap Navigation to achieve the above design re-using the components

    Home
    Profile
    Contact

...

...

...

PS: I'm trying to create a shared component for navigation and re-use it.
EDIT: To render the angular component of click of navigation button in the line

...

A: Add a selector attribute to your component, then use the selector in the tab-pane. For example:
import { ... } from '...';
@Component({
    selector: 'my-component',
    templateUrl: './my-component.component.html'
})
export class MyComponent {
    // ...
}

    <my-component></my-component>


text:
Q: Simple injector - can I intercept object creation I know I can use container.Options.RegisterResolveInterceptor to get notified each time an object is resolved, but for my scenario, I'd like to get notified only when the object was created.
For instance, if the type was registered as Lifestyle.Singleton, I'd want my delegate to run the first time the type is resolved (when the singleton instance gets created) but not on subsequent calls to resolve.
Is there an easy way to do this?

A: As you already found, the RegisterResolveInterceptor allows intercepting a type that gets resolved directly from the container. This means if you call GetInstance<ILogger>(), the RegisterResolveInterceptor allows to be wrapped around the ILogger, but it won't go off do any of its dependencies.
To hook onto the creation of a type, you can use one of the RegisterInitializer overloads. RegisterInitializer is primarily means to add some additional initialization to a type that is created by Simple Injector, but there are other interesting use cases for it.
In case you have a specific type you want to get notified about, you can use the RegisterInitializer<T>(Action<T>) overload, where you specify the type or abstraction you are interested in. For instance:
container.RegisterInitializer<ILogger>(logger =>
{
    System.Console.WriteLine(logger.ToString());
});

In this case, the initializer will get hooked to any registration that is assignable from ILogger, for instance:
container.Register<ILogger>(() => new DbLogger());
container.Register<ILogger, FileLogger>();
container.Register<EventLogLogger>();

All three registrations (assuming EventLogLogger implements ILogger) will get enriched with the initializer.
If however there isn't a particular type or abstraction you want to hook onto, but rather a wide range of types, or you need to have more information about the type (such as its lifestyle), you can use the second RegisterInitializer overload. This overload takes in an action that will be executed and a predicate that allows you to specify to which registrations the action will be supplied to. For instance:
container.RegisterInitializer(
    data => System.Console.WriteLine(data.Registration.ImplementationType.Name),
    context => context.Registration.Lifestyle == Lifestyle.Singleton);

The previous code snippet registers an initializer that will writes the name of the type created to the console, in case that registration is a Singleton. An example what you can do with this can be found in the Glimpse plugin for Simple Injector. The Glimpse plugin uses this RegisterInitializer overload so it can inform the user which types are created during a particular request.


text:
Q: Tracking iPhone on Yahoo Web Analytics using ASIHTTPRequest I'm trying to track an event in my app using Yahoo Web Analytics. The code I am using looks like
ASIHTTPRequest *yahooTrack = [ASIHTTPRequest requestWithURL:
    [NSURL URLWithString:@"http://s.analytics.yahoo.com/p.pl?a=xxxxxxxxxxxxx&js=no&b=yyyyyyyyyyyy&cf6=zzzzzzzzzzz"]];
yahooTrack.didFinishSelector = @selector(statisticsFinished:);
yahooTrack.delegate = self;
[yahooTrack startAsynchronous];

Then the statisticsFinished looks like:
NSLog(@"Cookies: %@", request.requestCookies);
NSLog(@"Redircount: %d", [request redirectCount]);
NSLog(@"Responsecode %d %@\nMsg: %@", request.responseStatusCode,
    request.responseStatusMessage, [request responseString]);

And all the information I get back looks correct. Cookies are set, redirectcount is 1 the first time (as it redirects to s.analytics.yahoo.com/itr.pl?.... a normal browser does). Then the redirectcount is 0 for subsequent request until the app is restarted and session cleared. The responseString returns GIF89a.
Even if the data looks correct, Yahoo still won't track. As soon as I call the tracking url directly in my browser it works as expected.
I realize Flurry is a better option, but I'm forced to use Yahoo in this case. Also, using a UIWebView probably would work, but I'm against putting in a webview just for tracking purposes.
Is there any difference in how ASIHTTPRequest and Safari would handle a call to a simple URL as this? Or do you see anything else that could explain why the tracking isn't working?

A: I finally found the problem. ASIHTTPRequest creates a user-agent based on your applications name, and requests from this user agent is ignored by Yahoo somehow (bug?). As stated in the documentation, you can override the user-agent as follows:
[request addRequestHeader:@"User-Agent" value:@"My-User-Agent-1.0"];
I used the user-agent string of Safari on iPhone, and it worked immediately! BTW; the same problem applies for Android, and the same fix works.


text:
Q: python matplotlib hist not showing missing bin properly I have a dataframe that is constructed with numbers from 1 to 16, but without number 15.
df = pd.DataFrame({'rand_int_no_15':[random.choice([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 16]) for cnt in range(100) ]})

Now I would like to display histogram in which I will see that there is no number 15.
In order to do so, I have executed
df.rand_int_no_15.hist(bins=np.arange(1, df.rand_int_no_15.max() + 1))

but, what I got is histogram from which I cannot conclude that number 15 doesn't exist.
I would have expected that bar above number 15 is empty.
Am I doing something wrongly?
Regards.


text:
Q: Is there a way to preserve or track vertex correspondence after a series of vertex removals In python-igraph, it seems to me that when you delete vertices from a graph, the vertices are renamed to using consecutive vertices from 0 to n.
To see what I mean, consider the following program:
from igraph import Graph

g=Graph.Full(4) # Vertex set is {0..3}

print g.neighbors(2) # Prints [0,1,3]
g.delete_vertices([1])
print g.neighbors(2) # Prints [0,1], but I'd want [0,3]

I could do my own manual bookkeeping, but is this already supported in the library somehow? Basically, I'd like to know after a series of vertex deletions, what the newly renamed vertices correspond to in the original graph (just like in the snippet above).

A: The easiest is to use the name vertex attribute to track the correspondence. Basically, if you assign names to the vertices, you can then use the names later wherever igraph expects a numeric vertex ID:
>>> g.vs["name"] = ["V{0}".format(i) for i in range(4)]
>>> g.vs[g.neighbors("V2")]["name"]
['V0', 'V1', 'V3']
>>> g.delete_vertices(["V1"])
>>> g.vs[g.neighbors("V2")]["name"]
['V0', 'V3']

The name attribute is indexed behind the scenes so looking up a vertex by name should have the same time complexity as a typical Python dict lookup.
For what it's worth, the vertex renumbering is a property of the underlying C library so there's not much that the Python interface can do about it.


text:
Q: image display in PHP when the image is in a remote directory I am learning PHP by myself for doing my final year project, but I cant figure it out how to display images on my website if the image is in my ftp.  I know how to do in html using local host, but I dont know how to do it on my specific remote host.
I am currently using the code:
echo '<img src="'.public_html/logo.gif.'" style=width:"' . 300 . 'px;height:' . 280 . 'px;">';

If I right click on the image on my directory and select copy url it gives me:
ftp://smart206@smartdatabasesystem.com/public_html/logo.gif

but if I put all of that it still doesnt work. I am using lunar pages host recommended by w3schools.
If someone has any idea of how to fix my problem, please reply. I read some tutorials, my image display incorrectly. The website I started to develop is smartdatabasesystem.com
Thank you :-)

A: Your FTP host and HTTP host are the same machine (both "local"), but the FTP root directory (and protocol - ftp://, obviously) are different. Your http root directory is INSIDE  your public_html directory, so your logo is available at:
http://smartdatabasesystem.com/logo.gif
Basically, for your server set up (this will be different on different servers), you can presume that any time you have an FTP location of ftp://smart206@smartdatabasesystem.com/public_html/[SOMETHING], the resource will be available at http://smartdatabasesystem.com/[SOMETHING]. If the file is below the /public_html/ directory, then the resource will not be available to the outside world through HTTP.
Also, Lunar pages is a fine host, but you might catch some flack for taking any suggestions from w3chools... they're not exactly well respected by more senior developers :)


text:
Q: CentOS 6.9 mirrorlist problem can't find mirrorlist I have problem with mirrorlist on CentOS 6.9.
I tried use baseurl=https://vault.centos.org/6.9/os/x86_64/ in /etc/yum.repos.d, but the are almost nothing, even no vim. Then I tried use mirrorlist=http://mirrorlist.centos.org/?release=6&arch=i386&repo=os&infra=stock, but suddenly the link isn't active. Then I tried use this link, but with release equals 7, but yum tried to reinstall whole the system since conflict between versions.
Can you provide me yum configuration for CentOS 6.9 i386.
Here the last configuration:
[centos-old.repo]
name=centos-old
mirrorlist=http://mirrorlist.centos.org/?release=7&arch=i386&repo=os&infra=stock
#baseurl=https://vault.centos.org/6.9/os/x86_64/
enabled=1
gpgcheck=0

Helpful info:
[root@host  yum.repos.d]# cat /etc/*release
CentOS release 6.9 (Final)
LSB_VERSION=base-4.0-ia32:base-4.0-noarch:core-4.0-ia32:core-4.0-noarch:graphics-4.0-ia32:graphics-4.0-noarch:printing-4.0-ia32:printing-4.0-noarch
CentOS release 6.9 (Final)
CentOS release 6.9 (Final)
[root@host  yum.repos.d]# uname -p
i686
[root@host  yum.repos.d]#


text:
Q: write pyspark dataframe to kafka I have pyspark data frame which I wanted to write to kafka topic.
df.show(n=5)
+-------+---------+
|county |category |
+-------+---------+
|Albany1|  Animal3|
|Albany2|  Animal5|
|Albany3|  Animal1|
|Albany4|  Animal2|
|Albany5|  Animal4|
+-------+---------+

df.printSchema()
root
 |-- county: string (nullable = true)
 |-- category: string (nullable = true)

code which I have tried
df.selectExpr("to_json(struct(*)) AS value") \
.write \
.format("kafka") \
.option("kafka.bootstrap.servers", "host:port") \
.option("topic", "test") \
.save()

I am getting below error.
 java.lang.RuntimeException: org.apache.spark.sql.kafka010.KafkaSourceProvider does not allow create table as select.

Please help. Thank you !!

A: I had the same error and could fix it by adding the option .format("console") :
df.selectExpr("to_json(struct(*)) AS value") \
.write \
.format("kafka") \
.option("kafka.bootstrap.servers", "host:port") \
.option("topic", "test") \
.format("console") \
.save()


text:
Q: How to redirect part of the link in wordpress? How to redirect part of the link in wordpress?
is there any plugin to do that?
for example:
redirectiong :
https://sajiran.com/product/ma25
to:
https://sajiran.com/new-address/ma25
for all links

A: Inside your .htaccess add the following:
Redirect 301 /product /new-address

This will redirect any link that starts with product to new-address


text:
Q: Segmentation Fault in X509_STORE_add_lookup() I am writing a program which connects to a remote server and uses a self signed certificate. I get the following errors at a couple of points in the program.
Program received signal SIGSEGV, Segmentation fault.
0xb7ec3688 in X509_STORE_add_lookup () from /lib/i386-linux-gnu/libcrypto.so.1.0.0

At this point:
    if (!SSL_CTX_load_verify_locations(
                ssl_ctx_p, "bundle_test.p12.pem", NULL))

And another:
Program received signal SIGSEGV, Segmentation fault.
0xb7ec389e in X509_STORE_get_by_subject () from /lib/i386-linux-gnu/libcrypto.so.1.0.0

Here:
ssl_ret = SSL_connect(ssl_p);

I am pretty new to this and do not know what is going wrong, if anybody could suggest a better way to debug or figure out the problem, I would appreciate it!

A: The function doesn't do much work itself. The only thing that can cause a segfault inside this function instead of inside X509_STORE_load_locations() is pointer dereference ctx->cert_store. Please verify that ssl_ctx_p is a valid context and not NULL.
int SSL_CTX_load_verify_locations(SSL_CTX *ctx, const char *CAfile,
                const char *CApath)
        {
        return(X509_STORE_load_locations(ctx->cert_store,CAfile,CApath));
        }


text:
Q: How to make a basic thread in C++ I have a class main.cpp, as well as MyClass.cpp.
In main.cpp, I have a lot of code. At the top though, I create a MyClass object and then I'd like to start a thread that is in MyClass. I'd like it to call a function Run() and have the function run at the same time that the rest of the functions in main.cpp run.
What is the easiest way to do this in C++. I've never done threading in C++, however I have done so in Java.
I'd like to avoid using external packages and such if possible.

A: The simplest way for you to go is to use boost thread library.
#include <boost/thread.hpp>
#include <boost/bind.hpp>

...

int main()
{
  ...
  MyClass mc;
  boost::thread bt(boost::bind(MyClass::Run, &mc));
  ...
  bt.join();
  ...
 }

A: The C++ language itself doesn't have any notion of threads*.  You can certainly write multithreaded programs in C++, but it will involve using a platform-specific thread library.  For example, you can use the "pthreads" library on Linux systems.  What is your target platform?
*The extensions added in the new C++11 spec add standardized support for threads, but many compilers and standard libraries do not yet implement this version of the standard.

A: Using standard C++:
#include <future>

int main() {
    MyClass mc;
    auto future = std::async(MyClass::Run,&mc);
    ...
}


text:
Q: Is there any way to convert string patterns as shown in the map below?
Trying to convert 'Currently' patterns in the above table to 'Turn It Into' patterns in the data set ...
Examples are shown in the next 2 columns for each one....
I tried different ways but I could not get required output ....
Here is the code to get the input data....
    data Current;
Input Currently :$40.;
Datalines;
HiKumar"^TM1()^",test
HiKumar"^TM2()^"
HiKumar^TM3()^HiKumar
HiKumar^f('VARNAME').any('#')^
HiKumar^f('VARNAME')^
HiKumar^f('VARNAME').get()=='#'^
HiKumar^f('VARNAME')=='#'^
HiKumar^f('VARNAME').toNumber()^
HiKumar^f('VARNAME').toString()^
HiKumar^f('VARNAME').toString().toLowerCase()^
HiKumar^f('VARNAME').toString().toUpperCase()^
HiKumar^f('IFCONDITION')?'THENTEXT':'ELSETEXT'^
HiKumar

HiKumar

HiKumar

HiKumar^MobileHeader()^
HiKumar^MobileFooter()^
HiKumar
HiKumar
HiKumar&nbsp
;
run;

A: I'd go with regular expressions. You'll need several; here's one to start.  (The quotation characters will probably be mucked up by the web browser and/or SAS, so I would recommend replacing those manually rather than trusting the copy/paste if they don't work at first).  This only identifies the fourth row, but similar regex's can be constructed for the other rows (and some you should be able to use for multiple rows).
data want;
set current;
rx_1 = prxparse("/\^f\('(\w*?)'\)\^/");
rc_1 = prxmatch(rx_1,currently);
if rc_1 ne 0 then have = prxposn(rx_1,1,currently);
run;


text:
Q: Undefined Index Error Reporting in WAMP and PHP I'm using wamp to develop a php application.  My problem is that everytime I call a variable that sometimes happens to not have a value, I get an error that says it's an undefined index.  Is there a way to change the error reporting to not display this error?  I have to use isset to determine if it's set or not before I output the variable, but I don't want to have to do this.  There are areas of my application that make this method inefficient.

A: If you don't want to change error_reporting level you should check, is variable exists, before using it. You may use
 if(isset($var))

for it. You may add some function, to not write it always. Example:
 function getPost($name,$default=null){
     return isset($_POST[$name])?$_POST[$name]:$default;
 }

Usage:
getPost('id');
getPost('name','Not Logged In');

A: You can just turn off the mechanism in php.ini.
This thread would help you.
http://www.wampserver.com/phorum/read.php?2,70609,70700
But it generally its better to take care of undefined variables as they might save you some run time trouble.
Update:
In php.ini change
error_reporting = E_ALL to error_reporting = E_ALL & ~E_NOTICE

A: There are multiple ways to get around this:
error_reporting(0) Use this at the top of your script
set display_errors = Off in php.ini
Use '@' before the statement that generates an error
But unless you are writing something trivial you absolutely must use array_key_exists or if(!empty($arrayName['key'])) for everything sent by the user.

A: Try this:
if(!isset($var)) $var="";

A: PHP.ini files reside in both :
bin\php\php5.x
and
bin\apache\apache2.x\bin
be sure to make the changes in the apache folder version.

Also setting :
display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL
log_errors = On
leaves errors from being displayed on the client, but still allows them to be logged in the error log.


text:
Q: Using a regex for importing dimensions in a ppm file I've a problem finding the proper regex to read a ppm file dimensions. I don't know if it's because my regex is wrong or if I misuse the Pattern.compile method, but I get a java.util.NoSuchElementException. Below my regex and the code along to it. It reads the whole file since my regex always return null.
Thanks.
package projet;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

public class Ppm extends File{
    private Dimensions d;
    private Color[][] p;
    public Ppm(String pathname) {
        super(pathname);
}
public void read(){
    try {
        Scanner s=new Scanner(new FileReader(this.getPath()));
        while(s.findInLine(Pattern.compile("/^\\d* \\d*\\s$/")) == null && s.hasNext()){
            System.out.println(s.nextLine());
        }
        s.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Ppm.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println("Check filepath.");
    }
}
}

Here's my sample file : https://www.dropbox.com/s/z35dvi90zdfkws0/carte1.ppm?dl=0
EDIT :
I tried with a matcher, but it still doesn't work, following the corrected regex. Here's my code, it never matches the pattern...
public class Ppm extends File{
    private Dimensions d;
    private Color[][] p;
    public Ppm(String pathname) {
        super(pathname);
        d=new Dimensions(0, 0);
    }
    public void read(){
        try {
            Scanner s=new Scanner(new FileReader(this.getPath()));
            Pattern p=Pattern.compile("^\\d+ \\d+\\s$");
            Matcher m;
            while(s.hasNext()){
                m=p.matcher(s.nextLine());
                if(m.matches()){
                    System.out.println("Found");
                }
            }
            //System.out.println("W : "+d.getWidth()+" H: "+d.getHeight());
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Ppm.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println("Check filepath.");
        }
    }
}

A: Your regex can never match.
Pattern.compile("/^\\d* \\d*\\s$/")

asks for a text has a slash before the beginning of the string and after  the end of the string. Unlike PHP, Java doesn't use regex delimiters. Try
Pattern.compile("^\\d* \\d*\\s$")

(and be aware that this also matches strings like " 1 " or "1  " or even "  ").


text:
Q: I want to print odd numbers using javascript I want to print odd number using JavaScript below is code which is not working please suggest the correct code.

<script>
    var myArray[];
    for(var i=1; i<10; i +=2){
        myArray.push(i);
    }
    </script>

A: You need to have var myArray = [] and then print the array.

A:

var myArray=new Array();
        for(var i=1; i<10; i +=2){
            myArray.push(i);
        }
console.log(myArray)


text:
Q: Compare two lists with index I have to write a boolean function who takes as argument two lists (L1 and L2) of equal character strings.
L1 is a list of male given names and L2 is a list of female given names of the same length.
L1[k] gives a gift to L2 [k].
This function should return True if two people exchange gifts with each other, for example:
>>> compare(['A','B','C','D','E'],['C','D','A','E','B'])
True

>>> compare(['A','B','C','D','E'],['B','C','D','E','A'])
False

I have to work with the index of lists.
I have written a function to get the index but I have absolutely no idea how to compare these two lists ...
def index(name,L):
    i = 0
    for lookup in L:
        if lookup == name: return i
        i += 1

Thank you!

A: It's easier (and maybe more efficient) to just make a dict that looks up giver -> recipient. Then you can use it to determine if the giving is symmetrical:
def compare(l1, l2):
    d = dict(zip(l1, l2))
    return any(l == d[d[l]] for l in l1)

compare(['A','B','C','D','E'],['C','D','A','E','B'])
# True

compare(['A','B','C','D','E'],['B','C','D','E','A'])
# False

If you want to test if all the giving is symmetrical, you can use all() instead of any().

A: list1 = ['A','B','C','D','E'] # 1
list2 = ['C','D','A','E','B']`
compared_names = [] # 2

for i in range(len(list1)): # 3
    for j in range(len(list2)): # 4
        if list1[i] == list2[j]: # 5
        compared_names.append(list2[j])
if list1 == compared_names: # 6
    print('True, the lists are equal')
    print('This is the compared_names List: ' + str(compared_names))
else: # 7
    print('False, the lists are not equal')
    print('This is the compared_names list is: ' + str(compared_names))

*

*The first 2 lists are going to be compared to each other

*The compared_names list will store the similar items from the lists

*The for loop is using the variable mn to loop through list1
you have to take the length of the list so that when index i
is plugged into the first if statement it is a numeral instead of a string
ie for i in list1 will return the char 'A', 'B'... so you can't
compare. Using the range(len()) will provide an index (0, 1,...) of the
list instead of the char ('A', 'B'...)

*Everything with the for list1 for loop applies to the list2
loop. Also, when the list1 loop runs it will enter index zero, and
then the female_names loop will run it's course (ie 0 through 4). Everytime
it cycles through an index it will check the if statement.

*The if statement will plug in the current index of each loop
so for the first loop around list1[0] == list2[1].
Since 'A' != 'C' it won't append 'C' to the compared_list, and
the new loop will go to the next indexes for the next loop around.

*Once both lists have been cycled through the if statement compares
both list1 and the compared_names list. If they match then
True and the compared_list will print out.

*If list1 and compared_names don't match False and the
compared_list will print out.

You can take this and turn it into a function like def compare(1, 2): ...
and turn the print into a return.

A: def compare(A,B):
    for i in range(len(A)):
        if B[A.index(B[i])]==A[i]:
            return True
        print(B[A.index(B[i])],A[i]) # print to understand more
    return False

Note
If the two lists don't have similar letters, this won't work, since it refers to the letters.


text:
Q: Concatenate multiple images vertically using convert produces many outputs I'm trying to append multiple .jpg files into a single large image file containing the result of vertically stacking the single ones.
It seems to me that Imagemagick's convert has a somewhat erratic behavior when it comes to -append, i.e vertical wise, when I try to expand a list of files passed as wildcard argument like in the instruction convert -append pg*.jpg out.jpg.
This command creates one output file for every source image there is in the directory. Even then those files aren't concatenations. They are simply copies of the original ones. I would expect one single output with the stacking.
It works just fine using +append, for horizontal stacking.
Also works when I type in the name of each individual file, convert -append pg-01.jpg pg-02.jpg pg-03.jpg pg-04.jpg ... output.jpg.
The expansion (*) works for a small subset of files, like 7 or 8.
I tried this
convert -append `for x in img/pg-*; do echo $x; done;` img/out.jpg
in the terminal but I don't know why it doesn't work!
Since I'm working with a bunch of images, I looking to know if there is any alternative for GNU/Linux or why it is behaving like this.
I'll appreciate any info.
Edit:
I forgot to mention that I  get this error: convert-im6.q16: width or height exceeds limit `pg-01.jpg' @ error/cache.c/OpenPixelCache/3911. when the unexpected output occurs. All images have the same width/height.

A: Commenting these lines:
  <policy domain="resource" name="width" value="16KP"/>
  <policy domain="resource" name="height" value="16KP"/>

In /etc/ImageMagick-6/policy.xml appears to have solved the issue.


text:
Q: Composable not recomposing when list is cleared in jetpack compose I have one MutableStateFlow which is kind of emptyList. When I add the item my view is recomposed without any problem. Now I want to recompose view when list is clear. I tried some piece of code but nothing happens.
PairViewModel
class PairViewModel : BaseViewModel() {
     val scanLowEnergyDevices by lazy { MutableStateFlow(emptyList<ScanResult>()) }

     fun addDevices(result: ScanResult) {
        scanLowEnergyDevices.value += result
    }
}

ContentStateful
@Composable
fun ContentStateful(
    context: Context = LocalContext.current,
    viewModel: BloodPressurePairViewModel = getViewModel()
) {
    val activity = context as ComponentActivity
    val scanDeviceList by viewModel.scanLowEnergyDevices.collectAsStateWithLifecycle()

    ContentStateLess(
        scanDeviceList = scanDeviceList,
        resetAction = {
            viewModel.scanLowEnergyDevices.value.toMutableList().clear()
        }
    )
}

ContentStateLess
@Composable
fun ContentStateLess(
    scanDeviceList: List<ScanResult>,
    resetAction: () -> Unit,
) {
    AnimatedVisibility(visible = scanDeviceList.isNotEmpty()) {
        Text(text = "scanDeviceList ${scanDeviceList.size}")
        Button(onClick = { resetAction() }) {
            Text(text = "Reset")
        }
    }
}

What is wrong in here? Thanks

A: Try to use SnapshotStateList like this
val scanLowEnergyDevices by lazy { mutableStateListOf<ScanResult>() }

add items like this
fun addDevices(result: ScanResult) {
    scanLowEnergyDevices.add(result)
    // scanLowEnergyDevices.value.add(result)
}

and clear the list like you would do with a standard collection like this
resetAction = {
    viewModel.scanLowEnergyDevices.clear()
    // viewModel.scanLowEnergyDevices.value.clear()
}

or in your use-case, since its wrap inside a State, just call the .value before the .add() and .clear() calls


text:
Q: Int value not being passed with object even though get/set methods are used I'm sorry if my headline is confusing, but I didn't know how to express my problem differently. I have 2 classes, both windows forms; one of them is a login interface, and the other is a shop interface that the user is taken to if his login is valid. Now, I'm trying to pass the username and password along to the shop interface class so I can subtract "purchases" from the correct row in the database, but for some reason this is not working. I have tested my method with just passing valid username and password strings directly through the code, and if I do that, the method works fine. Debug mode too shows that the value of the username and password is not passed along to the shop interface class through the get methods. Hope you can help, thanks in advance, and sorry for the quite big block of text :)
Here are the two classes in question, plus the class with the methods that I am using for the database:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShopshopFinalfinal
{
    public partial class LoginInterface : Form
    {
        DatabaseConnection dbConnection = new DatabaseConnection();
        private ShopInterface shop1Interface;
        private RegisterInterface reg1Interface;
        private string _username;
        private string _password;

        public void SetUsername(string username)
        {
            _username = username;
        }

        public void SetPassword(string password)
        {
            _password = password;
        }

        public string GetUsername()
        {
            return _username;
        }

        public string GetPassword()
        {
            return _password;
        }

        public LoginInterface()
        {
            InitializeComponent();
            txt_password.PasswordChar = '*';
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            if (dbConnection.CheckUsername(txt_username.Text) == 1 && dbConnection.CheckPassword(txt_password.Text) == 1)
            {
                SetUsername(txt_username.Text);
                SetPassword(txt_password.Text);
                //txt_username.Clear();
                //txt_password.Clear();
                shop1Interface = new ShopInterface();
                shop1Interface.Show();

            }
        }

        private void btn_register_Click(object sender, EventArgs e)
        {
           reg1Interface = new RegisterInterface();
            reg1Interface.Show();
        }
    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShopshopFinalfinal
{
    public partial class ShopInterface : Form
    {

        private DatabaseConnection dbConnection = new DatabaseConnection();
        private LoginInterface login = new LoginInterface();

        public ShopInterface()
        {
            InitializeComponent();
        }

        private void btn_buyapple_Click(object sender, EventArgs e)
        {

            //string username = login.GetUsername();
            //string password = login.GetPassword();

            dbConnection.Transaction(login.GetUsername(), login.GetPassword(), 10);

        }
    }
}

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShopshopFinalfinal
{
    class DatabaseConnection
    {
        private SqlConnection conn;
        private SqlDataReader rdr;
        private SqlCommand cmd;

        public DatabaseConnection()
        {
            conn = new SqlConnection(Properties.Settings.Default.connectionstring);
        }

        public int CheckUsername(string username)
        {
            int result = 0;

            //Opret den ønskede SQL kommmando - her tjekker den om username fra textboxen er lig en i User table.
            cmd = new SqlCommand("select * from dbo.Users where Username ='" + username + "'", conn);

            //Åbn forbindelsen til databasen.
            conn.Open();

            //Udfører det ønskede SQL statement på databasen.
            rdr = cmd.ExecuteReader();

            //Tjek om den har læst og om det er rigtigt.
            if (rdr.Read())
            {
                result = 1;
            }
            else
            {
                result = 0;
            }

            //Luk forbindelsen til databasen.
            conn.Close();

            return result;
        }

        public int CheckPassword(string password)
        {
            int result = 0;

            //Opret SQL-kommando - tjek om password fra textbox er lig med et i databasen.
            cmd = new SqlCommand("select * from dbo.Users where Password ='" + password + "'", conn);

            //Åben forbindelsen.
            conn.Open();

            //Udfør det ønskede SQL statement på databasen.
            rdr = cmd.ExecuteReader();

            if (rdr.Read())
            {
                result = 1;
            }
            else
            {
                result = 0;
            }

            conn.Close();

            return result;

        }

        public void RegisterUser(string username, string password)
        {
            conn.Open();

            cmd =
                new SqlCommand("insert into dbo.Users (Username, Password, IsAdmin, Balance) values ('" +
                               username +
                               "', '" + password + "', '0', '0')", conn);
            rdr = cmd.ExecuteReader();
            rdr.Close();
            conn.Close();
        }

        public void Transaction(string username, string password, int price)
        {

            conn.Open();

            cmd = new SqlCommand("update dbo.Users set Balance = Balance - " + price + " where Username = '"+username+"' and Password = '"+password+"'", conn);

            rdr = cmd.ExecuteReader();

            rdr.Close();

            conn.Close();
        }
    }
}

A: The problem is that you have the ShopInterface creating a brand new instance of LoginInterface, which would have all of its properties in their default state. This is not the same instance as the one that actually has the values, hence why they are blank.
I think that rather than trying to find a way to get ShopInterface to take the values from a LoginInterface (which would mean a strong dependency from ShopInterface to LoginInterface), a better approach would be to provide a way to pass them in:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShopshopFinalfinal
{
    public partial class ShopInterface : Form
    {

        private DatabaseConnection dbConnection = new DatabaseConnection();
        private string Username { get; set; }
        private string Password { get; set; }

        public ShopInterface(string username, string password)
        {
            InitializeComponent();
            Username = username;
            Password = password;
        }

        private void btn_buyapple_Click(object sender, EventArgs e)
        {

            dbConnection.Transaction(username, password, 10);

        }
    }
}

Then you can have the LoginInterface do this:
shop1Interface = new ShopInterface(txt_username.Text, txt_password.Text);
shop1Interface.Show();

A: You are almost there but you are not passing the data to the other form. Change this in ShopInterface:
private LoginInterface login = new LoginInterface();

to this:
public LoginInterface Login {get; set;}

Then in your LoginInterface do this before you show the shop1Interface:
private void btn_login_Click(object sender, EventArgs e)
{
    if (dbConnection.CheckUsername(txt_username.Text) == 1 && dbConnection.CheckPassword(txt_password.Text) == 1)
    {
        SetUsername(txt_username.Text);
        SetPassword(txt_password.Text);
        //txt_username.Clear();
        //txt_password.Clear();
        shop1Interface = new ShopInterface();

        // This is the line you need
        shop1Interface.Login = this;

        shop1Interface.Show();

    }
}

Now because you passed a reference to your LoginInterface to shop1Interface, you can now access it like this:
private void btn_buyapple_Click(object sender, EventArgs e)
{
    // Now it will work
    string username = this.Login.GetUsername();
    string password = this.Login.GetPassword();

    dbConnection.Transaction(login.GetUsername(), login.GetPassword(), 10);
}


text:
Q: Limit of product of kth roots For $n\geq 1$ , let $$A(n)=\prod_{k=1}^{n}(1+\frac{k}{n})^\frac{1}{k}.$$ I'd like to determine $$ \lim_{n->\infty} A(n).$$ Taking logarithms and using the following crude  bound gives $$\log(A(n))=\sum_{k=1}^{n}\frac{1}{k}\log(1+\frac{k}{n}) \geq \sum_{k=1}^{n}\frac{1}{n}\log(1+\frac{k}{n}).$$ By interpreting this latter sum as a Riemann sum for $\log(1+x)$ on $[0,1]$, we see that the desired limit is at least $4/e$. However, this lower bound is far from sharp and is clearly not strong enough to determine the actual limit. Appreciate if someone here could point me in the right direction.

A: $\log A(n)$ is the sequence of Riemann sums of $$\int_0^1 x^{-1}\log(1+x)dx= \int_0^1 \sum_{m\ge 1} \frac{(-1)^{m+1} }mx^{m-1}dx$$
What do you get next?


text:
Q: How can a second model reference a user instance that is a foreign key in the first model I have a product model that includes a user(the user that adds the product)
class PreOrder(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
contact = models.CharField(max_length=15)
product = models.CharField(max_length=50)
quantity = models.IntegerField()
unit_of_measurement = models.CharField(max_length=20, blank=True, null=True)
expected_time = models.DateField()

def __str__(self):
    return self.product

and cartItem model that references the product model (product field) and the owner of the product (product_owner field). The product_owner field is to keep tract of the owner of the product so that whenever an order is placed, I will know the owner whose products are being bought.
class CartItem(models.Model):
cart = models.ForeignKey('Cart',null=True, blank =True,on_delete=models.CASCADE)
product = models.ForeignKey(Product,related_name="product", on_delete=models.CASCADE)
quantity=models.IntegerField(default=1)
product_owner=models.ForeignKey(User, related_name="owner", on_delete=models.CASCADE,blank=True,null=True)
line_total=models.DecimalField(max_digits=10, decimal_places=2, default=0.00)

def __str__(self):
    try:
        return str(self.cart.id)
    except:
        return self.product.title

in the view.py I tried adding the owner of product as in the case below
if request.method == "POST":
    qty = request.POST['qty']
    product= Product.objects.get(slug=slug)

    cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product)

    cart_item.quantity = qty

    cart_item.product_owner = product.user
    cart_item.save()

when i submit locally, the owner gets added to the cartItem, but on the server, it throws an error: django.db.utils.ProgrammingError: column cart_cartitem.product_owner_id does not exist
 LINE 1: ...rtitem"."product_id", "cart_cartitem"."quantity", "cart_cart...
what is the best way to add the product owner to the cartItem?
Thank you.

A: The error is simply saying that the column it's trying to save data to does not exists.
django.db.utils.ProgrammingError: column cart_cartitem.product_owner_id does not exist LINE 1: ...rtitem"."product_id", "cart_cartitem"."quantity", "cart_cart...

Simply run in your terminal and try again.
python manage.py makemigrations
python manage.py migirate


text:
Q: Unable to Parse xml DOM (from file) with java script I've recently begun running into problems with javascript when I attempt to load element tags from a separate xml file into an html document. I know that I have enabled either XMLHttpRequest or activeX (depending on the internet browser) correctly, but I'm having problems getting the xml file and opening it to access it's tags. In order to open the file, I tried to use:
xhttp.open("GET",filepath,false);
xhttp.send();
xmlDoc=xhttp.responseXML;

the code appears to make it past the first line, but it gets tripped up at the second. I'm wondering if someone would be able to clarify the function of .send(), and if server permissions may by at fault; IE 7/8 it tells me "access is denied" when this block of code runs.

A: Make sure that ajax requests are sent to the same domain from the resources were accessed.
Taking your code sample here,
xhttp.open("GET",filepath,false);
xhttp.send();

You have requested for a resource with HTTP method GET. This request will be fired only once the send() method is called on the XHR object according to the specification[1]. The arguments for send() will be ignored if the method is GET.
Now once the xhr object is created, it goes through different states[2] such as

*

*UNSENT (numeric value 0)

*OPENED (numeric value 1)

*HEADERS_RECEIVED (numeric value 2)

*LOADING (numeric value 3)

*DONE (numeric value 4)

The moment the request is fired(ie , the send() is called), the xhr object will have a state of OPENED.
Now, if we look at the 3rd line of your code "xmlDoc=xhttp.responseXML;", it is quite unclear at what state you are trying to read the content. The best way to read the content is when the state reaches 4 or DONE
Just modify your code as given below:
 var xhr = new XMLHttpRequest();
    xhr.open("GET", somefilepath, true);
    xhr.send();
    xhr.onreadystatechange = function() {
     if(this.readyState == 4) {
      xmlDoc=xhr.responseXML;
     }
   }


text:
Q: How reliable is the "projection" media type in css? I'm working on a corporate project, creating a system that will be used for years.
I've recently come across the "projection" media type in css, and I'm imagining potential benefits it could have for the users, giving presentations, etc, but I don't know if that's just in my imagination, or if there is a real world advantage here. So far all I'm aware of is that some versions of Opera use the media type in fullscreen mode.
W3C media type entries: http://www.w3.org/TR/CSS2/media.html
Does any browser detect the projection media type when being used on a projector?
Is that even possible? I have a hunch that, as far as a browser is concerned, a projector is just a screen, so there's no detection. It would be great if I was wrong.
Has anybody had any success with the projection media type?

A: I use projection mode all the time, but unfortunately only Opera 12 and earlier implement it. You hit F11 to start it, and then the CSS projection media kicks in.
I put each slide in a div, and then use the CSS:
/* Each slide is a plain div.
   Special pages (intro material, etc,) have classes like cover, intropage, endpage */
body>div {
    border: medium black solid;
    margin: 1em 0;
    width: 40em;
    padding-bottom: 0;
    page-break-inside: avoid;
    overflow: hidden;
 }

@media projection { /* changes/adds the following properties */
    body {font-size: 20pt; margin-left: 0; padding: 0}
    body>div { page-break-after: always;
               border-style: none; margin: 0; width: 100%}
}

A: As far as my research has shown, the projection media type is only currently used by Opera in fullscreen mode.
Hooking my computer up to a projector and setting the display mode to "projector" in my display settings seems to have no effect on the stylesheet chosen by any browser.
Code Style has a good summary of different browsers and their compatibility with the different CSS Media Modes.


text:
Q: How to make this CLR work with 2005? I am trying to make a clr stored procedure for a sql 2005 database that uses .net 3.5 assemblies
So first I had to change sql 2005 to recognize system.core as unsafe what I am not too happy about(I rather have had it say SAFE).
Now I get this error
 Msg 6522, Level 16, State 1, Procedure StoredProcedure1, Line 0
A .NET Framework error occurred during execution of user defined routine or aggregate 'StoredProcedure1':
System.Security.HostProtectionException: Attempted to perform an operation that was forbidden by the CLR host.

The protected resources (only available with full trust) were: All
The demanded resources were: MayLeakOnAbort

System.Security.HostProtectionException:
   at StoredProcedures.StoredProcedure1(String UtcDateTime)

Here is my code
Exec StoredProcedure1 '7/8/2010 5:00:00 am'

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void StoredProcedure1(string UtcDateTime)
    {
        SqlPipe p = SqlContext.Pipe;
        DateTime converted = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(Convert.ToDateTime(UtcDateTime), "Pacific Standard Time");

        p.Send(converted.ToString());

    }
};

I did not know how to pass in a datetime into it so I used a string then converted it.

A: To get this to work you'd have to set it as UNSAFE.
Apparently, some TimeZoneInfo methods have HostProtectionAttribute set which means they can't be used in SQL Server CLR code.
Unless you decide "I don't care about stability and know better". I take no responsibility if your server becomes a smoking crater in the ground if you use UNSAFE...


text:
Q: Pythonic way for double for loop I have the following code:
import numpy as np
epsilon = np.array([[0.        , 0.00172667, 0.00071437, 0.00091779, 0.00154501],
           [0.00128983, 0.        , 0.00028139, 0.00215905, 0.00094862],
           [0.00035811, 0.00018714, 0.        , 0.00029365, 0.00036993],
           [0.00035631, 0.00112175, 0.00022906, 0.        , 0.00291149],
           [0.00021527, 0.00017653, 0.00010341, 0.00104458, 0.        ]])
Sii = np.array([19998169., 14998140.,  9997923.,  7798321.,  2797958.])
n = len(Sii)

epsilonijSjj = np.zeros((n,n))
for i in range(n):
    for j in range(n):
        epsilonijSjj[i,j] = epsilon[i][j]*Sii[j]

print (epsilonijSjj)

How can I avoid the double for loop and write the code in a fast Pythonic way?
Thank you in advance

A: Numpy allow you to multiply 2 arrays directly.
So rather than define a 0 based array and populating it with the altered elements of the other array, you can simply create a copy of the other array and apply the multiplication directly like so:
import numpy as np

epsilon = np.array([[0.        , 0.00172667, 0.00071437, 0.00091779, 0.00154501],
           [0.00128983, 0.        , 0.00028139, 0.00215905, 0.00094862],
           [0.00035811, 0.00018714, 0.        , 0.00029365, 0.00036993],
           [0.00035631, 0.00112175, 0.00022906, 0.        , 0.00291149],
           [0.00021527, 0.00017653, 0.00010341, 0.00104458, 0.        ]])
Sii = np.array([19998169., 14998140.,  9997923.,  7798321.,  2797958.])

epsilonijSjj = epsilon.copy()
epsilonijSjj *= Sii

print(epsilonijSjj)

Output:
[[    0.         25896.8383938   7142.21625351  7157.22103059
   4322.87308958]
 [25794.23832127     0.          2813.31555297 16836.96495505
   2654.19891796]
 [ 7161.54430059  2806.7519196      0.          2289.97696165
   1035.04860294]
 [ 7125.54759639 16824.163545    2290.12424238     0.
   8146.22673742]
 [ 4305.00584063  2647.6216542   1033.88521743  8145.97015018
      0.        ]]

Or, just do this, which is faster because it doesn't require creating a copy of an array:
import numpy as np

epsilon = np.array([[0.        , 0.00172667, 0.00071437, 0.00091779, 0.00154501],
           [0.00128983, 0.        , 0.00028139, 0.00215905, 0.00094862],
           [0.00035811, 0.00018714, 0.        , 0.00029365, 0.00036993],
           [0.00035631, 0.00112175, 0.00022906, 0.        , 0.00291149],
           [0.00021527, 0.00017653, 0.00010341, 0.00104458, 0.        ]])
Sii = np.array([19998169., 14998140.,  9997923.,  7798321.,  2797958.])

epsilonijSjj = epsilon * Sii


text:
Q: Getting XHTML embedded in XML I'm trying to get XHTML embedded in an XML node like this:
<entry xmlns="http://www.w3.org/2005/Atom">
    ...
    <content type="xhtml">

some text

    </content>
    ...
</entry>

I expect to get:

some text

But all I get is:
some text

And this is my code so far:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder db = factory.newDocumentBuilder();
Document doc = db.parse(methodeArticleXml);

System.out.println(doc.getElementsByTagName("content").item(0).getTextContent());

The parser is treating the content as XML instead XHTML or plain text, is there a way around this?
I can't change the format of the document, so using CDATA is not an option.

A: Here's a hack with a regex
Pattern pattern = Pattern.compile("<content[^>]*>(.*?)</content>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(xml);
while (matcher.find()) {
    String content = matcher.group(1);
    doStuff(content);
}


text:
Q: How read data from serialport? I write simple program to send i read data form serial port. I was able to send the message correctly (and I correctly received it on my another device), but when I try to read a message sent form another device it get an error:
Error reading: Resource temporarily unavailable

This is my code:
char port_name[] = "/dev/ttyACM0";

    int port = open(port_name, O_RDWR | O_NOCTTY | O_NDELAY);
    if(port < 0){
        fprintf(stderr, "Error opening: %s\n", strerror(errno));
    }
    struct termios settings;
    memset(&settings, 0, sizeof(settings));

    tcgetattr(port, &settings);

    cfsetispeed(&settings, B9600);
    cfsetospeed(&settings, B9600);
    settings.c_cflag &= ~PARENB;
    settings.c_cflag &= ~CSTOPB;
    settings.c_cflag &= ~CSIZE;
    settings.c_cflag |= CS8;
    settings.c_lflag &= ~(ECHO | ECHONL | ICANON | IEXTEN | ISIG);
    settings.c_cflag &= ~CRTSCTS;
    settings.c_cflag |= (CLOCAL | CREAD);
    settings.c_cc[VMIN] = 0;
    settings.c_cc[VTIME] = 10;

    tcflush(port, TCIFLUSH);
    int er = tcsetattr(port, TCSANOW, &settings);
    if(er < 0){
        fprintf(stderr, "Error set: %s\n", strerror(errno));
    }

    char* str = "ABCD";

    int res = write(port, str, strlen(str));
    if(res < 0){
        return;
    }

    char buffer[1000];
    memset(&buffer, '\0', sizeof(buffer));

    int n = read(port, &buffer, sizeof(buffer));
    if(n < 0){
        fprintf(stderr, "Error reading: %s\n", strerror(errno));
        return;
    }

    printf("Read %i bytes. Reseived message: %s", n, buffer);

    close(port);

How could I fix that?

A: You opened the device with O_NDELAY, which places the descriptor into non-blocking mode. If there is nothing to be read then EWOULDBLOCK is returned from read. You could for example:

*

*remove O_NDELAY from there for this simple program

*use poll/select etc to wait for the descriptor to become readable.


text:
Q: List Table action argument not cleared I use a subclass of the list table class in my plugin to list logged mails. You can select multiple mails to resend or delete. The form data is send to the same page again.
The entries are sortable. This means for the header columns links are created by appending the orderby and order GET-parameters (base class behavior) to the current url.
Select a mail and action resend.
Before actions:
admin.php?page=wpml_plugin_log

Submit
After page submitted and actions handled:
admin.php?page=wpml_plugin_log&bulkactionsnonce=3bb20a74fd&_wp_http_referer=%2Fwp-admin%2Fadmin.php%3Fpage%3Dwpml_plugin_log&search_date&s&_wpnonce=35ec405ae8&action=resend&email%5B0%5D=59&action2=-1&orderby=timestamp&order=asc

But I expect no 'action', 'action1', 'email' arguments in the url anymore.
The link after the actions are processed contains the 'action' param. This means if you change the order of the columns the mail is resend over and over again (this makes no sense). The url also grows and results in a URI too long webserver-error (in case of apache) after some time of usage.
How can I avoid this behavior?

A: Let me start with a question: What if the user simply refreshes the page after the action is processed? It will resubmit the action.
So the issue is not only with the links for the sortable column header and how WP_List_Table is generating them but with the way you are handling the action requests.
The best practice is to redirect the user back to a URL excluding the action parameter after processing the action, and have the page rendered on the second request instead of rendering it on the action request.
For example:

*

*User starts here: admin.php?page=wpml_plugin_log

*User sends a request to admin.php?page=wpml_plugin_log&action=delete&id=123

*Delete action is handled

*User is redirected back to admin.php?page=wpml_plugin_log&delete_success=123
As you see above, you may also add some other parameters (delete_success) to the redirect URL to pass the state of the handled action to the second request.


text:
Q: How to delete multiple columns by title? I have a worksheet that has about 80 columns, I want to remove a bunch of them and these are updated on an ongoing basis and may move around so I want to delete them by their column title. However, when I run this macro, it works, but I actually need to run it at least 4-5 times for it to completely remove all the correct columns. What is going on here? Is there a correct and more elegant way to do this?
Sub Modify_Table()
    ' Remove specific columns
    Set MR = ActiveSheet.Range("A1:BQ1")

    For Each cell In MR
        If cell.Value = "Attack ID" Then
            cell.EntireColumn.Delete
        ElseIf cell.Value = "Last Change (UTC)" Then
            cell.EntireColumn.Delete
        ElseIf cell.Value = "Tools/Malware" Then
            cell.EntireColumn.Delete
        ElseIf cell.Value = "Labels" Then
            cell.EntireColumn.Delete
        ElseIf cell.Value = "Attacker Profile" Then
            cell.EntireColumn.Delete
        ElseIf cell.Value = "Leak Rate" Then
            cell.EntireColumn.Delete
        ElseIf cell.Value = "Footprint" Then
            cell.EntireColumn.Delete
        ElseIf cell.Value = "Target Node" Then
            cell.EntireColumn.Delete
        ElseIf cell.Value = "Test Time (UTC)" Then
            cell.EntireColumn.Delete
      ...
        Else
    End If
    Next

End Sub

A: Iterate from the last item to the first item when deleting items.  Otherwise, you will end up skipping items.  This is because the items are shifted when you delete one
In this case, I would create a range that contains all the headers to be deleted and then delete them all at once.
Sub Modify_Table()
    ' Remove specific columns
    Dim HeaderRange As Range

    Set HeaderRange = ActiveSheet.Range("A1:BQ1")

    Dim Target As Range
    Dim Cell As Range
    Dim Titles As Variant
    Titles = Array("Attack ID", "Last Change (UTC)", "Tools/Malware", "Labels", "Attacker Profile", "Leak Rate", "Footprint", "Target Node", "Test Time (UTC)")

    For Each Cell In HeaderRange
         If Not IsError(Application.Match(Cell.Value, Titles, 0)) Then
            If Target Is Nothing Then
                Set Target = Cell
            Else
                Set Target = Union(Target, Cell)
            End If
         End If
    Next

    If Not Target Is Nothing Then Target.EntireColumn.Delete

End Sub

A: I wasn't able to get TinMan answers working, could be my tables but combining his one and linked post by chris neilsen. I was able to get it working in my environment.
Sub Modify_Table()
    ' Remove specific columns

    Dim HeaderRange As Range

    Set HeaderRange = ActiveSheet.Range("A1:BQ1")

    Dim Target As Range
    Dim Titles As Variant
    Titles = Array("Attack ID", "Last Change (UTC)", "Tools/Malware", "Labels", "Attacker Profile", "Leak Rate", "Footprint", "Target Node", "Test Time (UTC)")

    Dim c As Long
    For c = ActiveSheet.UsedRange.Columns.Count To 1 Step -1
        If Not IsError(Application.Match(ActiveSheet.UsedRange.Columns(c).Cells(1, 1), Titles, 0)) Then
            ActiveSheet.Columns(c).EntireColumn.Delete
        End If
    Next c
End Sub


text:
Q: unified_thread fql table available to public or not? I see facebook removed the banner from the unified_thread documentation page (which previously stated it was for developers accounts only) but I still get the "must be a developer" error.  Am I doing something wrong, or did FB just remove it by mistake?

A: My testing shows a "ERROR: Error 298 You must be a developer of the application".
I assume they removed it by mistake, because other pages, such as the Graph API Thread documentation still shows the message.


text:
Q: Tag Form fecha sozinha Quando envio esse código html via ajax ele exibe corretamente, porém fecha a tag Form logo após a abertura da mesma, existe outra forma de fazer isso? ou há algum erro de sintaxe.
$FormUserCad = '

<form action="oi.php" method="post">

Nome:

<input name="nome" type="text">

Idade:

<input type="text">

Rua:

<input type="text">

...
</form> <--

$retorno = array('codigo' => 0, 'mensagem' => $FormUserCad);
            echo json_encode($retorno);
            exit();

A: Ajuste seu html para a forma correta da estrutura html. E depois tente usar o htmlspecialchars
$FormUserCad = '

       <form action="oi.php" method="post">

Nome:

<input name="nome" type="text">

Idade:

<input type="text">

Rua:

<input type="text">

        ...

       </form>

';

    $retorno = array('codigo' => 0, 'mensagem' => htmlspecialchars($FormUserCad,ENT_QUOTES));
    echo json_encode($retorno);
    exit();


text:
Q: In Android how do I upload something to an anonymous Dropbox File Request? The Dropbox Android SDK supports uploading a file to the user's Dropbox account through the DropboxAPI.UploadRequest API. However, this API requires a valid Session object, meaning it is only meant to be used to modify files of the logged in user. But Dropbox also supports anonymous file requests which allow anybody, even non Dropbox users, to upload files to a directory.
How can I upload a content to these Dropbox file requests without requiring the user to have a Dropbox account?

A: The Dropbox File Requests feature doesn't require end-users to have a Dropbox account to submit files via the web site, however Dropbox doesn't offer a programmatic interface for doing so. We'll consider this a feature request for one though.


text:
Q: OSX: Mimic Ubuntu IP Masquerading via iptables with ipfw Good day,
I am attempting to replicate a setup I have between a router and an Ubuntu PC, and have the same setup working on my MacBook (10.6, Snow Leopard).
First, I have a router that has a USB port. When I plug it into my Ubuntu PC, it creates an RNDIS connection, allowing me to connect to the router over the USB cable via an IP connection. When I plug it into my computer via USB, it gets assigned an IP address of 172.16.84.1, and a new adapter appears when I type ifconfig. I can then SSH into the device via ssh admin@172.16.84.1.
When I log in to the device, I flush the routes, then create the default route:
admin@localhost> route -f
admin@localhost> route add default 172.16.84.2

Now, in my Ubuntu machine, I use iptables to enable IP masquerading:
root@Valhalla> sudo iptables -t nat -A POSTROUTING -s 172.16.84.2 -j MASQUERADE

Once this is all done, the router has internet access over the USB connection to my PC.
I am trying to replicate this exact setup on my MacBook now (Snow Leopard), but iptables does not exist for OSX, not even a Macports version exists. I have scoured through other questions on StackOverflow that cover the usage of the ipfw command, which apparently works as a drop-in replacement for iptables. However, the syntax is significantly different, and I'm pretty much lost.
Does anyone with some experience with ipfw have some suggestions on how I could accomplish this and create a NAT connection via IP masquerading like I could with my Ubuntu PC?
Thank you for your assistance.

A: why you just not use simple internet sharing on you macosx ?
System Preferences > Sharing > Internet Sharing
for ipfw nat rules are (lats say that your internet is en0 and local interface en1)

*

*sysctl -w net.inet.ip.fw.one_pass=1 (you need to be root)

*sysctl -w net.inet.ip.forwarding=1

*/sbin/ipfw add 1040 allow ip from any to any via en1 (allow everything that will pass via local interface)

*/sbin/ipfw add divert natd all from any to any via en0

*/sbin/ipfw add pass all from any to any natd -interface en0 (where en0 your outgoing interface)

*/usr/sbin/natd -interface en0 (nat itself)

A: well, the easiest way to do it using OSX is simply by using the System Preferences->Sharing->Internet Sharing. You check Internet Sharing, and configure it so it states Share your connection from Ethernet 2 (as I suppose your USB network device appears as), To computers using Ethernet (as I suppose you want your local network to be on Ethernet, otherwise choose airport or anything relevant).
The bearded way to do it is to indeed use ipfw and route. A simple google search gives a good tutorial on both methods at the following URL:
http://www.ibiblio.org/macsupport/ipfw/ (the commandline way is after the GUI way)
HTH


text:
Q: Using SqlBotDataStore for bot state falls back instead to state.botframework.com I'm using the Nuget Microsoft.Bot.Builder.Azure package extensions to store my bot's state. BotBuilder 3.14.0, Bot.Builder.Azure 3.2.5.
I've been successfully using TableBotDataStore up until now, using Azure table storage. On starting a conversation, I can immediately inspect the table and see relevant rows created in it.
I tried using SqlBotDataStore, having run the script to create the table in my (Azure) SQL Server DB. I registered it as per the sample code, but on redeployment I find that, although no errors are thrown, no entries are created in the SqlBotDataEntities table, and instead state.botframework.com is being called as part of the request dependencies.
var sqlStore = new SqlBotDataStore(ConfigurationManager.
    ConnectionStrings["SqlBotStorage"].ConnectionString);

builder.Register(c => sqlStore)
                    .Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)
                    .AsSelf()
                    .SingleInstance();

has replaced the (working)
var azureTableStore = new TableBotDataStore(
    ConfigurationManager.ConnectionStrings["TableStorageCS"].ConnectionString,
    sBotStorageTableName);

builder.Register(c => azureTableStore)
                    .Keyed<IBotDataStore<BotData>>(AzureModule.Key_DataStore)
                    .AsSelf()
                    .SingleInstance();

builder.Register(c => new CachingBotDataStore(azureTableStore,
                    CachingBotDataStoreConsistencyPolicy
                    .ETagBasedConsistency))
                    .As<IBotDataStore<BotData>>()
                    .AsSelf()
                    .InstancePerLifetimeScope();

I know the connection string is kosher, as I tried a test in a dummy action method:
IBotDataStore<BotData> sqlds = new SqlBotDataStore(
    ConfigurationManager.ConnectionStrings["SqlBotStorage"].ConnectionString);

var key = new Address("botidhere", "effbee", "uid1", "c1", "x.com");
var bd = new BotData(data: new Dialogs.SimpleResponseDialog("message here"));
await sqlds.SaveAsync(key, BotStoreType.BotUserData, bd, default(CancellationToken));

and that adds a row just fine.
What else am I missing? The relevant connection string is stored in Azure application settings, as a connection string of type 'SQLAzure':
Server=tcp:xxxx.database.windows.net;Initial Catalog=xxxx;Persist Security Info=False;User ID=xxxx;Password=xxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;

A: I appear* to have fixed it - I was missing the AzureModule registration line:
builder.RegisterModule(new AzureModule(System.Reflection.Assembly.GetExecutingAssembly()));

Here's the thing though - this wasn't needed for using TableBotDataStore. Only SqlBotDataStore.
Another thing: adding the line fixed the issue immediately in an Azure deployment slot with a debug build, system.debug=true.  However, deploying to the main webapp (non-slot) with a release build, system.debug=false caused the app to be unable to start. '503 Service Unavailable'. No logs. Reverting immediately to table storage and all was well again.
I'm currently try..catching the above line, but I can't see an exception thrown, yet it has started working now. One to keep an eye on!
*with caveats above...


text:
Q: A* Python implementation problems So, I've got an assignment, I need to implement the A* algorithm in Python, but I've hit a roadblock.
I've written most of it, but I can't figure out why isn't it working properly (i.e doesn't produce the best path)
I figured maybe someone more knowledgeable might point out the obvious issue with it.
from mpl_toolkits import mplot3d
from matplotlib import cm
from queue import PriorityQueue
import matplotlib.pyplot as plt
import numpy as np

#Defining working files and work area size
N = 100
# fileNameIn = 'surface_'+str(N)+'x'+str(N)+'_separator.txt'
# fileNameEnd = 'surface_'+str(N)+'x'+str(N)+'_separator.end_points.txt'
fileNameIn = 'surface_'+str(N)+'x'+str(N)+'.txt'
fileNameEnd = 'surface_'+str(N)+'x'+str(N)+'.end_points.txt'

#This is needed for 3D plotting, otherwise the surface is rendered above the obstacles and paths
surfaceAlpha = 0.5

#Initial values
x0 = 0
y0 = 0
xn = 0
yn = 0
lepes1 = 0
lepes2 = 0

#Clearing/creating result file
f = open('result.txt', 'w')
f.write("")
f.close()

#Allocating work area matrix
matrix = np.zeros((N, N))

#Reading in the work area
def ReadIn():
    fi = open(fileNameIn, 'r')
    lines = fi.readlines()
    fi.close()

    global matrix
    x = 0
    y = 0
    z = 0.0
    b = 0

    for line in lines:
        tmp = line.split()
        x = int(tmp[0])
        y = int(tmp[1])
        z = float(tmp[2])
        b = int(tmp[3])
        if (b != 0):
            z = -1 *z

        matrix[x][y] = z

#Reading in the end-points
def ReadEnd():
    fe = open(fileNameEnd, 'r')
    lines = fe.readlines()
    fe.close

    global x0, y0, xn, yn
    x0, y0 = map(int, lines[0].split())
    xn, yn = map(int, lines[1].split())

#Plotting in 2D
def Heatmap2D(Xe1, Ye1, Xe2, Ye2, matrix):

    Xo = []
    Yo = []

    for i in range(N):
        for j in range(N):
            if (matrix[i][j] < 0):
                Xo.append(i)
                Yo.append(j)

    plt.figure(1)
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.imshow(abs(matrix.transpose()), cmap=cm.coolwarm)
    plt.colorbar()
    plt.plot(Xe1, Ye1, color='green')
    plt.plot(Xe2, Ye2, color='purple')
    plt.scatter(Xo, Yo, color='black', s=1)
    plt.scatter(x0, y0, color='yellow', s=10)
    plt.scatter(xn, yn, color='orange', s=10)

#Plotting in 3D
def Heatmap3D(X, Y, Xe1, Ye1, Ze1, Xe2, Ye2, Ze2, matrix):
    Z = abs(matrix)
    Zo = []

    for i in range(N):
        for j in range(N):
            if (matrix[i][j] < 0):
                Zo.append((i, j, abs(matrix[i][j])))

    fig3D = plt.figure(2)
    ax3D = fig3D.add_subplot(111, projection='3d')
    #ax3D.scatter(X, Y, Z, c=Z, cmap=cm.coolwarm, alpha=surfaceAlpha) #Worse performance
    ax3D.plot_surface(X, Y, Z, cmap=cm.coolwarm, alpha=surfaceAlpha)

    for it in Zo: ax3D.scatter(it[1], it[0], it[2], c='black', alpha=1, s=1)
    ax3D.scatter(y0, x0, abs(matrix[x0][y0]), c='yellow', s=10)
    ax3D.scatter(yn, xn, abs(matrix[xn][yn]), c='orange', s=10)

    ax3D.plot3D(Ye1, Xe1, Ze1, 'green', alpha=1)
    ax3D.plot3D(Ye2, Xe2, Ze2, 'purple', alpha=1)

#Calculating euclidean distance between two points
def Distance(x1, y1, x2, y2):
    z1 = abs(matrix[x1][y1])
    z2 = abs(matrix[x2][y2])

    return np.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2)

#Heuristic calculation
def H_score(x, y, H):
    z = abs(matrix[x][y])
    zn = abs(matrix[xn][yn])

    if (H == 0):
        return abs(x - xn) + abs(y - yn) + abs(z - zn) #Manhattan
    elif (H == 1):
        return max(abs(xn - x), abs(yn - y))#, abs(zn - z)) #Chebyshev
    else:
        return Distance(x, y, xn, yn) #Euclidean

#Exact calculation
def G_score(prevG, x, y, x1, y1, H):
    d = 0
    z = abs(matrix[x][y])
    z1 = abs(matrix[x1][y1])

    if (H == 0):
        d = abs(x - x1) + abs(y - y1) + abs(z - z1) #Manhattan
    elif (H == 1):
        d = max(abs(x1 - x), abs(y1 - y))#, abs(z1 - z)) #Chebyshev
    else:
        d = Distance(x, y, x1, y1)

    d = d + prevG

    return d / 1.0 #Division is only here for testing

#Check if 2 points are neighbours or not
def Neighbour(x1, y1, x2, y2):
    szomsz = False

    if ((abs(x1 - x2) <= 1) and (abs(y1 - y2) <= 1) and IsValid(x1, y1) and IsValid(x2, y2) and (not ((x1 == x2) and (y1 == y2)))):
        szomsz = True
    else:
        szomsz = False

    return szomsz

#Check if point is valid (i.e is inside of work area/matrix and is not an obstacle)
def IsValid(x, y):
    valid = False

    if ((x >= 0) and (x < N) and (y >= 0) and (y < N) and (matrix[x][y] >= 0.0)):
        valid = True
    else:
        valid = False

    return valid

#Check if point is end point
def IsGoal(x, y):
    if (x == xn and y == yn):
        return True
    else:
        return False

#Check if element is in OpenList
def OLCheck(elem):
    global OpenList

    check = False
    for it in OpenList.queue:
        if (it[0] >= elem[0] and it[1] == elem[1] and it[2] == elem[2]):# and it[3] == elem[3]):
            check = True
            break

    return check

#Check if element is in CloseList
def CLCheck(elem):
    global CloseList

    check = False
    for it in CloseList:
        if (it[0] == elem[1]):# and it[1] == elem[2] and it[2] == elem[3]):
            check = True
            break

    return check

#Getting neighbours
def Expand(elemP, H):
    global OpenList, CloseList
    X = [-1, 0, 1]
    Y = [-1, 0, 1]
    xp = elemP[1][0]
    yp = elemP[1][1]

    factor = 1.09 * 100 #For testing purposes

    for ix in X:
        x = xp + ix
        for iy in Y:
            y = yp + iy
            if (Neighbour(xp, yp, x, y)):
                G = G_score(elemP[3] / factor, xp, yp, x, y, H)

                f = G + H_score(x, y, H)

                elem = (f, (x, y), (xp, yp), G)

                if ((not CLCheck(elem)) and (not OLCheck(elem))):
                    OpenList.put(elem)

#A* algorithm
def A_star(H):
    global OpenList, CloseList, dist, Result

    if (OpenList.empty()):
        print('ERROR: Empty Open List!')
        return -1

    maxLepesek = 10000
    lepesek = 0

    while (not OpenList.empty()):
        elem = OpenList.get()
        x = elem[1][0] #Current
        y = elem[1][1]
        xp = elem[2][0] #Previous of current
        yp = elem[2][1]
        G = elem[3] #G_score of current

        CloseList.append(((x, y), (xp, yp), G))

        if (IsGoal(x, y)): break        #End of algorithm

        if (lepesek >= maxLepesek):
            print('ERROR:', maxLepesek, 'lepes elerve'); return -2     #Failsafe

        if (len(CloseList) <= 1): dist = 0.0
        else: dist = dist + G #Distance(x, y, xp, yp)

        Expand(elem, H)
        lepesek = lepesek + 1

    print('A* lepesek: ', lepesek, '/', maxLepesek)
    return 0

#Getting Result array from CloseList
def getResult():
    global distS
    Res = []

    #for it in CloseList: Res.append(it[0])
    #return Res

    Res.append((xn, yn))

    while ((x0, y0) not in Res):
        tempR = Res[len(Res) - 1]
        for it in reversed(CloseList):
            if (it[0] == tempR):
                distS = distS + it[2]
                Res.append(it[1])
                break

    return Res[::-1]

#Writing out
def Kiir(Result):
    print('Length:', dist)
    print('Length (post Result calculation):', distS)
    print('Steps:', lepes-1)
    print('\n')

    f = open('result.txt', 'a')

    f.write(str(Result))
    f.write("\n")

    f.close()

# Main part =======================================================
ReadIn()
ReadEnd()

# a =============================================
OpenList = PriorityQueue()
OpenList.put((0, (x0, y0), (x0, y0), 0))
CloseList = []
Result = []
dist = 0.0
distS = 0.0
retval = -1

Xe1 = []
Ye1 = []
Ze1 = []
retval = A_star(1)
if (retval == 0):
    Result = getResult()

lepes = len(Result)

for it in Result:
    Xe1.append(it[0])
    Ye1.append(it[1])
    Ze1.append(matrix[it[0]][it[1]])

for i in range(len(Result)-1):
    x1 = Result[i][0]
    y1 = Result[i][1]
    z1 = matrix[x1][y1]
    x2 = Result[i+1][0]
    y2 = Result[i+1][1]
    z2 = matrix[x2][y2]

print("Chebyshev: (Green)")
Kiir(Result)

# b =============================================
OpenList = PriorityQueue()
OpenList.put((0, (x0, y0), (x0, y0), 0))
CloseList = []
Result = []
dist = 0.0
distS = 0.0
retval = -1

Xe2 = []
Ye2 = []
Ze2 = []
retval = A_star(2)
if (retval == 0):
    Result = getResult()

lepes = len(Result)

for it in Result:
    Xe2.append(it[0])
    Ye2.append(it[1])
    Ze2.append(matrix[it[0]][it[1]])

for i in range(len(Result)-1):
    x1 = Result[i][0]
    y1 = Result[i][1]
    z1 = matrix[x1][y1]
    x2 = Result[i+1][0]
    y2 = Result[i+1][1]
    z2 = matrix[x2][y2]

print("Euclidean: (Purple)")
Kiir(Result)

# plot ==========================================

X, Y = np.meshgrid(range(N), range(N))
Heatmap2D(Xe1, Ye1, Xe2, Ye2, matrix)
#Heatmap3D(X, Y, Xe1, Ye1, Ze1, Xe2, Ye2, Ze2, matrix)
plt.show()

My best guess is that I do not compute the G_score correctly (I do not really take into consideration the distance from the first node, because when I do, the code tends to run forever :c )
Here are the input files:
surface_100x100.txt
https://pastebin.com/N9dHG5K9
surface_100x100.end_points.txt
0 0
99 30


text:
Q: image of convex closed, bounded subspace of H by monotonous continuous operator is closed Let H be a Hilbert space and K a convex closed, bounded subspace of H.
Let $F : H → H$ be continuous monotonous function.
Prove that $F(K)$ is closed.
My argument is the following:
K is closed under H so K is a Hilbert space. F is continuous and monotonous so F(K) is a Hilbert subspace of H. I am not sure how to go from there.
Any hints or help?
Thank you.

A: This is not true for $K$ being a subspace. Take $F$ to be linear, compact, and monotone. Let $K=H$. Compact operators do not have closed range.
It is true, if $K$ is assumed to be a convex, closed, bounded subset of $H$. Let $(x_n)$ be a sequence in $K$ such that $F(x_n)\to y$. It remains to show that there exists $x\in K$ with $F(x)=y$.
Since $K$ is weakly sequentially compact, we can assume (after possibly extracting a subsequence) that $x_n \rightharpoonup x$ with $x\in K$.
Take some $v\in H$. By monotonicity, we have
$$
\langle F(x_n)-F(v),x_n-v\rangle\ge0.
$$
Passing to the limit shows
$$
\langle y-F(v),x-v\rangle\ge0\quad \forall v.
$$
Setting $v=x+ tw$ for some $w\in H$, $t>0$ gives
$$
\langle y-F(x+ tw),-t w\rangle\ge0
$$
Dividing by $t$, letting $t\searrow 0$ gives
$$
\langle y-F(x),-w\rangle\ge0\quad \forall w
$$
hence $y=F(x)$.