text:
Q: How to compare 2 array and display them in one table I have 2 arrays, one array contains staff info while the second one contains staff sales.
For staff info array it contain id and name while staff sales array contain staff id and total sales.
I tried to display those 2 array but when i tried only 2 data is display.
While i needed the id without the sales to be display also.
My Code :
<?php
$employees = [
    $i = [

        "id" => "1",
        "name" => "Aliff",
    ],
    $p = [

        "id" => "2",
        "name" => "Aina",
    ],
    $a = [

        "id" => "3",
        "name" => "Ana",
    ]
];
$employee_sales = [
    $i = [
        "id" => "1",
        "amount" => "500",
    ],
    $p = [
        "id" => "3",
        "amount" => "300",
    ],
];
?>

<?php
// echo '
';
// var_dump($employees);
// var_dump($employee_sales);
foreach ($employees as $employee) {
    foreach ($employee_sales as $employee_sale) {
        if ($employee['id'] == $employee_sale['id']) {
        ?>

                <?= $employee['id']; ?>
                <?= $employee['name']; ?>
                <?= $employee_sale['amount']; ?>

        <?php
        }
    }
}
?>

<?php
foreach ($employees as $employee) {
?>

            <?= $employee['id']; ?>
            <?= $employee['name']; ?>

<?php } ?>

<?php
foreach ($employee_sales as $employee_sale) {
?>

            <?= $employee_sale['id']; ?>
            <?= $employee_sale['amount']; ?>

<?php } ?>

I want staff id number 2 to be display also even though that staff didnt have any total sales.
Want to display the amount = 0 because the staff didnt have any sales.

A: Add a variable that tells whether any sales were printed for the employee. If not, print a row with empty sales.
foreach ($employees as $employee) {
    $sales_found = false;
    foreach ($employee_sales as $employee_sale) {
        if ($employee['id'] == $employee_sale['id']) {
        $sales_found = true;
?>

    <?= $employee['id']; ?>
    <?= $employee['name']; ?>
    <?= $employee_sale['amount']; ?>

<?php }
    }
    if (!$sales_found) { ?>

        <?= $employee['id']; ?>
        <?= $employee['name']; ?>
        0

    <?php
    }
} ?>

A: Please check this one.
<?php
 $employees = array(1=> array('id' => "1" , 'name' => 'Aliff')  ,2 => array('id' => "2" , 'name' => 'Aina'),3 => array('id' => "3" , 'name' => 'Ana')  );

  $employee_sales = array(1 => array('id' => "1" , 'amount' => '500')  ,2 => array('id' => "3" , 'amount' => '300'));

  $data = array();
 foreach ($employees as $key => $value) {

   $data[$value['id']] = $value['name'];

 }

   $data1 = array();
 foreach ($employee_sales as $key1 => $value1) {
    $data1[$value1['id']] = $value1['amount'];

 }

?>

     <?php foreach ($data as $key => $value) {?>
     <?php if(isset($data1[$key])){?>

    <?= $key; ?>
    <?= $value; ?>
    <?= $data1[$key]; ?>

    <?php }else{?>

    <?= $key; ?>
    <?= $value; ?>
    0

    <?php } ?>

<?php } ?>

A: First of all you can reindex your arrays to be much easier to access data by employee id. Also, you can display all data in a single table:

          ID
          Name
          Amount

<?php
    $employees = array_combine(array_column($employees, 'id'), $employees);
    $employee_sales = array_combine(array_column($employee_sales, 'id'), $employee_sales);

    foreach ($employees as $employeeId => $employee) {
?>

            <?= $employee['id']; ?>
            <?= $employee['name']; ?>
            <?= (isset($employee_sales[$employeeId]) ? $employee_sales[$employeeId]['amount'] : 0) ?>

<?php
    }
?>

A: <?php

$employees = [
    [
        "id" => "1",
        "name" => "Aliff",
    ],
    [
        "id" => "2",
        "name" => "Aina",
    ],
    [
        "id" => "3",
        "name" => "Ana",
    ]
];

$employee_sales = [
    [
        "id" => "1",
        "amount" => "500",
    ],
    [
        "id" => "3",
        "amount" => "300",
    ],
];

$id_sales = array_column($employee_sales, 'amount', 'id');
?>

            id
            name
            sales

    <?php foreach ($employees as $employee) { ?>

            <?= $employee['id']; ?>
            <?= $employee['name']; ?>
            <?=
            isset($id_sales[$employee['id']])
                ? $id_sales[$employee['id']]
                : '0' ?>

    <?php } ?>

A: You can use below loop in your code.
<?php
foreach ($employees as $employee) {

?>

    <?php echo $employee['id']; ?>
    <?php echo $employee['name']; ?>

    <?php
        $key = array_search($employee['id'], array_column($employee_sales, 'id'));
        echo ( $key !== false ) ? $employee_sales[$key]['amount'] : 0;
    ?>

<?php
} ?>

array_search is used to find the index of matching employee_id in employee_sales array, and that index is used to fetch amount.
If it is not found we return 0


text:
Q: ValueError: pos_label=1 is not a valid label: array(['COLLECTION', 'PAIDOFF'], dtype='I have face this error of pos_label firstly I import this library
from sklearn.metrics import jaccard_similarity_score

because of Version error I again import this library
from sklearn.metrics import jaccard_score

This is my code for running:
depth_range = range(1, 10)
jaccard_similarity_score_ = []
f1_score_ = []

for d in depth_range:
    dt = DecisionTreeClassifier(criterion = 'gini', max_depth = d)
    dt.fit(X_train, y_train)
    dt_yhat = dt.predict(X_test)
    ja = jaccard_score(y_test, dt_yhat, "yes")
    jaccard_similarity_score_.append(ja)
    f1_score_.append(f1_score(y_test, dt_yhat, average = 'weighted'))

I get this error :

ValueError: pos_label=1 is not a valid label: array(['COLLECTION', 'PAIDOFF'], dtype='<U10')

A: You need to mention pos_label value to the category which you want to predict as 1. So, for your case, PAIDOFF will be a positive label, so include pos_label='PAIDOFF'.

A: In the last line change the same to:
f1_score(y_test, dt_yhat, average = 'weighted', pos_label="PAID_OFF")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Thymeleaf th:each filtered with th:if I need to iterate and create <span> elements for each of the component in the components array which has the name of 'MATERIAL'
My code is as below
<span th:each="component : ${body.components}"
      th:object="${component}">
        <button th:if="*{name} == 'MATERIAL'"
                th:text="*{title}"></button>
</span>

This code works all good until this produces a set of empty <span> elements if the name is not equal to 'MATERIAL'. I don't want this empty <span> elements to get created.
I also tried the below
<span th:each="component : ${body.components}"
      th:object="${component}"
      th:if="*{name} == 'MATERIAL'">
         <button th:text="*{title}"></button>
</span>

This results in empty output and doesn't print anything at all. Can someone please help me on this.

A: You should reference the iteration item property directly using a dot (.) sign instead of going through an SpEL expression evalution (*{name}) inside your  html element:
<span th:each="component : ${body.components}"
      th:object="${component}"
      th:if="${component.name} == 'MATERIAL'">
  <button th:text="*{title}"></button>
</span>


text:
Q: How to manage timezone difference in order created date while creating order programatically I am creating order programmatically on magento 2.2 and using this
$order = $this->orderRepository->get($order_id);
$order->setCreatedAt($orderData['created_at']);
$order->save();

where $this->orderRepository referes to
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository
The created_date comes from an excel and has the
date (2019-01-11 18:43:08)
 , but created_at coloumn under sales_order it is saved as  2019-01-12 00:13:07 .

. Here are the timezone settings that i have in backend
I need to have the same dates  in order that i have in csv and and same need to be reflected on other places like order grid. Please advice


text:
Q: SKAction followPath end to end action I'm trying to use SKAction followPath with a given path, I noticed that the two methods available both take a duration.
    [SKAction followPath:<#(CGPathRef)#> asOffset:<#(BOOL)#> orientToPath:<#(BOOL)#> duration:<#(NSTimeInterval)#>]
    [SKAction followPath:<#(CGPathRef)#> duration:<#(NSTimeInterval)#>]

How can I get the action to stop only when it has reached the last point on the path?

A: Both actions stop at the last point. Duration is how long it takes the node to get to the last path point.


text:
Q: How to convert a gradle project back to normal android project? I screwed up and thought that it would be a good idea to try to convert my project into a gradle project without having any knowledge of how that system works. I converted the project inside of eclipse by using "configure > convert to gradle project".  When that didn't work I made the mistake of that hitting "configure > convert to maven project" which made things 10x worse.  What is the best way for me to convert the project back to how it was before, so I can learn gradle before messing around with my project.

A: Right click your project -> Gradle -> Disable Gradle Nature (in eclipse luna)


text:
Q: AngularJS Chart for Races I have my file JSON like this and with this time format, there are time of laps:
[{"time":"00:05:52.92"},{"time":"00:06:22.26"},{"time":"00:06:22.26"},{"time":"00:02:22.26"},{"time":"00:07:22.26"},{"time":"00:06:22.26"},{"time":"00:00:22.26"},{"time":"00:01:22.26"},{"time":"00:04:22.26"}]

With angularjs, I don't know what kind of chart use, and which dependecies use for this, can you give me some advices please. I can use my json like this or I have to trasform in seconds? if I must trasform in what? just seconds?

A: with this function I solved my problems:
function (secs){
    var divisor_for_minutes = secs.value % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);
    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);
    return minutes + ":" + divisor_for_seconds.toFixed(2);
    }


text:
Q: Mathematical optimization in R I have the following data frames:
Required <- data.table( Country=c("AT", "BE", "BG", "CY"),Mat1=c(0,5,0,5),Mat2=c(0,3,2,0),Mat3=c(10,2,0,12))
Supplied <- data.table( Country=c("AT", "BE", "BG", "CY"),Mat1=c(0,4,0,10),Mat2=c(20,20,20,0),Mat3=c(8,10,0,10))

> Required
   Country Mat1 Mat2 Mat3
1:      AT    0    0   10
2:      BE    5    3    2
3:      BG    0    2    0
4:      CY    5    0    2

> Supplied
   Country Mat1 Mat2 Mat3
1:      AT    0   20    8
2:      BE    4   20   10
3:      BG    5   20    0
4:      CY   10    0   10

"Required" shows the requirement of three types of materials to different countries, while "Supplied" shows the supply capacity of these countries. I seek to apply an optimization algorithm by which the "Required" data frame is modified according to the supply capacity. For instance, 5 units of "Mat1" are required to the country "BE", while it can only supply 4 units. The algorithm should look for the less constrained country to supply this material, in this case countries "BG" and "CY" both have 5 units "available". The less constrained country is thus the one that has the most units of material available in absolute terms.
The resulting requirement table "RequiredNew" should thus be:
> Required
       Country Mat1 Mat2 Mat3
    1:      AT    0    0    8
    2:      BE    4    3    3
    3:      BG  0.5    2    0
    4:      CY  5.5    0    3

Any ideas on how to proceed? This is an example and the actual table is quite bigger, so I seek a programatical approach.
Many thanks in advance.

A: This is a little bit convoluted, but it should work:
library(data.table)

Required <- data.table( Country=c("AT", "BE", "BG", "CY"),Mat1=c(0,5,0,5),Mat2=c(0,3,2,0),Mat3=c(10,2,0,2))
Supplied <- data.table( Country=c("AT", "BE", "BG", "CY"),Mat1=c(0,4,5,10),Mat2=c(20,20,20,0),Mat3=c(8,10,0,10))

# I prefer to work with matrices, so here I turn Required and Supplied into matrices
req <- as.matrix(Required[,-1,with=FALSE])
row.names(req) <- Required$Country
sup <- as.matrix(Supplied[,-1,with=FALSE])
row.names(sup) <- Supplied$Country

# create a copy of Required data.table to contain the result (we'll overwrite the values)
RequiredNew <- copy(Required)

# for each material...
for(col in 1:(ncol(req))){

  # for each country we compute the remaining stock and requirement after satisfying itself
  netreq <- req[,col] - sup[,col]
  netreq[netreq < 0] <- 0
  netstk <- sup[,col] - req[,col]
  netstk[netstk < 0] <- 0

  # we loop until we satisfy all the requirements or we finish the stock
  finalreq <- req[,col] - netreq
  while(sum(netreq) > 0 && sum(netstk) > 0){
    maxavailidxs <- which(netstk == max(netstk))
    requiredqty <- min(sum(netreq),sum(netstk[maxavailidxs]))
    deltareq <- (requiredqty * netreq) / sum(netreq)
    deltastk <- rep(0,length(netstk))
    deltastk[maxavailidxs] <- requiredqty / length(netstk[maxavailidxs])

    netreq <- netreq - deltareq
    netstk <- netstk - deltastk

    finalreq <- finalreq + deltastk
  }

  # we set the current material final requirement column into the result data.table
  set(RequiredNew,NULL,col+1L, finalreq)
}

RequiredNew
> RequiredNew
   Country Mat1 Mat2 Mat3
1:      AT  0.0    0    8
2:      BE  4.0    3    3
3:      BG  0.5    2    0
4:      CY  5.5    0    3


text:
Q: HostnameVerifier is not safe I submitted an app review on the google store and it prompted me that HostnameVerifier is not safe,As shown here is my code, I don't know where is the problem
Can anyone help me with this HostnameVerifier is not safe


text:
Q: Reuse result from first observable in second in c# The result of the first observable (itemsCache.GetAllKeys()) is a list of strings. If that list contains certain string (DOKUMENTI_KEY), then the second observable should be called. If the first observable doesn't contain the string, then an empty list should be returned.
    public static IObservable<TResult> If<TSource, TResult>(
                this IObservable<TSource> source,
                Func<TSource, bool> predicate,
                Func<TSource, IObservable<TResult>> thenSource,
                Func<TSource, IObservable<TResult>> elseSource)
            {
                return source
                  .SelectMany(
                    value => predicate(value)
                      ? thenSource(value)
                      : elseSource(value));
            }

    public IObservable<List<Dokument>> GetDokumenti()
            {
                return Observable.If(
                    () => itemsCache.GetAllKeys().SelectMany(x => x).Contains(DOKUMENTI_KEY).GetAwaiter().GetResult(),
                    itemsCache.GetAllKeys().SelectMany(y => y).Where(a => a == DOKUMENTI_KEY).SelectMany(z => itemsCache.GetObject<List<Dokument>>(z)),
                    Observable.Return(new List<Dokument>())
                );

        }

Is there a better way to do this?


text:
Q: Objective C: Terminating app due to uncaught exception 'NSInvalidArgumentException' My app is crashing with the error  "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[CALayer firstName]: unrecognized selector sent to instance 0x4d382c0'".
This is what I was trying to do.
1) I have created a 'Person' class to store information like firstName, lastName, email add and telephone number
Person.m file:
@implementation Person
@synthesize firstName, lastName, email, phoneNumber;

