text:
Q: Не подцепляется юзернейм в ForeignKey Есть форма, на которой пользователь загружает фото, после чего создается объект Photo, где поле img- сама картинка, поле usr- username залогиненного в данный момент User. При субмите все проходит успешно, создается Photo object, но usr не подцепляет username пользователя, загрузившего фото. В чем дело?
class UploadFormView(View):
    form_class = UploadForm
    template_name = 'upload_form.html'

    def get(self, request):
        form = self.form_class(None)
        return render(request, self.template_name, {'form':form})

    def post(self, request):
        form = self.form_class(request.POST, request.FILES)

        if form.is_valid():
            photo = form.save(commit=False)
            img = form.cleaned_data['img']
            usr = request.user.username
            photo.save()
            return redirect('regindex:index')

models.py:
class Photo(models.Model):
    img = models.ImageField()
    usr = models.ForeignKey(User, on_delete=models.CASCADE)

A: *

*Вам нужно указать self.request, т.к. вы работаете с классом.

*Не нужно указывать username.

Вот исправленная строчка:
usr = self.request.user

[UPDATE]
# views.py
class UploadFormView(View):
    form_class = UploadForm
    template_name = 'upload_form.html'

    def get(self, *args, **kwargs):
        form = self.form_class(None)
        return render(self.request, self.template_name, {'form':form})

    def post(self, *args, **kwargs):
        form = self.form_class(self.request.POST, self.request.FILES)

        if form.is_valid():
            photo = form.save(commit=False)
            photo.img = form.cleaned_data['img']
            photo.usr = self.request.user
            photo.save()
            return redirect('regindex:index')

# models.py - без изменений
class Photo(models.Model):
    img = models.ImageField()
    usr = models.ForeignKey(User, on_delete=models.CASCADE)

И если вы используете метод .save() - ваша форма должна быть модельная (т.е. ModelForm)
class UploadForm(forms.ModelForm):
    class Meta:
        model = Photo
        # fields = ('img', )
        exclude = ('usr',)


text:
Q: Changing Time Format in AngularJS $scope.timing = "1:2"; // Ex: "0.3", 10:1", "2:11", "11:41"

I want the above $scope.timing in 01:02 format.
How can i can achieve this?

A: You could use moment.js, as anshulk commented. this also is an opportunity to use a custom filter in the template

function hhSSfilter(input) {
  var result = input.split(':').map(d => {
     return d.length < 2 ? '0' + d : d;
  });
  return result.join(':');
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: React Native functional component navigationOptions headerRight not being set Previously I have set the headerRight option in the root component that renders child component with Screen options like this
export default function App() {
  return (
    <RecipeProvider>
      <NavigationContainer>
        <Stack.Navigator initialRouteName="Recipes">
          <Stack.Screen
            name="Recipes"
            component={RecipeList}
            options={({ navigation }) => ({
              headerRight: () => (
                <TouchableOpacity
                  style={styles.button}
                  onPress={() => navigation.navigate("New Recipe")}
                >
                  <FontAwesomeIcon icon={faPlus} size={20} />
                </TouchableOpacity>
              ),
            })}
          />

and now I would like to move the headerRight inside the component definition (so I don't end up with a huge App file with details that are only relevant to the screen component themselves)
I have read other solutions and tried the following
export default function RecipeList({ navigation }) {
  const { recipes } = useContext(RecipeContext);

  return (
    <View style={styles.container}>
      <FlatList
        numColumns={2}
        data={recipes}
        keyExtractor={(recipe: Recipe) => recipe.id}
        renderItem={({ item }) => {
          return (
            <RecipeItem
              name={item.name}
              minutes={item.minutes}
              image={item.image}
              title="Go to Detail Screen"
              onPress={() => {
                navigation.navigate("Recipe Details", { item });
              }}
            />
          );
        }}
      />
    </View>
  );
}

RecipeList.navigationOptions = ({ navigation }) => ({
  headerRight: () => (
    <TouchableOpacity
      style={styles.button}
      onPress={() => navigation.navigate("New Recipe")}
    >
      <FontAwesomeIcon icon={faPlus} size={20} />
    </TouchableOpacity>
  ),
});

But the headerRight button doesn't show no more ... any ideas ?
Thank you all <3

A: My headerRight is below and it works for me
EditScreen.navigationOptions = navData => {
 const submitFn = navData.navigation.getParam('submit');
  return {
    headerTitle: 'Edit Data'
    headerRight: (
     <HeaderButtons HeaderButtonComponent={HeaderButton}>
       <Item
         title="Save"
          iconName={
            Platform.OS === 'android' ? 'md-checkmark' : 'ios-checkmark'
          }
        onPress={submitFn}
      />
     </HeaderButtons>
    )
   };
 };


text:
Q: Android: Progress Bar while loading In Android development, I am loading a drawable from a url with this code:
public Drawable getImageFromURL(String sURL) {
    Object content = null;
    try {
        URL url = new URL(sURL);
        content = url.getContent();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    InputStream is = (InputStream) content;
    return Drawable.createFromStream(is, "src");
}

But I want to display this ProgressBar while it loads the drawable:
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        progressBar = ProgressDialog.show(TabMenu.this, getString(R.string.name), getString(R.string.specials));
        progressBar.setIcon(R.drawable.icon_template);

How do I do that? I call getImageFromURL() in the onCreate() methode of the Activity.
Thanks for your help!

A: You need to download the image in a new thread. You can use a AsyncTask for simplicity as in this example which implements also the progressbar

A: private Handler handler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        // do something

        switch (msg.what){
            case 1:
               //ALL FUNCTION(S) -----------------------------
               //-----------------------------------------------------
               //-----------------------------------------------------
               p_dialog.dismiss();
               break;

           // if error
           case 0:
               Toast.makeText(aktiviti.this, "Error", Toast.LENGTH_SHORT).show();
               p_dialog.dismiss();
               break;
        }
    }
};

ON CREATE --------->                                                <----------------
Button new_button = (Button) findViewById(R.id.new_button);

new_button.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {

        p_dialog = ProgressDialog.show((activity_name).this, "", "Loading Image...");

        new Thread(new Runnable() {
            public void run() {
                processThread();
            }}).start();
        }

        private void processThread() {
            try{
                handler.sendEmptyMessage(1);
            }
            catch (Exception e){
                handler.sendEmptyMessage(0);
            }
        }
    }
});

Good Luck!


text:
Q: Is this a mistake on my part or theirs? I'm not sure if I'm the one making the mistake, or my math book. It looks like the negative sign completely disappeared.
$$\frac{3x^2}{-\sqrt{18}} \cdot \frac{\sqrt{2}}{\sqrt{2}} = \frac{3x^2\sqrt{2}}{-\sqrt{36}} = \frac{3x^2\sqrt{2}}{6} = \frac{x^2\sqrt{2}}{2}$$
Here is the original image.
Also, I am new to Stackexchange, so tell me if I am doing something wrong.

A: Be cautious about the negative sign,
$$\frac{3x^{2}}{-\sqrt{18}} \times \frac{\sqrt{2}}{\sqrt{2}}=- \frac{3x^{2}}{\sqrt{18}} \times \frac{\sqrt{2}}{\sqrt{2}} =- \frac{3x^{2}}{3\sqrt{2}} = -\frac{x^{2}}{\sqrt{2}}$$
Maybe, there is a typo in the textbook.

A: It's probably them. It starts out correct, but when they go to take the negative square root of 36, there was an error. The correct approach is (or should I say, should be): $$\frac{3x^2}{-\sqrt{18}}\cdot \frac{\sqrt{2}}{\sqrt{2}} = \frac{3x^2\sqrt{2}}{-\sqrt{36}} = \frac{3x^2\sqrt{2}}{-6} = -\frac{x^2\sqrt{2}}{2}$$ This is because $-\sqrt{36}$ is actually $-(\sqrt{36})$. Or you could just apply the fraction rule and make it negative and go from there. It'll still give you the same answer.


text:
Q: Why does this Angular 6 onclick function not working properly? So, I built a quick Angular 6 app to help estimate bill amounts given the start and end date of the period a user wants to calculate for. (ex. 1 and 5 would return the total amount of bills from the 1st to the 5th).
Anyways, I have a button run the following function when clicked (this.bills$ is the json data im using) but its not working when i enter a startDay higher than the endDay.

  estimateBills() {
    this.estimateText = 0;

    console.log('00: startDay is: ' + this.startDay + ' and, endDay is: ' + this.endDay);

    if (this.startDay < this.endDay) {
      console.log('1: startDay is: ' + this.startDay + ' and, endDay is: ' + this.endDay);
      for (var i = 0; i < this.bills$.length; i++) {
        if (this.startDay <= this.bills$[i].DueDate && this.endDay >= this.bills$[i].DueDate) {
          console.log('Bill DueDate is: ' + this.bills$[i].DueDate + ' and Amount is ' + this.bills$[i].Amount);
          this.estimateText = +this.estimateText + this.bills$[i].Amount;
        }
      }
    }
    else if (this.startDay > this.endDay) {
      console.log('2: startDay is: ' + this.startDay + ' and, endDay is: ' + this.endDay);
      for (var i = 0; i < this.bills$.length; i++) {
        console.log('looping');
        if (this.startDay <= this.bills$[i].DueDate || this.endDay >= this.bills$[i].DueDate) {
          console.log('Bill DueDate is: ' + this.bills$[i].DueDate + ' and Amount is ' + this.bills$[i].Amount);
          this.estimateText = +this.estimateText + this.bills$[i].Amount;
        }
      }
    }
    else {
      this.estimateText = 1;
    }

  }

Here are some examples of what i get when run the function. For some reason it does not realize that the startDay is higher than the endDay! idk what is going wrong
When startDay is smaller than endDay (correct output)
When endDay is smaller than startDay (incorrect output)

A: Most probably the reason is that both this.startDay and this.endDay are strings, therefore "28" < "4" comparison is true (first characters '2' and '4' are compared in this case).
Explicit cast to numbers may help here, i.e. Number(this.startDay) < Number(this.endDay).


