text:
Q: encoding: unrtf SYMBOL.charmap needs to be altered I'm trying to convert some files from RTF to text. The originals were created with some Windows application (probably Word) but the conversion is taking place on a Linux server. The tool I wish to use is unrtf since it comes with my Linux distro (SLES !!.x) pre-installed... or at least I didn't have to intall it.
There isn't a lot of doco on unrtf. It works well and there is a man page with some limited info. My problem is that the encoding coming out is ISO-8859-1 and I need ISO-8859-15 in order to get a Euro symbol (€). What I'm getting is a not symbol (¬). Viewing the document in hex-mode I see that there is a value of xAC00 at the point where the symbol € should be.
Searching the web I found out that € has a unicde value of x20AC and ¬ has a unicode value of x00AC. A bit more searching suggested for an encoding of ISO-8859-15 the correct value would be x00A4. A lot of the information I found was contradictory and confusing (not to mention way off the topic which is unrtf after all).
Amongst the commands I've tried are:
unrtf --text $RTF > $XRTF
unrtf --text $RTF | iconv -c -f UTF-8 -t ISO-8859-15  > $XRTF

where $RTF and $XRTF are the input and output files respectively. I checked the supposed encoding of my rtf file with
file -bi $RTF

and this returned an answer of ISO-8859-1. So I tried the following:
unrtf --text $RTF | iconv -c -f ISO-8859-1 -t ISO-8859-15  > $XRTF

In one final grasp at straws I tried creating my own SYMBOL.charmap file and changed the value for the not symbol to "U<20AC>" which is the syntax for that file. Then I tried the command:
unrtf --text -P $HOME/usr/local/share/unrtf $RTF > $XRTF

All these attempts achieved absolutely nothing... except the second one which simply removed the not symbol altogether by virtue of the -c option (I think).
Anybody have any ideas on how I could achieve the desired conversion?

A: I haven't got a complete solution, but I do have an effective work-around. The first thing to note is that the encodings ISO-8859-1 and ISO-8859-15 are almost the same (see this link). There are 8 differences. Secondly, how chars are displayed depends on the software reading the file and not on the conversion software (in this case unrtf).
Thus the task is reduced to just the one symbol (€ in place of ¬), since the others are not in use in the relevant files. This comes down to changing "xAC" to "xA4" in each file after the conversion. This can be done with a simple sed command:
sed 's/\xAC/\xA4/g' temp1.txt > temp2.txt

That's it. As I say: it's a work-around.
Changing the SYMBOL.charmap file should have worked, but then I'm no expert on unrtf, so maybe I just did it incorrectly.


text:
Q: 21 women can complete the work in 20 days by working 10 hours a day. How long will 21 men complete the work by working 8 hours a day if 3 men=5 women? Twenty one women can complete a piece of work in 20 days by working 10 hours a day. In how many days 21 men will complete the work by working 8 hours a day if 3 men work as much as 5 women?
21 women can do--------20*10=200 units of work
21 men can do----------8*x units of work
3M=5W( given)
M=$5/3$W
$21*8*x=5/3*20*100$
It does not give me the right answer

A: There are the same number of men as women here. If three men do as much work as 5 women, then it will take the men $\frac{3}{5}$ as much time. It takes the women, as you calculuated, 200 hours. Thus, it will take the men $3\cdot 200/5=120$ hours. At 8 hours per day, it will take the men $120/8=15$ days to finish.

redpajama_set_name: RedPajamaStackExchange


text:
Q: scipy splrep() with weights not fitting the given curve Using scipy's splrep I can easily fit a test sinewave:
import numpy as np
from scipy.interpolate import splrep, splev
import matplotlib.pyplot as plt
plt.style.use("ggplot")

# Generate test sinewave
x = np.arange(0, 20, .1)
y = np.sin(x)

# Interpolate
tck = splrep(x, y)
x_spl = x + 0.05 # Just to show it wors
y_spl = splev(x_spl, tck)
plt.plot(x_spl, y_spl)

The splrep documentation states that the default value for the weight parameter is np.ones(len(x)). However, plotting this results in a totally different plot:
tck = splrep(x, y, w=np.ones(len(x_spl)))
y_spl = splev(x_spl, tck)
plt.plot(x_spl, y_spl)

The documentation also states that the smoothing condition s is different when a weight array is given - but even when setting s=len(x_spl) - np.sqrt(2*len(x_spl)) (the default value without a weight array) the result does not strictly correspond to the original curve as shown in the plot.
What do I need to change in the code listed above in order to make the interpolation with weight array (as listed above) output the same result as the interpolation without the weights?
I have tested this with scipy 0.17.0. Gist with a test IPython notebook

A: You only have to change one line of your code to get the identical output:
tck = splrep(x, y, w=np.ones(len(x_spl)))

should become
tck = splrep(x, y, w=np.ones(len(x_spl)), s=0)

So, the only difference is that you have to specify s instead of using the default one.
When you look at the source code of splrep you will see why that is necessary:
if w is None:
    w = ones(m, float)
    if s is None:
        s = 0.0

else:
    w = atleast_1d(w)
    if s is None:
        s = m - sqrt(2*m)

which means that, if neither weights nor s are provided, s is set to 0 and if you provide weights but no s then s = m - sqrt(2*m) where m = len(x).
So, in your example above you compare outputs with the same weights but with different s (which are 0 and m - sqrt(2*m), respectively).


text:
Q: Remove Appendices from table of content I used this code to generate appendices
\documentclass [a4paper,12pt,oneside,final]{book}
\usepackage[title]{appendix}
\begin{document}
\dominitoc
\tableofcontents
\listoffigures \addcontentsline{toc}{chapter}{List of Figures} \mtcaddchapter
\listoftables \addcontentsline{toc}{chapter}{List of Tables} \mtcaddchapter
\begin{appendices}
\chapter{Appendix A}
\section{aaaa}
\end{appendices}
\end{document}

The appendices appear at the end of the table of contents
How i can remove them so they will not appear
any suggestion?

A: You can add
\addtocontents{toc}{\setcounter{tocdepth}{-1}}

at the very beginning of the subappendices environment.
\documentclass [a4paper,12pt,oneside,final]{book}
\usepackage[title]{appendix}
\usepackage{minitoc}

\begin{document}
\dominitoc
\tableofcontents
\listoffigures \addcontentsline{toc}{chapter}{List of Figures} \mtcaddchapter
\listoftables \addcontentsline{toc}{chapter}{List of Tables} \mtcaddchapter

\begin{appendices}
\addtocontents{toc}{\setcounter{tocdepth}{-1}}
\chapter{Appendix A}
\section{aaaa}
\end{appendices}

\end{document}

If chapters, in particular thise for the appendices, are beign \included, it's best to place the line
\addtocontents{toc}{\setcounter{tocdepth}{-1}}

in the subsidiary file just before the \chapter command.


text:
Q: How to change or multiply the xticks by a factor in plt.acorr (matplotlib) I am plotting the autocorrelation function via plt.acorr of a time-series called data. The sampling rate of the recorded time-series is 2.16 seconds or 0.4629 Hz.
Problem: plt.acorr spaces the lags' xticks in accordance to the sampling point sequence, meaning that each lag's xtick on the x-axis corresponds to the numbers 1, 2, 3, and so on.
Question: Is there a possibility to change the xticks when using plt.acorr so that the xticks are evenly spaced starting from 0, over 1, to x in seconds?
Or, if the above is not possible, would it be possible that the x-axis at least shows the real time difference (in seconds) between each time lag (see picture below)?
import matplotlib.pyplot as plt
import numpy as np

data = [7.27958e-01, 6.59925e-01, 2.62454e-01, -1.73168e-01, 9.55694e-01,
2.25121e-01, 1.08360e+00, 3.71316e-01, -3.17764e+00, -1.15648e+00, -2.42453e+00]

plt.acorr(x=data, maxlags=None, normed=True, usevlines=True,
              color="blue", lw=2)

plt.xticks(np.arange(0, 10, 1))
plt.xlim([-0.1, 10])

plt.show()

A: You can update the plt.xtick() labels to show the numbers using the np.arange() as you did earlier but using 2.16 as the increment. Please see the code below. Note that we are only changing the x-axis labels. Hope this is what you are looking for...
import matplotlib.pyplot as plt
import numpy as np
data = [7.27958e-01, 6.59925e-01, 2.62454e-01, -1.73168e-01, 9.55694e-01, 2.25121e-01, 1.08360e+00, 3.71316e-01, -3.17764e+00, -1.15648e+00, -2.42453e+00]
plt.acorr(x=data, maxlags=None, normed=True, usevlines=True, color="blue", lw=2)
plt.xticks(np.arange(0, 11, 1), np.round(np.arange(0, 21.6001, 2.16), 2))
plt.xlim([-0.1, 10])
plt.show()

Plot


text:
Q: MPI_Send arguments         #define SPEEDS 5
typedef struct
    {
      float directions[SPEEDS];
    } input;

    input data[1000];
    int start=10;
    int xx=10;

    MPI_Send(data + start * xx, yy, MPI_FLOAT, MASTER, tag, MPI_COMM_WORLD);

How can I understand the first argument of MPI_Send? data is just an array but we're adding and multiplying numbers to it?