-(Person *)initWithfirstName:(NSString *)thisFirstName lastName:(NSString *)thisLastName email (NSString *)thisEmail phoneNumber:(NSString*)thisPhoneNumber
{
    if(self = [super init])
    {
        self.firstName = thisFirstName;
        self.lastName = thisLastName;
        self.email = thisEmail;
        self.phoneNumber = thisPhoneNumber;
    }
return self;
}
@end

2) Store a list of people in a mutable array
Person *firstPerson = [[Person alloc] initWithfirstName:@"Zen" lastName:@"Yong" email:@"" phoneNumber:@""];
person = firstPerson;

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:person, nil];

personArray = array;

[array release];

3) List the list of person's information in a table view
int row = [indexPath row];
Person *aPerson = (Person *)[self.personArray objectAtIndex:row];

cell.textLabel.text = aPerson.firstName;

Can you help to advise why I am getting the error listed at the beginning of the thread?
Appreciate your help on this!
Zhen

A: You're crashing due to a dangling pointer.  You set personArray array to be the array you created, but then you release the array, leaving personArray as a dangling pointer.  From what you posted I'm assuming personArray is a property on the class.  If so, changing:
personArray = array;

to
self.personArray = array;

should fix the problem.  The way you have it now the array pointer is just being assigned to the personArray pointer.  You have to call set setter method for the property to get the proper memory management.

A: This problem typicaly occurs when you have over released an object and the space has been reused for something else (a CALayer in your case).  I can't see the specific problem here that might be causing that, but you have a definite bug:
Person *firstPerson = [[Person alloc] initWithfirstName:@"Zen" lastName:@"Yong" email:@"" phoneNumber:@""];
person = firstPerson;

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:person, nil];

personArray = array;

[array release];

That creates an array and then immediately releases it.  It's likely that the array has been deallocated.  The person object in it, however, has not been released, so unless you do it later, it leaks.  You probably wanted something more like:
Person *firstPerson = [[Person alloc] initWithfirstName:@"Zen" lastName:@"Yong" email:@"" phoneNumber:@""];

NSMutableArray *array = [[NSMutableArray alloc] initWithObject: firstPerson];

[firstPerson release];

You then have to save the array somewhere, so if personArray is an instance variable, you can just do
personArray = array; // personArray must be nil beforehand to stop leaks.

or if it is a property (this is better):
[self setPersonArray: array]; // or equivalently self.personArray = array;
[array release];

On a final unrelated note, it is considered better not to use properties in the -init or -dealloc methods.  Your -init should probably look like:
if(self = [super init])
{
    firstName = [thisFirstName copy];
    lastName = [thisLastName copy];
    email = [thisEmail copy];
    phoneNumber = [thisPhoneNumber copy];
}

And don't forget to release everything in -dealloc.


text:
Q: Angular app lifetime in a browser I tried to google the following question, but nothing came up (which is super weird I need to).
What is an Agular app lifetime in a browser?
Or to rephrase when a user opens an Angular website, the app instances in the browser and stays live until the user leaves the website or closes the browser or?
On the separate note is it better to use a service for holding global variables (e.g. logged user name) or $rootScope?
Thanks!

A:
What is an Agular app lifetime in a browser?

The angular app persists while that particular tab/site is open.  If you navigate away from it and then back to it, for all intents and purposes, that's a fresh instance of the application.  You could mimic a persistent session but that would entail a custom implementation on your part.
Here is a post on preserving data on a refresh of the application that you might be interested in - AngualrJS: sustaining data on html refresh

On the separate note is it better to use a service for holding global variables (e.g. logged user name) or $rootScope?

This is well documented and you can find myriad sources both here on SO as well as the internet, but it's better to use an angular service to share data among various controllers.  It's not recommended that you pollute the $rootScope if you can avoid it.
Here is the same question asked on SO with solutions:

*

*angular set a variable accessible to any scope

*How to use variables from a controller in another controller in AngularJS

A: If you use angular's routing or another way to load views that doesn't reload a page, then an angular application will stay active until you leave the page (closing or refreshing).
Every time you load a page through angular its controller's data is in its initial state so any modification to a controller's data will get lost when you change page (unless you persist it somewhere, that is)
Regarding your second question, the best way should be to get a user's data after every page change (to check if the user is still logged in. Saving a user's data client side without checking if it's still valid might be a security issue). But in any case, a service is a better way to store data than using rootScope


text:
Q: using XML files to store layout of platformer blocks Hi all thanks for looking and hopefully helping me out on this as i am completely stuck!
I am coding a game in XNA. Platform game, very simple for now. I have the player all sorted can jump, walk, run and is animated for each action. I have scrolling background which loops two copies of a 8-bit street location. I also have a powerup which currently just increases the players score. I have also created a PlatformBlock class which is a simple texture and a position (oh and a bool to see if contains powerup).
Anyway, my question is... I want to store the positions for my blocks in a XML document. But I am totally unsure of the format to type the XML in (eh.  ... etc... I'm lost), I'm also unsure of how to call it from within XNA so that it will place the List blocks accordingly.
Please can someone type it in simple plain english as I have browsed literrally 15-20 tutorials on this matter and still cannot even start to add it into my game. I once a few months ago did manage to get this up and running for a breakout style game and in the end it worked well but I have no longer got that file, cant find the specific tutorial i used. In other words....PLEASE HELP :)

A: Depend how complex game will be. You can simply store level like this in .txt file, where x is platform and . blank space.
...................
..xxxxxx......xxxx.
...................
.......xxxxxxx.....
...................

but also you can store this into XML:
<Items>
  <Item>
    <Position>0,10</Position>
    <Name>Wall</Name>
    <Rotation>0</Rotation>
    <ImageName>-</ImageName>
  </Item>
  <Item>
    <Position>10,10</Position>
    <Name>Wall</Name>
    <Rotation>0</Rotation>
    <ImageName>-</ImageName>
  </Item>
</Items>

but in any way, you actually need to create "game level editor" using your game engine (or any other), and after that you create a game. choice is yours how you will store game level.


text:
Q: Type of definition "around a central point" with vague boundaries Some time ago, I read somewhere how traditional definitions fail in real world since they define precise boundaries depending on whether something follows certain condition or not; however, real world is full of edge cases where an object might seem to satisfy two (near) exclusive definitions.
The solution to this problem was to define things not in terms of boundaries but in terms of central points which will correspond with objects that follow the definitions precisely. The farther you go from the central point, objects will follow the definition less rigidly. Thus, the edge cases will be somewhere midway the two central points.
It's been a few years and now, I can't seem to find what this second type definition is called (neither do I remember where I read this). Any ideas what is this concept called?

A: Consider the notion of family resemblance, inaugrurated by Wittgenstein. Wittgenstein argued that