text:
Q: Php pdo update statement I need to update my database so I write:
try {
                $STH = $db->prepare("UPDATE zemljiste (naziv, ha, ar, m2, udeo_ha, udeo_ar, udeo_m2, lokacija, osnov, kat_kul, 2013_kol, ocekivano) VALUES (:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12) WHERE id = :id_akt AND user_id=:13");
                $STH->bindParam(':id_akt', $_POST['naziv']);

                $STH->bindParam(':1', $_POST['naziv']);
                $STH->bindParam(':2', $_POST['ha']);
                $STH->bindParam(':3', $_POST['ar']);
                $STH->bindParam(':4', $_POST['m2']);
                $STH->bindParam(':5', $_POST['udeo_ha']);
                $STH->bindParam(':6', $_POST['udeo_ar']);
                $STH->bindParam(':7', $_POST['udeo_m2']);
                $STH->bindParam(':8', $_POST['lokacija']);
                $STH->bindParam(':9', $_POST['osnov']);
                $STH->bindParam(':10', $_POST['kultura']);
                $STH->bindParam(':11', $_POST['prinos_2013']);
                $STH->bindParam(':12', $_POST['ocekivano']);
                $STH->bindParam(':13', $user_id);

                $STH->execute();

but I get error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
  error in your SQL syntax; check the manual that corresponds to your
  MySQL server version for the right syntax to use near '(naziv, ha, ar,
  m2, udeo_ha, udeo_ar, udeo_m2, lokacija, osnov, kat_kul, 2013_ko' at
  line 1Data submitted successfully

How I can solve this?
What is exactly error in my code?

A: You're using a syntax for INSERT statement in UPDATE, which is wrong.
It should look like this,
UPDATE table SET key=:value, key1=:value1 WHERE id=:id AND foo=:bar. So just replace,
"UPDATE zemljiste (naziv, ha, ar, m2, udeo_ha, udeo_ar, udeo_m2, lokacija, osnov, kat_kul, 2013_kol, ocekivano) VALUES (:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12) WHERE id = :id_akt AND user_id=:13"

with
UPDATE zemljiste SET naziv =:1, ha =:2, ...... WHERE id=:id_akt AND user_id = :13

A: UPDATE syntax is wrong and you should avoid integer placeholders
$query ="UPDATE `zemljiste`
         SET naziv = :naziv, ha = :ha, ar = :ar, m2 = :m2, udeo_ha = :udeo_ha,
         udeo_ar = :udeo_ar, udeo_m2 = :udeo_m2, lokacija=:lokacija, osnov = :osnov,
         kat_kul = :kultura, 2013_kol=:prinos_2013, ocekivano = :ocekivano
         WHERE id = :id_akt AND user_id=:user_id";

$STH = $db->prepare($query);

$STH->bindParam(':id_akt', $_POST['naziv']);
$STH->bindParam(':naziv', $_POST['naziv']);
$STH->bindParam(':ha', $_POST['ha']);
$STH->bindParam(':ar', $_POST['ar']);
$STH->bindParam(':m2', $_POST['m2']);
$STH->bindParam(':udeo_ha', $_POST['udeo_ha']);
$STH->bindParam(':udeo_ar', $_POST['udeo_ar']);
$STH->bindParam(':udeo_m2', $_POST['udeo_m2']);
$STH->bindParam(':lokacija', $_POST['lokacija']);
$STH->bindParam(':osnov', $_POST['osnov']);
$STH->bindParam(':kultura', $_POST['kultura']);
$STH->bindParam(':prinos_2013', $_POST['prinos_2013']);
$STH->bindParam(':ocekivano', $_POST['ocekivano']);
$STH->bindParam(':user_id', $user_id);

$STH->execute();

A: You are using the wrong syntax for update. It should be:
UPDATE zemljiste SET naziv=:1, ha=:2, ar=:3, ... WHERE ...


text:
Q: SSIS package with logging enabled using an "ssis log provider for text files" writes thousands of null characters I have an SSIS package set up with logging that writes to a text file.  This works fine except for the fact that it logs thousands and thousands of NUL characters to the file each time the package runs.
Any idea why this is happening and what can be done to prevent it?

A: This sounds like one or more settings in the SSIS logging tasks it not set correctly.
Under SSIS > Logging, you probably have a task under the container Package selected that is returning NULL.  Check all of the boxes under Package.  Then select the Details tab and verfiythat all of the correct Events are selected.  One of those may also be returning null each time it takes place.
I recommend unchecking some of the options and running the package to see if this changes your log results.  I also apply text log files and have had similar issues in the past that were resolved by this approach.


text:
Q: Locality of homogeneous pseudo-differential operator Let $P$ be a polynomial in several variables, and let $P(D)$ be the corresponding differential operator. Obviously, $P(D)$ is a local operator, in the sense that I need only to know the function $u$ in a neighborhood of a point $x$ in order to evaluate $P(D)(u)(x)$.
If $P$ is not a polynomial, we can still define $P(D)$ using the Fourier representation. Does this always produce a non-local operator? How can I check this, e.g. when $P$ is a rational fraction not reducible to a polynomial (if this matters)? (I browsed through Taylor's and Hörmander's books on pseudo-differential operators, but could not find this result. But I suppose that my question is very classical.)

A: A linear operator $P\colon C_c^\infty(X)\to \mathcal D'(X)$ with kernel $K\in\mathcal D'(X\times X)$ is local if and only if $\operatorname{supp}K\subseteq \Delta_X$, where $\Delta_X$ is the diagonal in $X\times X$. If $P$ happens to be a pseudodifferential operator, then its kernel $K$ is conormal with respect to $\Delta_X$. Having both properties the same time means that $P$ is a differential operator.
The original version of this theorem (in the language of sheaves) is due to Jaak Peetre (1959).


text:
Q: Is there any examples of realtime element resizing? I have a concept that is similar to newsmap.jp where elements are given a value based on a specific value and they resize based on on that value in a grid like container in realtime with out any page refreshing
Has anyone every seen something like that? If not do you have any pointers in the right direction for how I would begin building it. I'm good with PHP but not so much with jquery.
UPDATE 1: These are good but I am looking for a script that is constantly resizing the elements (based on an algorithm). Basically it's something that is responsive to the sizes of the continuously changing elements in around it rather than something that changes only when the browser window re-sizes. Does that make sense?

A: You can take a look here http://masonry.desandro.com/
But you can change the size of divs or any other elements, with jquery/javascript.
See example on jquery:

Lorem ipsum sit amet

A: Do you mean a "Masonry" Effect? Look here: http://isotope.metafizzy.co/ or http://packery.metafizzy.co/

A: There are several such plugins for jQuery. You can find a lot in this page:
http://www.wtfdiary.com/2012/08/6-amazing-jquery-plugins-to-design.html
and this page:
http://bashooka.com/coding/jquery-plugins-for-creating-grid-layout/
My favorite ones are isotope:
http://isotope.metafizzy.co/index.html
and BlocksIt:
http://www.inwebson.com/jquery/blocksit-js-dynamic-grid-layout-jquery-plugin/


text:
Q: I want to load all the images in a folder in a google maps info window I am loading a bunch of markers into google maps from an xml file. Each marker's name will correspond with a folder of images on the server. When populating the information box I want to display all the images in the corresponding folder.
www.frackwatch.co.za
Everything works except the images do not display. In their place instead is [Object][Object].
function load() {
  var map = new google.maps.Map(document.getElementById("map"), {
    center: new google.maps.LatLng(-31.5, 24.0),
    zoom: 7,
    mapTypeId: 'satellite'
  });

  var infoWindow = new google.maps.InfoWindow;

  // Change this depending on the name of your PHP file
  downloadUrl("genxml.php", function(data) {
    var xml = data.responseXML;
    var markers = xml.documentElement.getElementsByTagName("marker");
    for (var i = 0; i < markers.length; i++) {

      var info = markers[i].getAttribute("info");
      var name = markers[i].getAttribute("name");
      var point = new google.maps.LatLng(
          parseFloat(markers[i].getAttribute("lat")),
          parseFloat(markers[i].getAttribute("lng")));
      var folder = "attachments/" + name +"/";

      var html = "" + info + "
" + $.ajax({
        url : folder,
        success: function (data) {
          $(data).find("a").attr("href", function (i, val) {
            if( val.match(/\.(jpeg|png|gif)$/) ) {
              $("body").append( "" );
            }
          });
        }
      });

      var marker = new google.maps.Marker({
        map: map,
        position: point,
        icon: icn
      });
      bindInfoWindow(marker, map, infoWindow, html);
    }
  });
}

function bindInfoWindow(marker, map, infoWindow, html) {
  google.maps.event.addListener(marker, 'click', function() {
    infoWindow.setContent(html);
    infoWindow.open(map, marker);
  });
}

function downloadUrl(url, callback) {
  var request = window.ActiveXObject ?
      new ActiveXObject('Microsoft.XMLHTTP') :
      new XMLHttpRequest;

  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      request.onreadystatechange = doNothing;
      callback(request, request.status);
    }
  };

  request.open('GET', url, true);
  request.send(null);
}

function doNothing() {}

Correct code but only loads images for the first marker:
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(-29, 25.0),
zoom: 6,
mapTypeId: 'satellite'
});

var infoWindow = new google.maps.InfoWindow;