A: The expression data + start * xx is "address arithmetic": it means "the address of data plus start*xx times the size of whatever type is in data.
In other words, it's equivalent to
MPI_Send( &( data[start*xx] ), ....


text:
Q: Deleting all the ids using Promise.all First, apologies because I couldn't figure out a better title for this question. I am gonna try to explain my issue, let me know if you can't understand what is going on.
When deleting a movie, I also would like to delete the id of the movies from its genres arrays. Each Genre has a movie array with all the movie ids in that genre and each movie has a genre array with all the genre ids of that movie.
async delete(req, res, next) {
    try {
      const movie = await Movie.findOne({ _id: req.params.id });
      if (!movie) return res.status(400).send({ error: "Movie not found" });

    // Here I find all the genres. I get an array with all the genres objects
    // [{genre1}, {genre2}] inside the genre object there is an array with all the movie ids that belongs to that genre
      let _genres = await Genre.find({ _id: { $in: movie.genre } });

    // Now I am trying to return all the genre that are different from the movie._id I am deleting
      _genres = await Promise.all(_genres.map(async (genre) => {
        genre.movies.filter(item => item !== movie._id);
        await genre.save();
        return genre;
      }));

      await movie.remove();
      return res.send({ deleted: true });
    } catch (e) {
      next(e);
    }
}

I am not getting any error, but it is not deleting the movie id from the genre. Thanks.

A: Thanks to Bergi I was able to figure it out. Filter does not alter your object so I had to reassign it, I also had to convert the ids to strings to make sure they can be compared. Thanks Bergi.
Working code, if you think I can write it a better way let me know.
  async delete(req, res, next) {
    try {
      const movie = await Movie.findOne({ _id: req.params.id });
      if (!movie) return res.status(400).send({ error: "Movie not found" });

      movie.genre.forEach(async (id) => {
        const genre = await Genre.findById(id);
        if (genre) {
          genre.movies = genre.movies.filter(item => item.toString() !== movie._id.toString());
          await genre.save();
        }
      });

      await movie.remove();
      return res.send({ deleted: true });
    } catch (e) {
      next(e);
    }
  }


text:
Q: How do I specify which version of python I want to use with make? How do I specify which version of python I want to use with make?

A: Typically python is the name of the system's default Python version, but all installed versions are also available with names like python2.7 or python3.2.  You can use those names in a command in a Makefile, or you can put them on the #! line of a Python script if you want to invoke it that way.

A: A makefile just calls a command, you can check what python version is using calling whereis python (on UNIX) or checking the PATH environment (Windows). To override the default python you can make the call with the absolute path... just guessing anyway.


text:
Q: How can I bind a button on the .kv file to make it play a sound? Hello StackOverflow community,
I would like to ask for some help as before asking I did a long research but found nothing to help me out.
I have a school project that I decided to code with Python using Kivy for cross-platform. My project is about a SoundBox, to simplify I need to first create buttons and bind them to play various sounds. On pure python code (without a .kv file), I learned how to bind a button to make it play a sound, so I decided to reach the next level that is the Screen Management part. I kind of learned that to using now a .kv file to make it simple but I'm stuck on how to bind a button using .kv file.
I tried out some stuff but always ended up with errors on the console, also (but it's not really important for now), my Fade Transition doesn't work.
Your help is highly appreciated, thanks in advance.
.py:
from kivy.app import App
from kivy.uix.button import Button
from kivy.core.audio import SoundLoader
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition

sound = SoundLoader.load('Sunset_Lover.ogg')
sm = ScreenManager()

class ScreenManager(ScreenManager):
    pass

class Menu(Screen):
    pass

class Genre(Screen):
    pass

class TestApp(App):
    def build(self):
        sm.add_widget(Menu(name='menu'))
        sm.add_widget(Genre(name='genre'))
        return sm
    def son(self, instance):
        if sound:
            sound.play()

if __name__ == "__main__":
    TestApp().run()

.kv:
#: import FadeTransition kivy.uix.screenmanager.FadeTransition

<ScreenManager>:
    FadeTransition:
    Menu:
    Genre:
<Menu>:
    BoxLayout:
        Button:
            text: "Commencer"
            size_hint: 1, 1
            pos_hint: {'x': 0.3, 'y':0.3}
            on_press: root.manager.current = 'genre'
<Genre>:
    BoxLayout:
        Button:
            text: "Exemple1"
            size_hint: 0.2, 0.2
            pos_hint: {'x': 0.2, 'y':0.2}
            on_press: root.son()

A: The problem is that you have sound out of any scope you could use in kv file. First, move it somewhere, where you can access it:
class TestApp(App):
    def build(self):
        self.sound = SoundLoader.load('file')
        sm = ScreenManager()
        sm.add_widget(Menu(name='menu'))
        sm.add_widget(Genre(name='genre'))
        return sm

Then collect the arguments in more efficient way - this way you can use it both in kv and python and the additional args will be collected (won't throw an error)
    def son(self, *args):
        if self.sound:
            self.sound.play()

Then in kv you have to make sure the ScreenManager recieves only the appropriate widgets i.e. Screens only. To get the transition working, you have to add it to a variable it's used from:
<ScreenManager>:
    transition: FadeTransition()
    Menu:
    Genre:

And to actually play the sound (run the method) you can call it from the place you define it in i.e. from App instance:
<Genre>:
    BoxLayout:
        Button:
            text: "Exemple1"
            size_hint: 0.2, 0.2
            pos_hint: {'x': 0.2, 'y':0.2}
            on_press: app.son()  # here

A: You can import it to the kv file:
#: import sound __main__.sound

Button:
    on_release: sound()


text:
Q: Cannot render list created in one component in another Ok. I have the app.js (which will render all components on my screen) and inside this file i embeded two other js files (components). The first one is basically a button that adds one more word to an array. It goes something like this:
import { useState } from "react";

function DescriptionSector() {
  const [title, setTitle] = useState([]);
  return (
    <button onClick={() => setTitle([...title, "New title defined"])}>add word</button>

)

This first component is working just fine as I used console.log to test it.
THe problem is with the second part.
The second part consists basically of a list that renders the array create on the first part and here's where i having trouble.
function FinancialResume({ title }) {
  return (

      {title.map(e => {
      return (

{e}

      )
    })}

  )

}

I tried using the props object to send the updated array like this:
import { useState } from "react";

function DescriptionSector() {
  const [title, setTitle] = useState([]);
  return (
     <button
        onClick={() => {
          setTitle([...title, "New title defined"]);
          FinancialResume(title);
        }}
      >
        add word
      </button>

)

BUT IT DIDNT WORKED
EDIT: here's my app.js

import DescriptionSector from "./Components/descriptionSector/description";
import FinancialResume from "./Components/financialresume/financialresume";

function App() {
  return (

        <DescriptionSector />

        <FinancialResume />

)}

export default App;

A: Assuming you want the changes made in DescriptionSector to be rendered by FinancialResume, one way you can do that with React is by passing props from a shared parent.
Let App control the title state. It can pass the setter down to DescriptionSector and the value down to FinancialResume.
React states are reactive to changes. App and FinancialResume will re-render when title changes without you having to call any functions.
function App() {
  const [title, setTitle] = useState([]);

  return (

        <DescriptionSector setTitle={setTitle} />

        <FinancialResume title={title} />

  );
}

function DescriptionSector({ setTitle }) {
  return (
    <button
      onClick={() => {
        setTitle((title) => [...title, "New title defined"]);
      }}
    >
      add word
    </button>
  );
}

function FinancialResume({ title }) {
  return (

      {title.map((e, i) => {
        return
{e}
;
      })}

  );
}

There are of course other ways to manage shared state such as Context and state stores like Redux Toolkit but those are more advanced topics.


text:
Q: How to remove underline from BasicTextField? How I can remove underline from my TextField? I don't want to use different TextField()
val style = TextStyle(
    color = MaterialTheme.colors.primary,
    fontSize = 16.sp,
    fontWeight = FontWeight.SemiBold,
    textDecoration = TextDecoration.None,
    textAlign = TextAlign.Center
)

BasicTextField(
    modifier = Modifier
        .fillMaxWidth()
        .align(Alignment.Center),
    textStyle = style,
    value = value,
    onValueChange = { value = it },
    singleLine = true
)


text:
Q: Use returned data from Ajax call, dynamic content I'm trying to dynamically create some content using Ajax, php/Codeigniter and Javascript by submitting a form from a view to a controller that fetches and populates an array. The idéa is to fetch data using input from the form and create the charts (based on the fetched data) in the first view to be displayed in a pop up div.
I call this from the main view to submit the form:
function test() {
    var url = "path/to/controller/";
    $.ajax({
        type: "POST",
        url: url,
        data: $("#myForm").serialize(),
        success: function(data) {
            $('#test-container').show();
            $('#test-container').html(data);
        }
    });
}

to a function in the controller script that fills an array, let's call it fetchedData;
function getSomeData() {
    /* ..Fetching data.. */
    return fetchedData;
}

now I want to use that populated array in the first view where the Ajax call was made from in a pop up div like:

    /* ...Use the content of the returned array (fetchedData) to make some charts with javascript and php..  */

Nothing is being displayed since I am unsure of what to do to get a hold of the data in the array. Is this possible or it the wrong approach? Should I perhaps load the content as a new view in the controller and try to present that in the pop up div..?

A: The "return fetchedData;" of a php function returns the data in PHP.
It does not however return "data" to the ajax function that called the PHP script.
To get the data back, you need to convert $fetchedData to a string and echo that string which then gets to the browser where your javascript function is running. And of course, you need to parse the string to turn it into an object.
So your php must encode the data, like so:
$data_json = htmlentities(json_encode($data));
echo $data_json;

And then you can parse the resulting json data into an object;
var data = $.parseJSON(json_data);

A: Different data types can be returned to the ajax request. This code
$('#test-container').html(data);

implies that - at the very least - plain text is being returned, although most likely the text includes html markup too. You need to know what type data is going to be in order to utilized it.  Understand too that data is whatever you echo out of your php function. The most common data types returned are text/html and json.
if fetchedData is an array then you want to return json which typically shows up at the browser as a javascript object.
By constructing an associative array in PHP like
$foo = 'fooish';
$bar = 123;
$out = array('somedata' => $foo, 'otherdata' => $bar);

and then echoing the json encoded version of this back to the client
echo json_encode($out);

the data object of success will look like
{somedata: 'fooish', otherdata: 123}

You can use standard javascript notation to access the properties of the object like this data.somedata or data.otherdata.
On the other hand, if you create some html and echo that back from the server
echo "
The value of $foo is $bar
";

then data will contain the string  "The value of fooish is 123" and using the call $('#test-container').html(data); will likely produce an output in the browser. (It should anyway if an html element with the id of 'test-container' exists.)
I hope this help you get a handle on possible ways to get the results you want.


text:
Q: SQL SELECT query returns duplicates I'm trying to select some records but instead of 124 I get 992 records with the next query. Can anyone help me please? I get duplicates of the same records and I don't know why.
SELECT uszc_posts.*, uszc_postmeta.*, uszc_users.*, uszc_utilizatori_acord.*
FROM uszc_posts, uszc_postmeta, uszc_users, uszc_utilizatori_acord
WHERE uszc_posts.ID = uszc_postmeta.post_id
AND uszc_users.ID = uszc_posts.post_author
AND uszc_users.user_email = uszc_utilizatori_acord.email
AND uszc_posts.ID IN (783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1150, 1151, 1152, 1153, 1154, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340, 1341, 1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363)
ORDER BY `uszc_posts`.`post_date`  ASC

I've also tried using SELECT DISTINCT(post_author) but I get only 25 results instead of 124.

A: You are not really getting duplicates, you are getting very similar rows due to the way you are joining to the postmeta table. For example, assume you have one post with ID of 1, and it has three postmeta values, 1, 2, 3, if you run the following query you will get back 3 rows.
SELECT p.ID, pm.meta_value FROM posts p, postmeta pm WHERE p.ID = pm.post_id

Results:
p.ID  pm.meta_value
===================
1     1
1     2
1     3

Depending on your desired results, there are different solutions to this problem. If you just want aggregate data for your posts, you can GROUP BY p.ID to return a single row for each of the posts, however you will lose resolution on your postmeta values, and can't guarantee which one will be returned. You could specify a postmeta value to further reduce the duplicates, however there may still be duplicate entries for a particular key in this table, thus you would still need a GROUP BY if you only want one row per post.
This is how I would write your query
-- using COUNT(p.Id) will show you how many results were GROUP(ed) BY the p.ID
SELECT COUNT(p.Id) num_results, p.*, pm.meta_key, pm.meta_value, u.*, ua.*
FROM uszc_posts p
LEFT JOIN uszc_postmeta pm
    ON pm.post_id = p.ID AND pm.meta_key = '?????' -- the key you are interested in
LEFT JOIN uszc_users u
    ON u.ID = p.post_author
LEFT JOIN uszc_utilizatori_acord ua
    ON ua.email = u.user_email
WHERE p.ID IN (783, 784, 785....)
GROUP BY p.ID
ORDER BY p.post_date ASC


text:
Q: How do you install Django 2x on pip when python 2x is your default version of python but you use python 3x on Bash I need to install Django 2.2.2 on my MacBook pro (latest generation), and I am a user of python 3x.  However, my default version of python is python 2x and I cannot pip install Django version 2x when I am using python 2x.  Could anyone explain how to change the default version of python on MacBook I have looked at many other questions on this site and none have worked.  All help is appreciated thank you :)

A: You can simply use pip3 instead of pip to install Python 3 packages.

A: If I understand you correctly, you have python2 and python3 in your laptop but python2 is default and you want to install django 2.2.2 which is the latest version.
First always use a virtual environment.
Do the following on your terminal:
python3 -m venv env

Then:
source env/bin/activate

After that, then use pip like below:
pip install django

The latest django will be installed on that environment


text:
Q: What programming solution can one use, when a variable needs to take one of n unique, finite values, where n is greater then 2? For the sake of argument, let's assume that all of these values are completely unique, and cannot be defined by a range (less then x, but more then y).
For example, if I had to represent, let's say, a variable, whose value could either be an apple, or a banana. I could represent this variable with a boolean, and just assume that true means apples and false means bananas throughout my program. But what if that variable can take up three values, such as apples, bananas, and oranges?
One solution would be to wrap this around in a bean class, make it private, and then write a method that only allows you to set a value if it's one of these 'n' values, essentially adding a check.
Another solution can be to make an enumerated type.
But what else?

A: Do absolutely not use booleans to represent something like this.
Booleans are for logical values; representing true and false. Nothing else. As soon as you get into the true means Apple and false means Banana business you are getting into the business that each and any code that needs to deal with "fruits" needs to understand this (arbitrary) mapping from boolean to Apple/Banana.
The correct solution in languages such as Java or C++ for such problems: enums. Ensure that the compiler understands the valid values for "objects" of such types; instead of inventing your own mapping!

A: If, as you suggest, you can use a boolean to represent two options, where you know that a particular value represents a particular object, in your case a fruit (but without the ability to check that it is one of a specified range), then how about a short to represent 3 or more, or maybe a byte? Even a char[] or string would suffice.
However if you require the checking capability, then you would need an enum or a class.
However, you could use a struct containing both a short (or byte), and an array, or a hashtable, or some other list look up mechanism, which contains the possible [legal] values that the short can take, and then sprinkled around within the rest of your code, you write access funtions which assign values to the short which only correspond to values which are held in the String array.
However, this latter option is obviously the same as a class, but with its methods external to the object. After all, the simple definition of a class is a struct which contains its own methods.


text:
Q: Sqlite&Python: Exiting for loop Can someone please explain why the first loop gets exited, when the second loop is done.
First i get all table names in database(Total 4 results)
Then i want to get all data from that table.
But i only get the data from the first table for some reason.
If i remove the loop that gets the data from the table, then it runs the first for loop all the way to the end.
#Get all tables in database file
for tablename in c.execute("SELECT name FROM sqlite_master WHERE type='table';"):
    print(tablename[0])

    for elementdate in c.execute('SELECT * FROM %s ORDER BY Date DESC' % tablename[0]):
        print(elementdate)

Output:
table_1
(1, '20120210', 360)
(2, '20100210', 204)
Loop Excited

Same code just without last for loop
#Get table names
for tablename in c.execute("SELECT name FROM sqlite_master WHERE type='table';"):
    print(tablename[0])

    #for elementdate in c.execute('SELECT * FROM %s ORDER BY Date DESC' % tablename[0]):
    #   print(elementdate)

Output:
table_1
table_2
table_3
table_4
Loop Excited

Have i found an error or am i just dumb?

A: You shouldn't execute few queries in the same cursor before fetching results of first one:
c.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = c.fetchall()
for tablename in tables:
    print(tablename[0])
    c.execute('SELECT * FROM %s ORDER BY Date DESC' % tablename[0])
    for elementdate in c.fetchall():
        print(elementdate)

A: A single cursor object works only with a single query at a time; execute() overwrites any previous results.
If you want to execute two queries at the same time, use two cursors:
c = db.cursor()
c2 = db.cursor()
for row in c.execute("SELECT name FROM sqlite_master WHERE type='table'"):
    tablename = row[0]
    for row2 in c2.execute("SELECT * FROM %s ORDER BY Date DESC" % tablename):
        ...

Note: it would be a bad idea to modify the table while some other query on it is still running.


text:
Q: AutoHotKey change keys if variable is true I'm new to AutoHotKey and am trying to create a script to let me use my Roku's Bluetooth remote with my PC. The issue with the remote is that all the keys are weird. What I would like is so that when I press x and y at the same time, all the necessary keys are remapped to the ones for the remote and vise-versa for the keyboard. Here is what I have right now (doesn't work):
state = keyboard

loop{
    if (GetKeyState("x", "P") && GetKeyState("y", "P")){
        if (state == "keyboard") {
            state = roku
            Sleep 30

        }
        else if (state == "roku") {
            state = keyboard
            Sleep 30
        }
    }
    if (state == "roku"){
        4::send h
        u::send {up}
        l::send {left}
        r::send {right}
        d::send {down}
        e::send {esc}
        6::send {backspace}
        c::send r
        8::send f
        s::send {enter}
        3::send c
        a::send {space}
    }
}

Does anyone know why this doesn't work?

A: ~x & y::(HotkeysState:=!HotkeysState)

#If HotkeysState
    4::SendInput h
    u::SendInput {up}
    l::SendInput {left}
    r::SendInput {right}
    d::SendInput {down}
    e::SendInput {esc}
    6::SendInput {backspace}
    c::SendInput r
    8::SendInput f
    s::SendInput {enter}
    3::SendInput c
    a::SendInput {space}
#If


text:
Q: Observing frequency of waveform in LTspice I'm using Ltspice for circuit simulation. I stimulate the circuit using run command in the menu stimulate. But I didn't find how to measure(simply in hertz) frequency from there. So how can I observe the frequency of a waveform from LTspice?

A: As Vicente commented, mouse-based methods are error-prone. That being said, if you don't need an exact measure, and for completeness, here is another mouse based method:
Enable two graph "cursors" by clicking the name of the waveform you want to measure (see below, circled in red). The first click will create one cursor, another click will create another cursor. Note that if you don't move the first one, the second will be created on top of the first (not an issue).

Now hover your mouse-cursor over the uh, waveform-cursor. Your mouse-cursor should become a yellow number (1 or 2, see below). You can then click and drag the cursor to move it.

At this point, you can line up your two waveform-cursors across one complete cycle. The frequency, along with other information, will be shown in the small cursor window (see below).

Also note that sidA30's method will zoom after un-clicking, which can be annoying. To avoid zooming, you can right-click before letting go of the left-click. This cancels the selection and thus doesn't zoom.

A: Double click on the part of the circuit you want to measure and a waveform window should pop up (when the simulation is running) and your waveform you want to measure will show. Either adjust the runtime of the simulation or zoom in on the waveform so you can actually see the entire waveform cycles. Then click on part of the cycle and drag your mouse the the exact same point to the next cycle - the bottom of the waveform window will show the frequency of the distance between these two points.

Click on image and you will see what I mean.

A: Short answer: right-click the waveform, go to "View"->"FFT", then select the waveform from menu and an appropriate number of samples.
Page 31 of this manual goes into more details.


text:
Q: Implementing verification method to allow only String input in Java Im trying to implement a method to verify and only allow string input to be stored by the program. Found the Integer.parseInt() method and reversed it so that upon catching exception > it returns and shows no error the user prompting user has entered the correct input. However, it so happens that if input is a mix of String and integers, NumberFormatException is not thrown. or is it? Is there another method to achieve above verification without using String.contains() and comparing to array of all integers ({1,2,3,4,5,6,7,8,9,0})?
below is the snippet of the code for the method to validate string and the driver class which calls the method.
-validation method
public static boolean validateName(String name)
    {
        try
        {
            Integer.parseInt(name);
            System.out.println("Kindly refrain from entering numbers into name field");
            System.out.println("Only characters and symbols allowed in name");
            return false;
            //error flagged as name only accepts character and symbol
        }
        catch (NumberFormatException e)
        {
            return true;
        }
    }

driver class calling for method validateName()
...
        //name entry and validation
        do
        {
            System.out.println("Please enter your name:");
            name=input.nextLine();
            flag=validateName(name);
        }
        while(!flag);
...


text:
Q: Merge blocked: merge conflicts must be resolved I am trying to merge my master branch to a production branch in Gitlab for my CI/CD pipeline.
I get a warning that the source branch is 1 commit behind the target branch. I tried the recommended fix from gitlab(Here and Youtube), but I am having no luck.
In my local environment, I created a production branch. I tried to merge my master to production, but continue to get errors. These are some of the commands I have been using(not in that order) that have been ineffective.
git pull master production --allow-unrelated-histories
git ls-tree production
git config pull.rebase false
git ls-tree production
git rebase master/production
git push -u  origin production
git merge --no-ff 'master'
git rebase --continue

Thanks in advance

A: You would need at least to make sure you are in the right branch before any merge:
git fetch
git switch production
git pull production
git merge --no-ff master
git push

That would update production first, then merge master to it.
And it does not prevent possible conflicts to be resolved during the merge.


text:
Q: Can a webworker capture touch input? Can a web worker thread capture input events on canvas? That is touch/click events occurring within the canvas object on an HTML page. I would then message those events to the main thread.

A: Seems the answer is no per the conversation on this thread.


text:
Q: Inserting Value into database of hidden fields Query is If I select 'Select a New Parent category' from dropdown, a new textbox gets appear. I wants to insert that value into database. That textbox is hidden bydefault.
HTML FILE

            <form method="POST" action="" name="form1"  enctype="multipart/form-data" >

Add category

                    Select parent Category:	<select name="parentcat" id="parentcat">

                    <?php
            include "../storescripts/connect_to_mysql.php";
                        $result=mysql_query("SELECT parent from category"); while($row=mysql_fetch_array($result)){
                            echo "<option>".$row['parent'];"</option>";
                        } ?>
                            <option value="Create a New Parent Category">Create a New Parent Category</option>
                        </select>

<input type="text" id="other" name="other" placeholder="New Parent Category Name:" style="display: none;"/>

                    	<input type="text" name="catname" placeholder="SubCategory name" id="catname">

                    Status:

                    <select name="status" >
                        <option selected="Active">Active</option>
                        <option>Inactive</option>
                    </select>

Category Image :	<input type="file" name="imageUpload" id="imageUpload">

                    <input type="submit" name="submit" value="Insert">

                </form>

Here is my complete HTML file,bydefault 'other' dropdown is hidden. Now Here I'm providing my php code that inserts values into database, issue is how can I insert value of hidden filed into database. My database fields includes : cat_id(Auto-increment),cat_name,parent,cat_status,cat_image.
Here Is my php code for inserting values into database.
<?php
                                 if(isset($_POST['submit']))
                                 {
                                 $parentcat=$_POST['parentcat'];
                                $catname=$_POST['catname'];
                            $status=$_POST['status'];
                                 $target_dir = "../uploads/";
                                  $target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
                                  $uploadOk = 1;
                                  $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

                                    if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
                                        echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
                                    } else {
                                        echo "Sorry, there was an error uploading your file.";
                                    }

                                    $image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable

                                $sql = mysql_query("SELECT cat_id FROM category WHERE cat_name='$catname' LIMIT 1");
                                  $CatMatch = mysql_num_rows($sql); // count the output amount
                                    if ($CatMatch > 0) {
                                    echo 'Sorry you tried to place a duplicate "Category Name" into the system, click here';
                                    exit();

                                  }

                                  else{
                                   $sql=mysql_query("INSERT INTO `category` (`cat_name`, `parent`, `cat_status`,`cat_image`) VALUES ('$catname', '$parentcat', '$status','$image') ");
                                   echo $sql;
                                }

                                }

?>

For an eg. If I Select A new parent category then Subcategory named textbox appears and I want to insert that value into database. How Can i do that.

A: Change your jquery code like this

Also change your HTML code for #other input box like this
<input type="hidden" id="other" name="other" placeholder="New Parent Category Name:"/>

Let me know if it works for you.

Edit
In your PHP file, Instead of $catname=$_POST['catname']; add this
$catname = ( $parentcat == "Create a New Parent Category") ? $_POST['other'] : $_POST['catname'];


text:
Q: How to rotate a jpeg lossless (90, 180, 270, 360) I want to rotate an jpeg image lossless.
My code works with success but is with loss:
ByteArrayInputStream inputstream = new ByteArrayInputStream(imgByteArraySource);
BufferedImage oldBufferedImage = ImageIO.read(inputstream);

BufferedImage newBufferedImage = rotate(oldBufferedImage, degrees);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(newBufferedImage, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();

I found an old post on this site:
Lossless JPEG Rotate (90/180/270 degrees) in Java?
Maybe there is a better solution.
I'm not very confident about the media-util library (it is old, and it is packaged in a .exe file).
Has someone an idea?
Is there a new and better way to do this?
Thanks in advance.
Bobby

A: It is only possible to rotate losslessly in 90 degree increments.
To do it in 90 increments, you need to either compress using the same quantization tables used in the original (which still may introduce loss, depending upon the encoder) or use a special program that rearranges the MCUs in the JPEG stream.
Any time you decompress a JPEG using different quantization tables you will get loss.


text:
Q: close approximation of divergent integral I want to calculate the integration of this function:
$$ \int_{-\infty }^\infty { 1\over \sqrt{(x-a)^2 + (y-b)^2}} dy $$ where $ a $ and $ b $ are the constants.  The integral comes out to be $$ \ln \left ( \left | \sqrt{(x-a)^2 + (y-b)^2} + y -b \right | \right ) + C $$  Which is divergent in nature over the limits. I have following questions:

*

*Is there any other way to deal with such integrals?

*Is there any way to find any approximate function of this which does not have this divergence issue?

I am quite new to this stuff, so sorry for any mistakes in this post. thanks for any help in advance.
The above question is already answered by Dr. MV, i have a query while following the same rule in second half of my equation :
$$ \int_{-\infty }^\infty { y\over \sqrt{(x-a)^2 + (y-b)^2}} dy $$ the integral of this comes out to be
$$ \ln \left ( \left | \sqrt{(x-a)^2 + (y-b)^2} + y -b \right | \right ) + \sqrt {(x-a)^2 + (y-b)^2} + C $$
this function still remains divergent. is there any way to deal with this
thanks for any help

A: The integral of interest fails to exist even as a Cauchy Principal Value.  To see this, we write
$$\begin{align}
\text{PV}\left(\int_{-\infty }^\infty { 1\over \sqrt{(x-a)^2 - (y-b)^2}} dy\right)&=\lim_{L\to \infty}\int_{-L}^L \frac{1}{\sqrt{(x-a)^2+(y-b)^2}}\,dy\\\\
&=\lim_{L\to \infty} \left. \left(\log\left((y-b)+\sqrt{(x-a)^2+(y-b)^2}\right)\right)\right|_{-L}^L\\\\
&=\lim_{L\to \infty}\log\left(\frac{(L-b)+\sqrt{(x-a)^2+(L-b)^2}}{-(L+b)+\sqrt{(x-a)^2+(L+b)^2}}\right)\\\\
&= \infty
\end{align}$$
If we wish to analyze the behavior of the integral before passing to the limit, we can proceed as follows.
$$\begin{align}
\log\left(\frac{(L-b)+\sqrt{(x-a)^2+(L-b)^2}}{-(L+b)+\sqrt{(x-a)^2+(L+b)^2}}\right)&=\log\left(\frac{(L-b)\left(\sqrt{1+\left(\frac{x-a}{L-b}\right)^2}+1\right)}{(L+b)\left(\sqrt{1+\left(\frac{x-a}{L+b}\right)^2}-1\right)}\right)\\\\
&\sim 2\log(L)
\end{align}$$


text:
Q: Android BufferedReader is redirected I need to read in a webpage using a BufferedReader. When I run the code snippet as a Java application on my computer it works fine. However when I run the code on the phone, the BufferedReader is redirected to the wrong webpage. How can I stop the BufferedReader from being redirected?
The page I am trying to visit is a youtube account's subscribers. I can view the page on my computer just fine, but not on my phone.

A: As a web server can identify the browser / platform used to request a page by using the "user agent string", you must change the user agent of the jdk before downloading the web page from your java file. You should add this line to your java program :
System.setProperty( "user.agent" , <user agent string from your browser > );

you acn find a lot of user agent strings here. Pick one that is not associated to a mobile platform like :
Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre

Regards,
 Stéphane


text:
Q: Establishing chronology of a list based on a directed graph tree So, in a personal project I've been working on I came across a following problem, and I've been struggling to come up with a solution since my maths skills are not terribly great.
Lets say you have a following tree of numbers a b c d e f g h:
    a
   / \
   b  c
 / |  |
g  d  f
|  |
h  e

Each step down the tree means that the next number is bigger then the previous one. So a < b, d < e, a < c. However, it is impossible to determine whether b > c or c < b - we can only tell that both numbers are bigger then a.
Lets say we have an ordered list of numbers, for instance [a, b, c, d, e]. How do we write an algorithm that checks if the order of the numbers in the list (assuming that L[i] < L[i+1]) is, in fact, correct in relation to the information we have accoring to this tree?
I. E, both [a, c, b, d, e] and [a, b, d, c, e] are correct, but [c, a, b, d, e] is not (since we know that c > a but nothing else in relation to how the other numbers are structured).
For the sake of the algorithm, lets assume that our access to the tree is a function provably_greater(X, Y) which returns true if the tree knows that a number is higher then another number. I.E. provably_greater(a, d) = True, but provably_greater(d, f) = False. Naturally if a number is provably not greater, it also returns false.
This is not a homework question, I have abstracted the problem quite a lot to make it more clear, but solving this problem is quite crucial for what I'm trying to do. I've made several attempts at cracking it myself, but everything that I come up with ends up being insufficient for some edge case I find out about later.
Thanks in advance.

A: Your statement "everything that I come up with ends up being insufficient for some edge case I find out about later" makes it seem that you have no solution at all. Here is a brute-force algorithm that should work in all cases. I can think of several possible ways to improve the speed, but this is a start.
First, set up a data structure that allows a quick evaluation of provably_greater(X, Y) based on the tree. This structure can be a set or hash-table, which will take much memory but allow fast access. For each leaf of the tree, take a path up to the root. At each node, look at all descendant nodes and add an ordered pair to the set that shows the less-than relation for those two nodes. In your example tree, if you start at node h you move up to node g and add (g,h) to the set, then move up to node b and add the pairs (b,h) and (b,g) to the set, then move up to node a and add the pairs (a,h), (a,g), and (a,b) to the set. Do the same for leaf nodes e and f. The pair (a,b) will be added twice to the set, due to the leaf nodes h and e, but a set structure can handle this easily.
The function provably_greater(X, Y) is now quick and easy: the result is True if the pair (Y,X) is in the set and False otherwise.
You now look at all pairs of numbers in your list--for the list [a,b,c,d,e] you would look at the pairs (a,b), (a,c), (b,c), etc.  If provably_greater(X, Y) is true for any of those pairs, the list is out of order. Otherwise, the list is in order.
This should be very easy to implement in a language like Python. Let me know if you would like some Python 3 code.

A: I'm going to ignore your provably_greater function and assume access to the tree so that I can provide an efficient algorithm.

*

*First, perform a Euler tour of the tree, remembering the start and end indexes for every node.  If you use the same tree to check a lot of lists, you only have to do this once.  See https://www.geeksforgeeks.org/euler-tour-tree/

*Create an initially empty binary search tree of indexes

*Iterate through the list.  For each node, check to see if the tree contains any indexes between its start and end Euler tour indexes.  If it does, then the list is out of order.  If it does not, then insert its start index into the tree.  This will prevent any provably lesser node from appearing later in the list.
That's it -- O(N log N) altogether, and for each list.
A TreeSet in Java or std::set in C++ can be used for the binary search tree.


text:
Q: Decoding using huffman code I created a program to read a file and encodes it character by character into a variable length binary code. ex. the most common character would be 110, next common 0010, etc. I then put the entire binary code into a text file. So the code would look something like 11010011001110000110001010110110... and it goes on. How would I go about decoding the binary coding back into characters?

A: If you really generated a Huffman code, then it is a prefix code.  That is, no valid code is also the prefix of another valid code.  Therefore you simply start at the beginning and whatever code matches those bits is the first symbol.  Remove those bits and repeat.  Your first symbol is associated with the code 101.  Remove the 101, and look in your codes for 1, 10, 100, 1001, 10011, etc. until you find a match.


text:
Q: Is it possible to modify CRM 2011 tooltips? Is it possible to modify CRM 2011 tooltips?  After fooling around with it for hours, it seems to be impossible.
The two different things I tried were:

*

*Browsing through the customizations XML looking for something tooltip-like to modify.

*Using Javascript to modify different "title" attributes I found in the HTML.

Everything I tried in Javascript went something like:
var StuffControl = document.getElementById("internal_field_name");
StuffControl.title = "whatever I want my tooltip to say";

When I tried running the above Javascript code on a lookup field specifically, it was able to execute and modify the lookup "title" attributes.  Infact, I was able to find two different "title" attributes embedded within one lookup field, and I successfully changed both of them.  However, changing either of the "title" attributes I found embedded within that lookup never resulted in actually modifying the tooltip.  The tooltip always stays set to its existing value.
I assumed the "title" attribute was the one I was looking to change, since that is the generic HTML tooltip attribute.  I also tried changing other attributes, but came up with the same results.

A: To modify a field label tooltip (which I believe all field types have), use the following Javascript:
document.getElementById("field_name_c").setAttribute("title", "tooltip text");

To modify a lookup button tooltip (lookup fields have two tooltips, one for the label and one for the button, aka the magnifying glass), use the following Javascript:
document.getElementById("field_name").setAttribute("title", "tooltip text");

The "_c" appended to the end of the internal name of the field stands for "caption", and is therefore associated with the label HTML element of that field.  In the case of lookup fields specifically which have the second additional tooltip, the exact internal name of the field matches the id of the lookup button HTML element.


text:
Q: How to swipe multi buttons with one touch I have 5 buttons; each allows touchUpInside-action and touchDragOutside-action...as well as doubleTap-action and longPress-action via tapGestureRecognizers.
I would also like to allow user to start a swipe from any UIButton and Any addition UIButton that the swipe touches, these buttons (including first touch) perform their @IBAction func Swipe.
so a continuously swipe like so

would perform @IBAction func swipe for UIButtons 1,2,3,4 and 5.

A: You can try something like this:
// Create an array to hold the buttons you've swiped over
var buttonArray:NSMutableArray!

override func viewDidLoad() {
    super.viewDidLoad()

    // Make your view's UIPanGestureRecognizer call panGestureMethod:
    // (don't use a UISwipeGestureRecognizer since it's a discrete gesture)
    panGesture.addTarget(self, action: "panGestureMethod:")
}

func panGestureMethod(gesture:UIPanGestureRecognizer) {

    // Initialize and empty array to hold the buttons at the
    // start of the gesture
    if gesture.state == UIGestureRecognizerState.Began {
        buttonArray = NSMutableArray()
    }

    // Get the gesture's point location within its view
    // (This answer assumes the gesture and the buttons are
    // within the same view, ex. the gesture is attached to
    // the view controller's superview and the buttons are within
    // that same superview.)
    let pointInView = gesture.locationInView(gesture.view)

    // For each button, if the gesture is within the button and
    // the button hasn't yet been added to the array, add it to the
    // array. (This example uses 4 buttons instead of 9 for simplicity's
    // sake
    if !buttonArray.containsObject(button1) && CGRectContainsPoint(button1.frame, pointInView){
        buttonArray.addObject(button1)
    }
    else if !buttonArray.containsObject(button2) && CGRectContainsPoint(button2.frame, pointInView){
        buttonArray.addObject(button2)
    }
    else if !buttonArray.containsObject(button3) && CGRectContainsPoint(button3.frame, pointInView){
        buttonArray.addObject(button3)
    }
    else if !buttonArray.containsObject(button4) && CGRectContainsPoint(button4.frame, pointInView){
        buttonArray.addObject(button4)
    }

    // Once the gesture ends, trigger the buttons within the
    // array using whatever control event would otherwise trigger
    // the button's method.
    if gesture.state == UIGestureRecognizerState.Ended && buttonArray.count > 0 {
        for button in buttonArray {
            (button as UIButton).sendActionsForControlEvents(UIControlEvents.TouchUpInside)
        }
    }
}

(Edit: Here are a few answers I've written in the past explaining what I meant by UISwipeGestureRecognizer being a discrete gesture: stackoverflow.com/a/27072281/2274694, stackoverflow.com/a/25253902/2274694)


text:
Q: Getting a list of public Google+ URLs from Google API call? I'm a pretty rudimentary programmer - I've got a project from work that basically needs me to assemble a spreadsheet of around 8000 public Google+ URLs. I'm having some issues understanding the Developers Console, as a beginner.
I'm looking to return a list of URLs and Google+ Display names of all profiles that have a specific word in the display name (these are all corporate accounts).
Any advice would be greatly appreciated.

A: You will want to use the people.search API method. This will return a list of people and pages that match the query. The results are not limited to searching displayName so you will have to do further filtering server side.


text:
Q: How to change the text color of month in GitHub square calendar android I am using this GitHub calendar in my app. Now see this picture below -

The title of the month is dark and it does not suit the theme. So how can I change it?
 <color name="Navigation_Color">@color/motivationQuoteColor</color> <!--same as selected color-->

    <color name="calendar_selected_day_bg">#c2e4ff</color>
    <color name="calendar_highlighted_day_bg">@color/toolbarColor</color>
    <color name="calendar_text_selected">@color/colorPrimaryDark</color>
    <color name="calendar_text_unselectable">@color/whiteTextColor</color>
    <color name="calendar_text_active">@color/whiteTextColor</color>
    <color name="calendar_text_inactive">@color/motivationQuoteColor</color>
    <color name="calendar_divider">@color/whiteTextColor</color>
    <color name="calendar_bg">@color/motivationQuoteColor</color>
    <color name="calendar_inactive_month_bg">@color/motivationQuoteColor</color>
    <color name="calendar_active_month_bg">@color/motivationQuoteColor</color>
    <color name="calendar_selected_range_bg">@color/motivationQuoteColor</color>

Above are the only choices of colors, provided by the project from GitHub. I want to make the color white for the month's title. By the way, I searched google and I found that (github.com) but it did not work for me.
Edit - I found that (GitHub issue) one also but not worked
Here is my XML code:
 <com.squareup.timessquare.CalendarPickerView
                android:id="@+id/calendar"
                android:layout_width="match_parent"
                android:layout_height="370dp"
                android:background="@color/calendar_bg">

            </com.squareup.timessquare.CalendarPickerView>

A: after going through the link of github you have given
add the following code in your styles.xml:-
<resources xmlns:tools="http://schemas.android.com/tools">
.
.
.
<style name="CustomCalendarTitle">
<item name="android:textSize">@dimen/calendar_text_medium</item>
<item name="android:gravity">center</item>
<item name="android:paddingBottom">@dimen/calendar_month_title_bottommargin</item>
<item name="android:paddingTop">@dimen/calendar_month_topmargin</item>
<item name="android:color">@color/custom_calendar_text_selector</item>
 <item name="android:textColor">@color/colorAccent</item>

</style>
</resources>

Replace this:-
 <com.squareup.timessquare.CalendarPickerView
            android:id="@+id/calendar"
            android:layout_width="match_parent"
            android:layout_height="370dp"
            android:background="@color/calendar_bg">

        </com.squareup.timessquare.CalendarPickerView>

by
use this in xml:-
<com.squareup.timessquare.CalendarPickerView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/calendar_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/custom_background"
android:clipToPadding="false"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:scrollbarStyle="outsideOverlay"
app:tsquare_dayBackground="@drawable/custom_calendar_bg_selector"
app:tsquare_dayTextColor="@color/custom_calendar_text_selector"
app:tsquare_displayDayNamesHeaderRow="false"
app:tsquare_dividerColor="@color/transparent"
app:tsquare_headerTextColor="@color/custom_header_text"
app:tsquare_titleTextStyle="@style/CustomCalendarTitle"
/>


text:
Q: how to make this template code work from sheets app I'm trying to make this script to work on google sheets app so it sends a pdf copy to my email when I type Send in cell L6
the code work perfect on computer but not on ipads , anyway to do this from app ?
function onEdit2(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var r  = sheet.getRange('L6').getValue();
  if (r == "Send") {
    var ss = SpreadsheetApp.getActiveSpreadsheet()
    var ssID = ss.getId();
    var sheetgId = ss.getActiveSheet().getSheetId();
    var sheetName = ss.getName();

    var token = ScriptApp.getOAuthToken();

    var email = "EMAIL HERE";
    var subject = "Daily report ";
    var body = "Please find the attached Daily report";

    var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
      + "format=xlsx" +  "&gid="+sheetgId+ "&portrait=true" +
      "&exportFormat=pdf";

    var result = UrlFetchApp.fetch(url, {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });

    var contents = result.getContent();

    MailApp.sendEmail(email,subject ,body, {
      attachments: [{
        fileName: sheetName + ".pdf",
        content: contents,
        mimeType: "application//pdf"
      }]
    })
  }
}

A: The way it worked for me by " installed Trigger "
from the script editor : Edit - current project Triggers
I added new trigger that will run the code below based on " On edit " and voila it worked , from sheets app if I typed " Send " in Cell L6 it will send a PDF copy of the active sheet to the email listed in the code.
function onEdit2(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  var r  = sheet.getRange('L6').getValue();
  if (r == "Send") {
    var ss = SpreadsheetApp.getActiveSpreadsheet()
    var ssID = ss.getId();
    var sheetgId = ss.getActiveSheet().getSheetId();
    var sheetName = ss.getName();

    var token = ScriptApp.getOAuthToken();

    var email = "EMAIL HERE";
    var subject = "Daily report ";
    var body = "Please find the attached Daily report";

    var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export?"
      + "format=xlsx" +  "&gid="+sheetgId+ "&portrait=true" +
      "&exportFormat=pdf";

    var result = UrlFetchApp.fetch(url, {
      headers: {
        'Authorization': 'Bearer ' +  token
      }
    });

    var contents = result.getContent();

    MailApp.sendEmail(email,subject ,body, {
      attachments: [{
        fileName: sheetName + ".pdf",
        content: contents,
        mimeType: "application//pdf"
      }]
    })
  }
}

A: Create a Google Script in the very same Spreadsheet or in another one (Tools / Script editor), add the script you already have, grant the authorizations required, and trigger it with a simple form (Tools / Create a form) (trigger → Edit / Current project's triggers). The long URL to view the form can be easily opened by means of a URL shortener or something by the sort. Forms work in cell phones too and without need to sign in to your account. With this method you can even add a useless conditional password to run the script.
function createPDF(e) {
  var input = e.values[1];
  if (input == 'my_password'){
    // your scripts to create and send the PDF goes here
  }
}

It's a simplistic solution, but it works.


text:
Q: Excluding empty spaces from being counted In Python 3 In Python 3, how do I exclude an empty space from being counted in a sentence?
Example:
name = input('Please enter your name: ')
greetings = input('Hi {}, please enter a sentence here: '.format(name))
print(str(name) + ', your sentence has ' + str(len(greetings)) + ' characters.')

When I run this program, it counts all characters that I enter into the input and it also counts the empty spaces, too. But I only want the program to count the characters, not the empty spaces.
How do I do this?

A: Instead of
greetings = input('Hi {}, please enter a sentence here: '.format(name))
use
greetings = input('Hi {}, please enter a sentence here: '.format(name.replace(" ","")))
basically he takes every empty space from name and replaces it with nothing

A: there can be many solutions to this problem.
I suggest to use regex, which is highly flexible and robust at the sametime.
Below is the code -
import re

def remove(string):
    pattern = re.compile(r'\s+')
    return re.sub(pattern, '', string)
name = input('Please enter your name: ')
greetings = input('Hi {}, please enter a sentence here: '.format(name))
print(str(name) + ', your sentence has ' + str(len(remove(greetings))) + ' characters.')

Good luck, enjoy!!


text:
Q: C++ private static member variables This C++ code is producing linker errors at compile time:
// A.h
class A {
    public:
        static void f();
    private:
        static std::vector<int> v;
};

// A.cpp
void A::f() {
    // this line is causing trouble
    int i = v.size();
}

Moving the vector declaration into the cpp file works. However I want to understand the linker error "Undefined symbols" cause in the above code. What is causing the linker error in the above code?

A: Static members have to be defined in a compilation unit:
// A.cpp

vector<int> A::v;

A: // A.h
class A {
    public:
        static void f();
    private:
        static std::vector<int> v;
};

// A.cpp
//modify add this line
static std::vector<int> A::v;
void A::f() {
    // this line is causing trouble
    int i = v.size();
}


text:
Q: How do I determine which table should be to the left of my join? I am practicing SQL joins on learnsql.com and when joining three tables, I'm having trouble determining which table should be to the left of the join clause and which should be to the right.

Show the name of each product and its calorific value for all products that in the 'dairy' department.

Since the question begins by asking for the name of each product, I made the assumption that my answer should be ... FROM product p .... and then I would left join the nutrition_data and department data on it.

List all products that have fewer than 150 calories. For each product show its name (rename the column to product) and the department in which can be found (name the column department).

I interpreted the second question the same way, that it should be a list of all the products (... FROM product ...) and then the department and nutrition_data would be joined to that.
Below is a picture of the tables and the answer to the first question, the wrong answer to the second question and the right answer to the second question.
https://imgur.com/a/qLqpjGo
Because the question asked for a list of all the products, I thought the product table should be the first table after the FROM clause and then all the other tables would be joined to it. This logic worked for the first question, and since the second question is similar in nature, I assumed it was the same logic. However for the second, the solution is ... FROM department ... and then the product and nutrition_data is joined to the department table.
How do I determine which table should be to the left of my join?

A: "all products" is what calls an outer join: all products even when they don't have calorific information
"all products that have fewer than 150 calories" cannot show the products without calorific information. Then I see no outer join here. Except if no calorific information means no calories


text:
Q: PHP Unzip File and Extract Files On By One I want to create a PHP code to unzip a file, then extract it to a folder. I know to extract all the file inside the zip, but, I want to extract it one by one, because I want to check each file need to be below 1MB
Here's my code:
$zip = new ZipArchive();
for ($i=0; $i<$zip->numFiles;$i++)
    {
        $current = $zip->statIndex($i);
        if($current["size"] > (1*1024*1024))
        {
            printf("%s (size: %d bytes) is too big, failed to upload this photo
", $current["name"], $current["size"]);
        }
        else
        {
            $location = 'picture/'.$current['name'];
            if(move_uploaded_file($current['name'], $location))
                printf("%s successfully uploaded
", $current["name"]);
            else
                printf("Failed
");
        }
    }

I always failed on these line code : if(move_uploaded_file($current['name'], $lokasi)) it always return Failed, and I know $current['name'] is only the file name, not the file inside the zip. Anyone know how to get file inside the zip (one by one)?

A: Finally, from this link I read, so I choose to extract the file with array method. Here's my end code for my problem:
for ($i=0; $i<$zip->numFiles;$i++)
        {
            $current = $zip->statIndex($i);
            if($current["size"] > (1*1024*1024))
            {
                printf("%s (size: %d bytes) is too big, failed to upload this image!
", $current["name"], $current["size"]);
            }
            else
            {
                $location = $folder.'/'.$folder2.'/';
                if($zip->extractTo($location , array($current['name'])))
                    printf("%s successfully uploaded
", $current["name"]);
                else
                    printf("Failed
");
            }
        }

A: http://docs.php.net/move_uploaded_file says:
This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism)The zip archive file may be uploaded. But the files your script extracts from it are not.
And getting the stat entry doesn't actually extract the data to the local file system. For that you might be interested in ZipArchive::extractTo and/or ZipArchive::getStream


text:
Q: inserting/updating problem with foreach loop Problem is that when I run this loop it insert only a few rows from dataset. But there's many rows in dataset. Also in database has no rows. Why not my loop is working? I also want if data already have in database that will be updated with current dataset data.
  conn.Open();
  foreach (DataRow row in dataset.Tables[0].Rows)
  {

 string cardno = row["cardno"].ToString();
 string style = row["style"].ToString();
 string process = row["process"].ToString();
 int quantity = int.Parse(row["quantity"].ToString());
 float price = float.Parse(row["price"].ToString());
 float total_price = float.Parse(row["total_price"].ToString());
 string month = dateTimePicker2.Value.ToString("MMMM");
 int year = int.Parse(dateTimePicker2.Value.ToString("yyyy"));

 string queryInsert = "EXEC SP_AmountProcess '" + cardno + "','" + style + "','" + process + "','" + price + "','" + quantity + "','" + total_price + "','" + month + "','" + year + "','" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "';";

 SqlCommand cmd2 = new SqlCommand(queryInsert, conn);
 cmd2.ExecuteNonQuery();
 }
 dataGridView1.DataSource = null;
 //dataset.Reset();
 MessageBox.Show("Process Success");
 conn.Close();

 :::Store Procedure (SP_AmountProcess)::::
 CREATE procedure [dbo].[SP_AmountProcess]
  @cardno nvarchar(50),
  @style nvarchar(255),
  @process nvarchar(255),
  @rate float,
  @quantity int,
  @amount float,
  @month nvarchar(50),
  @year int,
  @process_time datetime

 AS

 IF NOT EXISTS (SELECT '#' FROM TBL_PROCESS_AMOUNT WHERE YEAR =@year AND MONTH=@month AND CARDNO= @cardno)
 BEGIN
 UPDATE [dbo].[TBL_PROCESS_AMOUNT]  SET [CARDNO] =@cardno,[STYLE]=@style,[PROCESS]=@process,[QUANTITY]=@quantity,[RATE]=@rate,[AMOUNT]=@amount,[MONTH]=@month,[YEAR]=@year,[PROCESS_TIME]=@process_time  WHERE YEAR =@year AND MONTH=@month AND CARDNO=@cardno ;
 END
 ELSE
 BEGIN
 INSERT INTO [dbo].[TBL_PROCESS_AMOUNT] ([CARDNO] ,[STYLE] ,[PROCESS] ,[QUANTITY] ,[RATE] ,[AMOUNT] ,[MONTH] ,[YEAR] ,[PROCESS_TIME]) VALUES (@cardno,@style,@process,@quantity,@rate,@amount,@month,@year,@process_time);
 END ;

A: change this approach in sp please check i think this might be helpful to u..
:::Store Procedure (SP_AmountProcess)::::
CREATE procedure [dbo].[SP_AmountProcess]
  @cardno nvarchar(50),
  @style nvarchar(255),
  @process nvarchar(255),
  @rate float,
  @quantity int,
  @amount float,
  @month nvarchar(50),
  @year int,
  @process_time datetime

 AS

 IF NOT EXISTS (SELECT '#' FROM TBL_PROCESS_AMOUNT WHERE YEAR =@year AND MONTH=@month AND CARDNO= @cardno)
 BEGIN
INSERT INTO [dbo].[TBL_PROCESS_AMOUNT] ([CARDNO] ,[STYLE] ,[PROCESS] ,[QUANTITY] ,[RATE] ,[AMOUNT] ,[MONTH] ,[YEAR] ,[PROCESS_TIME]) VALUES (@cardno,@style,@process,@quantity,@rate,@amount,@month,@year,@process_time);
 END
 ELSE
 BEGIN
 UPDATE [dbo].[TBL_PROCESS_AMOUNT]  SET [CARDNO] =@cardno,[STYLE]=@style,[PROCESS]=@process,[QUANTITY]=@quantity,[RATE]=@rate,[AMOUNT]=@amount,[MONTH]=@month,[YEAR]=@year,[PROCESS_TIME]=@process_time  WHERE YEAR =@year AND MONTH=@month AND CARDNO=@cardno ;

 END ;


text:
Q: Cron Expression time change for core_email_queue_send_all currently, core_email_queue_send_all cron expression is */1 * * * *
I want to change to */5 * * * *
How can I change the time?

A: Create your own extension, make it depend on Mage_Core and add this to your config.xml:
<?xml version="1.0"?>
<config>
    <!-- ... rest of your configuration ... -->
    <crontab>
        <jobs>
            <core_email_queue_send_all>
                <schedule><cron_expr>*/5 * * * *</cron_expr></schedule>
            </core_email_queue_send_all>
        </jobs>
    </crontab>
</config>

This way you avoid changing core files which is a no-go.
In case you wonder how to make your extension depending on another: here is an example for a fictive extension Mzeis_Test (code goes into app/etc/modules/Mzeis_Test.xml):
<?xml version="1.0"?>
<config>
    <modules>
        <Mzeis_Test>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Core />
            </depends>
        </Mzeis_Test>
    </modules>
</config>

A: Take a look at Sending Emails by Queue in Magento 1.9.1
Email cron setting is defined in

app/code/core/Mage/Core/etc/config.xml

<core_email_queue_send_all>
     <schedule><cron_expr>*/1 * * * *</cron_expr></schedule>
     <run><model>core/email_queue::send</model></run>
</core_email_queue_send_all>


text:
Q: Cloudfront distribution pointing to S3 bucket and ELB I am trying to configure my cloudfront distribution to route requests for mydomain.com to an S3 bucket and requests for mydomain.com/api/* to an ELB.
In route 53, I have dev.mydomain.com pointing to the cloudfront distribution with an alias record
Alias to cloudfront in route53
I have configured two origins in cloudfront - one to S3 and one to a publicly accessible ELB
Cloudfront origins setup
I have configured one (on top of default) behavior to route api/* requests to the ELB origin
Cloudfront behaviors setup
I have no issues with the S3 bucket. When I added the new behavior to route api/* requests to the ELB, I am receiving a 502 gateway error whenever I hit api/* routes.
When I make a request to the ELB from the origin I provided to Cloudfront, I am seeing the following response in Postman:
Error: Hostname/IP does not match certificate's altnames:
Host: mydomain-api-dev-env.us-east-1.elasticbeanstalk.com. is not in the cert's altnames: DNS:*.mydomain.com

This leads me to believe the 502 is because the ELB url is not included in mydomain.com's cert.
Assuming that this is my issue, how would I go about resolving this certificate issue since I don't own the elasticbeanstalk.com domain?

A: You have to associate your own domain with the load balancer and add proper SSL to it. Then in your CF distro, you are going to use your own ALB's domain, not the one provided by AWS.


text:
Q: Initialise empty data frame of same structure as another my R code reads data from a csv file. This data has headers and is stored in the data.frame mydata. The headers come from the csv file.
I would like to scale the data to within the [0,1] range and thus doing create another, empty, data.frame called scaled. I then loop through each column and divide by the maximum allowed value, I assume the minimum value is zero.
foreach(i = 1:ncol(mydata)) %do% {
    if (i == 1){
        maxval <-100  # Max depth = 100
    }
    else{
        maxval <- max(mydata[,i],na.rm=TRUE)
    }
    scaled[,i] <- mydata[,i] / maxval
}

How do I create the empty scaled data.frame with the same headers and structure as mydata?
Many thanks

A: Try following:
col1 <- 100:102
col2 <- 200:202
col3 <- 300:302

df <- cbind(col1,col2,col3)

firstrow = df[,1]/100 # first scaled by 100
scaled <- apply(df, 2, function(col) {col = col / max(col)})
scaled[,1]=firstrow

which gives
scaled

>   scaled
     col1      col2      col3
[1,] 1.00 0.9900990 0.9933775
[2,] 1.01 0.9950495 0.9966887
[3,] 1.02 1.0000000 1.0000000


text:
Q: How to skip phrase only if it exists I've been cutting my teeth on regex over the past couple of days, and have encountered an issue I cant seem to get past.
Lets assume the following 3 string values
AKA NAME:FOO
FOO
AKA NAME:

My goal is to capture the value of the string after AKA NAME: in a named match group, and if AKA NAME: is not present, capture the entire string in the match group.  If "AKA NAME:" IS present with no subsequent value, the regex expression should fail. I have developed the following expression
^(?:AKA NAME:)?\s*(?<VALUE>(.|\n|\r){1,225})$

This will correctly capture the word "FOO" in the first 2 strings above, however, in the third it captures "AKA NAME:" in the match group.  I figured putting ? after the non-capture group containing "AKA NAME:" would have caused the engine to skip this value, but it is not.
Can someone give me some guidance?

A: You can try with:
(?:AKA NAME:)*(.+)*

and check if $1 exist.
DEMO

A: Use a look behind assertion and then exclusion set for "AKA NAME:" only:
EDITTED:
(?<=AKA NAME:)\s?(\w+)|(?!AKA NAME:)^(\w+)
DEMO

A: I think you can use this regex:
"^(AKA NAME\s*:)?\s*(.*)$"gm

and get \2 for your result.
[Regex Demo]

A: ^(AKA NAME:)?(.*)$
\2 should contain what you're looking for.


text:
Q: Using AngularJS, how do I pass a controllers scope to a directives html template I'm having trouble accessing variables in my controllers scope inside a directives html template. I'm unsure how I should be passing it's scope to my html for display because I plan to use multiple copies of this same directive.
Currently no matter even if I remove the controller from the project, the value of the expression's in compound.html displays  "0".
How do I pass the controller "compoundController" to "compound.html" directive template?
Index
<compound objectid="{{controll.compoundId}}"></compound>

Directive
angular.module('ireg').directive('compound', function () {
    return {
        restrict:'E',
        scope: {
            objectid:'@objectid'
        },
        controller: 'compoundController',
        templateUrl: 'compound.html'
    }
});

Controller
angular.module('ireg').controller("compoundController",
  ['$scope','$routeParams','compoundService',
  function($scope,$attrs,compoundService ){
    var vm = this;
    vm.objectid = 2;
    vm.compoundData;

    vm.getPayload = function(scope, compoundController){
        var promise = compoundService.getData($scope.objectid);
        promise.then(
            function(payload) {
                vm.compoundData = payload.data[0];
            }
        );
    };

}]);

Service
angular.module('ireg').factory('compoundService', function($http) {
    return {
        getData: function(id) {
            var url = "http://localhost:8080/return-compound-data.php?compound=" +id;
            return $http.get(url);
        }
    }
});

Compound.html

 {{compound-controller.compound-data.project_name}}

                Compound Number

                {{controll.compound_number}}

A: Use the '='operator in the directive fore the scope mapping and leave the curly brackets in the html tag away.
<compound objectid="controll.compoundId"></compound>

 scope: {
        objectid:'=objectid'
    },

EDIT: At second sight there are plenty of bugs in your code. I didn't really understand how your code is supposed to work, but I made a working plunker. Hope this helps


text:
Q: Unable to use gdal_merge.py from Python Script If I execute this script in windows with x86 Python, works just fine. Also from command line directly.
import os, subprocess

gm = os.path.join('C:\\', 'Program Files (x86)', 'GDAL', 'gdal_merge.py')

merge_command = ["python", gm, "-o", "C:\\temp\\merge2.asc", "C:\\temp\\507.asc", "C:\\temp\\508.asc"]

subprocess.call(merge_command, shell=True)

However, in another machine, with windows and python x64, command line tool works, but the python script does not (it only differs from the previous one in the program files directory where gdal_merge.py is located).
import os, subprocess

gm = os.path.join('C:\\', 'Program Files', 'GDAL', 'gdal_merge.py')

merge_command = ["python", gm, "-o", "C:\\temp\\merge2.asc", "C:\\temp\\507.asc", "C:\\temp\\508.asc"]

subprocess.call(merge_command, shell=True)

What could be happening? Can anyone help?

A: I was able to make it work under python 32 bits, while in 64 bits, with their respective GDALs, it didnt work. May be some bug, I guess.


text:
Q: PHP Script ends before timeout without error I have a PHP Script, it needs execution time of at least 1000 seconds to complete.
It terminates after around 265 seconds each time with no errors. Since I am using loops I tested number of iterations and it is independent of that, further ruling out a possibility of occurrence of an error in the loop.
I have set max_execution_time to 10800 in php.ini, and also changing memory_limit doesn't affect the results.
Please help! I have scratched my head thoroughly!

A: give:
set_time_limit(0);

in the beginning of script. so that the code execution will not time out unless its completed.

A: Did you check your log file? If you get error 6 or segmentation fault. Then your script is is actually crashing php without showing any errors on the browser (if it is browser and not cli).
If you are using apache on unix, then you should find this log in /var/log/apache2/error.log.
Otherwise you can define the path of the log file in .htaccess by add this line:
php_value error_log "/path/to/somewhere/convenient/php_errors.log"

Change the path to somewhere where your httpd has write permission and where you have read permission.

A: This same error happened to me.  One of my PHP functions died without any errors sent to stderr, stdout, nor any other log file.
What happened was I was using a helper PHP script written by some other developer that was setting the memory limit to 512MB half way through the operation of my program.  The sub module poisoned the well by also setting the error log settings to silent at some point mid-way through the processing of my script.
You can prove if this is happening to you by printing out the php system settings available to your PHP script on EVERY iteration of the loop.  When the subscript did the dirty deed, the PHP engine throws a fit after the garbage collector runs at a random point in the future, then dies immediately without error.  It's a bug in the PHP garbage collector when sub modules mess with system settings as the garbage collector is doing its work.
Solution: Edit the php helper sub-modules, and make sure they don't tweak the system settings, as the garbage collector is doing its work.  The PHP interpreter will freak out and die without any errors or output at a random interval after the poisoning of the PHP system variables.

A: On PHP, the only way to hide errors from logs even when the display_errors and error_reporting are properly indicated is to use the Error Control Operators,
for example: the following code will raise a Fatal error but a "hidden" one, it will not appear neither on the logs or on the browser.
@echo "forgetting the last quote;

So set the display_errors value to On and the error_reporting depending on the PHP version you are using (see differences here), and check if you are using a "@" symbol on your code.


text:
Q: Can "anachronism" refer to things that have not been done in the proper order? I've looked in a few online dictionaries, and I don't see any definitions of "anachronism" that seem to encompass this situation. However, I feel like, etymologically, this term could be used in the following way:

Since some construction was begun before the designs were truly complete, I have added four days to our estimate to account for the inefficiencies caused by these various anachronisms.

It seems like it should be able to be used this way, but I'm not aware of any precedent. If this cannot be a usage of "anachronism," can you suggest a word that could be used in this context? I'm mainly looking for a noun that refers to actions that occurred in an order other than the proper/established order.

A: The OED carries only two senses of the word anachronism (see below), which involve the ascribing of something to a wrong time-period, such as when the clock strikes in Shakespeare's Julius Caesar. They didn't have striking clocks in ancient Rome, whilst they had them in Shakespeare's day.
I feel sure that the instance you quote is a malapropism. I would have said ...inefficiencies caused by these premature starts.

1.An error in computing time, or fixing dates; the erroneous reference of an event, circumstance, or custom to a wrong date. Said
  etymologically (like prochronism) of a date which is too early, but
  also used of too late a date, which has been distinguished as
  parachronism.

*Anything done or existing out of date; hence, anything which was proper to a former age, but is, or, if it existed, would be, out of
  harmony with the present; also called a practical anachronism. Also
  transf. of persons.

A: "out-of-sequence events" is as concise a substitute as I can come up with.
If you want to be crude and sarcastic, you could say "because we did it bass-ackwards"  (which is, if you didn't know, a euphemism for "ass-backwards"). But this refers to the  out-of-sequence-ness of the whole series of events, not to any one event.


text:
Q: How to extract selected attribute(s) from an NSArray of Core Data entity objects and form into a joint string? Normally, if I have an NSArray of just NSString's, I can use the NSArray's method:
- (NSString *)componentsJoinedByString:(NSString *)separator

to get a String (like "John,David,Peter"). However, if I have an NSArray of Core Data Entity objects and I just need to to get 1 attribute within (say, the "name" attribute only of each entity object), what is the easiest way to do this?
The Core Data entity object can have many attributes (name, phone, birthdate), but I just want a string like "John,David,Peter".

A: The following will do a fetch for only the name properties of the Person objects:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
request.propertiesToFetch = @[@"name"];
request.resultType = NSDictionaryResultType;
NSArray *array = [managedObjectContext executeFetchRequest:request error:nil];
NSString *names = [[array valueForKey:@"name"] componentsJoinedByString:@","];
NSLog(@"%@", names);

You need to set the resultType to NSDictionaryResultType otherwise it will ignore propertiesToFetch. The result from the fetch is an array of Dictionaries. Using valueForKey and componentsJoinedByString will create a single string out of all the names.

A: Your best option is the straightforward one of building up a NSMutableString by iterating over the items in you array and asking each one for its name to use in appendString:.  You could add a description method to the entity object and then use the method you mentioned but description is used for other things and would probably cause conflicts.

A: // Assuming you have the list of entities - NSArray *entityObjects
NSMutableString *nameAttributes = [[NSMutableString alloc] init];
for(int i = 0; i < [entityObjects count]-1; i++){
    [nameAttributes appendString:[NSString stringWithFormat:@"%@, ", [entityObjects objectAtIndex:i].name]];
}
    [nameAttributes appendString:[NSString stringWithFormat:@"%@", [entityObjects lastObject].name]];

A: If you have an NSArray *objects of Core Data objects, each of which has a name attribute, then you can use
NSArray *names = [objects valueForKey:@"name"];

to get a new array with all the names, which you can then concatenate with
NSString *allNames = [names componentsJoinedByString:@","];

A: You can simply do like that,
NSString *toCollectString =@"";

for(int k =0;k<self.arrayHoldingObjects.count;k++)
{
   ModelName *model = [self.arrayHoldingObjects objectAtIndex:k];
   NSString *str = model.name;
   toCollectString = [toCollectString stringByAppendingString:str];
}

You will get the names in toCollectString.


text:
Q: Pokemon Type Encounter Abilities I just heard Prof. Sycamore say that Static increases Electric type Encounters.
The only other ability like this was Magnet Pull for steel. I was unaware of Static though. Are there more type specific encounter abilities? and what are they?

A: Static and Magnet Pull are the only abilities that affect the chances of the type of wild Pokemon that can be encountered in the grass.
Other abilities such as Intimidate, Illuminate, and White Smoke also affect the encounter rate, but in a different way.


text: Q: Unix AIX version 7.1 and 7.2 I am working on Unix AIX, after searching I found log format for AIX v6.1 but didn't find logs for V7.1 and V7.2 Please let me know the link for log reference guide or syslog log messages because I need to understand the log fields.


text:
Q: Dynamic height of ImageView in scrollView I am trying to add 3-4 imageviews in a scroll view. Imageviews have dynamic heights. Height of first view have 70% of the screen and second and third have 30% height. I am using constraint layout and guidelines but the height is getting set according to the height of the scroll view but not according to the screen height. Is there a way to do this with constraint layout.

A: Have you tried doing it programmatically?
First, get the Screenheight for your device: How to determine the screen width in terms of dp or dip at runtime in Android?
Secondly, get your Imagview and set its height according to xx% of the determined screen height.
BR


text:
Q: How to connect to local react app from another PC from same network? How I can connect to my react-app from another PC, but we are in the same network? I just wan't to show the website which I'm making on my colleague PC, cause he is going to use it after it, how I can do it? Or is there any good way to deploy it locally somehow?

A: This solution work for me

Simply run HOST=0.0.0.0 npm run start.

get IP of your host PC by using ifconfig command

Afterwards open the url from another device on the network.

A: If you are using create-react-app, you could use HOST environment variable, like this:
$ HOST=0.0.0.0 react-scripts start instead of npm start
Then you can access the website on the other computer's IP like 192.x.x.x:3000
Other than this, you can use ngrok or localtunnel which will create your localhost:3000 public to other computers with a specific link.


text:
Q: rsync don t work as expected I have a script which download and compress a folder of a remote server (example: /home).
I m trying to make the "restore" script, but I have a strange behavior.
restore.sh:
($1 is IP adress, $2 is full path)
if [ $# -lt 2 ]
then
    echo "Error"
    exit 1
else
    D=$(mktemp -d)
    echo "From $D/$2"
    echo "To user@$1:/$2"
    tar xfz /backup/$1.tar.gz -C $D
    rsync -ncavzPe ssh --partial --delete $D/$2 user@$1:/$2
    rm -r $D
    exit 0
fi

Let s say the remote server is 127.0.0.12, and I want to restore /home.
$ssh 127.0.0.12
$password:
$ls /home/user
a b c x y z
$logout
$sh restore.sh 127.0.0.12 /home
From /tmp/tmp.R8iAewFEIR//home
To user@127.0.0.12://home
user@127.0.0.12's password:
sending incremental file list
home/
home/user/
home/user/1
home/user/2
home/user/.cache/
home/user/.cache/motd.legal-displayed

sent 351 bytes  received 40 bytes  46.00 bytes/sec
total size is 0  speedup is 0.00 (DRY RUN)
$

Isn t it supposed to delete a, b, c, x, y and z? Is it just because of the dry-run? Is it sending to another folder? I broke a server trying similar things yesterday and am too afraid to try it without the -n.

A: if [ $# -lt 2 ]
then
    echo "Error"
    exit 1
else
    D=$(mktemp -d)
    echo "From $D/$2"
    echo "To user@$1:/$2"
    tar xfz /backup/$1.tar.gz -C $D
    rsync -cavzPe ssh --partial --delete $D/$2/* user@$1:/$2/
    rm -r $D
    exit 0
fi

I was forgetting to enter in the folder in the source of rsync.


text:
Q: WP Multisite Subdirectory Custom Permalinks 404 I'm running a Multisite Subdirectory setup with the following structure.

*

*Example.com/ (main site)

*Example.com/en-us

I'm trying to achieve the following using a custom structure in the permalink settings:

*

*Example.com/blog/postname

*Example.com/en-us/blog/postname

It works for the main site however it gives a 404 on the /en-us/ site.
I'm also running the latest version.
I must be missing something? Any help is really appreciated.


text:
Q: NotifyAll not working This code is printing the Even/Odd numbers from two different threads. Here my programme stucks in the wait() and unable to wake up the slept thread using notifyAll().
Want to know, Why notifyAll is unable to wake up all the slept threads?
Need to know what I am doing wrong here.
class EvenOddThread {
  public static void main (String [] args) {
  Runnable runnEven = new ThreadPrint (true, 10);
  Runnable runnOdd = new ThreadPrint (false, 10);

  Thread t1 = new Thread (runnEven);
  Thread t2 = new Thread (runnOdd);

  t1.start ();
  t2.start ();
  }
}

class ThreadPrint implements Runnable {
  private boolean isEvenPrint = false;
  private int maxPoint = 0;
  ThreadPrint (boolean isEven, int max) {
    isEvenPrint = isEven;
    maxPoint = max;
  }

  @Override
  public void run () {
    Print p = new Print();
    if (isEvenPrint)
      p.printEven(maxPoint);
    else
      p.printOdd(maxPoint);
  }
}

class Print {

  public synchronized void printEven (int maxPoint) {
    int even = 0;
    while (even <= maxPoint) {
      System.out.println(even);
      even = even + 2;
      try {
      wait();
    }
    catch (Exception e) {
      System.out.println(e);
    }

    notifyAll();
    }
  }

  public synchronized void printOdd (int maxPoint) {
    int odd = 1;
    while (odd <= maxPoint) {

    System.out.println(odd);
    odd = odd + 2;
    try {
      wait();
    }
    catch (Exception e) {
      System.out.println(e);
    }

      notifyAll();
    }
  }
}

Thanks,
Shivam

A: Both threads enter wait after printing the first number. Since both threads are paused, neither thread can wake up the other.
In order to have a pair of threads alternate in this way, you could have separate conditions that control the progress of each thread. Each thread would unblock the other thread after completing its own unit of work. This can be done with a Semaphore, CyclicBarrier, or Phaser.

A: notifyAll() should notify all threads waiting on specific object, not all threads waiting anywhere. What you do, you make an instance of Print for each thread - and then use unqualified wait(), notifyAll() - meaning your threads communicate using variables local to each one of them.
So first you have to make them use same synchronization/signaling object(s).
Second, you need to provide some initial kick, at least. Be careful here, as you need to make this signal when you are sure at least one of them is already listening. Best case is to ensure both of them are listening, so you can escape zillions of possible race condition situations.
=rant=
Sun made big mess here, IMO, by hiding (mutex, condition, signal) triad from programmers - most probably in a bid to make multithreading simpler. They failed.
=/rant=

A: Seems like you just want two threads print odd/even number in a ping-pong style. Then you can make use of ReentrantLock. There are several of ways to do this.
I. Locks
public static final ReentrantLock lock = new ReentrantLock();
public static final int LIMIT = 50;
public static int toPrint = 0;

public static void main(String[] args){
    Thread t1 = new Thread(() -> {
        while (true){
            try {
                lock.lock();
                if(toPrint > LIMIT) break;
                else if(toPrint % 2 == 0) {
                    System.out.println(toPrint++);
                }
            } finally {
                lock.unlock();
            }
        }
    });

    Thread t2 = new Thread(() -> {
        while (true) {
            try {
                lock.lock();
                if (toPrint > LIMIT) break;
                else if (toPrint % 2 == 1) {
                    System.out.println(toPrint++);
                }
            } finally {
                lock.unlock();
            }
        }
    });
    t1.start();
    t2.start();
}

II. Volatile (fragile, but works)
public static final int LIMIT = 50;
public static volatile int toPrint = 0;

public static void main(String[] args){
    Thread t1 = new Thread(() -> {
        while (true){
            int cur = toPrint;
            if(cur > LIMIT) break;
            else if(cur % 2 == 0){
                System.out.println(cur);
                toPrint = cur + 1;
            }
        }
    });

    Thread t2 = new Thread(() -> {
        while (true) {
            int cur = toPrint;
            if(cur > LIMIT) break;
            else if(cur % 2 == 1){
                System.out.println(cur);
                toPrint = cur + 1;
            }
        }
    });
    t1.start();
    t2.start();
}

A: class EvenOddThread {
  public static void main (String [] args) {
  Runnable runnEven = new ThreadPrint (10);

  Thread t1 = new Thread (runnEven);
  Thread t2 = new Thread (runnEven);

  t1.start ();
  t2.start ();

  }
}

class ThreadPrint implements Runnable {
  private int maxPoint = 0;
  private int counter = 0;
  ThreadPrint (int max) {
    maxPoint = max;
  }

  @Override
  public void run () {
    while (counter <= maxPoint) {
      synchronized(this) {
        if (counter % 2 == 0) {

          System.out.println("By Thread" + Thread.currentThread().getName() +" :: "+ counter);
          counter ++;
          notify();
          try {
            wait();
          }
          catch (Exception e) {
            System.out.println(e);
          }
        }
        else if (counter % 2 != 0){
          System.out.println("By Thread" + Thread.currentThread().getName() +" :: "+ counter);
          counter ++;
          notify();
          try {
            wait();
          }
          catch (Exception e) {
            System.out.println(e);
          }
        }
      }
    }
  }
}

Thanks, guys for your answers but I took help from
here to figure out what should I do to correct my code.
Now, It's working the way I want. :)


text:
Q: Why does trying to divide these Dataframe columns cause a TypeError? I have this dataset, which comes from an excel report:
when I use the following code:
import pandas as pd

df = pd.read_excel(r'C:\Users\Charles\Documents\CLS\CLS Python\Dashboard.xlsx')

profit = df['Gross Margin']
sales = df['Total Billing Rate']
df['Net_%'] = profit / sales

it results in:
TypeError: unsupported operand type(s) for /: 'str' and 'int'

I have tried googling and using int and float but cannot get the code to even begin running.  What am I doing wrong?

A: The error means that when you are trying to perform / operation, left hand side of it is str, while right hand side is int, which is not allowed.
The problem is, df['Gross Margin'] seems to include some - entries, which are str, so whole column gets read as str. Probably what you should do is replace - with 0 or some other value like this:
df['Gross Margin'] = df['Gross Margin'].replace('-', 0)