things which could be thought to be connected by one essential common feature may in fact be connected by a series of overlapping similarities, where no one feature is common to all. Games... have become the paradigmatic example of a group that is related by family resemblances.

This site describes the motivating idea behind family resemblance as the idea that

[at least some] words are loosely defined by a combination of common, or related, features rather than a rigorous single feature.

This seems to be what you describe: words defined in terms "central points" rather than precise "boundaries".
As an example, a definition of the word "game" might be given by listing many features of games (some of which might be exclusive). Something is likely a game if it satisfies many (but not necessarily all) of the conditions. Different games will satisfy different conditions. Something that only satisfies a few of the conditions might be a borderline case, that is, it's unclear whether it should count as a game or not.
You might call such definitions family resemblance definitions.
Others use disjunctive definitions, although this term is a bit misleading.


text:
Q: How do you deal with a public repository that has already been rebased? This question has likely been asked before but I'm having a heck of a time searching for it.
Very frequently, experienced git users will say "do not rebase repositories that have already been exposed publicly!" and rightly so. But I don't see any information that deals with the fallout. I know it's a situation we're not supposed to get ourselves into, but what do we do when it does happen?
Original: A--B--C--D--E--F
My Repo:  A--B--C--D
                    \
                     X--Y--Z
Rebased:  A--B
              \
               L--M--N--O