// Change this depending on the name of your PHP file
downloadUrl("genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {

  var info = markers[i].getAttribute("info");
  var id = markers[i].getAttribute("id");
  var point = new google.maps.LatLng(
      parseFloat(markers[i].getAttribute("lat")),
      parseFloat(markers[i].getAttribute("lng")));
  var folder = "/attachments/" + id +"/";

var marker = new google.maps.Marker({
    map: map,
    position: point,
    icon: icn
  });
$.ajax({
url : folder,
success: function (data) {
    var html = "" + info + "
";
    $(data).find("a").each(function () {
    $this = $(this)
    if($this.attr('href').match(/\.(jpg|png|gif|jpeg)$/)) {
    html +=  "";
  }
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
});
}

function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}

function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
  new ActiveXObject('Microsoft.XMLHTTP') :
  new XMLHttpRequest;

request.onreadystatechange = function() {
if (request.readyState == 4) {
  request.onreadystatechange = doNothing;
  callback(request, request.status);
}
};

request.open('GET', url, true);
request.send(null);
}

function doNothing() {}

A: var html = "" + info + "
" + $.ajax({url : folder,success:     function (data) {$(data).find("a").attr("href", function (i, val) {if( val.match(/\.(jpeg|png|gif)$/) ) { $("body").append( "" );} });}});;

The $.ajax function does not return anything. Check the documentation.
So the var html = [...] + $.ajax is broken.
You are trying to display all images in a folder in a InfoWindow ?
If so, it should something like :
var folder = "attachments/" + name +"/";
var marker = new google.maps.Marker({
    map: map,
    position: point,
    icon: icn
});

$.ajax({
  url : folder,
  success: function (data) {
    var html = "" + info + "
";
    $(data).find("a").each(function () {
      $this = $(this)
      if($this.attr('href').match(/\.(jpeg|png|gif)$/)) {
        html +=  "";
      }
    });
    bindInfoWindow(marker, map, infoWindow, html);
   }
 });

bindInfoWindow should be in the ajax callback otherwise the result can be there yet.
A cleaner way would be that genxml.php lists all images so you won't have to request the files in folder afterwards.


text:
Q: Python scraper does return empty I have the following code to scrape the statistics of a Football match from flashscore:`
from requests_html import AsyncHTMLSession
from collections import defaultdict

url = 'https://www.flashscore.com/match/fXAklYDd/#match-statistics;0'

asession = AsyncHTMLSession()

async def get_scores():
    r = await asession.get(url)
    await r.html.arender()
    return r

results = asession.run(get_scores)
results = results[0]

stats = results.html.find("div.statRow")

dict_res = defaultdict(list)

for ind in range(len(stats)):
    dict_res['stats'].append(stats[ind].text)

df_res = pd.DataFrame(dict_res)
print(df_res)

Where the line stats = results.html.find("div.statRow") should return the statistics of the match
This generates the following output:
Empty DataFrame
Columns: []
Index: []

Can someone explain to me what I am doing wrong?
I do not understand why it does not show the statistics in a DataFrame.
Thanks in advance!

A: await r.html.arender(sleep = 1)

Just had a reading at the documentation of requests_html and found out that the sleep value to be helpful in this case
This is the output:
0   59%\nBall Possession\n41%
1       16\nGoal Attempts\n12
2         5\nShots on Goal\n5
3        5\nShots off Goal\n5
4         6\nBlocked Shots\n2
5          3\nCorner Kicks\n5
6              1\nOffsides\n1
7      3\nGoalkeeper Saves\n4
8               11\nFouls\n24
9          2\nYellow Cards\n3
10     422\nTotal Passes\n305
11            19\nTackles\n17
12           122\nAttacks\n94
13  46\nDangerous Attacks\n39
14  62%\nBall Possession\n38%
15        4\nGoal Attempts\n8
16        1\nShots on Goal\n4
17       1\nShots off Goal\n3
18        2\nBlocked Shots\n1
19         0\nCorner Kicks\n3
20             1\nOffsides\n0
21     3\nGoalkeeper Saves\n0
22               3\nFouls\n14
23         0\nYellow Cards\n1
24     231\nTotal Passes\n139
25              8\nTackles\n4
26            67\nAttacks\n36
27  20\nDangerous Attacks\n19
28  56%\nBall Possession\n44%
29       12\nGoal Attempts\n4
30        4\nShots on Goal\n1
31       4\nShots off Goal\n2
32        4\nBlocked Shots\n1
33         3\nCorner Kicks\n2
34             0\nOffsides\n1
35     0\nGoalkeeper Saves\n4
36               8\nFouls\n10
37         2\nYellow Cards\n2
38     191\nTotal Passes\n166
39            11\nTackles\n13
40            55\nAttacks\n58
41  26\nDangerous Attacks\n20

To clean the output from the break lines you need to use replace("\n", " ") at the end of the append
for ind in range(len(stats)):
    dict_res['stats'].append(stats[ind].text.replace("\n", " "))

Here is the output afterwards:
0   59% Ball Possession 41%
1       16 Goal Attempts 12
2         5 Shots on Goal 5
3        5 Shots off Goal 5
4         6 Blocked Shots 2
5          3 Corner Kicks 5
6              1 Offsides 1
7      3 Goalkeeper Saves 4
8               11 Fouls 24
9          2 Yellow Cards 3
10     422 Total Passes 305
11            19 Tackles 17
12           122 Attacks 94
13  46 Dangerous Attacks 39
14  62% Ball Possession 38%
15        4 Goal Attempts 8
16        1 Shots on Goal 4
17       1 Shots off Goal 3
18        2 Blocked Shots 1
19         0 Corner Kicks 3
20             1 Offsides 0
21     3 Goalkeeper Saves 0
22               3 Fouls 14
23         0 Yellow Cards 1
24     231 Total Passes 139
25              8 Tackles 4
26            67 Attacks 36
27  20 Dangerous Attacks 19
28  56% Ball Possession 44%
29       12 Goal Attempts 4
30        4 Shots on Goal 1
31       4 Shots off Goal 2
32        4 Blocked Shots 1
33         3 Corner Kicks 2
34             0 Offsides 1
35     0 Goalkeeper Saves 4
36               8 Fouls 10
37         2 Yellow Cards 2
38     191 Total Passes 166
39            11 Tackles 13
40            55 Attacks 58
41  26 Dangerous Attacks 20


text:
Q: can't access ubuntu on my PC someone was trying to help me about a year ago. When I try to input my password the computer switches to the terminal window. They suggested that I download a new version of ubuntu and install it in my pc. I don't know how to initialize a disc to download and run a new version of ubuntu. can someone walk me through the process?

A: just follow these points and you should have a successful installation of Ubuntu in no time!
Step 1
Download the iso file. To install Ubuntu, one needs the iso files, please go to this link. The downloads page shall have two options, to download 12.04 which is the latest LTS version of Ubuntu or 13.10 which was released last month. For the sake of this question, I suggest you download the LTS version, i.e 12.04.
Step 2
Make a bootable USB. The easiest way to install Ubuntu is via the bootable USB option. Now, I assume that you're on Windows so go this link and download the Windows version of Unetbootin.
Step 3
Now, our real work would start.

*

*Open Unetbootin

*Under the option for image files choose the iso file that you've downloaded

*Under the option of choosing the drive where it would be installed choose your USB drive. Please be careful, choose only your USB drive

*Let Unetbootin make the Bootable USB now.

*Once that is done, reboot your machine and enter the Boot Order Menu. Here, choose your USB drive.

*Now,  in a few minutes you should be able to boot into Ubuntu, but, we haven't installed Ubuntu yet, you're merely trying it out.

*On your Ubuntu Desktop you should be able to see an option called Install Ubuntu.Choose that option and the loader shall start working.

*Depending on your choice, you may choose to Install Ubuntu and Replace Everything else or Install it alongside Windows or A custom Setup, choose whichever one suits you best.

*Let the installer do it's magic and soon enough, you'll have a successful installation of Ubuntu upon rebooting.


text: Q: Tensor product of two fields Let $F, k'$ be two fields containing a given field $k$.  The book I'm reading (Borel, Linear Algebraic Groups) uses some facts about the structure of the tensor product $F \otimes_k k'$, for example the fact that every prime ideal is minimal.  Does anyone know a reference which explains some of these properties?


text:
Q: Team Fundation Server Error al Descargar archivos (descargado) he estado creando una app desde mi notebook desde hace tiempo y me he comprado una de escritorio, para poder migrar esta app use TFS, el problema esta que al descargar los archivos en la pc estos me aparecen de la siguiente manera.

He intentado con estos 3 puntos que aparecen haciendole click derecho pero ninguno pude ayudarme

Al instalar funcionalidades que faltan me dice que ya estan todas instaladas y el resto no hace nada.


text:
Q: A pod cannot connect to a service by IP My ingress pod is having trouble reaching two clusterIP services by IP. There are plenty of other clusterIP services it has no trouble reaching. Including in the same namespace. Another pod has no problem reaching the service (I tried the default backend in the same namespace and it was fine).
Where should I look? Here are my actual services, it cannot reach the first but can reach the second:
- apiVersion: v1
  kind: Service
  metadata:
    creationTimestamp: "2019-08-23T16:59:10Z"
    labels:
      app: pka-168-emtpy-id
      app.kubernetes.io/instance: palletman-pka-168-emtpy-id
      app.kubernetes.io/managed-by: Tiller
      helm.sh/chart: pal-0.0.1
      release: palletman-pka-168-emtpy-id
    name: pka-168-emtpy-id
    namespace: palletman
    resourceVersion: "108574168"
    selfLink: /api/v1/namespaces/palletman/services/pka-168-emtpy-id
    uid: 539364f9-c5c7-11e9-8699-0af40ce7ce3a
  spec:
    clusterIP: 100.65.111.47
    ports:
    - port: 80
      protocol: TCP
      targetPort: 8080
    selector:
      app: pka-168-emtpy-id
    sessionAffinity: None
    type: ClusterIP
  status:
    loadBalancer: {}
- apiVersion: v1
  kind: Service
  metadata:
    creationTimestamp: "2019-03-05T19:57:26Z"
    labels:
      app: production
      app.kubernetes.io/instance: palletman
      app.kubernetes.io/managed-by: Tiller
      helm.sh/chart: pal-0.0.1
      release: palletman
    name: production
    namespace: palletman
    resourceVersion: "81337664"
    selfLink: /api/v1/namespaces/palletman/services/production
    uid: e671c5e0-3f80-11e9-a1fc-0af40ce7ce3a
  spec:
    clusterIP: 100.65.82.246
    ports:
    - port: 80
      protocol: TCP
      targetPort: 8080
    selector:
      app: production
    sessionAffinity: None
    type: ClusterIP
  status:
    loadBalancer: {}

My ingress pod:
apiVersion: v1
kind: Pod
metadata:
  annotations:
    sumologic.com/format: text
    sumologic.com/sourceCategory: 103308/CT/LI/kube_ingress
    sumologic.com/sourceName: kube_ingress
  creationTimestamp: "2019-08-21T19:34:48Z"
  generateName: ingress-nginx-65877649c7-
  labels:
    app: ingress-nginx
    k8s-addon: ingress-nginx.addons.k8s.io
    pod-template-hash: "2143320573"
  name: ingress-nginx-65877649c7-5npmp
  namespace: kube-ingress
  ownerReferences:
  - apiVersion: extensions/v1beta1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: ingress-nginx-65877649c7
    uid: 97db28a9-c43f-11e9-920a-0af40ce7ce3a
  resourceVersion: "108278133"
  selfLink: /api/v1/namespaces/kube-ingress/pods/ingress-nginx-65877649c7-5npmp
  uid: bcd92d96-c44a-11e9-8699-0af40ce7ce3a
spec:
  containers:
  - args:
    - /nginx-ingress-controller
    - --default-backend-service=$(POD_NAMESPACE)/nginx-default-backend
    - --configmap=$(POD_NAMESPACE)/ingress-nginx
    - --publish-service=$(POD_NAMESPACE)/ingress-nginx
    env:
    - name: POD_NAME
      valueFrom:
        fieldRef:
          apiVersion: v1
          fieldPath: metadata.name
    - name: POD_NAMESPACE
      valueFrom:
        fieldRef:
          apiVersion: v1
          fieldPath: metadata.namespace
    image: gcr.io/google_containers/nginx-ingress-controller:0.9.0-beta.13
    imagePullPolicy: Always
    livenessProbe:
      failureThreshold: 3
      httpGet:
        path: /healthz
        port: 10254
        scheme: HTTP
      initialDelaySeconds: 30
      periodSeconds: 10
      successThreshold: 1
      timeoutSeconds: 5
    name: ingress-nginx
    ports:
    - containerPort: 80
      name: http
      protocol: TCP
    resources: {}
    terminationMessagePath: /dev/termination-log
    terminationMessagePolicy: File
    volumeMounts:
    - mountPath: /var/run/secrets/kubernetes.io/serviceaccount
      name: default-token-dg5wn
      readOnly: true
  dnsPolicy: ClusterFirst
  nodeName: ip-10-55-131-177.eu-west-1.compute.internal
  restartPolicy: Always
  schedulerName: default-scheduler
  securityContext: {}
  serviceAccount: default
  serviceAccountName: default
  terminationGracePeriodSeconds: 60
  tolerations:
  - effect: NoExecute
    key: node.kubernetes.io/not-ready
    operator: Exists
    tolerationSeconds: 300
  - effect: NoExecute
    key: node.kubernetes.io/unreachable
    operator: Exists
    tolerationSeconds: 300
  volumes:
  - name: default-token-dg5wn
    secret:
      defaultMode: 420
      secretName: default-token-dg5wn
status:
  conditions:
  - lastProbeTime: null
    lastTransitionTime: "2019-08-21T19:34:48Z"
    status: "True"
    type: Initialized
  - lastProbeTime: null
    lastTransitionTime: "2019-08-21T19:34:50Z"
    status: "True"
    type: Ready
  - lastProbeTime: null
    lastTransitionTime: "2019-08-21T19:34:48Z"
    status: "True"
    type: PodScheduled
  containerStatuses:
  - containerID: docker://d597673f4f38392a52e9537e6dd2473438c62c2362a30e3d58bf8a98e177eb12
    image: gcr.io/google_containers/nginx-ingress-controller:0.9.0-beta.13
    imageID: docker-pullable://gcr.io/google_containers/nginx-ingress-controller@sha256:c9d2e67f8096d22564a6507794e1a591fbcb6461338fc655a015d76a06e8dbaa
    lastState: {}
    name: ingress-nginx
    ready: true
    restartCount: 0
    state:
      running:
        startedAt: "2019-08-21T19:34:50Z"
  hostIP: 10.55.131.177
  phase: Running
  podIP: 172.6.218.18
  qosClass: BestEffort
  startTime: "2019-08-21T19:34:48Z"

A: It could be connectivity to the node where your Pod is running. (Or network overlay related) You can check where that pod is running:
$ kubectl get pod -o=json  | jq .items[0].spec.nodeName

Check if the node is 'Ready':
$ kubectl get node <node-from-above>

If it's ready, then ssh into the node to further troubleshoot:
$ ssh <node-from-above>

Is your overlay pod running on the node? (Calico, Weave, CNI, etc)
You can further troubleshoot connecting to the pod/container
# From <node-from-above>
$ docker exec -it <container-id-in-pod> bash
# Check connectivity (ping, dig, curl, etc)

Also, from using the kubectl command line (if you have network connectivity to the node)
$ kubectl exec -it <pod-id> -c <container-name> bash
# Troubleshoot...


text:
Q: Add custom NicEdit editor button for youtube videos I've used the nicEdit - http://nicedit.com/
I need to insert the videos from youtube. I need to insert only url for example: http://www.youtube.com/watch?v=4GuqB1BQVr4
and replace to

How can i insert the videos from youtube using nicEdit?

A: JDandChips code works great, however I found that it was placing the video at the bottom of the content. To insert it at the cursor
find
 this.ne.selectedInstance.setContent(this.ne.selectedInstance.getContent() + youTubeCode);
 this.removePane();

change to
  this.removePane();
  this.ne.nicCommand('insertHTML', youTubeCode);

works great for me.
Here's the full plugin code
var nicCodeOptions = {
buttons : {
    'xhtml': { name: 'Edit HTML', type: 'nicCodeButton' },
    'youTube' : {name : 'YouTube', type : 'nicYouTubeButton'}
},
iconFiles: {
    'youTube': '/nicedit/youtube.gif'
}
};

var nicYouTubeButton = nicEditorAdvancedButton.extend({
width: '350px',

addPane: function () {
    this.addForm({
        '': { type: 'title', txt: 'YouTube Url' },
        'youTubeUrl': { type: 'text', txt: 'URL', value: 'http://', style: { width: '150px'} },
        'height': { type: 'text', txt: 'Height', value: '560', style: { width: '150px'} },
        'width': { type: 'text', txt: 'Width', value: '315', style: { width: '150px'} }
    });
},

submit: function (e) {
    var code = this.inputs['youTubeUrl'].value;
    var width = this.inputs['height'].value;
    var height = this.inputs['width'].value;

    if (code.indexOf('watch?v=') > 0) {
        code = code.replace('watch?v=','embed/');
    }

    var youTubeCode = '';

    this.removePane();
    this.ne.nicCommand('insertHTML', youTubeCode);
}
});
nicEditors.registerPlugin(nicPlugin,nicYouTubeOptions);

The nicCommand to insert html for other plugins that require inserting the html at the cursor position.
Sorry, meant to say for a plugin to insert any html at the cursor position GO HERE.

A: Adding a custom nicEdit button
You need to add a custom button as outlined here: http://wiki.nicedit.com/w/page/516/Creating%20a%20Plugin
There are parts of this documentation that I found confusing when I first read it, so I will walk you through how to add the working button.
If you have the development version of nicEdit.js, go to the bottom of the file and you will see a custom button called "nicCodeButton".
Below this add your own custom button, which should look like this:
YouTube button code
var nicYouTubeButton = nicEditorAdvancedButton.extend({
    width: '350px',

    addPane: function () {
        this.addForm({
            '': { type: 'title', txt: 'YouTube Url' },
            'youTubeUrl': { type: 'text', txt: 'URL', value: 'http://', style: { width: '150px'} },
            'height': { type: 'text', txt: 'Height', value: '560', style: { width: '150px'} },
            'width': { type: 'text', txt: 'Width', value: '315', style: { width: '150px'} }
        });
    },

    submit: function (e) {
        var code = this.inputs['youTubeUrl'].value;
        var width = this.inputs['height'].value;
        var height = this.inputs['width'].value;

        if (code.indexOf('watch?v=') > 0) {
            code = code.replace('watch?v=','embed/');
        }

        var youTubeCode = '';

        this.ne.selectedInstance.setContent(this.ne.selectedInstance.getContent() + youTubeCode);
        this.removePane();
    }
});

Next you need to add your button to the custom config and an icon image for the panel to use, also found at the bottom of the file. It will look like this once complete:
Add you button to config
/* START CONFIG */
var nicCodeOptions = {
    buttons : {
        'xhtml': { name: 'Edit HTML', type: 'nicCodeButton' },
        'youTube' : {name : 'YouTube', type : 'nicYouTubeButton'}
    },
    iconFiles: {
        'youTube': 'nicEditorIcons2.gif'
    }
};
/* END CONFIG */

That's it!
(The above code has been tested if you'd like to use it)

A: I had difficulty getting this to work even with all your guidance here so I will try to post as much help as possible on this. Chances are that its not the final solution but maybe this can help anyone looking to try and get a button added.
I had difficulty even getting a button to show so I reduced it all to virtually nothing to figure it out.
var nicYouTubeOptions = {
  buttons : {
    'youtube': {name : 'YouTube Link', type : 'nicYouTubeButton'}
  },
  iconFiles: {
    'youtube': 'images/youtube.gif'
  }
};

So this first section of code sets up your button details. In other words the image you use for the button and the text you see when you hover over it. The final part listed next to type is 'nicYouTubeButton' and this declares what function is to be called when the button is pressed.
var nicYouTubeButton = nicEditorAdvancedButton.extend({

});

This is just simply the function (currently empty) which does everything.
nicEditors.registerPlugin(nicPlugin,nicYouTubeOptions);

This final line registers the plugin using the OPTIONS function and not the BUTTON function.
To get this working in the editor now, you need to add the button (declared as 'youtube', note lowercase here) which has been created in the OPTIONS variable. To do this you need to modify the line near the top of the file marked like so:
buttonList : ['save','bold','italic','underline','left','center','right','justify','ol','ul','fontSize','fontFamily','fontFormat','indent','outdent','image','upload','link','unlink','forecolor','bgcolor','xhtml','table','youtube'],

As you can see, I have already added 'youtube' to the list making sure to add that comma between items.
Simply add the following code in your EMPTY function nicYouTubeButton:
width: '350px',

addPane: function () {
    this.addForm({
        '': { type: 'title', txt: 'YouTube Url' },
        'youTubeUrl': { type: 'text', txt: 'URL', value: 'http://', style: { width: '150px'} },
        'height': { type: 'text', txt: 'Height', value: '560', style: { width: '150px'} },
        'width': { type: 'text', txt: 'Width', value: '315', style: { width: '150px'} }
    });
},

submit: function (e) {
    var code = this.inputs['youTubeUrl'].value;
    var width = this.inputs['height'].value;
    var height = this.inputs['width'].value;

    if (code.indexOf('watch?v=') > 0) {
        code = code.replace('watch?v=','embed/');
    }

    var youTubeCode = '';

    this.ne.selectedInstance.setContent(this.ne.selectedInstance.getContent() + youTubeCode);
    this.removePane();
}

Be sure not to remove any of the } or {
Hope this helps any of you having difficulty getting it to show up like me.


text:
Q: Вызвать хук с дополнительными параметрами В woocommerce есть хук
add_filter('woocommerce_product_variation_get_stock_quantity','product_get_stock_quantity', 10, 2);

Как вызвать этот хук, чтобы можно было передать в него дополнительные параметры?
Он принимает только два параметра, а нужно передавать в него дополнительные параметры
Этот хук woocommerce_product_variation_get_stock_quantity вызывается так:
            $variation = wc_get_product( $item['variation_id'] );
            $old_quantity = $variation->get_stock_quantity();

Как передать в функцию $variation->get_stock_quantity() дополнительные параметры?
т.е. если в do_action определено только два параметра, можно ли как-то переопределить, чтобы принимал 3 параметра?


text:
Q: SQL - Converting MONTH extract from number to full month name Having trouble with a particular stored procedure. I think I have it mostly correct...
I basically want to be able to search for a month and year and have any products' rows sold within that timeline show up.
CREATE PROCEDURE sp_products
    @productname    CHAR(20),
    @month      CHAR(9),
    @year           CHAR(4)

AS
SELECT  p.ProductName,
        p.UnitPrice,
        p.UnitsInStock,
        s.Name

FROM        Orders o
INNER JOIN  OrderDetails od
ON          o.OrderID = od.OrderID
INNER JOIN  Products p
ON          od.ProductID = p.ProductID
INNER JOIN  Suppliers s
ON          p.SupplierID = s.SupplierID

WHERE   p.ProductName = @productname
AND     MONTH(o.OrderDate) = @month
AND     YEAR(o.OrderDate) = @year

Giving me a "Conversion failed when converting the varchar value 'December ' to data type int." error.
Here's the query it needs to work with:
EXEC sp_products '%tofu%', 'December', 1992

I think I know what I need to do, just don't know how to do it...
Help!

A: MONTH() returns an int.
Instead of MONTH(o.OrderDate), try DATENAME(m, o.OrderDate)
EDIT:
Also note that your input will not give you results are you are using wildcards without using the LIKE operator.
Update your procedure with this line:
WHERE p.ProductName LIKE @productname

A: The following two conditions are probably making your query non-sargable, because in each case you are applying a function to a column being filtered on:
AND     MONTH(o.OrderDate) = @month
AND     YEAR(o.OrderDate) = @year

I would change them like this:
SELECT     …
           …
           …

FROM       Orders o

/* this join actually replaces those two filters */
INNER JOIN (SELECT CAST('1-' + @month + CAST(-@year AS varchar(5))) AS Month) d
ON         o.OrderDate >= d.Month AND o.OrderDate < DATEADD(MONTH, 1, d.Month)

INNER JOIN … /* the rest of your joins */

WHERE      p.ProductName = @productname  /* only one condition here now */

That is, the @year and @month arguments are formatted as a string convertible to a datetime value representing the first of the corresponding month, then you are besically filtering using this logic:
order date >= the first of the given month
and
order date < the first of the next month after the given

And of course, as you've already been told, the @productname filter in your query should probably use the LIKE comparison instead of the =, because it seems like you want to search by a mask as well as by a specific name. So the WHERE clause would then look like this:
WHERE      p.ProductName LIKE @productname

A: To convert a month string to a 1-12 representation of a month, use the inbuilt function DATENAME - reconstruct your date with something like, 01 December 1922, then use that for the input into DATENAME

A: As answered by jlnorsworthy
"Instead of MONTH(o.OrderDate), try DATENAME(m, o.OrderDate)"
This will work
For no result pls check what the input you are passing
EXEC sp_products '%tofu%', 'December', 1992
you are comparing it with = operator
WHERE   p.ProductName = @productname

change = to like it will work.


text:
Q: about nl, br and security while working with textarea and mysql in PHP I'm getting data from my textarea with the following code
$about_me=mysql_real_escape_string(nl2br($_POST['about_me']));

which
1. Receives  data, using $_POST.
2. nl2br makes brakes so If I echo this code to user he will see if there were new lines.
3. mysql_real_escape_string to secure code from mysql injections before entering it to database.
So if I echo this code everything works fine.
But If I edit it again through textarea, php goes to mysql gets data, puts it to textarea and I see
 signs...
How can I get rid of them while editing my text again in textarea ?

A:
How can I get rid of them while editing my text again in textarea ?

Stop using nl2br(), of course. It's entirely wrong here.

You use nl2br() when you want to output data that contains linebreaks to HTML, not when you want to store it in the database. Store data unchanged, format it for viewing.
If you output it into a <textarea> you don't need to use it either, since textareas display linebreaks (whereas HTML in general does not). For the textarea you need htmlspecialchars(), but apparently this is already happening - otherwise you would not see literal
 showing up.

A: <?php
function br2nl($string){
  $return=eregi_replace('
',chr(13).chr(10),$string);
  return $return;
}
?>

Use this while getting data from database and before printing into textarea .
http://php.net/manual/en/function.nl2br.php
Check examples on this page


text:
Q: :via => [:options] in ruby on rails routes In some Rails app, I saw this in the routes.rb
root :to => "home#index", :via => [:get]
root :to => "accounts#manage", :via => [:options]

I could not understand how these two root URLs can exist. Googling didn't help clear the :options argument either. Can anyone help?
Thanks

A: As per the HTTP spec (and explained a bit more here), there is an OPTIONS verb - which routes can support.
The impetus for using OPTIONS is to request documentation for a web service API; results are meant to provide information regarding how the API may be used.
ActionDispatch::Routing::HTTP_METHODS
=> [:get, :head, :post, :put, :delete, :options]

To get back to your question, in a typical browser GET request, the first route will be used.  When an OPTIONS request is made, the second route will be used.

A: You can use the :via option to constrain the request to one or more HTTP methods
See the rails guide on routing
:post, :get, :put, :delete, :options, :head, and :any are allowed as a value to this option.
As explained in a blog post, OPTIONS is just another HTTP verb to support CORS requests (a way to make cross domain AJAX requests).
Update found a blog post explaining :options

A: For Rails 5 and above:
in routes.rb
  match "/404", :to => "errors#not_found", via:  :all
  match "/500", :to => "errors#internal_server_error", via: :all

For controller:
class ErrorsController < ApplicationController
  layout 'xyz'
  def not_found
  end

  def internal_server_error
  end
end

This will work in production, if you want the same for the development also, then in development.rb
change:
  config.consider_all_requests_local = false


text:
Q: Take photo by camera in android studio, resize image and send .png image to mssql server by jdbc I want to take a photo by android camera and save in in memory and after resizing send to MSSQL server by JDBC method. anybody can help me with any answer code?
       //capture picture from camera
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            // capture picture
            Intent camIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            try {
                startActivityForResult(camIntent, CameraRequest);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(InstallForm.this, "camera not found", Toast.LENGTH_SHORT).show();
            }
        }
    });

    // Checking camera availability
    if (!isDeviceSupportCamera()) {
        Toast.makeText(getApplicationContext(),
                "Sorry! Your device doesn't support camera",
                Toast.LENGTH_LONG).show();
        // will close the app if the device does't have camera
        finish();
    }

 //capture image
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        if (requestCode == CameraRequest) {
            clear.setVisibility(View.VISIBLE);
            imgView.setVisibility(View.VISIBLE);
            uploadimage.setVisibility(View.VISIBLE);
            resultPhoto = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
            imgView.setImageBitmap(resultPhoto);
            filename.setText(" service Image " + number);

        }

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgView.setImageResource(0);
                clear.setVisibility(View.GONE);
                imgView.setVisibility(View.GONE);
                uploadimage.setVisibility(View.GONE);
                filename.setText("no image");
            }
        });

        generateNewAttachmentList(newAttachmentList);

    }catch(Exception e){

        e.printStackTrace();
        Log.d( "Exception : " , e.getMessage() );
    }

    }

private void generateNewAttachmentList(ArrayList<AttachmentListData> newAttachmentList) {
    newAttachmentListView.setHasFixedSize(true);
    LinearLayoutManager MyLayoutManager = new LinearLayoutManager(InstallForm.this);
    MyLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    newAttachmentListView.setLayoutManager(MyLayoutManager);
    attachmentListAdapter = new AttachmentListAdapter(newAttachmentList, InstallForm.this);
    newAttachmentListView.setAdapter(attachmentListAdapter);
}

//
I can take pacture by camera and show in image wiew and in continue  I want to save my image in phone memory, then resize it and send to MSSQL server by jdbc.
any answer


text:
Q: php script using json encode loading only first record <?php
require_once 'connect.php' ;

$sql = "SELECT Title,Date,Time,Location,image_url FROM events ";

$result = $conn->query($sql);

if ($result->num_rows > 0) {

    $data = array();
    while($row = $result->fetch_assoc()) {
       $data['events'] = $row ;

    }

}

echo json_encode($data);
header('Content-Type: application/json');

?>

A: Insert entries in the list, with few minor suggestions
require_once 'connect.php' ;

$sql = "SELECT Title,Date,Time,Location,image_url FROM events ";

$result = $conn->query($sql);

// Move $data declaration up for zero result.
$data = array('events' => []);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
       // Insert $rows in events array
       $data['events'][] = $row ;

    }
}

// Send headers first before sending any data
header('Content-Type: application/json');
echo json_encode($data);


text:
Q: REACT_APP_* vs NODE_PATH Environment Variables What is the difference between a regular CRA environment variable (that MUST begin with REACT_APP_) and the NODE_PATH variable (that is used to avoid having to use relative paths for imports, ../../../foo etc.)
From my testing, no variables can be used unless they begin with REACT_APP, so how is the NODE_PATH variable not ignored like other variables that do not begin with REACT_APP?

A: NODE_PATH is accessible because it's added in the Webpack configuration in react-scripts.
You can see the code that adds it here:
https://github.com/facebook/create-react-app/blob/25184c4e91ebabd16fe1cde3d8630830e4a36a01/packages/react-scripts/config/env.js#L61
You'll see in that file that you can also set NODE_ENV which sets which environment you are running in (e.g. development, staging, etc.) as well as PUBLIC_URL
To answer your question on the differences:
NODE_PATH allows you to use absolute paths for imports. For example, you can set your NODE_PATH to the following:NODE_PATH=src:src/components:src/containers and then in your React code you could write something like this: import Button from 'button' instead of import Button from '../../../button' as long as you have that module in one of the folders src, src/components, or src/containers because create-react app will look for the button module those folders. You wouldn't actually use the NODE_PATH variable in your React code that same way that you use REACT_APP_* variables. Basically, it tells your app where to look for modules.
REACT_APP_* variables are injected into your application at build time using the Webpack configuration from the file I linked to.
This: const GRAPHQL_URI = REACT_APP_GRAPHQL_URI
becomes this: const GRAPHQL_URI = https://example.com
if you have this in your .env file: REACT_APP_GRAPHQL_URI = https://example.com


text:
Q: Online journal pages field that is compatible with natbib+bibtex and biblatex+biber? I want to know how I should properly use the provided page field of an article published in an online journal (such as PLoS Computational Biology).
Even though articles published in online journals do not have actual page numbers, both the journals themselves and Google Scholar provide a pages field holding values such as e1000112 (PLoS) and 20122863 (Proceedings of the Royal Society).
Semantics aside, using the pages field for this would be a non-issue, but the fact that the second value does not start with a letter means that the printed citation shows p. 20122863 which is wrong because that number is not an actual page number.
Also, it seems to me that the pages field should not be used for this purpose, so I tried to find an alternative and found eid [source]:

eid
The Electronic identifier is for electronic journals that also appear in print. This number replaces the page number, and is used to find the article within the printed volume. Sometimes also called citation number.

But I am not sure whether this is suitable because it mentions printed volumes and I am positive that not every online journal ends up publishing printed volumes.
Question:

What field should I use for the pages field provided by online journals that is compatible with both natbib+bibtex and biblatex+biber?

A: tl;dr: A universal solution is very nearly impossible, biblatex offers the bookpagination (and pagination field) and a well-coded style will make use of those, so bookpagination = {none} seems a good way to go for biblatex.
The Long Answer
A solution that works for both natbib and biblatex is almost impossible (one might say all but impossible) for the simple reason that it is not natbib or biblatex that decides what is printed and how the bibliography looks like, but the bibliography style (\bibliographystyle in "BibTeX packages"for lack of a better name [the .bst styles]; style, bibstyle with biblatex [the .bbx styles]); so a universal solution would have to work with all the styles (.bst as well as .bbx) available today - that is quite a lot of styles.
While most of the styles adhere to a general semantics and best practice, we cannot be sure that all styles will display, say, the pages field in a certain way (well, we can be quite sure with the pages field as it is so essential and standard, but the eid field is a different matter altogether).
Most of the "exotic" fields such as eid, eprint etc. are bound to be unsupported by a number of styles - even the more basic (and arguably quite un-exotic - by modern standards at least) URL field is lacking in some styles, simply because they were completed before the advent of the URI, which was standardised in 1994 (RFC1738), case in point: ieeetr.bst seems to have been the same since 1988 (save for a clarification of the licence).
Having said all that, the pages field is probably your best bet for a widely applicable solution, plus it does not seem to be too far off semantically.
But even the treatment of the pages field is not standardised or normalised across bibliography styles: Some .bst styles check whether the pages field contains multiple pages in order to decided whether to print "p." or "pp." (plain.bst and ieeetr.bst), but there is no need to do that in a German style since in both cases the abbreviation will be "S.", consequently natdin.bst does not care to check for "multiple pages", it behaves differently if a URL is present, though.
biblatex offers a lot of these functionalities out of the box, so almost all styles make use of them (that is also thanks to the fact that a lot of the biblatex styles out there are coded quite well), I have yet to come across a style that tries to implement these checks itself.
biblatex will check if the pages field actually contains a "page range", page ranges consist of characters recognised as numbers (see \DeclareNumChars) and those recognised as range separators/indicators (see \DeclareRangeChars) as well as certain other commands (see \DeclareRangeCommands and \DeclarePageCommands). If the pages field contains only characters and commands declared there, it passes the \ifpages test. If a pages field passes the \ifpages test and it is printed with \mkpageprefix, the page prefix "p."/"pp." will be added if it does not, the pages field is printed as is without a prefix. In fact, we can control the prefix added to the pages field as described in §2.3.10 Pagination, p. 35, of the biblatex documentation, we can even define our own prefix (as shown in Citing specific slides of a presentation).
The "pagination scheme" is even settable on a per-entry basis with pagination (controls how in-text citations have the postnote formatted if it passes \ifpages) and bookpagination (controls the pages and pagetotal fields).
So what you could do for these special pages fields is to add bookpagination = {none} to the corresponding entry (or hope for a character that throws \ifpages to false, the e in the PLoS entries does exactly that).
An example with bookpagination = {none}:
@article{Clune22032013,
  author   = {Clune, Jeff and Mouret, Jean-Baptiste and Lipson, Hod},
  title    = {The Evolutionary Origins of Modularity},
  volume   = {280},
  number   = {1755},
  pages    = {20122863},
  bookpagination = {none},
  date     = {2013},
  doi      = {10.1098/rspb.2012.2863},
  eprint   = {http://rspb.royalsocietypublishing.org/content/280/1755/20122863.full.pdf+html},
  journal  = {Proceedings of the Royal Society B: Biological Sciences}
}

The MWE
\documentclass{article}
\usepackage[style=authoryear, backend=biber]{biblatex}
\usepackage{filecontents}
\usepackage{hyperref}

\begin{filecontents*}{\jobname.bib}
@article{Clune22032013,
  author   = {Clune, Jeff and Mouret, Jean-Baptiste and Lipson, Hod},
  title    = {The Evolutionary Origins of Modularity},
  volume   = {280},
  number   = {1755},
  pages    = {20122863},
  bookpagination = {none},
  date     = {2013},
  doi      = {10.1098/rspb.2012.2863},
  eprint   = {http://rspb.royalsocietypublishing.org/content/280/1755/20122863.full.pdf+html},
  journal  = {Proceedings of the Royal Society B: Biological Sciences}
}
\end{filecontents*}
\addbibresource{\jobname.bib}

\begin{document}
  \cite[3]{Clune22032013}

  \printbibliography
\end{document}

yields, note that for in-text references the pages prefix is enabled (and the default page one), while the prefix for the journal pages is disabled.


text:
Q: Why am I getting segmentation Fault on fscanf() function? I don't understand why I'm getting a segmentation fault when I call fscanf() function. I know I'm getting the file correctly opened using fopen().
ST_CHAR* GetLeafFromBitmap(const ST_CHAR* filename, ST_UINT8 u8dido, ST_UINT16 u16idx)
{
    FILE* fp;
    ST_CHAR* ps8buff;
    ST_CHAR ps8numstring[20];
    ST_CHAR* ps8curleaf;
    ST_CHAR  ps8didostr[10];
    ST_CHAR  ps8idxstr[10];

    sprintf(ps8idxstr, "%d", u16idx);
    sprintf(ps8didostr, "%d", u8dido);
    strcpy(ps8numstring, ",");
    strcat(ps8numstring,ps8idxstr);
    strcat(ps8didostr, ps8numstring);
    printf("didostr : %s\n", ps8didostr);
    if((fp = fopen(filename, "r")) == NULL)
    {
        fprintf(stderr, "\nError %d: Loading from \"%s\" file failed: %s\n", errno, filename, strerror(errno));
        return -1;
    }
    while(fscanf(fp, "%s", ps8buff) != EOF)
    {
        if(strstr(ps8buff, ps8didostr) != NULL)
        {
            ps8curleaf = GetLeaf(ps8buff);
            return ps8curleaf;
        }
    }
    return NULL;
}

I'd really appreciate if any code guru can point out what I'm possibly doing wrong to get the error.

A: ST_CHAR* ps8buff;
...
while(fscanf(fp, "%s", ps8buff) != EOF)

Two things:
1) You are writting to an uninitialized pointer, you need to reserve space for it (via malloc) or use an array like ST_CHAR ps8buff[some_size];
2) You don't have to check for EOF in fscanf, on success it returns the number of input items successfully matched and assigned, instead:
while(fscanf(fp, "%s", ps8buff) == 1)


text:
Q: Does converting 128kbps m4a to 128kbps mp3 mean anything? So I have quite a bunch of these m4a files and I want to know if converting 128kbps m4a to mp3 will degrade it's quality in any way.
For those who ask why I do it I have huge podcast library and it's in MP3 so I would like to have these full folders look nice as well.

A: Typically both m4a and mp3 contain lossy compressed audio data. The conversion of one format of data to another means that it will be decoded and passed through another encoder which will "lose" some amount of data in order to achieve high compression ratio.
Even encoding from the same type to the same type will lose some data with each encode and this problem is known as generation loss. It happens due to the fact that that each encode relies on some (usually audibly trivial) approximations that allow for higher compression, on each pass those successive approximations change subtly and introduce unwanted noise.
Out of preference you should prefer not to transcode audio or video data in this way. For one or two transcode cycles you might be alright, but eventually it will get to a point where it is noticable as noise or compression artifacts in the sound.


text:
Q: LVM - Reducing COW size down to maximum usable size I am doing snapshots on an LVM Volume. It works, but since a few minutes I do get a warning message.
The command is:

sudo lvcreate -s /dev/$VG/$LV -n $SNAP_NAME $VS 2>>$LOG

The VG has enough space for a new LV. However the system issues a warning:

Reducing COW size 30.00 GiB down to maximum usable size 24.10 GiB

What does it mean, and why is this suddendly apearing?

A: Just found the reason. COW means (copy on write) and indicates that the lv volume size is 24G but the snapshot command used creates 30G.


text:
Q: How to get last modified date from Microsoft sharepoint site's RSS Feed? From Microsoft Sharepoint site's RSS Feed, I am geting pubDate and lastBuildDate. I want last modified date of a file. Is this possible? If yes, can you please tell me how?
Thanks in advance.

A: It is right there in the View Settings

If this is not an answer to your question it is because your question is almost impossible to understand.


text:
Q: 404 not found when accessing www I tried:
www Host(A) 38.67.136.195
And everytime you accessed my site using www.synergyweight.com then it gave a 404 error.
So I changed it up using a Cname
www Alias(CNAME) synergyweight.com
Neiter one will work.
I can ping www.synergyweight.com, but nothing is being displayed except Not Found error and it's not an asp.net error.

A: It seems your IIS instance is not set up with the bindings necessary to accept requests for www.synergyweight.com.
Check the bindings for this site and make sure that you have an entry that specifies the FQDN 'www.synergyweight.com'
Your DNS is set up fine.


text:
Q: Running programs only if they are installed, and ignoring them otherwise When writing shell scripts, is the an idiom or swift way to run a program only if it is installed, and if it is not, just let it be (or handle the error in some other way apart from installing it)?
More specifically, I have a lot of servers which I access over ssh, and whenever I get a new server, I simply copy all my rc-files to it. The .zshrc starts tmux unless it is already running. Some of the servers (not all) do not have tmux installed. I do not want to install it because of disk space limitations, I do not want to have different rc-files for different servers, and I do not want my rc-files to be interrupted when executing them.
I have seen solutions involving apt-cache policy <package-name>, so I guess I could use that and pipe it to something like grep -e 'Installed: (none)', but that would assume that the server is running Debian or Ubuntu, which I can not do, and it would only work for packages that were installed with apt, not things I have installed in other ways.

A: command -v <command> is the common (and POSIX) way to check if a command could be executed (is executable and on the $PATH).
E.g:
command -v tmux >/dev/null &&
  tmux a -t name

(>/dev/null since, if the command exists, its path will be printed to STDOUT.)
It could be nice to put it in a reusable function:
maybe() {
  ! command -v "${1}" >/dev/null ||
    "$@"
}

Then one could use:
maybe tmux a -t name

And if tmux is available then tmux a -t name will be run, otherwise it'll be silently ignored.
Or, if you want some feedback when a command is not available:
maybe() {
  if command -v "${1}" >/dev/null
  then
    "$@"
  else
    printf 'Command "%s" not available, skipping\n' "${1}" >&2
  fi
}

A: This might help-
1) Assuming tmux is available in PATH (as it must be executable)
isAvailable=$(type -P tmux)
if [[ -x $isAvailable ]]; then

...

2) Verify file is present on a specific path (Copying all rc-files)
export FILEPATH="..."
if[[ -f $FILEPATH ]]; then


text:
Q: Succession of the Iron Throne after GoT Season 5 (spoilers) - who's in line? So at the end of Season 5 of Game of Thrones,

 Stannis Baratheon dies (probably).

Suppose that Tommen is discovered to be the son of Cersei and Jaime, due to

 The Spanish Inquisition! Umm, I mean, the meddlesome High Sparrow and the faith militant looking for muck to stick to the current royals.

Also, suppose Gendry is unknown to the general public.
Now, by the laws and customs of the 7 kingdoms, and assuming you're not a Targaryen loyalist - who's next in line for succession?
Also, more specifically,

 Are there some distant Baratheons (third-degree cousins or something) who might fit the bill? All of Robert's brothers are dead, and he has no cousines, and IIRC also no second-degree cousins.

A: In the canon of the show, if you assume that it is somehow proved that Robert Baratheon has no legitimate heirs, then the Baratheon line is effectively over.
According to GRRM, if there are no legitimate heirs to a House left alive, then it's possible for an illegitimate child to inherit. So if any of Robert's kids were still alive, and acknowledged, they'd become Lord of House Baratheon.
However, I strongly doubt that rule applies to the Iron Throne itself -- and since you need a King to legitimize a bastard, by the time Gendry came up in the rotation he'd have no one left to do it.
At that point, we start walking back up the family tree. On TV, we know next to nothing about Robert's extended family, and things aren't much better in the novels. There's no indication that Steffon Baratheon had any brothers, though there's no confirmation that he didn't. Similarly, grandpa Ormond is, as far as we know, an only son.
While the line of succession can pass down through the female side of the family, it's only female children of a male heir. For example, there's no hopping over to Cassia Estermont's branch of the tree just because she married Steffon.
In theory, someone in Westeros would have to dig up the complete geneology of the Baratheons and trace it back until they found a male in Robert's ancestral line who had a brother or sister, then back down until they found someone alive.
In practice, the noble families of Westeros would just pick someone to support as the next King, who may or may not have some tangential claim to the throne. They would likely start a civil war over it, and whoever was left standing would win. Which, of course, is exactly what happened anyway.

A: Since no one has provided this answer yet: it's possible the throne would pass to Daenerys.
The question is how strongly Robert's lineage contributed to his inheriting the throne. Of the rebelling Houses (Lannister, Baratheon, Stark, and Arryn), Robert was selected to be king in part because he was part Targaryen. If Dany and Viserys were removed from the line of succession, the throne would have passed to Robert anyways.
In reality of course, Robert became king because he conquered the kingdoms. But legally, it's implied the maesters were pacified with some explanation of "we can't have the throne pass to the Mad King's small children, so the throne passes to Robert." (There's actually some precedent to this. Prince Maegor was passed over in the line of succession because he was an infant, and because it was feared he inherited his father Prince Aerion Brightflame's madness)
So legally speaking, it may be that since every other Baratheon and Targaryen descendant was dead or an unacknowledged bastard and Daenerys appears to be free of madness, it would pass to her. But as Stannis learned, who is legally entitled to the Iron Throne often means very little.
In the books, it's a bit trickier. Edric Storm was an acknowledged bastard of Robert's, gently-bred, and very charismatic; I could see Baratheon loyalists backing him. But more importantly, if you believe certain theories and certain characters, there are other Targaryen descendants who would inherit before Dany.

A: It depends, but thanks to the Noble Houses constantly intermingling amongst one another, we'll likely be able to trace the ancestry back far enough to produce an heir, hopefully.

In Westeros, they follow the Primogeniture rules of succession[1]; which means that the Heir must be a legitimate male, until such time as all of the prime legitimate males are deceased, at which point, it goes to the eldest female. But if none are found, then it goes to the subject's next male heir (brother, cousin etc), and the process is repeated until a suitable candidate is found[2].
There is an issue of difference between the books and the TV-show. In the show Game of Thrones, bastards are not permitted to inherit anything under any circumstances![3] (unless they are legitimised by Royal Decree).
Whereas in the books, A Song of Ice and Fire, bastards are allowed to inherit, "if the father has no other trueborn children nor any other likely kin to follow him."[4]@.
This may cause some slight complications in our calculations, so I will separate the results below.

Books

*

*Let's assume Stannis is deceased, and his issue also all deceased

*Robert is deceased, his issue are either baseborn[5] (illegitimate) or not even his (Joffrey, Myrcella, Tommen)

*Renly is deceased, without issue

Let's follow the white rabbit:

*

*There is no possibility of jumping the lineage to a married branch of a house, if that were the case, then Stannis' successorship would go to Selyse Baratheon nee Florent's family; who's lineage is another clusterf#@$ ending in Melessa Tarly nee Florent[6] (Sam Tarly's mother, so Sam's brother Dickon would be Stannis' heir, lol). So no help there. We have to go further up the tree.

*Stannis had a father, Steffon Baratheon. Steffon didn't seem to have any siblings, and all of his children are deceased without heirs (we're also skipping his wife, as above), so let's go further.

*Steffon's father, Ormund Baratheon seemed to have a sister; she was unnamed but was originally betrothed to Prince Duncan Targaryen (Duncan The Small). Duncan broke off the betrothal when he fell in love with Jenny of Oldstones. This is what caused King Aegon V Targaryen to marry off his daughter Rhaelle to Ormund Baratheon. There is no other detail on this unnamed sister, but her children would have been next in-line if they were included!

*

*We could go even further back though, Lyonel The Laughing Storm Baratheon, who was Ormund's father, but again Lyonel seemed to be an only child.

*It's getting quite sparse, and at this point it is worthless to dig any further back as the only other person we have information on is Orys Baratheon (the first Stormlord and first Hand of the King), but the line seems to whittle down to single children#, and there would probably not be any living descendants or "likely kin to follow",  leading us back to Lyonel Baratheon, etc.

*Let's come back down to earth and dig a little bit closer to home. Robert had many baseborn children[5], a few of which were acknowledged by him, including Edric Storm and Mya Stone. Mya is the eldest of his bastards, Gendry is the eldest male but Edric is the eldest acknowledged male (and is also the most lordly, having been grown up at Storm's End under the care of Ser Cortnay Penrose.

*

*If these bastards are allowed to be in line, then they can probably continue the Baratheon lineage nicely, given that they are all such strong embodiments of Robert's characteristics and the "Baratheon look".

If it were up to me, I'd go with Edric Storm (being that he is the most lordly), but it could easily go to our favourite bastard, Gendry The Bull!

Show

*

*Stannis - deceased and so are his issue

*Robert - deceased without legitimate issue

*Renly - deceased without issue

So the problem here is that there's no history past Stannis' parents (Steffon Baratheon and Cassana Baratheon nee Estermont), so there's no guarantee who their ancestors were. But the only thing we do know for sure is that they had a Targaryen great-grandmother, Rhaelle Baratheon nee Targaryen[6] (this is the same as the books). Unfortunately though, this doesn't help us, as the succession doesn't jump to someone who married into the family.
The only hope at this point, is:

*

*Option 1: to do a depth-first search into the family tree, and find a child or sibling from either Steffon Baratheon (Stannis' father), Ormund Baratheon (Stannis' grandfather), Lyonel Baratheon (Stannis' great-grandfather) or all the way back to Orys Baratheon (the first Stormlord).

*Option 2: Legitimise one of the bastard sons of Robert - most likely, Gendry (given that in the show, Edric "Ned" Storm doesn't exist).

Final outcome
So there you have it, when it truly comes down to it, the only hope we have for the Baratheon lineage is for one of Robert's bastards to pick up the mantle!

@ Pay attention to this, it will be important for us here.
# There are several families which we can follow, but none seem relevant at this point, these include:

*

*Davos Baratheon

*Borros Baratheon

*Boremund Baratheon

*Robar Baratheon

*Jocelyn Baratheon

A: The closest thing to a distant cousin that the Baratheons have (if Tommen and Myrcella, thus the Lannisters, are disinherited) are either the Estermonts through Cassia Estermont (the mother of Robert, Stannis and Renly), or ... the Targaryens! Robert's paternal grandmother is Princess Rhaelle Targaryen.


text:
Q: Why I still cannot use fragment when using Eclipse(Android)? First, I've upgraded to API-21 including eclipse android toolkit and SDK.
I want to use the fragment feature and still want to support those 2.x phones
I know that I must use support library - v4.
But the problem is when I create an Android project, it always shows "Navigation Type "Scrollable Tabs + Swipe" requires a minimum SDK version of at least 11, and the current min version is 8".
How could I solve this tricky problem?
======================================
My settings:
Minimum required SDK: API 8
Target SDK: API 17
Compile With: API 17
======================================
Thanks!!

A: Eclipse's project templates make use of features that require a number of APIs (mostly ActionBar), which are not provided by the support library. While you can use Fragments, with the support library, you don't have the other features associated with the APIs.
You could still implement swipe/scroll tabs by yourself though. However, you will have to create them manually (and not using Eclipse's built-in project templates).
You will need to use android.support.v4.view.PagerTabStrip, android.support.v4.view.ViewPager and android.support.v4.app.Fragment. The documentation is pretty clear and should point you in the right direction.


text:
Q: Why in binary star system the 2 bodies revolve around their center of mass? Can you prove it mathematically?
Is it just an observation?
I know the force between them is $\frac{Gm_1m_2}{r^2}$.
Centripetal force on any one of them is $\frac{mv^2}{r_1}$, where $r_1$ is radius of curvature.
Why is that radius of curvature about center of mass only? Why it can't be any other point?

A: If we start from the fact that the orbits of the two bodies have equal time periods, this means they have equal angular velocity $\omega$
From $a=\omega^2r$, where $a$ is the acceleration, this means that $\frac{a}{r}$ is the same for each body.
so if $r_1$ is the distance from the orbital centre for body $m_1$ and similar for the $2$ subscripts
$$\frac{Gm_2}{r_1(r_1+r_2)^2} = \frac{Gm_1}{r_2(r_1+r_2)^2}$$
The left term is the $\frac{a}{r}$ for body $m_1$, and the right term is for body $m_2$,
then $$m_2r_2 = m_1r_1$$
and this equation is true only if the orbital centre is also the centre of mass.

A: Given two bodies, you have their positions $\mathbf{r}_1=(x1,\,y1,\,z1),\,\mathbf{r}_2=(x_2,\,y_2,\,z_2)$ and velocities $\dot{\mathbf{r}}_1,\,\dot{\mathbf{r}}_2$. The force of gravity only depends on $\mathbf{r}_1-\mathbf{r}_2$, and there's a force that body $1$ experiences $\mathbf{F}_1$ and a force that body $2$ experiences $\mathbf{F}_2$. These forces should be equal and opposite due to Newton's third law and also due to the nature of gravitational force.
Since the force depends on the difference, we notice that everything will behave the same even if we add some offset $\mathbf{r}_c$ to the vectors $\mathbf{r}_{1},\mathbf{r}_{2}$.
If we let $(m_1 + m_2)\mathbf{r}_c = m_1 \mathbf{r}_1 + m_2 \mathbf{r}_2$, this is a nice choice because $(m_1 + m_2)\ddot{\mathbf{r}}_c = m_1 \ddot{\mathbf{r}}_1 + m_2 \ddot{\mathbf{r}}_2 = \mathbf{F}_1 + \mathbf{F}_2 = 0$. $\mathbf{r_{c}}$ will be constant because the forces $F_{1}$ and $F_{2}$ were equal and opposite.
For convenience, now I'll use the position vectors
$\mathbf{s_{1}} = \mathbf{r_{1} - r_{c}}$.
$\mathbf{s_{2}} = \mathbf{r_{2} - r_{c}}$.
$\mathbf{s_{c}} = \mathbf{r_{c} - r_{c}} = 0 $.
I'm now doing everything in the center-of-mass frame, where the center of mass takes coordinate 0.
$m_1 \mathbf{s_{1}} + m_2 \mathbf{s_{2}} = m_1 r_1 - m_1 r_c + m_2 r_2 - m_2 r_c = 0$.
This is the best part, because now s1 and s2 (our positions for particles 1 and 2) are related, and I can solve for one to get rid of the other.
Let's define a reduced mass $\mu = \frac{m_{1}m_{2}}{m_{1}+m_{2}}$
$F = \frac{Gm_{1}m_{2}}{\left(\mathbf{r_{1}}-\mathbf{r_{2}}\right)^{2}}
= \frac{Gm_{1}m_{2}}{\left(\mathbf{s_{1}}-\mathbf{s_{2}}\right)^{2}}
= \frac{Gm_{1}m_{2}}{\left(\mathbf{s_{1}}+\frac{m_{1}}{m_{2}}\mathbf{s_{1}}\right)^{2}}
=G \frac{m_{1}}{m_{1}+m_{2}}\frac{m_{2}}{m_{1}+m_{2}}\frac{m_{2}^{2}}{s_{1}^{2}}
= G \mu^{2}\frac{m_{2}}{m_{1}}\frac{1}{s_{1}^{2}}
$
Note that $\Delta{}s = s_{1}-s_{2} = s_{1} + \frac{m_{1}}{m_{2}}s_{1} = \frac{m_{1}+m_{2}}{m_{2}}s_{1} = \frac{m_{1}s_{1}}{\mu}$ so that
$F = \frac{G m_{1}m_{2}}{\Delta{}s^{2}}$
Whether you write the Force as depending on $s_{1}, s_{2}, or \Delta{}s$, you now have an equation relating the acceleration of a position to the position itself, rather than the difference of two positions $r_{1}-r_{2}$.
The solution to this vector differential equation is an ellipse, hence binary star systems will always be an ellipse around the center of mass, because such transformations and choices of coordinates are always possible and binary star systems as assumed will always obey these basic equations.


text:
Q: switch on / off flash light programmatically on android smartphones (without using the camera) I saw your question about How to turn on camera flash light programmatically in Android?"How Turn on only Camera flash light programmatically in android?".
I'm trying to do the same.
The links you used to solve your problem seem to be out of order: http://code.google.com/p/quick-settings/
Could you share your solution ?
I have another question: is there a way to see in the emulator whether the flash light is on or off ?
Thank you for your help.


text:
Q: How to calculate $O(\sum_{k=1}^{K}(N-k)(k+1)^2)$? Using the formula for the sum of the squares and the sum of first $K$ numbers I can get that:
$$\sum_{k=1}^{K}(N-k)(k+1)^2=\dfrac{1}{12}K(-3K^2+2K^2(2N-7)+3K(6N-7)+26N-10)$$
Now I guess I can simplify the formula if I would like to get the big-O. I think for $N=K$, it is fine for me. $$O(K^4).$$
What about $N>K$ and $N<K$ ?

A: If you are only interested in asymptotics then the sum is $O(\Sigma_{k=1}^K(Nk^2-k^3))$ which is equal to $O(NK^3-K^4)$.
If you have $K>N$ then the sum is negative. We can use Big-$O$ notation even for negative functions. Please refer https://en.wikipedia.org/wiki/Big_O_notation. So, in the case $K>N$ too, we can say that the sum is $O(NK^3-K^4)$ or $O(K^4-NK^3)$, as we take the absolute values of the function instead.


text:
Q: How to access to a ListItem in the ListView I am trying to access one of the ListItem in the ListView and it is as shown below.
A lot of people discussed for similar problem. But I tried and non of them worked.
My code is listed below.
 pos = 0;//position of ListItem
 for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
 {
     if(tel.equals(cursor.getString(2)))
         break;
     pos++;
 }
 LayoutInflater mInflater = LayoutInflater.from(context);
 View myView = mInflater.inflate(R.layout.my_list_fragment, null);
 lvObjects = (ListView)myView.findViewById(android.R.id.list);
 View v = lvObjects.getChildAt(pos);

My problems are
(1)View v is always Null.
(2)getChildAt() returns only visible View. If I want to access for the hidden View, how to achieve?

A: You simply should not do this! ListView does not render views it does not need to render, and it does reuse already created view objects. This is are optimizations.
Instead, supply implementation of Adapter or extend one, override getView method and manipulate view created by super.getView or created by your code.
If the ListView already showed the items you can make it redraw the items by calling ListView.invalidateViews. It will call the adapter to draw views.
If you are using BaseAdapter and the underlying have changed, then call notifyDataSetChanged on the adapter.


text:
Q: PHP displays as plaintext on web server? I wrote an HTML page using XAMPP on my Windows computer, and everything works great locally. However, I want to host the content on a website, and I have no idea how to do it. Here it is as is, with a PHP code displayed, instead of actually running.
Does github.io support running PHP at all? I read that it doesn't. If so, where would I be able to host my code so that my PHP and JavaScript could run given that I point my browser to the webpage's URL? Also, XAMPP had linked it to an MySql database, but I am unsure of how to set that up as well on a server.
These seem like simple questions for the beginning web developer, but I scoured Google and couldn't find an answer. Thank you.

A: To deploy php on the server you have to check:

*

*Is there PHP?

*Take care of pretags

*Check version of php (it will run with error if php parser is on)

*Configure your wwwroot or httpdocs or hotdocs (webpage public folder)

*Take care of .htaccess if something is crashing

And not every server is apache and not every server is node and not every... Just ask support of this hosting because in some cases you have to "turn on" PHP by some fancy button.
Have a nice day!

A: No, Github Pages doesn't have PHP, it's only meant to host static pages. It does support Jekyll, a static site generator (in that it generates static pages once per push which are then hosted as-is), but that's about all.
PHP/MySQL is only one of the many sets of possible web application technologies, so you can't expect it to be everywhere where web hosting is. It has to be either explicitly listed on hosting service's website, or be available for installation in case you get yourself a full-fledged server machine (maybe virtual) to run your website.
Browser-based JavaScript will still be run by the client, since it's not the server's responsibility to run it, just the delivery. So it can be hosted on GitHub Pages. Also, 3rd party services that don't depend on your own server's code execution are usable too: stuff like commenting systems, searches (you can even make a client-side one!) and analytics.


text:
Q: How can I store preferences for a Google Chrome extension? As a simple example, let's say I want to insert a word at the bottom of every webpage, and I want the user to be able to change that word. So I have an options page (within the extension), within which I take user input and use it to call "localStorage.preferences = x;".
Next, the user navigates to http://www.google.com/, and I inject a script which writes the word found in localStorage.preferences. The problem is, since I'm now at a different domain, I'm seeing the localStorage for google.com, not my extension.
How can I share data between my extension's options page and a script injected into some 3rd-party webpage?

A: It's not, perhaps, the most direct response to your question, but one way to potentially get around this would be to use message passing to fake direct access to local storage from another domain. Assuming you're running your Javascript in the context of a content script, you could pass a message to the background page asking for a key, which would return the contents of localStorage.


text:
Q: How to solve, in an elegant way and using JavaScript, the UTC problem, which subtracts a day when instantiating a Date in the format '2018-10-25'? I'm working on legacy system and in DB the birthday is coming this way '1992-05-18' in json. I am using AngularJS and when applying the data binding of this variable in an input type = "date", of an update form, it is necessary to instantiate a Date object. Like this:
//person.byrthday = '1992-04-26'
var person.birthday = new Date (person.birthday);
// after person.byrthday = '1992-04-25T00:00:00.000Z'

How can I solve this problem through Front End in an elegant way, without "breaking" two way data binding?
I find myself in Brasil UTC -03:00

A: There are a few ways to solve this problem. A quick and dirty solution could be to leverage moment.js. You can convert the response from the API to a true date format this way.
If you don't want to use an additionally library, you can make a function to parse the date string. You can do the following to parse is to become a correct date:
var dateSplit = person.birthday.split('-');
var mydate = new Date(dateSplit[0], dateSplit[1] - 1, dateSplit[2]);
person.birthday= mydate;

Take note that the month index starts at 0 (aka January=0). Hopefully this helps.


text:
Q: How to create a root user / admin database with access to child databases New user here, excuse me if that isn't grammatically correct, but this is what I want to do -
I have a server set-up with multiple sites on one VM instance - I want to create an admin mysql database which only the account holder has access to and multiple "child" databases for each individual site on the instance which do not have root user but can be accessed via the parent/admin user.
Is there a way to do this?

A: *

*"Site" usually refers to different physical locations.

*Perhaps, your "site" is "customer" ("account holder"); that is someone who owns his own "database".  And then you, as the owner of the MySQL instance, need some table(s) in the "admin" database to keep track of your customers?

*One instance of MySQL can contain several "databases".

*Each database can contain several "tables".

*About the only purpose for "database" is, as you suggest, for "admin", etc.  That is, a way of organizing "tables".

*"Child database" is not a valid term.
The above bullet items help you with terminology and nudge you toward some of the answers you seek.
As for "security", you should give each account holder his own login(s), but grant access to only his one database.
You, as the admin, should have the password for the user root so that you can do things like CREATE DATABASE and CREATE USER and GRANT when adding a new account holder.  The account holder will not (or probably should not) be granted privileges to do those things.  They can, however, be allowed to do virtually anything to the the tables in their database.
It sounds like you are building a DBaaS.  You need to learn a lot more about DBA activities.  When things crash (or whatever), you have to be ready to jump in and fix them.


text: Q: How do I construct a piecewise with the given information? The average retail price of a gallon of gas in the Philippines is assumed to be 54.50 Php. In the a gasoline manufacturing company, individual gasoline retailers are only allowed a minimum of 100 gallons if they want to purchase from the company. If clients purchase over 100 gallons to 300 gallons, they will receive a 5% discount and a 10% discount if they purchase over 300 gallons to 400 gallons.Construct a piecewise function P such that P(x) gives you the wholesale price of gasoline


text:
Q: OpenGL Texture binding to object I started learning OpenGL some days ago and I have some difficulties in understanding a thing. I followed this tutorial: https://www.youtube.com/playlist?list=PLEETnX-uPtBXT9T-hD0Bj31DSnwio-ywh until the fifth part and it works perfectly but when I tried to make another separate triangle and another texture for it, the two triangles had the same texture. I don't understand how to bind a texture to an object, this program binds a texture for every object in the scene or maybe I didn't understand how to do it properly.
Here is my source: https://github.com/deiandrei/blackunity_opengl_alpha
Have a good day!

A: What are these "objects" you're talking about? OpenGL doesn't know what a "object" is. OpenGL just knows points, lines and triangles and all it bothers is drawing one after another with the state currently enabled. Once something has been drawn, OpenGL already forgot about it.
So the typical OpenGL program drawing structure roughly looks like this:
glBindTexture(GL_TEXTURE_2D, texture_A);
draw_triangles(); /* the triangles are drawn using texture_A */
draw_lines(); /* the lines are drawn using texture_A */

glBindTexture(GL_TEXTURE_2D, texture_B);
draw_some_other_triangles(); /* the other triangles are drawn using texture_B */


text:
Q: Clean windows and ubuntu to free up disk space Is there any other way to free up disk space on windows xp and on ubuntu 9.10 removing unnecessary files and folders/directories?
For windows, as far as I know I use Disk cleanup, Disk Defragment, and removing cookies and histories from IE browser. Is there any other way to clean up apart from these.
The ubuntu cloud server has left only 900MB of disk space. I'll just empty the directory /tmp and wondering if there is any other location to clean up.

A: You can use du to investigate which directories are using the most space.  I typically run du repeatedly, working my way down the file hierarchy to find if I have any large files that I no longer need and have forgotten about.
du -sch /*

Then, if I see /var is taking up a lot of space, I'll du in that directory:
du -sch /var/*

... etc.
You can also clean up downloaded packages (.debs) that are cached by apt.
apt-get clean