So I fetch, that should be pretty simple, right? And... then what happens? If I do a `pull --rebase, it should fail at some point because C--D is missing. What are the errors that I will actually encounter and how do I fix it?

A: There's a section in the git-rebase manpage called "RECOVERING FROM UPSTREAM REBASE" that describes this quite well.
Fetching
For your specific case, let's walk through what happens. If you simply fetch, all that's doing is updating your remote tracking branch. That still works fine - it will give you a warning, though:
From <url>:
 + abc123...def456 master    -> origin/master  (forced update)

Pulling
A pull, whether normal (merging) or rebasing, calls fetch internally. So if you haven't already fetched, you will see the "forced update" warning. If you have fetched already, the forced update warning was given before, and there's no forced update to warn about now. You could also miss the forced update warning if there's a large diff report as part of the merge after it. After fetching, git-pull then calls merge or rebase as requested. This is where it gets really scary. As far as Git is concerned now, commits C and D are just local commits now. It doesn't matter that at one point they were published. So Git will merge/rebase just like it normally would.
The merge:
- A - B - L - M - N - O (origin/master)
   \                   \
    C - D - X - Y - Z - Q (master)

The rebase:
 - A - B - L - M - N - O (origin/master) - C' - D' - X' - Y' - Z' (master)

Now, either one could very well run into conflicts, if the removal of commits C and D makes the later commits different. Merge conflicts are the only other errors you'd notice. But if they were isolated changes, then everything goes "fine". If the user doesn't notice, then the might subsequently push this history, and thus reintroduce the removed commits! Sometimes this could be relatively benign. Maybe L is actually C with a typo fixed in the commit message, and MNO are identical to DEF, just with different parents. So reintroducing C and D would do nothing more than clutter the history. But maybe it's horribly dangerous: maybe removing C fixed some terrible bug, and it's just been reintroduced.
Avoiding the problem
And this is why it's a really bad idea to rewrite published history. The best case is ending up with some duplicated commits, and the worst case is a user unknowingly breaking everything. So if it does happen, the very first thing you have to do is tell everyone and direct them how to recover. The next thing is to vigilantly monitor everything subsequently published to make sure it doesn't reintroduce the old commits. If you're on the other side of this, fetching from a public repo, hopefully you trust the maintainers enough to never rebase the stable branch, or to tell you if they do. If you don't trust them, then it's good practice to fetch then merge/rebase, rather than pulling, so that you can notice the "forced update" message and proceed very carefully.
Recovering locally
The details of how to recover vary; I recommend the aforementioned manpage. It's hard to tell exactly what you need to do - it depends on whether C was rewritten into L (and maybe D into M) or they're entirely new commits, and on whether you want to rebase or merge. If you just want to rebase, rebasing XYZ onto O would be sufficient. If you want to merge, you'd rebase XYZ onto either B or M, then merge O.

A: You should do (as in "How do I recover/resynchronise after someone pushes a rebase or a reset to a published branch?"):
git checkout yourBranch
git branch old-upstreamBranch D # BEFORE fetching!

           E--F (origin/upstreamBranch)
          /
A--B--C--D (old-upstreamBranch)
          \
           X--Y--Z (yourBranch)

git fetch

     L--M--N--O (origin/upstreamBranch)
    /
A--B--C--D (old-upstreamBranch)
          \
           X--Y--Z (yourBranch)

At this point, you cannot simply rebase your branch on top of the rewritten upstreamBranch: that would introduced C and D which were explicitly left asside when upstreamBranch was rewritten.
You need to rebase just yourBranch, and not the commits before it.
That is why you put an old-upstreamBranch tag before fetching:
git rebase --onto origin/upstreamBranch old-upstreamBranch yourBranch

                X--Y--Z (yourBranch)
               /
     L--M--N--O (origin/upstreamBranch)
    /
A--B--C--D (old-upstreamBranch)

git branch -D old-upstreamBranch

                X--Y--Z (yourBranch)
               /
     L--M--N--O (origin/upstreamBranch)
    /
A--B

But: With Git 2.0, all you will need to do is:
fork_point=$(git merge-base --fork-point origin/upstreamBranch yourBranch)
# return D
git rebase --onto origin/upstreamBranch $fork_point yourBranch

No more "making a branch before fetching!
If you realize the issue after git fetch, you can still rebase your branch nicely on top of the rewritten upstream branch.

Since commit ad8261d from John Keeping (johnkeeping), git rebase can use that same new --fork-point option.


text:
Q: Simple between function gives error? I had done this very simple code:
Number.prototype.between = function(a,b){
    return this >= a && this < b ? 1 : 0;
};

But when testing:
5.between(1,10);

Gives me this error:
Uncaught SyntaxError: Unexpected token ILLEGAL(…)
  InjectedScript._evaluateOn @ VM225:875
  InjectedScript._evaluateAndWrap @ VM225:808
  InjectedScript.evaluate @ VM225:664

What did I wrong?

A: JavaScript engine is trying to parse 5. as a floating number and since the token after the . is not a valid number, it is failing with the SyntaxError.
To fix this, you can

*

*Leave a space after the number
console.log(5 .between(1, 10));
// 1

*use parens to explicitly say that 5 itself is a single expression
console.log((5).between(1, 10));
// 1

*use double dots like this
console.log(5..between(1, 10));
// 1

PS: Avoid modifying the prototype of the builtins. You can always build a utility function.

A: make it
Number(5).between(1,10);
Reason being - (thanks to felix-kling for the same)
As per specs, the decimal point (.) is not optional in the production roles, so it is always considered to be part of the number literal. Basically, 5.toString() is similar to "5"toString(): A literal followed by an identifier.
Which is why 5.toString() gives the following error

Uncaught SyntaxError: Unexpected token ILLEGAL

just tested (5).between(1,10); will also do since it will then be an expression that evaluates to a Number type
for (var key in (5) ){ console.log( key " - " (5)[key] ); }

outputs

between - function (a,b){
      return this >= a && this < b ? 1 : 0; }

A: You can't directly call any function on an hardcoded number, put it in (5):
Number.prototype.between = function(a,b){
    return this >= a && this < b ? 1 : 0;
};

(5).between(1,10);


text:
Q: how to list every available identifier in ffi of pypy cffi? I can list available function names and enumerator names by
lib = ffi.dlopen(...)
print dir(lib)

Howerver, dir(lib) doesn't return defined typedefs and structs.
When I tried to load an arbitrary module with an arbitrary c header file using cffi, I had to parse the header file to get the list of typedefs and structs. Is there a better way to do the same thing?

A: It's not possible so far to enumerate the types.  You could file an enhancement request at https://bitbucket.org/cffi/cffi/issues.


text:
Q: Configuring NGINX for W3 Total Cache I installed the W3 Total Cache plugin which automatically configured my nginx configuration file. Unfortunately, no CSS or other static files are showing up for me. Everything 404s except for the themeless homepage.
This is the nginx configuration: http://pastie.org/2296620 I was hoping someone could point out what's the problem.
Thank you,
Mike

A: Well, I'd start simple -- take out all that W3TC cache guff and have a basic site config, and get that working first.  Check your error log for why exactly the request is 404ing; chances are you've just made a mess of a link or something.  Also, I see a great many pitfalls in your config that you might want to look into fixing.

A: The main problem I see is the WordPress rewrite.
In this section remove the root and index directives and put them right under listen 80 then change the if rewrite to try files.
To help keep things organized I would move the W3 Total Cache config to a separate file and use an include to add it.
Here is an example:
server {
    listen 80;

    server_name domain.com www.domain.com;

    root /srv/www/domain/public;

    access_log /var/log/nginx/example.access.log;
    error_log /var/log/nginx/example.error.log;

        client_max_body_size 8M;
        client_body_buffer_size 128k;
    location / {
        #try_files $uri $uri/ /index.php;
                try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    location /search { limit_req zone=one burst=3 nodelay; rewrite ^ /index.php; }

    fastcgi_intercept_errors off;

    location ~ \.php {
    try_files $uri =404;
    fastcgi_param  QUERY_STRING       $query_string;
    fastcgi_param  REQUEST_METHOD     $request_method;
    fastcgi_param  CONTENT_TYPE       $content_type;
    fastcgi_param  CONTENT_LENGTH     $content_length;

    fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
    fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
    fastcgi_param  REQUEST_URI        $request_uri;
    fastcgi_param  DOCUMENT_URI       $document_uri;
    fastcgi_param  DOCUMENT_ROOT      $document_root;
    fastcgi_param  SERVER_PROTOCOL    $server_protocol;

    fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
    fastcgi_param  SERVER_SOFTWARE    nginx;

    fastcgi_param  REMOTE_ADDR        $remote_addr;
    fastcgi_param  REMOTE_PORT        $remote_port;
    fastcgi_param  SERVER_ADDR        $server_addr;
    fastcgi_param  SERVER_PORT        $server_port;
    fastcgi_param  SERVER_NAME        $server_name;

    fastcgi_pass 127.0.0.1:9000;
 }

    include w3-total-cache-config.conf;

}

I recently wrote a blog post on setting up Nginx with W3 Total Cache that you might also find helpful.


text:
Q: How can I load a style in GtkSourceView in python? How can I load a new style in a GtkSourceView ?
In Gedit I can see it lists the styles found in /usr/share/gtksourceview-3.0/styles, how can I get my own GtkSourceView to load one of these styles ?

A: Use the set_style_scheme() method. Style schemes can be obtained from the default GtkSource.StyleSchemeManager object.


text:
Q: Get method unauthorized with Jsonwebtoken in nodejs and angular cli I am building an application using nodejs and angular-cli
I'm using JsonWebToken to authenticate user account . But it always return Unauthorized 401 .
Here my code :
// CODE FOR AUTHENTICATE
    router.post('/authenticate', (req, res, next) => {
      const username = req.body.username;
      const password = req.body.password;

      User.getUserByUsername(username, (err, user) => {
        if(err) throw err;
        if(!user){
          return res.json({success: false, msg: 'User not found'});
        }

        User.comparePassword(password, user.password, (err, isMatch) => {
          if(err) throw err;
          if(isMatch){
            const token = jwt.sign(user.toJSON(), config.secret, {
              expiresIn: 604800 // 1 week
            });

            res.json({
              success: true,
              token: 'JWT '+token,
              //token:token,
              user: {
                id: user._id,
                name: user.name,
                username: user.username,
                email: user.email
              }
            });
          } else {
            return res.json({success: false, msg: 'Wrong password'});
          }
        });
      });
    });

// GET PROFILE

    router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next) => {
        res.json({user: req.user});
      });

// Get user by Id
    module.exports.getUserById=function(id,callback){
        User.findById(id,callback);
    }

// Get user by username
    module.exports.getUserByUsername=function(username,callback){
        const query={username:username}
        User.findOne(query,callback);
    }

// compare password
    module.exports.comparePassword=function(candidatePassword,hash,callback){
        bcrypt.compare(candidatePassword,hash,(err,isMatch)=>{
            if(err) throw err;
            callback(null,isMatch);
        });
    }

Can you explain me why ?


text:
Q: how to get difference between two date hey i want to get difference between two dates like
date1= 2014-03-3
date2= 2014-03-4

when i sub this two date like date2-date1 then it should give us 2
ie. i just want to add new day after 12 am at night..how is it possible using php function?
I tried some code like
<?php $date1=date_create("2013-03-15");
$date2=date_create("2013-12-12");
$diff=date_diff($date1,$date2); ?>

but it does not work
please help

A: Try
$datetime1 = new DateTime('2014-03-3');
$datetime2 = new DateTime('2014-03-4');
$interval = $datetime1->diff($datetime2);
$dayCount = $interval->format('%a');
echo $dayCount;

See demo here

A: If you are interested just in numeric value you can do:
$diff = strtotime($date2) - strtotime($date1);

A: This could help you
   $date1 = new DateTime("2013-03-15");
   $date2 = new DateTime("2013-12-12");
   $interval = $date1->diff($date2);
   echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days ";

A: Check this if it helps you
$datetime1 = strtotime('2014-03-3');
$datetime2 = strtotime('2014-03-4');
$timeDiff = $datetime2-$datetime1;
$dayCount=floor($timeDiff/(60*60*24)); //calculate day count.
echo $dayCount;

it will give you count 1, and if you provide the date with time then also it will work.


text:
Q: how to close mobile navigation menu on click outside sidenav menu this is my js to open and close sidenav with id="mySidenav".
 function openNav() {
  document.getElementById("mySidenav").style.width = "250px";
}

function closeNav() {
  document.getElementById("mySidenav").style.width = "0";
}

How to close the sidenav on clicking outside the sidenav and also when screen size is >600px?


text:
Q: Dúvida no carregamento da aquisição do rest para a view estou seguindo uma vídeo aula e surgiu uma dúvida.
criei duas pastas uma para o front (que é executado pelo servidor http-server porta 8080)
segunda pasta para o back ( que é executado pelo nodemon porta 3000)
mas infelizmente não carrega as coisas do back para o front... segue meus códigos se alguém puder me dar uma ajuda, por favor.

/*PASTA front arquivo main.js*/
(function () {
    'use strict';

    var ajax = new XMLHttpRequest();
    ajax.open('GET', 'http://localhost:3000/user/maria');//esse trecho de código não altera nem com nome invalido que n tenha no objeto do js do back.
    ajax.send();

    ajax.addEventListener('readystatechange', function () {
        if (ajax.readyState === 4) {
            console.log(ajax.responseText, ajax.status);
        }
    }, false);

})();

/* PASTA back arquivo index.js */
'use strict';

var express = require('express');
var cors = require('cors');
var app = express();

app.use(cors());

var users = {
    joao: {
        nome: 'Joao',
        idade: 30
    },
    maria: {
        nome: 'Maria',
        idade: 22
    },
    fernando: {
        nome: 'Fernando',
        idade: 20
    }

};

app.get('/', function (request, response) {
    response.send('
Home
');
});

app.get('/user', function (request, response) {
    response.send('User');
});

app.get('/user/:username', function (request, response) {
    var username = request.params.username;
    if(users[username])
        return response.json(users[username]);
    response.status(404).json({ error: 'Usuário não encontrado'});
});

app.listen(3000);
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title> AJAX </title>

 FRONT


text:
Q: Get url Address from current page I have a c# code and need to get full URL address from current page.
In method I have :
string url = HttpContext.Current.Request.Url.AbsoluteUri;

but there is error. HttpContext does not exist in the current context
i have dll (using System.Web;)
second try was:
string url = Request.Url.Host;

but error on Request does not exist.
how can get URL address ?
my main question is. why i got error on HttpContext   or Request.Url.Host ?


text:
Q: KeyValue error when trying to convert datetime.datetime object using strftime in Python I'm attempting to convert values within a series from one datetime object format to another.
I've used the following to convert the original entry into a datetime object:
import datetime as dt
for each in DataFrame_name['Series_name']:
    DataFrame_name['Series_name'][each] = dt.datetime.strptime(each,"%Y-%m-%d %H:%M")

This has been effective at converting string entries such as '2019-07-01 12:14' into datetime objects.
However, when I attempt to convert this datetime format to '%Y-%m', I get the a KeyError: datetime.datetime(2019, 7, 1, 12, 14)
for each in DataFrame_name['Series_name']:
    DataFrame_name['Series_name'][each].strftime('%Y-%m')

KeyError: datetime.datetime(2018, 2, 1, 0, 0)

Has anyone seen/solved this before?

A: Take another, more pandasonic approach.
Assume that the source DataFrame is:
                Dat  Score
0  2019-07-01 12:14    120
1  2019-07-02 10:20    130
2  2019-08-07 18:33    610

where Dat column is kept as a String and Score as int64 (as it could be
read from an Excel or CSV file).
To convert Dat column from String to datetime, instead of importing
datetime and your loop, just execute a single statement:
df.Dat = pd.to_datetime(df.Dat)

When you print(df), you will get:
                  Dat  Score
0 2019-07-01 12:14:00    120
1 2019-07-02 10:20:00    130
2 2019-08-07 18:33:00    610

The type of Dat is now datetime64[ns] and the format it is printed
is as it is for datetime type.
Then, instead of reformatting it to text, convert it to Period
with Month frequency, again with a single instruction:
df.Dat = df.Dat.dt.to_period('M')

The result is:
       Dat  Score
0  2019-07    120
1  2019-07    130
2  2019-08    610

and the type of Data is period[M].


text:
Q: Bound for tail probability Suppose $\{X_k\}$ is a sequence of r.v.s. s.t. $X_k\rightarrow0$ in probability. Can we bound $\mathbb{P}\{|X_k |>k\epsilon\}$ for some $\epsilon>0$ without any restriction on $X$'s?
Thank's!

A: Define $p_j(\varepsilon):= \mathbb{P}\{|X_j |>j\epsilon\}$; since $j\geqslant 1$, the inequality $p_j(\varepsilon)\leqslant \mathbb{P}\{|X_j |>\epsilon\}$ holds, hence $p_j(\varepsilon)\to 0$.
Define $X_j:=j^2\mathbf 1(A_j)$, where $(A_j)_{j\geqslant  1}$ is sequence  of measurable sets such that $\mathbb P(A_j)\to 0$. Then $X_j\to 0$ in probability, but for each positive $\varepsilon$, we have for $j\gt 1/\varepsilon$,
$$A_j\subset\{X_j\gt j\varepsilon\},$$
hence the decay of the sequence $\left(p_j(\varepsilon)\right)_{j\geqslant 1} $ is slower than that of the sequence $\left(\mathbb P(A_j)\right)_{j\geqslant 1}$.


text:
Q: RESTful search centering on specific record within a larger query set So I have a query that returns lets say 1000 records.  I'm using paging to grab sections of that, and I know the total number of records due to the $inlinecount=allpages tag.  I'd like to be able to grab a specific record, and know where in the 1000 records it lands.  Let's say the record I'm looking for actually lands on record number 481, is there a way to figure that out?  If I can know that, I can figure out which paging group I need to grab to get to the result.
My goal is to show the user the same list, unfiltered, but focus on the record they are looking for.  They then can scroll backwards or forwards from that record as if they had just jumped to the middle of the total records.
Is there a tricky way to query RESTful data services to do something like what I'm asking?


text:
Q: Injecting a concrete implementation of a WCF ServiceContract based off value in a config file dymamically Say I have the following service contract and two concrete implementations:
[OperationContract]
public interface ISearchService {
    public ICollection<string> Search(string text);
}

[SearchServiceBehaviour]
public class SolrSearchService : ISearchService {
    public ICollection<string> Search(string text) {
        // Implementation...
    }
}

[SearchServiceBehaviour]
public class SqlSearchService : ISearchService {
    public ICollection<string> Search(string text) {
        // Implementation...
    }
}

These are attributed with a ServiceBehavior so that I can create the instance whilst the service is running based off a config file:
public class SearchServiceBehaviour : Attribute, IServiceBehavior {
    public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) {
        foreach (var item in serviceHostBase.ChannelDispatchers) {
            var dispatcher = item as ChannelDispatcher;

            if (dispatcher != null) {
                dispatcher.Endpoints.ToList().ForEach(e => {
                    e.DispatchRuntime.InstanceProvider = new SearchServiceInstanceProvider();
                });
            }
        }
    }
}

public class SearchServiceInstanceProvider : IInstanceProvider {
    public object GetInstance(InstanceContext instanceContext, Message message) {
        // Should cache and only do this at an interval.
        ConfigurationManager.RefreshSection("appSettings");
        var index = ConfigurationManager.AppSettings["UseSolr"] as string;

        bool UseSolr;
        bool.TryParse(index, out UseSolr);

        if (UseSolr)
            return new IndexedSearchService();
        else
            return new SearchService();
    }
}

My question is how can I inject the concrete implementation using Ninject based off a changing value in a config file? It seems to be I should be doing the following:
public class SearchServiceModule : NinjectModule {
    private bool UseSolr;

    public SearchServiceModule() {
        // Should cache and only do this at an interval.
        ConfigurationManager.RefreshSection("appSettings");
        var index = ConfigurationManager.AppSettings["UseSolr"] as string;

        bool.TryParse(index, out UseSolr);
    }

    public override Load() {
        if (UseSolr)
            Bind<ISearchService>().To<SolrSearchService>();
        else
            Bind<ISearchService>().To<SqlSearchService>();
    }
}

And then in the InstanceProvider:
public object GetInstance(InstanceContext instanceContext, Message message) {
    return _kernel.Get<ISearchService>();
}

However, the bindings in Ninject don't change after I change the value in the config file. Is there a way to change the binding based off the value in the config file? Am I doing something wrong here?

A: Your module does not behave as you expect because there is a field and a local variable with the same name.
Also have a look at conditional bindings. .When()

A: You're self-hosting in a Windows service. Saving a .config file does not automatically cause the Windows Service to recycle and notice your .config change (unlike IIS). So if you're building your kernel at startup, there is no trigger to cause it to be rebuilt.
You will have to change your implementation to use the .When() method to conditionally provide the implementation based off of the config setting. That would look something like this:
public override Load()
{
    Bind<ISearchService>().To<SolrSearchService>().When(r => ShouldUseSolr());
    Bind<ISearchService>().To<SqlSearchService>().When(r => !ShouldUseSolr());
}

private static ShouldUseSolr()
{
    // Should cache and only do this at an interval.
    ConfigurationManager.RefreshSection("appSettings");
    var index = ConfigurationManager.AppSettings["UseSolr"] as string;

    bool result;

    bool.TryParse(index, out result);

    return result;
}


text:
Q: Optimization Algorithm for Trading Items When you have something that you want to sell or something you want to buy there's basically two options: to use money or to trade it with another item. This happens in real life and also in games where you have a trading system in place (an open market).
My question is: is there an optimal algorithm capable of receiving all of the available deals on the market and returning the best, optimal sequence of trades to get to item x that minimizes the overall cost?
I'll give you an example:
Lets say that on the market we have this two tables, one for the people that want to trade/sell something, and one for the people that want to buy something:
Sellers:

Item I Have
Items I Want
(or) Price I Want

Item A
-
140

Item A
-
160

Item B
-
50

Item C
Item A + Item B
220

Item D
Item C
240

Item E
Item A + Item D
360

Item X
Item E
360

Buyers:

Item I Want
Price I'll Pay

Item A
150

Item B
70

It has to take into consideration some of the following scenarios:

*

*Get to Item x only using money;

*Get to Item x using money and trades;

*Get to Item x using only trades;

*Consider several small trades before getting the final trade;

*The market is dynamic and the prices are not really "fixed". Meaning that some sellers/buyers are definitely buying/selling at prices bellow or up the average. The algorithm should thrive on this "misplaced" deals.

I don't know if I was able to make myself clear. I have a background in engineering and programming, and tried to find something that would tackle this problem but couldn't find much. I imagine that there's something to do with Greedy Algorithms, but I honestly don't know it there's something already proven to be good for this problem or if neural networks could do something for me here.
I know that this problem isn't trivial at all. In fact, there's a lot of people that make a living buying/selling items for profit like that. But they rely mostly on their knowhow and mining of opportunities that appear on the market.

I initially thought that I could transform this problem into a "traveling salesman" type of problem, where the cities are the items, and the distance between the cities is the price, and I would use some of the already established algorithms for this problem on it. But I don't know if it will work (if someone else already tried it).

A: You can solve this with a single source shortest path algorithm for weighted directed graphs which allows negative-weight edges, such as the Bellman–Ford algorithm.
The nodes in the graph are sets of items, the source node is the set of items you start with (possibly the empty set), the edges are either buying an item (the edge weight is the purchase price), selling an item (the edge weight is the negative sale price), or trading a set of items (the edge weight is zero).
The Bellman–Ford algorithm will find paths minimising the cost (i.e. maximising the amount of money you have remaining) to each possible set of items you can end up with. Then you can simply take the minimum cost of a path to any set containing the item you wish to acquire.
It's possible that your economy allows arbitrage, i.e. some sequence of trades, purchases and sales by which you can end up with the same items you started with but with more money. (In your example, you can buy item A for 140 and sell it for 150.) In this case the graph contains a negative-weight cycle, so there is no "best" price for any item because you can exploit the arbitrage opportunity for unbounded profit. If there is a negative-weight cycle, the Bellman–Ford algorithm will detect and report it instead of finding shortest paths.


text:
Q: How to retrieve image using url path saved in database using c#? I need to retrieve images from a server using url path. I'm working in a console application that generates pdf reports, i'm using entity models to retrieve data from DB and using html to create the reports.
I though that by getting the urlpath from server and putting it inside ex:
string html = "";

would work, it just comes out blank.
This is my query:
using (var context = new dbName_pdf.dbName_dbEntities())
        {
            var db_data= (from lo in context.tbl_loans
                         join doc in context.tbl_docinfo on lo.idDocInfo equals doc.idDocInfo
                         join insp in context.tbl_inspections on lo.idLoan equals insp.idLoan
                         join p1 in context.tbl_pir01 on lo.idLoan equals p1.idLoan
                         join pho in context.tbl_photos on lo.idLoan equals pho.idLoan
                         join me in context.tbl_members on insp.idMember equals me.id
                         join sig in context.tbl_inspector_signature on me.id equals sig.idMember
                         join p2 in context.tbl_pir02 on lo.idLoan equals p2.idLoan
                         join cm in context.tbl_comments_inspections on lo.idLoan equals cm.idLoan
                         where insp.StatusInspections == 3 && lo.idLoan == 5
                         orderby cm.CommentDateCreated descending
                         select new
                         {
                             Loan = lo,
                             DocInfo = doc,
                             Inspection = insp,
                             pir1 = p1,
                             pir2 = p2,
                             photos = pho,
                             members = me,
                             signature = sig,
                             inspection_comments = cm
                         });

The string i'm using to store the image:
string inspector_Signature = db_data.First().signature.locationSign;

Note: I searched for a solution but all the questions i found dealt with MVC/ASP.net which didn't applied to my situation.

A: For future folk, this is the answer.
I only needed to add the full url path.
string inspector_Signature = "http://www.webpage.com/" + db_data.First().signature.locationSign;

The image now renders when i add it to my html string:
string html = "";


text:
Q: React Native lazy loading 250 images in a Scroll View I have 250 objects in state, that I'm trying to load in a scroll view with an image for each one. I'm using react-native-lazyload, and it works for about the first 75 images, then the scrolling starts slowing down to a halt, almost at the same spot every time.
Is there a different way I can load these images? It seems like a Flatlist would be a better option than a Scrollview, but I have no function I can call onEndReach

A: I found a really good write-up on improving performance of Flatlists here. I ended up using a Flatlist with these setting:
  <FlatList
    containerContentStyle={styles.container}
    data={countries}
    renderItem={({ item }) => (
      <View style={styles.results}>
        <Results
          {...this.props}
          country={item}
          handleUpdate={this.handleUpdate}
          pendingCountry={pendingCountry}
        />
      </View>
    )}
    keyExtractor={item => item.alpha2code}
    ListHeaderComponent={() => this.renderHeader()}

    // Performance settings
    removeClippedSubviews={true} // Unmount components when outside of window
    initialNumToRender={2} // Reduce initial render amount
    maxToRenderPerBatch={1} // Reduce number in each render batch
    updateCellsBatchingPeriod={100} // Increase time between renders
    windowSize={7} // Reduce the window size
  />

I can now scroll through my entire list of 250 images at a reasonable pace with no issues. When I start scrolling back up from the bottom, the screen gets a little jerky, but this is the best solution I've gotten to work.


text:
Q: Whether every RSS source have only one channel? There is a example of RSS data:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">

<channel>
  <title>菜鸟教程首页</title>
  <link>http://www.runoob.com</link>
  <description>免费编程教程</description>
  <item>
    <title>RSS 教程</title>
    <link>http://www.runoob.com/rss</link>
    <description>菜鸟教程 Rss 教程</description>
  </item>
  <item>
    <title>XML 教程</title>
    <link>http://www.runoob.com/xml</link>
    <description>菜鸟教程 XML 教程</description>
  </item>
</channel>

</rss>

I saw many RSS sources, only have one channel, I am not sure whether the standard is just one channel of a RSS source.

A: According to this RSS 2.0 specification:

Subordinate to the <rss> element is a single <channel> element, which contains information about the channel (metadata) and its contents.

I cannot find a formal specification of RSS 1.0 or 0.9x that define how many channel elements a feed may contain.


text:
Q: Python - collect output of recursive function I have written a function designed to flatten a json. The function works recursively - if a key, value pair's value is not a json, the key,value pair is returned, otherwise, the function is called again on the value:
def flatten_json(j):
    for k, v in j.items():
        if isinstance(v, dict):
            flatten_json(v)
        else:
            yield (k,v)

flat_json = {x[0]: x[1] for x in flatten_json(j)}

The idea being that whenever the function yields a tuple, it is collected into the flat_json dict. As it stands, nested outputs are ignored - only the top level key, value pairs appear in flat_json.

A: This is exactly what yield from is for :), to yield elements one by one from calling a generator from within a generator (whether that is a recursive call or not).
try:
def flatten_json(j):
    for k, v in j.items():
        if isinstance(v, dict):
            yield from flatten_json(v)
        else:
            yield (k,v)

j = {'foo': 'bar', 'foo1': 'bar1', 'nest1': {'foo2': 'bar2'}}
flat_json = {x[0]: x[1] for x in flatten_json(j)}
print(flat_json)

Output:
{'foo': 'bar', 'foo1': 'bar1', 'foo2': 'bar2'}

running example here: https://ideone.com/Z5aO9V

A: Yield it like the normal data:
yield (k, flatten_json(v))


text:
Q: Input string was not in a correct format when convert string to double I am a beginner using c#. I'm trying to code using if else statement in c# . When I run the program, this error message appear. It appears along the line double x = Convert.ToDouble("XValue");. I was trying to convert the string X value to double to match with my variable x.
    static void Main(String[] args)
    {
        connectDB();
        OpenConnection();

        MySqlCommand command = c.CreateCommand();
        command.CommandText = "SELECT * FROM gazecoords INNER JOIN gazeperiod ON gazecoords.gazeID = gazeperiod.gazeID INNER JOIN trialImage on gazeperiod.imageID = trialImage.imageID INNER JOIN areacoords on trialImage.imageID = areacoords.trialImageID;";
        try
        {
            c.Open();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        MySqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine(reader["imageID"].ToString());
            Console.WriteLine(reader["topLeftX"].ToString());
            Console.WriteLine(reader["topRightX"].ToString());
            Console.WriteLine(reader["topLeftY"].ToString());
            Console.WriteLine(reader["bottomLeftY"].ToString());
            Console.WriteLine(reader["XValue"].ToString());
            Console.WriteLine(reader["YValue"].ToString());
            Console.WriteLine(reader["in"].ToString());

            while (reader.Read())
            {

                double x = Convert.ToDouble("XValue");
                double y = Convert.ToDouble("YValue");
               List <int> image = new List<int>(Convert.ToInt32("imageID"));
               // int coordsID = Convert.ToInt32("coordsID");
                double topLeftX = Convert.ToDouble("topLeftX");
                double topRightX = Convert.ToDouble("topRightX");
                double topLeftY = Convert.ToDouble("topLeftY");
                double bottomLeftY = Convert.ToDouble("bottomLeftY");
                int inside = Convert.ToInt32("in");
                inside = 0;

                foreach (int coordsID in image)
                {
                    if (x > topLeftX && x < topRightX && y > topLeftY && y < bottomLeftY)
                    {
                        Console.WriteLine("The value inside are the area is {0}", inside + 1);
                    }
                    else
                        Console.WriteLine("0");
                    Console.ReadLine();
                }
            }
        }
    }

A: It should be
double x = Convert.ToDouble(reader["XValue"]);

It was trying to convert string "XValue" to Double which is not possible but now it will convert value of reader["XValue"].

A: You are not passing reader["XValue"] to double x = Convert.ToDouble("XValue");
 XValue is a string which is causing error while converting to double.
Change it to
double x = Convert.ToDouble(reader["XValue"]);

A: Perhaps, XValue is null:
double x = Convert.ToDouble(reader["XValue"] ?? 0);


text:
Q: Shopping context modelling I want to write my first application (e-commerce) in a DDD manner and I'd like to know whether I'm getting everything right so I want your opinion on my modelling - how can it be improved, what should I look for etc. Every feedback will be greatly appreciated.
I've divided my application into several bounded contexts (catalog, shopping, ordering) and below example is based on the shopping one. I am trying to use CQRS as well (thus AddProductToCart command).
My business requirements are as follows:

*

*Customer should be able to add product to his cart

*Price for added product should be specific to user and is based on several factors: (global discounts, user discounts and customer country (some countries have lowered base prices)

I've recognised following actors (please note comments on methods and classes):
/**
 * A customer (Aggregate Root) having an unique cart
 */
class Customer
{
    /**
     * @var int
     */
    private $customerId;

    /**
     * @var string
     */
    private $country;

    /**
     * @var Cart
     */
    private $cart;

    /**
     * @var PriceProvider
     */
    private $priceProvider;

    /**
     * Adds product to customers cart with user-specific price
     *
     * @param $productId
     * @return CartLine
     */
    public function addProductToCart($productId)
    {
        $price = $this->priceProvider->priceForProduct($productId, $this->customerId, $this->country);
        return $this->cart->addLine($productId, $price);
    }
}

/**
 * Simple CartLine object for persisting purposes
 */
class CartLine
{
    public $productId;
    public $price;
    public $cartId;

    function __construct($cartId, $productId, $price)
    {
        $this->cartId    = $cartId;
        $this->price     = $price;
        $this->productId = $productId;
    }
}

class Cart
{
    private $cartId;

    public function addLine($productId, $price)
    {
        return new CartLine($this->cartId, $productId, $price);
    }
}

/**
 * Provides price for specific country
 */
class PriceProvider
{
    public function priceForProduct($productId, $userId, $country)
    {
        // Logic for determining product price for customer
        // Based on available global discounts, user discounts and country
    }
}

/**
 * Command for adding product to cart
 */
class AddProductToCart
{
    public $customerId;
    public $productId;
}

/**
 * An application service to bind everything together
 */
class CustomerService
{
    public function addProductToCart(AddProductToCart $command)
    {
        /** @var Customer $customer */
        $customer = $this->customerRepository->customerOfId($command->customerId);
        $cartLine = $customer->addProductToCart($command->productId);

        $this->cartLineRepository->save($cartLine);
    }
}

Is this a correct approach? Do I violate any DDD principles here? Can I improve something?

A: CQRS generally involves command handler.
Command is associated to "imperative" verb.
CustomerService is too broad and so does not represent the intent of the "command".
I would change CustomerService by AddProductToCart:
class AddProductToCart
{
    public function handle(AddProductToCartCommand $command) {
      ...
    }
}

By the way, by splitting all your various functionalities into appropriate commands, you would be able to make several versions of one specific command them if you need to.

A: So in sparse order (and partially depending on the programming language):

*

*Your aggregate root should be explicitly marked (using an IAggregateRoot interface for example) so if your language supports generic, you can implement only repository of an aggregate root.

*Your constructors should be always private, use factory instead. Use constructor only for initialization issue. In your next future the building rule of a Customer could increase in complexity and factory will permit you flexibility.

*Invariant logic is Domain Logic. Logic that depends on use case is Application Logic (i.e. PriceProvider is not related to domain logic)


text:
Q: Processing cannot find library I've tried importing from a jar file (quickhull3d for example) in Processing 2.2.1 and 3.2.1 on Linux and Mac based on the instructions given here
My directory structure looks like this
../Processing/Sketchbook/libraries/quickhull3d/library/quickhull3d.jar
The Processing IDE preferences set the sketchbook location to ../Processing/Sketchbook
In my .pde file, I have the opening line
import quickhull3d.*;

and I get the error:
No library found for quickhull3d
Libraries must be installed in a folder named 'libraries' inside the 'sketchbook' folder.
Note: I have seen this question asked repeatedly both here and on the Processing forum and to the best of my ability to tell, I am following the instructions as written. I have restarted the IDE before attempting to run the sketch and I have also tried copying quickhull3d.jar to /mysketch/code, which is manually doing what the IDE would do if you were to drag and drop the file onto it.
Follow up: Upon further investigation, it looks like the problem is that the .jar file itself does not point to the correct locations for the xyz.class files, so I believe this may be the culprit. Additionally, I discovered that the ComputationalGeometry contributed library for Processing contains QuickHull3d, obviating the need for me to install it manually. In the future, I will make certain the paths in the .jar are correct.

A: If you're using the Processing editor, the easiest way to install a non-standard library is to just drag the .jar file onto your Processing editor. This will move the .jar file into your sketch folder, and you can use it just like you can use any other library.


text:
Q: Passing multiples Django Forms in context[] to templates I have a custom Django user schema to manage roles or user types:

*

*StudentProfile

*ProfessorProfile

*ExecutiveProfile

Due to part of my AbstractBaseUser model stay so:
class User(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(unique=True)
    username = models.CharField(max_length=40, unique=True)
    slug = models.SlugField(max_length=100, blank=True)
    is_student = models.BooleanField(default=False)
    is_professor = models.BooleanField(default=False)
    is_executive = models.BooleanField(default=False)

    other fields ...

I have the get_student_profile(),get_professor_profile() and get_executive_profile() methods to get the profile user data.
I've override the save() method in my custom model User to save the profile data when is_student or is_professor or is_executive have been checked at moment to create an user, their data will be saved in ther respective models:
class StudentProfile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    slug = models.SlugField(max_length=100,blank=True)
    origin_education_school = models.CharField(max_length=128)
    current_education_school = models.CharField(max_length=128)
    extra_occupation = models.CharField(max_length=128)

class ProfessorProfile(models.Model):
    CATHEDRAL_PROFESSOR = 'CATHEDRAL'
    RESEARCH_PROFESSOR = 'RESEARCH'
    INSTITUTIONAL_DIRECTIVE = 'DIRECTIVE'

    OCCUPATION_CHOICES = (
        (CATHEDRAL_PROFESSOR, 'Cathedral Professor'),
        (RESEARCH_PROFESSOR, 'Research Professor'),
        (INSTITUTIONAL_DIRECTIVE, 'Institutional Directive'),
    )
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    slug = models.SlugField(max_length=100,blank=True)
    occupation = models.CharField(max_length=255,blank = False)

class ExecutiveProfile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    slug = models.SlugField(max_length=100, blank=True)
    occupation = models.CharField(max_length=255,blank = False)
    enterprise_name = models.CharField(max_length=255,blank = False)

I have the forms to each profiles user
class UserUpdateForm(forms.ModelForm):
    class Meta:
        widgets = {'gender':forms.RadioSelect,}
        fields = ("username", "email", "is_student",           "is_professor", "is_executive",)
        model = get_user_model() #My model User

class StudentProfileForm(forms.ModelForm):
    class Meta:
        model = StudentProfile
        fields = ('origin_education_school',current_education_school',
            'extra_occupation')

class ProfessorProfileForm(forms.ModelForm):
    class Meta:
        model = ProfessorProfile
        fields = ('occupation',)

class ExecutiveProfileForm(forms.ModelForm):
    class Meta:
        model = ExecutiveProfile
        fields = ('occupation', 'enterprise_name', 'culturals_arthistic','ecological')

I have this URL to access to profile user
url(r"^profile/(?P<slug>[\w\-]+)/$",
        views.AccountProfilesView.as_view(
            model=ProfessorProfile),
            name='profile'
    ),

In my AccountProfilesView I manage the profiles form and send them to template
class AccountProfilesView(LoginRequiredMixin, UpdateView):
    # All users can access this view
    model = get_user_model()
    success_url = reverse_lazy('dashboard')
    template_name = 'accounts/profile_form.html'
    fields = '__all__'

    def get_context_data(self, **kwargs):
        context = super(AccountProfilesView, self).get_context_data(**kwargs)
        user = self.request.user

        if not self.request.POST:
            if user.is_student:
                profile = user.get_student_profile()
                context['userprofile'] = profile
                context['form_student'] = forms.StudentProfileForm()
            elif user.is_professor:
                profile = user.get_professor_profile()
                context['userprofile'] = profile
                context['form_professor'] = forms.ProfessorProfileForm()
                print ("profesor form is", context['form_professor'])
            elif user.is_executive:
                profile = user.get_executive_profile()
                context['userprofile'] = profile
                context['form_executive'] = forms.ExecutiveProfileForm()
            elif user.is_student and user.is_professor and user.is_executive:
                student_profile = user.get_student_profile()
                professor_profile = user.get_professor_profile()
                executive_profile = user.get_executive_profile()
                context['student_profile'] = student_profile
                context['professor_profile'] = professor_profile
                context['executive_form'] = executive_profile

                student_form = forms.StudentProfileForm()
                professor_form = forms.ProfessorProfileForm()

                executive_form = forms.ExecutiveProfileForm()

                context['form_student'] = student_form
                context['form_professor'] = professor_form
                context['form_executive'] = executive_form
        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = super(AccountProfilesView, self).post(request, *args, **kwargs)
        user = self.request.user
        if user.is_student:
            context['form_student'] = forms.StudentProfileForm(self.request.POST)
        elif user.is_professor:
            context['form_professor'] = forms.ProfessorProfileForm(self.request.POST)
        elif user.is_executive:
            context['form_executive'] = forms.ExecutiveProfileForm(self.request.POST)

        elif user.is_student and user.is_professor and user.is_executive:
            context['form_student'] = forms.StudentProfileForm(self.request.POST)
            context['form_professor'] = forms.ProfessorProfileForm(self.request.POST)
            context['form_executive'] = forms.ExecutiveProfileForm(self.request.POST)

        return context

    def form_valid(self, form):
        context = self.get_context_data(form=form)
        user = self.request.user
        user = form.save()
        if user.is_student:
            student = context['form_student'].save(commit=False)
            student.user = user
            student.save()
        elif user.is_professor:
            professor = context['form_professor'].save(commit=False)
            professor.user = user
            professor.save()
        elif user.is_executive:
            executive = context['form_executive'].save(commit=False)
            executive.user = user
            executive.save()

        elif user.is_student and user.is_professor and user.is_executive:
            student = context['form_student'].save(commit=False)
            student.user = user
            student.save()

            professor = context['form_professor'].save(commit=False)
            professor.user = user
            professor.save()

            executive = context['form_executive'].save(commit=False)
            executive.user = user
            executive.save()
        return super(AccountProfilesView, self).form_valid(form)

What happen is that in the get_context_data() method the context['form_professor'] = forms.ProfessorProfileForm() and context['form_executive'] = forms.ExecutiveProfileForm() have been not passing to template
When I create the user with student profile (is_student) or with professor profile (is_professor) or with executive profile (is_executive) all works O.K., this mean, to the users profile by separated (users with only one profile) the render form profiles show the form according to the fields to profile respective.
In this sense, in the get_context_data() section, the following code works and pass the forms respective:
if user.is_student:
    profile = user.get_student_profile()
    context['userprofile'] = profile
    context['form_student'] = forms.StudentProfileForm()
elif user.is_professor:
    profile = user.get_professor_profile()
    context['userprofile'] = profile
    context['form_professor'] = forms.ProfessorProfileForm()
    print ("profesor form is", context['form_professor'])
elif user.is_executive:
    profile = user.get_executive_profile()
    context['userprofile'] = profile
    context['form_executive'] = forms.ExecutiveProfileForm()

But when I create an user with three profiles checked (is_student, is_professor, is_executive) just pass the  context['form_student'] = forms.StudentProfileForm()
My template in where I show the data is:
{% extends 'layout.html' %}
{% load bootstrap3 %}
{% block title_tag %}Accounts | Profile | iHost {{ block.super }}{% endblock %}
{% block body_content %}

My Profile

    <form method="POST">
        {% csrf_token %}

        # I ask for user profile of a separate way

        # Student Profile User
        {% if userprofile.user.is_student %}

            Student form
            {% bootstrap_form form_student %}
        {% endif %}

        # Professor Profile User
        {% if userprofile.user.is_professor %}
            {{ form_professor.as_p }}
        {% endif %}

        # Executive Profile User
        {% if userprofile.user.is_executive %}
            {{ form_executive.as_p }}
           {% comment %} {% bootstrap_form form_executive %}{% endcomment %}
        {% endif %}

        # I ask for an user with three profiles

        {% if userprofile.user.is_student  %}

        Student form
            {% if userprofile.user.is_professor %}
                {% if userprofile.user.is_executive %}
                    {% bootstrap_form form_student %}

                    Professor form does not arrive
                    {{ form_professor.as_p }}
                    {% comment %}  {% bootstrap_form form_professor %}{% endcomment %}

                    Executive form does not arrive
                    {{ form_executive.as_p }}
                    {% comment %}
                    {% bootstrap_form form_student %}
                    {% bootstrap_form form_professor %}
                    {% endcomment %}
                {% endif %}
            {% endif %}
        {% endif %}

        <input type="submit" value="Save Changes" class="btn btn-default">
    </form>

{% endblock %}

When I sign In with a user with three profiles, and I render the profile form, I get this behavior in relation to forms rendered.
form_professor and form_executive is not renderized

By this reason, I think that the professor and executive form instances does not have been passing to template,
This also is verified, because if I remove the comments and use django-bootstrap3 application in my template I cannot get the form_professor and form_executive instances form

*

*form_professor does not arrive to template

*form_executive does not arrive to template

In addition, although I think so that I can perform better the conditional logic in my template.
What happened to me here.
My idea is can render the profiles forms according to the profiles to the user in one template.
I appreciate highly their support.

UPDATE

According to the @Rohan answer below,  It's true, the  el ... if statement were the root of the problem. Now the forms render good.
My AccountProfilesView stay of this way:
class AccountProfilesView(LoginRequiredMixin, UpdateView):
    # All users can access this view
    model = get_user_model()
    #success_url = reverse_lazy('dashboard')
    template_name = 'accounts/profile_form.html'
    fields = '__all__'

    def get_context_data(self, **kwargs):
        context = super(AccountProfilesView, self).get_context_data(**kwargs)
        user = self.request.user

        if not self.request.POST:
            if user.is_student:
                profile = user.get_student_profile()
                context['userprofile'] = profile
                context['form_student'] = forms.StudentProfileForm()
            if user.is_professor:
                profile = user.get_professor_profile()
                context['userprofile'] = profile
                context['form_professor'] = forms.ProfessorProfileForm()
                print ("profesor form is", context['form_professor'])
            if user.is_executive:
                profile = user.get_executive_profile()
                context['userprofile'] = profile
                context['form_executive'] = forms.ExecutiveProfileForm()
        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        context = super(AccountProfilesView, self).post(request, *args, **kwargs)
        user = self.request.user
        if user.is_student:
            context['form_student'] = forms.StudentProfileForm(
                self.request.POST)
        if user.is_professor:
            context['form_professor'] = forms.ProfessorProfileForm(
                self.request.POST)
        if user.is_executive:
            context['form_executive'] = forms.ExecutiveProfileForm(
                self.request.POST)
        return context

    def form_valid(self, form):
        context = self.get_context_data(form=form)
        user = self.request.user
        user = form.save()
        if user.is_student:
            student = context['form_student'].save(commit=False)
            student.user = user
            student.save()
        if user.is_professor:
            professor = context['form_professor'].save(commit=False)
            professor.user = user
            professor.save()
        if user.is_executive:
            executive = context['form_executive'].save(commit=False)
            executive.user = user
            executive.save()
        return super(AccountProfilesView, self).form_valid(form)

    def get_success_url(self):
        return reverse('dashboard')

But now, when I want save the forms deployed product of the three profiles, I get this error message.
File "/home/bgarcial/workspace/ihost_project/accounts/views.py", line 181, in post
    context['form_student'] = forms.StudentProfileForm(self.request.POST)
  File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/http/response.py", line 142, in __setitem__
    value = self._convert_to_charset(value, 'latin-1', mime_encode=True)
  File "/home/bgarcial/.virtualenvs/ihost/lib/python3.5/site-packages/django/http/response.py", line 115, in _convert_to_charset
    raise BadHeaderError("Header values can't contain newlines (got %r)" % value)
django.http.response.BadHeaderError: Header values can't contain newlines (got '
Origin education institute:	<input id="id_origin_education_school" maxlength="128" name="origin_education_school" type="text" value="Universidad CES, Escuela de Ingeniería" required />
\n
Current education institute:	<input id="id_current_education_school" maxlength="128" name="current_education_school" type="text" value="Universidad CES" required />
\n
Extra occupation:	<input id="id_extra_occupation" maxlength="128" name="extra_occupation" type="text" value="Networker" required />
')
[08/Apr/2017 16:45:05] "POST /accounts/profile/milena/ HTTP/1.1" 500 108439

There is some inconvenient when form is going to be render and I make sure to fill this forms with data entered in a POST method, that error happen and this screen I get:

A: Its problem with python code in the get_context_data function. You should not use if..elif.. to add required forms. With your code if a user has all profiles, the code will only go into 1st if and add only student profile form.
So rather you should have separate if statements for all types of profiles. In that case you do not need last if with anding for all types.
So change your code to
if user.is_student:
    profile = user.get_student_profile()
    context['userprofile'] = profile
    context['form_student'] = forms.StudentProfileForm()

#NOTE: no elif, only if
if user.is_professor:
    profile = user.get_professor_profile()
    context['userprofile'] = profile
    context['form_professor'] = forms.ProfessorProfileForm()
    print ("profesor form is", context['form_professor'])

if user.is_executive:
    profile = user.get_executive_profile()
    context['userprofile'] = profile
    context['form_executive'] = forms.ExecutiveProfileForm()

# NO need for last if user.is_student and user.is_professor and user.is_executive:


text:
Q: prove that $\zeta^{i}$ is a primitive root modulo p $\iff$ $\gcd(p-1,i) =1$ where $p$ is prime and $\zeta$ is a primitive root modulo p. I was going to use a case by case proof, but i am relativley new to primitive roots and I couldnt see how to sufficiently prove either case.

A: Simply use the definition of a primitive root modulo $p$ :
The powers $(\zeta^i)^1,(\zeta^i)^2,\ldots,(\zeta^i)^{p-1}$ have precisely the residues $1,2,\ldots,p-1$ modulo $p$ in some order .
Now let $k=\gcd(i,p-1)$ then because $k \mid i$ :
$$(\zeta^i)^{\frac{p-1}{k}} \equiv (\zeta^{\frac{i}{k}})^{p-1} \equiv 1 \pmod{p}$$ from Fermat's little theorem .
But we already know that : $$(\zeta^i)^{p-1} \equiv 1 \pmod{p}$$ so because the powers are distinct modulo $p$ it must follow that : $$p-1=\frac{p-1}{k}$$
$$k=1$$
$$\gcd(i,p-1)=1$$
Now let's prove that $\zeta$ is also a prmitive root modulo $p$ .
Shorter way
Let $ord_p(\zeta)=l$ . We only need to prove that $l=p-1$.
$$(\zeta)^l \equiv 1 \pmod{p}$$
so :
$$(\zeta^i)^l \equiv 1 \pmod{p}$$ but $\zeta^i$ is a primitive root so it has order $p-1$ .It follows then that $p-1 \mid l$ so $l=p-1$ .
Longer way
Now because $\gcd(i,p-1)=1$ it follows that the numbers $i,2i,\ldots,(p-1)i$ are all distinct modulo $p-1$ . If for example $xi \equiv yi \pmod{p-1}$ then :
$$p-1 \mid i(x-y)$$ but $\gcd(i,p-1)=1$ :
$$p-1 \mid x-y$$ but this means that $x=y$ .
Because of this it follows that the powers $$(\zeta)^1,(\zeta)^2,\ldots,(\zeta)^{p-1}$$ are equivalent modulo $p$ with the powers :
$$(\zeta^i)^1,(\zeta^i)^2,\ldots,(\zeta^i)^{p-1}$$ which are in turn equivalent modulo $p$ (because $(\zeta)^i$ is a primitive root ) with :
$$1,2,\ldots,p-1$$
But this means that $\zeta$ is also a primitive root modulo $p$, as wanted .


text:
Q: iPhone:Learning Cocos2D project I want to develop a game in a month by using the Cocos2D Open Source game engine. Learning Cocos2D is a bit hard and I don't know how to create my initial project by using the files provided by Cocos2D base project. I doubt whether it is possible?
Can I learn by using Cocos2D base project directly and modify it for my game application? Does the license allow me to use like that? ( Because I can't learn all OpenGL programming concepts and develop an application in a month, which is very hard. )
Appreciate your thoughts and advice.
Thank you.

A: For what it's worth, I tried to pick up Objective C a few times over the last year but gave up pretty quickly each time (though I used to do C a lot in the early 90s). Just over a week ago, though, I watched some screencasts and eventually decided to start making my own game. I then discovered and gravitated toward using Cocos2D.
Now, 9 days later, I have a prototype of a game done (it's a kinda clone of Robotron 2084). It's been great fun doing it so far and while this is not the most up to date version (this was at the 1 week mark), this video will give you an idea of what I've achieved: http://www.youtube.com/watch?v=lzD6va1GiTI
I started by using the default Cocos2D project and just figuring it out and adding stuff as I went. I did a TON of Googling and often ended up here on Stack Overflow and on the Cocos2D iPhone forums (which are VERY useful). I've scratched my head a lot but it's been a fun experience (except for tracking down memory leaks ;-)).
Cocos2D is, I believe, LGPL licensed but has some extra clauses tagged on to make it even more free so you can use it in your iPhone game projects commercially or not without any problems.
I've found you don't need to learn much about OpenGL. I've copied and pasted some free snippets from here and there but they've been simple to figure out. Things like drawing lines and boxes, etc. I haven't learnt any "hard" OpenGL stuff. I've just stumbled and got a pretty long way, IMHO. I now feel pretty confident and am still finishing off this game to get it on the App Store and want to develop more!
Make sure to start with the latest Cocos2D 0.99-rc because they changed a lot of names and it'll annoy you if you have to upgrade in future. It's very stable and works fine. Go to http://www.cocos2d-iphone.org/download and download it, unpack, then run the template installer. Then create a project using the Cocos2D template in XCode and Build & Run it on the iPhone Simulator. You'll get a basic example that you can then dig around in. Read the Cocos2D iPhone "Programming Guide" on their site too and gradually figure out how to change the scene to do something you want it to do. Small steps, etc :-)

A: , I have been programming games for iPhone for more than a year now! I started doing most of the things in Objective-C but then I learned that for most graphically ( or computation ) intensive games, Objective-C is not really the best option. There are a lot of paths like Pure Objective-C  for logic, and inline C functions for the more "intensive" parts of your game, Obj-C does also let you use C++ files ( for the model classes for example ) with Obj-C++ (which is basically a .m Obj-c source code file but renamed to .mm for Obj-c++ ).
Having said that, Cocos-2D is in my opinion a wonderful library, it's mostly written in Obj-C but has pure C parts for the most CPU intensive stuff (physics it's chipmunk physics and Box2D, they also have a hash table library written in pure C to avoid calling NSDictionary a lot). Cocos2D is not hard to use, and you can get a nice game working quite fast!
You can embed the whole Cocos-2D to a project of yours, or just embed some useful parts of it (like Cocos-Live for On-Line scores, the Texture loaders, etc). You could also start working directly from the Cocos-2D Xcode project and remove what you don't need (like examples etc).
For a simple explanation of the Cocos-2D license , read Here !
About OpenGL, with Cocos you won't need to learn it deeply, unless you start getting into very custom stuff.
Having said all that, here are my recommendations :
1) GUI takes time, GUI can take a lot (even more than 50%) of your source code actually... so take that into consideration if you are going to have game menus, etc.. and adjust your time schedules to make the GUI coding fit!
2) When you have learned Cocos a bit, start playing with OpenGL, it's a wonderful ride, and it's really great to know a bit about the "Engine" of your "Car" so if your "Car" (Cocos2D) break's or doesn't do exactly what you want, you can always tweak here and there to make it work.

A: If you have programmed games before AND you have some experience with Objective-C THEN you could develop a game in a month. The complexity of the game is a big factor.

A: I think Cocos2d is a very good framework to help you get started in 2D game programming for the iPhone.
Here is a very nice tutorial that will get you started:  link text


text:
Q: How to get data after @ in SQL I have a table in the database that looks like this

id
email

1
user@domain.com

2
user@domain2.com

3
user@domain3.com

I have a form that looks like this
<form action="action.php" method="post" class="email-form" name="email-form">
  <label for="email">Enter Email</label>
  <input type="email" class="email" id="email" name="email">
  <input type="submit" class="submit-email" name="submit-email" value="submit Email">
</form>

In the backend I'm trying to match the input email domain with the ones in the database, after "@".
What I've tried (if user enters: test@domain2.com)
$email = $_POST["email"];
$emailDomain = explode("@",$email);
$emailDomain = $emailDomain[1];
/*I get the value domain2.com*/

How should I add a Query that matches $emailDomain with the database's email domain.
I know that if I add
$sql = "SELECT * FROM table_name WHERE email = $emailDomain";

It will look for the exact email I want to look for whats after "@" in the email section

A: One simple approach uses SUBSTRING_INDEX:
SELECT id, email, SUBSTRING_INDEX(email, '@', -1) AS domain
FROM yourTable;

A: You already have the part after the @ stored in $emailDomain. Simply check whether the email field contains this value with the LIKE operator:
SELECT * FROM table_name WHERE email LIKE '%value%'

However, note that you cannot simply substitute value with your $emailDomain in the above query, as this would make it vulnerable to SQL injection. Instead, make sure to paramaterise the query, and use a prepared statement to avoid SQL injection:
$conn = new mysqli($servername, $username, $password, $dbname);

$email = $_POST["email"];
$emailDomain = explode("@", $email);
$emailDomain = $emailDomain[1];
$param = "%{$emailDomain}%";
$stmt = $conn->prepare("SELECT * FROM table_name WHERE email LIKE ?");
$stmt->bind_param("s", $param);
$stmt->execute();
$stmt->bind_result($result); // Store the output in $result


text:
Q: Unable to open View from capacitorjs CAPPlugin class on IOS I'm writing a capacitorjs plugin. On ios I need to open my custom UIViewContoller. I'm converting my Cordova plugin to a Capacitorjs plugin. I found how to open a native view from the capacitorjs ios api docs.
My issue is that the view doesn't display, I get a black screen on the simulator. It's like the controller can't find the xib view file. Degbugging I get the events firing: viewDidLoad(), ViewDidAppear(). The links between the controller and the xib are all good in xCode. I tested with an UIAlertController and it displays OK.
DispatchQueue.main.async {
    let  mapCtrl = NavigateRouteViewController(withRouteInfo: routeInfo)
    mapCtrl.modalPresentationStyle = .fullScreen
    self.bridge!.viewController!.present(mapCtrl, animated: true, completion: nil)
}

Any suggestions on what to try?


text:
Q: How to get g++ for Linux FC-14 I am trying to install some software using gmake (recommended by author) on a FC14 machine.  gmake fails when trying to call /usr/bin/g++, and there is no g++ in /usr/bin.
I have the "various compilers" package installed. When I search on "g++" for available packages using the gnome Add/Remove Software interface, I get two choices "Cross Compiling GNU G++ targeted at arm-gp2-linux" and "Cross Compiling GNU GCC targeted at avr."
I don't have an ARM processor and I don't know what avr is, so I'm wondering if one of these is the right package, or if I need something else.  Anyone have guidance?

A: I don't know about Fedora 14, but at least on RHEL-5 (based on an older Fedora release) the package you want is "gcc-c++"

A: Do a search for "gcc" instead of "g++" it's usually in that package or "gcc-c++".


text:
Q: How to delete items from ObservableCollection I have a collection ObservableCollection called Datasets. I have a method for delete items from Datasets but not working. Can anyone help me?
My property is not good, what to put in set?
    private void ExecuteRemoveDatasetCommand(DefaultDataset dataset)
    {
        Datasets.Remove(dataset);
    }
public ObservableCollection<DefaultDataset> DefaultDatasets
    {
        get
        {
            ObservableCollection<DefaultDataset> defaultDataSet = new ObservableCollection<DefaultDataset>();
            foreach (var data in TemplateSystems.Select(data => data.DefaultDataSets).FirstOrDefault())
            {
                defaultDataSet.Add(data);
            }
            return defaultDataSet;
        }
        set
        {
        }
    }

A: The main problem is  your DefaultDataset is not implemented the IEquatable Interface so the system not able to find your element is the list.


text:
Q: Changing text color in Listview using SimpleCursorAdapter.ViewBinder I've listed the names from database using SimpleCursorAdapter and I want to change the color of a particular name using SimpleCursorAdapter.ViewBinder's method. I've a problem while running this method, my database contains different names but the ListView will display all the namse as one particular name. What am I doing wrong? How to change the text color of a specific name? Is it possible using ViewBinder?
This is my part of of code for ViewBinder:
    SimpleCursorAdapter.ViewBinder binder = new SimpleCursorAdapter.ViewBinder() {

    @Override
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
        // TODO Auto-generated method stub
        String[] temp = dh.return_result();
        tv = (TextView)findViewById(R.id.textView1);
        tv = (TextView) view;
        for(int i = 0; i<temp.length; i++)
        {
            if(temp[i].equalsIgnoreCase("Ameer Zhann"))
            {
                tv.setText(temp[i]);
                tv.setTextColor(Color.rgb(58, 58, 224));
                return true;
            }
        }
        return false;
    }
};

and this is my output image:

How can I solve this?

A: Try this way:
public boolean setViewValue(View view, Cursor cursor, int columnIndex){
    int getIndex = cursor.getColumnIndex("Name");
    String empname = cursor.getString(getIndex);
    tv = (TextView) view;
    tv.setTextColor(Color.WHITE);
    tv.setText(empname);
    if(empname.equals("Any String"))
    {
        tv.setTextColor(Color.rgb(58, 58, 224));
        return true;
    }
    return false;
}

A: Code do exactly what you ask - for every element in Cursor you go through all list and set text of each element. I think that "Ameer Zhann" is last result in your list, so only this text left in TextView.
Method setViewValue(...) called for every element of Cursor. So, you don't need any cycle, just fill text with cursor value tv.setText(Cursor.getString(...));.
Also there is something strange with this code:
tv = (TextView)findViewById(R.id.textView1);
tv = (TextView) view;

view that comes as param - is already view with id R.id.textView1 - so just remove call of findViewById.

A: try with the else part
if(temp[i].equalsIgnoreCase("Ameer Zhann")){
    tv.setText(temp[i]);
    tv.setTextColor(Color.rgb(58, 58, 224));
}else{
    tv.setText(temp[i]);
}

and at the end return true instead of false