text:
Q: PHP PREG_JIT_STACKLIMIT_ERROR - inefficient regex I am getting PREG_JIT_STACKLIMIT_ERROR error in preg_replace_callback() function when working with a bit longer string. Above 2000 characters it is not woking (above 2000 characters that match regex, not 2000 character string).
I've read already that it's caused by inefficient regex, but I can't make my regex simpler. Here's my regex:
/\{@([a-z0-9_]+)-((%?[a-z0-9_]+(:[a-z0-9_]+)*)+)\|(((?R)|.)*)@\}/Us
It should match strings like these:
1) {@if-statement|echo this|echo otherwise@}
2) {@if-statement:sub|echo this|echo otherwise@}
3) {@if-statement%statament2:sub|echo this@}
and also nested like this:
4) {@if-statement|echo this|
      {@if-statement2|echo this|echo otherwise@}
    @}
I've tried to simplify it to:
/\{@([a-z0-9_]+)-([a-z0-9_]+)\|(((?R)|.)*)@\}/Us
But it looks like error is caused by (((?R)|.)*) part. Any advice?
Code for testing:
$string = '{@if-is_not_logged_homepage|

                <button id="login">
Log in
</button>

                    <form method="post" action="{^login^}" id="form_login_global">

                            {!auth:login_email!}

<input type="text" name="form[login]">

                            {!auth:password!}

<input type="password" name="form[password]">

                            <input type="checkbox" name="remember" id="remember_me_check" checked>
                            Remember

                            <button class="btn btn_check">Log in</button>

                    </form>

                    Idea

                    FFa

                    Buss

                        Załóż konto
                        <form method="post" action="{^login^}" id="form_register_home">

                                {!auth:email!}

<input type="text" name="form2[email]">

                                {!auth:password!}

<input type="password" name="form2[password]">

                                    <input type="checkbox" name="form2[terms]" id="terms_check">
                                    Agree

                                <button class="btn btn_check">{!auth:register_btn!}</button>

                        </form>

@}';

$if_counter = 0;

$parsed_view = preg_replace_callback( '/\{@([a-z0-9_]+)-((%?[a-z0-9_]+(:[a-z0-9_]+)*)+)\|(((?R)|.)*)@\}/Us',
        function( $match ) use( &$if_counter ){
            return '<-{'. ( $if_counter ++ ) .'}->';
        }, $string );

var_dump($parsed_view); // NULL

A: What is PCRE JIT?

Just-in-time compiling is a heavyweight optimization that can greatly
  speed up pattern matching. However, it comes at the cost of extra
  processing before the match is performed. Therefore, it is of most
  benefit when the same pattern is going to be matched many times.

and how does it work basically?

PCRE (and JIT) is a recursive, depth-first engine, so it needs a stack
  where the local data of the current node is pushed before checking its
  child nodes... When the compiled JIT code runs, it needs a block of
  memory to use as a stack. By default, it uses 32K on the machine
  stack. However, some large or complicated patterns need more than
  this. The error PCRE_ERROR_JIT_STACKLIMIT is given when there is not
  enough stack.

By first quote you will understand JIT is an optional feature that is on by default in PHP [v7.*] PCRE. So you can easily turn it off: pcre.jit = 0 (it's not recommended though)
However, while receiving error code #6 of preg_* functions it means possibly JIT hits the stack size limit.
Since capturing groups consume more memory than non-capturing groups (even more memory is intended to be used as per type of quantifier(s) of clusters):

*

*Capturing group OP_CBRA (pcre_jit_compile.c:#1138) - (real memory is more than this):

case OP_CBRA:
case OP_SCBRA:
bracketlen = 1 + LINK_SIZE + IMM2_SIZE;
break;

*Non-capturing group OP_BRA (pcre_jit_compile.c:#1134) - (real
memory is more than this):

case OP_BRA:
bracketlen = 1 + LINK_SIZE;
break;

Therefore changing capturing groups to non-capturing groups in your own RegEx makes it to give proper output (which I don't know exactly how much memory is saved by that)
But it seems you need capturing groups and they are necessary. Then you should re-write your RegEx for the sake of performance. Backtracking is almost everything in a RegEx that should be considered.
Update #1
Solution:
(?(DEFINE)
  (?<recurs>
    (?! {@|@} ) [^|] [^{@|\\]* ( \\.[^{@|\\]* )* | (?R)
  )
)
{@
(?<If> \w+)-
(?<Condition> (%?\w++ (:\w+)*)* )
(?<True> [|] [^{@|]*+ (?&recurs)* )
(?<False> [|] (?&recurs)* )?
\s*@}

Live demo
PHP code (watch backslash escaping):
preg_match_all('/(?(DEFINE)
  (?<recurs>
    (?! {@|@} ) [^|] [^{@|\\\\]* ( \\\\.[^{@|\\\\]* )* | (?R)
  )
)
{@
(?<If> \w+ )-
(?<Condition> (%?\w++ (:\w+)*)* )
(?<True> [|] [^{@|]*+ (?&recurs)* )
(?<False> [|] (?&recurs)* )?
\s*@}/x', $string, $matches);

This is your own RegEx that is optimized in a way to have least backtracking steps. So whatever was supposed to be matched by your own one is matched by this too.
RegEx without following nested if blocks:
{@
(?<If> \w+)-
(?<Condition> (%?\w++ (:\w+)*)* )
(?<True> [|] [^|\\]* (?: \\.[^|\\]* )* )
(?<False> [|] \X*)?
@}

Live demo
Most of quantifiers are written possessively (avoids backtrack) by appending + to them.

A: The problem as you can see is that your pattern is inefficient. The main reasons are:

*

*You use this kind of subpatterns: (a+)+b that is the best way for a catastrophic backtracking

*You use this kind of subpatterns too: (a|b)+ that may be a good design except for a backtracking regex engine like pcre

*You use the U modifier for an unknown reason that makes all your quantifiers non-greedy and generates a lot of useless tests

As an aside, there are too much useless capture groups that consumes memory for nothing. When you don't need a capture group, don't write it. If you really need to group elements, use a non-capturing group, but don't use non-capturing groups to make a pattern "more readable" (there are other ways to do that like named groups, free-spacing and comments).

If I understand well, you are trying to build a regex for preg_replace_callback to deal with the control statement of your template system.
Since these control statements can be nested and a regex engine can't match several times the same substring, you have to choose between several strategies:

*

*You can write a recursive pattern to describe a conditional statement that eventually contains other conditional statements.

*You can write a pattern that matches only the innermost conditional statements. (In other words it forbids nested conditional statements.)
In the two cases, you need to parse the string several times until there's nothing to replace. (Note that you can also use a recursive function with the first strategy, but it makes things more complicated.)
Let's see the second way:
$pattern = '~
{@ (?<cond> \w+ ) - (?<stat> \w+ (?: % \w+ )* ) (?: : (? \w+ ) )? \|

# a "THEN" part that doesn\'t have nested conditional statements
(?<then> [^{|@]*+ (?: { (?!@) [^{|@]* | @ (?!}) [^{|@]* )*+ )

# optional "ELSE" part (the content is similar to the "THEN" part)
(?: \| (?<else> \g<then> ) )? (*SKIP) @}~x';

$parsed_view = $string;
$count = 0;

do {
    $parsed_view = preg_replace_callback($pattern, function ($m) {
        // do what you need here. The different captures can be
        // easily accessed with their names: $m['cond'], $m['stat']...
        // as defined in the pattern.
        return $result;
    }, $parsed_view, -1, $count);
} while ($count);

pattern demo
As you can see the problem of nested statements is solved with the do..while loop and the count parameter of preg_replace_callback to see if something is replaced.
This code isn't tested, but I'm sure you can complete it and eventually adapt it to your needs.

As an aside, there's a lot of template engines that already exists (and PHP is already a template engine). You can use them and avoid to create your own syntax. You can also take a look at their codes.


text:
Q: Mensuration and similarity Cone P has a volume of 108cm^3
Calculate the volume of 2nd come , Q , whose radius is double that of cone P and its height is one-third that of cone p
Here's my working ....
$$V_Q=\frac13 \pi (2r)^2 \cdot  \frac{h}{3}\\
                = \frac{4}{9} \pi r^2 h\\
                = \frac{1}{3}\pi r^2 h \cdot \frac{4}{3}$$
I don't understand why must I do this.

A: Hint:
In your equation, you already have $$V_Q = \left(\frac{1}{3}\pi r^2h\right) \cdot 43$$
You also know what the volume of cone $P$ is, and you know that it is equal to $\frac{1}{3}\pi r^2 h$

A: It is not clear what is being asked here.
Everything you have done so far is correct, just express the volume of the new cone in terms of that of the old cone and substitute the volume of the old cone to get the answer.
That is nothing but four thirds of the volume of the cone P.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to correctly backpropagate in a fully connected Neural Network? I'm trying to write a neural network from scratch and It seems that I have misunderstood something or done something wrong because my model is not performing as well as it should. Can someone help me see the error of my ways?
These are the activation functions and loss function that I use.
def mse(y: np.ndarray,  y_pred: np.ndarray, derivative=False) -> np.ndarray:
    """Returns the mean square error between to vectors"""
    return  2*np.subtract(y_pred, y) if derivative else np.square(np.subtract(y_pred, y))

def sigmoid(x: np.ndarray, derivative=False) -> np.ndarray:
    return  sigmoid(x) * (1. - sigmoid(x)) if derivative else 1. / (1. + np.exp(-x))

def relu(x: np.ndarray, derivative=False) -> np.ndarray:
    if ~derivative:
        return np.maximum(0, x)
    x[x<=0] = 0
    x[x>0] = 1
    return x

And this is my implementation of a Neural Network that creates a fully connected network with layers_size that is something like this [input, x,x,x, output ]
@dataclass
class NN(Model):
    layer_sizes: Tuple[int]
    activation_functions: List[Callable]

    def random_initializers(self) -> None:
        """Make a random start for weights and bias"""

        self.num_layers = len(self.layer_sizes)-1

        self.parameters = {f"W{i+1}": np.random.randn(self.layer_sizes[i+1], self.layer_sizes[i]) * np.sqrt(1. / self.layer_sizes[i+1])
                       for i in range(self.num_layers)}

    def forward(self, X: np.ndarray) -> np.ndarray:
        self.parameters['A0'] = X

        for i in range(self.num_layers):
            self.parameters[f"Z{i+1}"] = np.dot(self.parameters[f"W{i+1}"], self.parameters[f"A{i}"])
            self.parameters[f"A{i+1}"] = self.activation_functions[i](self.parameters[f"Z{i+1}"])

        return self.parameters[f"A{i+1}"]

    def backward(self, loss_prime):
        update = {}

        # Calculate W update
        error = self.activation_functions[self.num_layers - 1](loss_prime, derivative=True)
        for i in range(self.num_layers)[:0:-1]:
            update[f"W{i+1}"] = np.dot(error, self.parameters[f"A{i+1}"])
            error = np.multiply( np.dot(self.parameters[f"W{i+1}"].T, error), self.activation_functions[i-1](self.parameters[f"Z{i}"], derivative=True))

        return update

    def update_weights(self, update: dict[str,np.ndarray]) -> None:
        """Updates the weights of the model after one step or epoch."""
        for key, value in update.items():
            for w_arr in self.parameters[key]:
                w_arr -= self.learning_rate * value

    def fit(self, X: np.ndarray, y: np.ndarray ) -> None:
        """trains the model using the vector features X and labels Y."""
        self.hist={"loss":[0], "frame":[]}
        # random start
        self.random_initializers()
        for epoch in tqdm(range(self.epochs)):
            loss= 0
            # for each sample in training set feed-forward and backpropagate
            for i, x in enumerate(X):
                # feed-forward
                pred = self.forward(x)
                # add loss
                loss+= self.loss(pred, y[i])
                error = self.loss(pred, y[i], derivative=True)
                # compute gradient update
                update = self.backward(error)
                # update weights
                self.update_weights(update)

The loss changes in the first couple of epochs but then stops changing after that.


text:
Q: Why ground is positive on this part? I'm using a powered device controller (PD is what they call a device that receives power over Ethernet), and its pins and way of connecting things is really weird. This part, LTC4265, takes in power over Ethernet (POE), negotiates how much power POE can provide to it, and then outputs that power.
What I'm really curious about is why its GND pin is called "input voltage positive rail" and its Vout is "output voltage negative rail". If you look at the data sheet at http://cds.linear.com/docs/Datasheet/4265fa.pdf, page 2 will show a typical application circuit. Also, pin definitions are on page 5. Anyway, it shows Vout outputting negative voltage. Essentially, the positive POE voltage is connected to GND pin, which is then connected to ground, and the negative POE voltage is connected to Vout. Why do they do things this way?
Thanks in advance for the help!

A: Because in telecommunications (phone central offices), things run off of -48 V. So there are plenty of parts and equipment built that way.
This link explains why. It has to do with electroplating.


text:
Q: Como estilizar uma tabela com primeira coluna na horizontal e header fixo na vertical Estou com um problema há dois dias e não consigo resolvê-lo. Preciso criar uma tabela onde a primeira coluna seja fixa na horizontal, mas permita movimenta-la verticalmente, e o header seja fixo na vertical mas permita movimentação horizontal. Preciso fazer isso para que o conteúdo da tabela possa ser movimentado horizontal através de um scroll na horizontal e para que o header sempre seja mostrado.
Já li algumas questões e a grande maioria utiliza position:fixed no entanto isso não funciona para mim. Preciso fazer isso apenas com CSS e HTML, sem JavaScript. Existe alguma forma de fazer isso?

.table .thead-white th {
  color: #fff;
  background-color: #4a5b7eff;
  border-color: #4a5b7eff;
  padding: 0.1rem .75rem 0.1rem .75rem;
  cursor: pointer;
}

.table .thead-white th:hover {
  background-color: #465577ff;
  color: #fff;
}

.table .thead-cinza th {
  color: #fff;
  background-color: #52658cff;
}

.table .thead-white th i {
  padding: 0.8rem 0.5rem 0.7rem 0.5rem;
  line-height: 1.5rem;
  font-size: 1.3rem;
}

.barras {
  color: #fff !important;
  background-color: #4a5b7eff !important;
  cursor: default !important;
  padding: 1rem !important;
}

.table {
  text-align: center;
}

.table-striped tbody tr:nth-of-type(odd) {
  background-color: #dadcddff !important;
}

.table td,
.table th {
  border-right: 0.5px solid #52658cff;
  border-left: 0.5px solid #52658cff;
  border-top: 0 !important;
  color: #52658cff;
  padding: 1.1rem 0 1.1rem 0;
  width: 20rem;
  min-width: 20rem;
}

.table thead th {
  border-bottom: 0 !important;
}

tbody tr th {
  color: #52658cff;
}

.container_info {
  width: 100%;
  background-color: #e6e7e8ff;
  margin: 0 !important;
  padding: 0 !important;
  margin-top: 0.2rem;
  word-wrap: break-word;
}

span {
  font-size: 16px !important;
  margin-bottom: 1rem;
}

.container_info .row {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

.border-azul {
  border-color: #52658cff !important;
}

.badge-danger {
  color: #fff;
  background-color: #c23531ff !important;
}

.badge-success {
  color: #373435ff !important;
  background-color: #91c7aeff !important;
}

.headcol {
  position: sticky !important;
  left: 0 !important;
  background-color: #dadcddff;
  z-index: 99 !important;
  border-right: 0.5px solid #52658cff !important;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

          Cód. Barras

          Grupo Comercial
          Cliente 1
          Cliente 2
          Cliente 3
          Cliente 4
          Cliente 5
          Cliente 6
          Cliente 7
          Cliente 8
          Cliente 9
          Cliente 10
          Cliente 11
          Cliente 12
          Cliente 13
          Cliente 14
          Cliente 15

          Drops

            66%

Concorrente 1

R$ 3,79

Concorrente 2

Concorrente 3

R$ 4,99

            100%

Concorrente 1

R$ 3,79

Concorrente 2

R$ 3,79

Concorrente 3

R$ 4,99

            0%

Concorrente 1

Concorrente 2

Concorrente 3

            0%

Concorrente 1

Concorrente 2

            50%

Concorrente 1

R$ 3,79

Concorrente 2

            66%

Concorrente 1

R$ 3,79

Concorrente 2

Concorrente 3

R$ 4,99

            0%

Concorrente 1

Concorrente 2

            0%

Concorrente 1

Concorrente 2

            66%

Concorrente 1

R$ 3,79

Concorrente 2

Concorrente 3

R$ 4,99

            66%

Concorrente 1

R$ 3,79

Concorrente 2

Concorrente 3

R$ 4,99

            66%

Concorrente 1

R$ 3,79

Concorrente 2

Concorrente 3

R$ 4,99

            66%

Concorrente 1

R$ 3,79

Concorrente 2

Concorrente 3

R$ 4,99

            0%

Concorrente 1

Concorrente 2

            0%

Concorrente 1

Concorrente 2

            0%

Concorrente 1

Concorrente 2


text:
Q: Child object 'str' object is not callable, unable to rectify from other similar posts I am attempting to create a child object from random variables within a list. I have included all code that I have tried. Googling the errors brings up many posts and solutions, none of which seem to be exactly parallel enough for me to utilize. Thanks for your time and consideration.
import random

class Monster:

    def __init__(self, name, level):
        self.name = name
        self.level = level

class Dragon(Monster):

    def breathe_fire(self):
        print("The Dragon breathes fire!")

class Skeleton(Monster):

    def strikes(self):
        print("The Skeleton strikes with its sword!")

MONSTERS = ["Skeleton", "Dragon"]
monster_type = random.choice(MONSTERS)
monster_level = 1
monster_stats = [monster_type, monster_level]
print(monster_stats)
# create object from child class and pass stats
#monster = random.choice(MONSTERS(*monster_stats)) <--'list' object is not callable
#monster = Dragon(*monster_stats) # <-- works, but is useless for my purposes
#monster = monster_type(*monster_stats)  <---  'str' object is not callable

A: You have quotes ("") around Skeleton and Dragon - making them strings
Remove the quotes to reference the class rather than the string
Note: this will not fix the error in this line: monster = random.choice(MONSTERS(*monster_stats))
To fix this, use: monster = random.choice(MONSTERS)(*monster_stats)

A: Try this:
import random

class Monster:
    name = None

    def __init__(self, level):
        self.level = level

class Dragon(Monster):
    name = "Dragon"

    def attack(self):
        print("The Dragon breathes fire!")

class Skeleton(Monster):
    name = "Skeleton"

    def attack(self):
        print("The Skeleton strikes with its sword!")

MONSTERS = [Skeleton, Dragon]

monster_cls = random.choice(MONSTERS)
monster_level = 1
monster_stats = [monster_level]  # maybe you have other stats too

monster = monster_cls(*monster_stats)

The main fix is to have a list of classes instead of strings: MONSTERS = [Skeleton, Dragon]
A couple of other suggestions:

*

*if the name is the type of the monster (and not an individual name like Smaug) then it doesn't need to be an arg to __init__

*you might find the rest of the code easier if all the monsters have a common method for making an attack, otherwise when you make a battle you will have to have lots of code like "if monster is a Dragon then breathe_fire else if monster is a Skeleton then strike"


text:
Q: Converting blob data into CSV file I am trying to convert blob data from ms-sql to csv file using python. Blob data itself has many other commas in it and that does not let me convert it properly.
Is there a way to escape commas in blob, but properly upload it to another db when needed.
I am doing this for a GAE project and downloading tables from a ms-sql db to upload GAE datastore. Since it supports xml as well, should I start using it?
--Update--
Converted sql row, which holds pdf file looks like this:
ObjectID,FileData,Extension,
2846748,"%PDF-1.3
%
3 0 obj
<<
/Producer (PDF-XChange 3.60.0102 \(Windows\))
/Author (HA)
/Creator (ABBYY PDF Transformer 2.0)
/CreationDate (D:20130612093531+02'00')
>>
endobj
5 0 obj
<<
/Type /XObject
/Subtype /Image
/Width 150
/Height 112
/BitsPerComponent 8
/ColorSpace /DeviceRGB
/Length 3682
/Filter [/DCTDecode]
>>
stream
ÿØÿàJFIFÿÛC

%# , #&')*)-0-(0%()(ÿÛC...goes and goes on...", .PDF

In first try uploading this to datastore I got null char error and then removed them using
temp = str(rows[i][j]).replace("\x00", "")

Then I added quote marks as @Greg offered
if "," in temp:
    temp = "\"" + temp + "\""

After this changes I tried to upload it to data store and got string is longer than 500 char error. I had export_transform: transform.blob_to_file('Filename', 'AttachmentBlobs') line in bulkloader.yaml for FileData attribute, but it was seen as string.
And I discovered blob data should be uploaded to GAE blob datastore, I am not doing these transactions form a html form, but form python scripts, so now going to work on uploading that data to blob datastore.

A: Normally, if a CSV field has commas in it, the field would be enclosed in "s. The python csv package deals with such things, so if you're just splitting strings on ",", then switching to a csv.reader would probably work.
Otherwise, I think you need to edit your question to include an example of your input and the code you have that's not doing what you want.


text:
Q: How to deploy files in JAR? I have some method which read some data from the file (actually, it is the bus time).
public void readData(String number) throws IOException{
    InputStream fis;
    BufferedReader br;
    String line;
    fis = new FileInputStream("n" + number);
    br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
    while ((line = br.readLine()) != null) {
        list.add(new Time(line));
    }
    br.close();
}

And I have my files into project with needed info.
But! (I am writing in Intellij IDEA, but deploying in Eclipse)
When I deploy project, my program doesn't see the files.
What should I do?
Is thinking about
fis = RaspFrame.class.getClassLoader().getResourceAsStream("n" + number);
Right?

A:
"Is thinking about:

    fis = RaspFrame.class.getClassLoader().getResourceAsStream("n" + number);

correct?"

Yes.  That is (roughly speaking) the way to open a stream to a resource held in a JAR file on your classpath.
(Your existing code is actually reading the files from the file system.  It is presumably working from within your IDE because copies of the files are held in the IDE project directory, and the IDE is making the project directory is the "current directory" when you run the program.)


text:
Q: How to change camera frame rate to create slow motion or time lapse video in Android I have a class setup that now gives me a preview on my surface view and allows me to record a video file. I would like to increase the FPS to create a slow motion video and decrease the FPS to create a time lapse video. I have tried using recorder.setVideoFrameRate() and ensured I call it in the right sequence but I just keep getting illegal state exceptions when ever I try to alter any settings on the recording.
Can anyone point me to a tutorial or an example on how to effectively control the settings for the camera?
Cheers.


text:
Q: foreign key problem in mysql hay i have two tables i want to relate them with a foreign key i made it locally and works fine using innoDB but when i upload it to my server database the type of table automatically change to myISAM. when i checked the type again i found that there is no innoDB engine type instead MyISAM, MEMORY, BLACKHOLE, EXAMPLE, ARCHIVE, CSV,FEDERATED, MRG_MYISAM were there. please help which storage engine out of these can support foreign key.

A: None of them. Only innodb supports FKs.


text:
Q: String with different operators in JavaScript match I have the following JS var:
var tokens = str.match(/\[|\]|< number|\)|and |(?:(?!and )[^\[\]])+/g);

tokens is later used in a switch() statement.
This matches occurrences of:

*

*[

*]

*< number

*)

*and (with a space at the end)

However, I would like to precede number not only by < but possibly also by other operators. The following are needed:

*

*>

*>=

*<

*<=
So match also has to look for < number, <= number, > number, >= number. Is there a quick and easy way to do this by, for instance, defining a wildcard/variable for the possible operators?

A: Use the expression [<>]=? number.
[<>] means either < or >.
=? is an optional = sign.


text:
Q: Obtaining JSON data with foreach in PHP A site contains monthly data in a JSON format. This can be queried like so:
http://www.example.com?startdate=1-1-1985&enddate=31-1-1985

I want to be able to run a script that will obtain the specific data I am looking for, starting from today's month, then work backward until null data is returned. Each month's value needs to add up. So far, this is what I've got:
//Build base URL:
$userid=$_GET['userid'];
$startdate=/*Beginning of today's month*/;
$enddate=/*End of today's month*/;
$url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;

//Set JSON variables:
$get=file_get_contents($url);
$json=json_decode($get);

//Set loop variables:
$value=0;
$month=0;

/*For each month from today backwards{
    $number=$json->integer;
    if($number!=null){
        $value=$value+$number;
        $month=$month+1;
    }else{
        break;
    }
}
echo $value;
echo $month;
*/

The part I'm having problems with is the beginning of the fourth part. How do I run a loop that starts with the range of today's month, obtain $number, then repeat with the previous month, until it reaches a month that returns null?

A: You could use the DateTime object and it's associated methods ( specifically sub in this case ) to count backwards by subtracting 1month at a time. An array stores the months/dates and the url is constructed using the variable counter $i
Initially this has a maximum backwards range of 20years ( which I guessed would be more than enough ) but it's easy to change.
$df='Y-m-d';
$userid=$_GET['userid'];

$timezone=new DateTimeZone('Europe/London');
$interval=new DateInterval('P1M');

$ts=date( $df, strtotime( date('Y-m-1') ) );
$tf=date( $df, strtotime( date('Y-m-1'). ' - 20 years') );

$start=new DateTime( $ts, $timezone );
$end=new DateTime( $tf, $timezone );

$dates=array();
$i=0;

while( $start->sub( $interval ) > $end ){
    $dates[]=$start->format( $df );
    if( $i > 1 ){

        $startdate=$dates[ $i - 1 ];
        $enddate=$dates[ $i ];
        $url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;
        echo $url,'<br />';

        /* uncomment when happy with mechanism */
        /*

        $data=file_get_contents( $url );
        if( $data ) ) {
            $json=json_decode( $data );
            #process.....
            break;
        }
        */
    }
    $i++;
}

A snippet of the output
http://www.example.com?userid=bobodaclown&startdate=2017-10-01&enddate=2017-09-01
http://www.example.com?userid=bobodaclown&startdate=2017-09-01&enddate=2017-08-01
http://www.example.com?userid=bobodaclown&startdate=2017-08-01&enddate=2017-07-01
http://www.example.com?userid=bobodaclown&startdate=2017-07-01&enddate=2017-06-01
http://www.example.com?userid=bobodaclown&startdate=2017-06-01&enddate=2017-05-01
http://www.example.com?userid=bobodaclown&startdate=2017-05-01&enddate=2017-04-01
http://www.example.com?userid=bobodaclown&startdate=2017-04-01&enddate=2017-03-01

A: By using strtotime() and mktime() functions you can while loop until you get Null results. The below code will print 5 urls for 5 months. Change while condition accordingly.
// define $i
$i=0;
$userid = '343';//$_GET['userid'];  //dont forget to replace with userid
do{
    $timestring =  strtotime("now -$i month");
    //get Month
    $month = date('m',$timestring);
    //get Year
    $year = date('Y',$timestring);
    // First date Month and Year
    $startdate = date('d-m-Y', mktime(0, 0, 0, $month, 1, $year));
    // Last date Month and Year
    $enddate = date('d-m-Y', mktime(0, 0, 0, $month+1, 0,$year));

    $url='http://www.example.com?userid='.$userid.'&startdate='.$startdate.'&enddate='.$enddate;
    // commenting your code
    //Set JSON variables:
    //$get=file_get_contents($url);
    //$json=json_decode($get);
    // $number=$json->integer;
    echo $url;
    echo "\n";
    $i++;
}while ($i!=5); // change while condition according to your requirement. while ($number!=null)

Out Put:
http://www.example.com?userid=343&startdate=01-12-2017&enddate=31-12-2017
http://www.example.com?userid=343&startdate=01-11-2017&enddate=30-11-2017
http://www.example.com?userid=343&startdate=01-10-2017&enddate=31-10-2017
http://www.example.com?userid=343&startdate=01-09-2017&enddate=30-09-2017
http://www.example.com?userid=343&startdate=01-08-2017&enddate=31-08-2017


text:
Q: Call operator (&) runs command in new window when omitting ".cmd" if a file with the same name exists in the same directory If I omit the suffix ".cmd" in a command, it gets opened in a new window. Why is this? What triggers the new window to open?
In Powershell 5 and Powershell Core 7, the first of the following causes a new window to open, while the other three show the outputs in the same window:

*

*& 'C:\some_path\node_modules\.bin\ava' 'help'

*& '.\node_modules\.bin\ava' 'help' (used cd C:\some_path before)

*& 'C:\some_path\node_modules\.bin\ava.cmd' 'help'

*& 'C:\some_path\node_modules\.bin\ava.ps1' 'help'
Meanwhile in cmd all three programs show their output in the same window, no new window gets opened at all:

*

*C:\some_path\node_modules\.bin\ava help

*.\node_modules\.bin\ava help (used cd C:\some_path before)

*C:\some_path\.bin\ava help

I used the help command only as example, finally I like to use ava debug --serial someFile.js

SW-Versions:

*

*Windows: Windows 10, Version 2004 (Build 19041.388)

*Node: v12.18.3

*AVA: 3.11.0

There are three relevant files located in the .bin directory:
ava.cmd
@ECHO off
SETLOCAL
CALL :find_dp0

IF EXIST "%dp0%\node.exe" (
  SET "_prog=%dp0%\node.exe"
) ELSE (
  SET "_prog=node"
  SET PATHEXT=%PATHEXT:;.JS;=;%
)

"%_prog%"  "%dp0%\..\ava\cli.js" %*
ENDLOCAL
EXIT /b %errorlevel%
:find_dp0
SET dp0=%~dp0
EXIT /b

ava.ps1
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent

$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
  # Fix case when both the Windows and Linux builds of Node
  # are installed in the same directory
  $exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
  & "$basedir/node$exe"  "$basedir/../ava/cli.js" $args
  $ret=$LASTEXITCODE
} else {
  & "node$exe"  "$basedir/../ava/cli.js" $args
  $ret=$LASTEXITCODE
}
exit $ret

ava
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")

case `uname` in
    *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
esac

if [ -x "$basedir/node" ]; then
  "$basedir/node"  "$basedir/../ava/cli.js" "$@"
  ret=$?
else
  node  "$basedir/../ava/cli.js" "$@"
  ret=$?
fi
exit $ret

Since the call is done by visual studio code debugging an AVA script with the proposed configuration, my influence on the used commands is limited.

$env:PATHEXT equals .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.CPL

If I rename the file ava to ava_2, no new window gets opened anymore. If a create an empty file named ava, the command & 'C:\some_path\node_modules\.bin\ava' 'help' opens a new window again.

A: Why not use Start-Process instead, so you can control whether it opens a new window or not?
Start-Process -FilePath 'C:\some_path\node_modules\.bin\ava' -ArgumentList 'help' -NoNewWindow -Wait

A: Add .cmd to pathext would fix it if it were missing.  Ava is a package for node.js javascript runtime.
$env:PATHEXT += ';.CMD'
C:\Windows\System32\node_modules\.bin\ava.cmd help

Adding it to the path would fix it:
$env:path += ';C:\Windows\System32\node_modules\.bin'
ava help

This same folder that has ava.cmd, has a file named ava that's a shell script, and a file named ava.ps1 that's a powershell script.  For some reason hiding or renaming the "ava" shell script fixes it as well.
Referring to the current directory also works:
.\Windows\System32\node_modules\.bin\ava help

Minimal reproducible example:
'' | set-content hi
'echo cmd:hi' | set-content hi.cmd
& $pwd\hi  # pops open another window for a split second


text:
Q: How do I toggle the other menu items off? macOS - Xamarin Forms (Visual Studio for Mac) Come up with this so far:
    public void appearanceAuto(NSObject sender)
    {
        ((NSMenuItem)sender).State = NSCellStateValue.On;

        Application.Current.UserAppTheme = OSAppTheme.Unspecified;
        Preferences.Set("AppTheme", (int)OSAppTheme.Unspecified, "Global");
        window.Appearance = null;
    }

    [Action("appearanceLight:")]
    public void appearanceLight(NSObject sender)
    {
        ((NSMenuItem)sender).State = NSCellStateValue.On;

        Application.Current.UserAppTheme = OSAppTheme.Light;
        window.Appearance = NSAppearance.GetAppearance(NSAppearance.NameAqua);
        Preferences.Set("AppTheme", (int)OSAppTheme.Light, "Global");
    }

    [Action("appearanceDark:")]
    public void appearanceDark(NSObject sender)
    {
        ((NSMenuItem)sender).State = NSCellStateValue.On;

        Application.Current.UserAppTheme = OSAppTheme.Dark;
        window.Appearance = NSAppearance.GetAppearance(NSAppearance.NameDarkAqua);
        Preferences.Set("AppTheme", (int)OSAppTheme.Dark, "Global");
    }

It sets the check item correctly but I don't know get to get at the other two menu items to turn theirs off?

I managed to consolidate the actions into one like this:
    [Action("appearanceChanged:")]
    public void appearanceChanged(NSObject sender)
    {
        var menuItem = (NSMenuItem)sender;
        if (menuItem == null)
            return;

        NSAppearance appearance = null;
        OSAppTheme theme = OSAppTheme.Unspecified;

        var identifier = menuItem.Identifier;
        if (identifier == "appearanceDark")
        {
            appearance = NSAppearance.GetAppearance(NSAppearance.NameDarkAqua);
            theme = OSAppTheme.Dark;
        }
        else if (identifier == "appearanceLight")
        {
            appearance = NSAppearance.GetAppearance(NSAppearance.NameAqua);
            theme = OSAppTheme.Light;
        }

        window.Appearance = appearance;
        Application.Current.UserAppTheme = theme;
        Preferences.Set("AppTheme", (int)theme, "Global");

        menuItem.State = NSCellStateValue.On;
    }
}

This article helped me.
This answer to a similar question on StackOverflow shows how to do it by having a IBOutlet and using that to loop the menu items. But I am not doing this in Xcode. I am doing this in Visual Studio for Mac and I don't know how to do that bit.
I see this tutorial explain about using IBAction but it refers to connection into ViewController.h and my MacOS project does not have such a file.
For some reason, when I try to CONTROL + Drag it only wants to make a IBAction and not a IBOutlet:

A: I have now found the answer to this issue. Firstly, I did not have to actually set the State inside my action handler. It could be done inside the validateMenuItem event handler instead (which I was lacking).
I had to open my menu in Xcode first and assign the Tag property for each menu item. Then I was able to do the following:
[Export("validateMenuItem:")]
public bool validateMenuItem(NSMenuItem menuItem)
{
    switch(menuItem.Tag)
    {
        case 1000:
            if (Application.Current.UserAppTheme == OSAppTheme.Unspecified)
                menuItem.State = NSCellStateValue.On;
            else
                menuItem.State = NSCellStateValue.Off;
            break;
        case 1001:
            if (Application.Current.UserAppTheme == OSAppTheme.Light)
                menuItem.State = NSCellStateValue.On;
            else
                menuItem.State = NSCellStateValue.Off;
            break;
        case 1002:
            if (Application.Current.UserAppTheme == OSAppTheme.Dark)
                menuItem.State = NSCellStateValue.On;
            else
                menuItem.State = NSCellStateValue.Off;
            break;
    }

    return true;
}

Works well!


text:
Q: Set environment variables from a file in gcloud run deploy command I am trying to deploy cloud-run service which demands the passing of around 20 variables. As a result by gcloud command becomes too long and I'd like to store these variables in a file and refer it in the --set-env-vars flag.
current command:
gcloud run deploy gh-gardenia-bp3-carepackage-service-anand --image  gcr.io/$Project_ID/$Environment/$Cloud_function_name:$Cloud_function_version --set-env-vars=KEY1=VALUE1,KEY2=VALUE2,KEY3=VALUE3,KEY4=VALUE4...

gcloud run deploy gh-gardenia-bp3-carepackage-service-anand --image  gcr.io/$Project_ID/$Environment/$Cloud_function_name:$Cloud_function_version --set-env-vars="file"

We are flexible in terms of the format of the file (Json/XML/Txt etc.)

A: You can use the preview run services replace command:
gcloud beta run services replace myservice.yaml

The YAML file has the format:
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: SERVICE
spec:
  template:
    spec:
      containers:
      - image: IMAGE
      - env:
        - name: KEY-1
          value: VALUE-1
        - name: KEY-N
          value: VALUE-N


text:
Q: Scala map on iterator does not produce side effects Why is it that,
scala> List(1,2,3,4).iterator.map((x: Int) => println(x))

does not print out
1
2
3
4

while
List(1,2,3,4).map((x: Int) => println(x))
List(1,2,3,4).foreach((x: Int) => println(x))
List(1,2,3,4).iterator.foreach((x: Int) => println(x))

all do?
In other words, why is it that a map on a iterator that maps type T to Unit and has side effects unable to show those side effects?
Edit:
Also why does the following invocation of lazyMap actually computes the new iterator (provide the complete new iterator) from beginning to end if iterator is lazy?
def lazyMap[T, U](coll: Iterable[T], f: T => U) = new Iterable[U] {
  def iterator = coll.iterator map f
}

scala> lazyMap(List(1,2,3,4), (x: Int) => x + 1)
res4: java.lang.Object with Iterable[Int] = (2, 3, 4, 5)

A: Cause map on iterator is lazy and you need some strictness:
scala> List(1,2,3,4).iterator.map((x: Int) => println(x))
res0: Iterator[Unit] = non-empty iterator

// nothing actually happened yet, just remember to do this printing things

scala> res0.toList
1
2
3
4
res1: List[Unit] = List((), (), (), ())

When you doing foreach on iterator it is quite obvious that you're doing side effects, so lazyness will be undesired. I wouldn't said so about map.
UPD
As for your edit: the reason for such behaviour, is that there is implicit call of toString for statement result which in turn stricts the iterator -- try this code on your own:
scala> { lazyMap(List(1,2,3,4), {(x: Int) => println(x); x + 1}); 1 }

and you'll see that function f is never called

A: The point of an Iterator is laziness.  In other words, when you create an Iterator, it will not evaluate anything until you go to read the data.  Here's what that looks like:
scala> val itr = List(1,2,3).iterator
itr: Iterator[Int] = non-empty iterator

Ok, we've got an iterator now.  But it hasn't actually looked at the list yet.
scala> val mappedItr = itr.map((x: Int) => println(x))
mappedItr: Iterator[Unit] = non-empty iterator

Now we have a new Iterator.  This one will, when data is accessed, apply the function that has been mapped.  But we still haven't actually looked at the original list.
scala> mappedItr.next
1

This is the first time we have accessed data, so it is the first time that the Iterator has looked into the list.  We called next, so we got the first element.  Since our iterator has a map queued up, it applies the mapped function when we access that element.  So we see the result of the function applied to the next item.
We can do it again to get the next element:
scala> mappedItr.next
2

And, again, it evaluates the function only when it needs to, in order to give us the final result.


text:
Q: What is behind the mysterious door? I saw this question about how to open it, and I wondered what is inside it.
Has anyone seen this door? What exactly could be behind the mysterious door?!
I tried opening it but couldn't. Even tried lighting up the mushrooms with different sequences.
 Perhaps it is supposed to open in the second play through?
Or maybe, you need to buy the key from those 2 girls [Bratty and Catty] who were selling trash?

Seeing the tag of Undertale, fills me with determination.

A: Behind the Mysterious Door lies a joke "developer" room. It contains only a few objects, each of which can be interacted with to show some text. The Undertale Wikia has a list of all of the text that the room contains.
Here's what the room looks like:


text:
Q: How do I automatically activate an item in the OS X Services Menu I need to have a service I created enabled by default in the services menu.
I've created a service for my OS X app (running on Snow Leopard). I've configured the Info.plist like so:
<key>NSServices</key>
<array>
    <dict>
        <key>NSSendTypes</key>
        <array>
            <string>NSStringPboardType</string>
        </array>
        <key>NSMessage</key>
        <string>dropService</string>
        <key>NSMenuItem</key>
        <dict>
            <key>default</key>
            <string>Drop Service</string>
        </dict>
        <key>NSPortName</key>
        <string>MyApp</string>
    </dict>
</array>

So far so good, I follow the other steps outlined in: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/SysServices/introduction.html and everything seems to be working correctly.
I ran the command:
/System/Library/CoreServices/pbs

And now my service shows up under "System Preferences -> Keyboard -> Keyboard Shortcuts -> Services". So the system knows about it. But it won't show up in the services menu unless I manually activate it.
When I try to debug the service, I get this message:
/Applications/TextEdit.app/Contents/MacOS/TextEdit -NSDebugServices com.myapp.MyApp
Drop Service (com.myapp.MyApp) is disabled in the services menu and disabled in the context menu, by the standard Services policy.

I have no idea what the "standard Services policy" is and I can't find any reference to this error on the Apple developer site.
I would think that automatically enabling service items is impossible but I've confirmed that certain apps do it (like Things from Cultured Code) so I know it can be done.
Any ideas?

A: I don't know any public API to do that, but I found a way to work around it. The list of all the activated services is kept in
~/Library/Preferences/pbs.plist

You just need to add an entry and reset pbs. I'm using the following code snippet:
NSString*pbsPlistPath=[@"~/Library/Preferences/pbs.plist" stringByExpandingTildeInPath];
NSMutableDictionary*dict=[NSPropertyListSerialization
                                  propertyListFromData:[NSData dataWithContentsOfFile:pbsPlistPath]
                                    mutabilityOption:NSPropertyListMutableContainers
                                                format:NULL
                                      errorDescription:NULL];
NSMutableDictionary*status=[dict objectForKey:@"NSServicesStatus"];
if(!status){
    status=[NSMutableDictionary dictionary];
    [dict setObject:status forKey:@"NSServicesStatus"];
}
if(status){
    NSMutableDictionary*m=[NSMutableDictionary dictionary];
    [m setObject:[NSNumber numberWithBool:YES] forKey:@"enabled_context_menu"];
    [m setObject:[NSNumber numberWithBool:YES] forKey:@"enabled_services_menu"];
    [status setObject:m
               forKey:@"com.my.app - Drop Service - dropService"];
}
NSData* data=[NSPropertyListSerialization dataWithPropertyList:dict
                                                        format:NSPropertyListBinaryFormat_v1_0
                                                       options:0
                                                         error:NULL];
[data writeToFile:pbsPlistPath atomically:YES];
system("/System/Library/CoreServices/pbs -flush");
system("/System/Library/CoreServices/pbs -flush_userdefs");

A: The correct way to get your service to be enabled by default without hacking any system plists is to edit your own plist. Specifically, add the NSRequiredContext key in each service dictionary. This information comes from this mailing list post (taken from this answer on a similar question).
As for the value you need to provide for that key, the documentation will fill you in.

A: Just add a NSRequiredContext key with a blank dictionary as its object in your Info.plist. Here's how it should look:
<key>NSRequiredContext</key>
<dict>
</dict>


text:
Q: window.scrollTo not scrolling to provided id I am working on a single document file. I want to scroll to the desired section with id="projectpage" when an anchor with id="about" is clicked.
About Me

I tried using
$('a#about').click(function(){
    $(window).scrollTo(0, document.getElementById('projectpage').offsetTop);

  });

or even
$('#about').click(function(){
    $(window).scrollTo(0, document.getElementById('projectpage').offsetTop);

  });

but nothing works.
When I click on the anchor with id="about", it just redirects me to the index.html(the main HTML with all document) file itself rather than going to the offsetTop of id="projectpage".

A: You need to prevent the default behavior of an anchor.... Using .preventDefault()
And replace $(window) for just window... You don't need jQuery to lookup for the window when you wish to apply a vanilla JS method on it.

$('#about').click(function(e) {
  e.preventDefault()
  window.scrollTo(0, document.getElementById('aboutpage').offsetTop);
});
section{
  height: 200px;
  border-top: 2px solid grey;
}

About Me

...

...

...

About

...

...

A: I made a small example for you using scrollIntoView(). Also, take into account the need for event.preventDefault() to disable the default ability to click on the tag a.
In addition, scrollIntoView() has a parameter with an animation transition effect:
behavior: "smooth"

Note: since you are using jquery, I see no point in casting to an element like:
document.getElementById('aboutpage')

Appeal, as in jquery:
$("#aboutpage")[0]

$('a#about').click(function(event){
  event.preventDefault();
    $("#aboutpage")[0].scrollIntoView({
    behavior: "smooth"
  });
});
#first {
  width: 100%;
  height: 1000px;
  background-color: green;
}

#aboutpage {
  width: 100%;
  height: 1000px;
  background-color: blue;
}

About Me


text:
Q: listView don't update I have a problem, please help.  I want ListView to update (refresh) each time I click on the radio button.  Any useful help will be welcomed.
public class thirdActivity  extends Activity {

SQLiteDatabase db;
String date, gorivo, kolicina, cijena, litra, ID, gor;
Integer index=0;
RadioButton vozilo1, vozilo2, vozilo3;
int vozilo= 1;

public ArrayList<HashMap<String, String>> list;
ListViewAdapter adapter=new ListViewAdapter(this, list);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.third);

     ListView listView=(ListView)findViewById(R.id.listView1);
    adapter.notifyDataSetChanged();
    populateList();
    adapter.notifyDataSetChanged();
     ListViewAdapter adapter=new ListViewAdapter(this, list);
    listView.setAdapter(adapter);

    vozilo1 = (RadioButton)findViewById(R.id.radio000);
    vozilo2    = (RadioButton)findViewById(R.id.radio100);
    vozilo3    = (RadioButton)findViewById(R.id.radio200);

    OnClickListener listenervoz1 = new OnClickListener() {
        @Override
        public void onClick(View v) {
            vozilo=1;
            populateList();
        }

    };

    OnClickListener listenervoz2 = new OnClickListener() {
        @Override
        public void onClick(View v) {
            vozilo=2;
            populateList();

        }
        };

    OnClickListener listenervoz3 = new OnClickListener() {
        @Override
        public void onClick(View v) {
            vozilo=3;

            populateList();

        }};

    Button btnvoz1 = (Button) findViewById(R.id.radio000);
    btnvoz1.setOnClickListener(listenervoz1);
    Button btnvoz2 = (Button) findViewById(R.id.radio100);
    btnvoz2.setOnClickListener(listenervoz2);
    Button btnvoz3 = (Button) findViewById(R.id.radio200);
    btnvoz3.setOnClickListener(listenervoz3);

}
public void populateList() {
    // TODO Auto-generated method stub

    Integer i = null;
    TextView ukupnoCijena = (TextView)findViewById(R.id.ukupno_cijena);
    TextView ukupnoKolicina = (TextView)findViewById(R.id.ukupnoKolicina);
    TextView tridesetCijena = (TextView)findViewById(R.id.tridesetCijena);
    TextView tridesetKolicina = (TextView)findViewById(R.id.tridesetkol);
    //TextView sveUkupnoC= (TextView)findViewById(R.id.ukupno_cijena0);
    //TextView sveUkupnoK = (TextView)findViewById(R.id.ukupnoKolicina0);
    list=new ArrayList<HashMap<String,String>>();

    HashMap<String,String> temp=new HashMap<String, String>();
        temp.put(FIRST_COLUMN, "ID");
        temp.put(SECOND_COLUMN, "DATUM");
        temp.put(THIRD_COLUMN, "KOLICINA l");
        temp.put(FOURTH_COLUMN, "CIJENA Kn");
        temp.put(FIFTH_COLUMN, "Go");
    list.add(temp);

    db=openOrCreateDatabase("PotrosnjaDB", Context.MODE_PRIVATE, null);
    db.execSQL("CREATE TABLE IF NOT EXISTS potrosnjaDB (" +
            "ID         INTEGER PRIMARY KEY, " +
            "datum      DATE ," +
            "gorivo     VARCHAR(10) ,"+
            "kolicina   NUMBER ," +
            "cijena     DECIMAL(4,2) ," +
            "vozilo     NUMBER)"
            );

    Cursor c=db.rawQuery("SELECT * FROM potrosnjaDB where vozilo="+vozilo+"  ;", null);

    if(c.moveToFirst())
    {

        for ( i= c.getCount(); i>0; i--) {
            ID=c.getString(0);
            date= c.getString(1).replace("-", ".");
            gor =c.getString(2).substring(0, 2);
            cijena = c.getString(3);
            kolicina = c.getString(4);

            HashMap<String, String> temp1 = new HashMap<String, String>();
            temp1.put(FIRST_COLUMN, ID); //
            temp1.put(SECOND_COLUMN, date); //
            temp1.put(THIRD_COLUMN,  cijena);
            temp1.put(FOURTH_COLUMN, kolicina); //
            temp1.put(FIFTH_COLUMN, gor);
            list.add(temp1);
            c.moveToNext();

        }
    }
    else {
        Toast.makeText(thirdActivity.this, "Podaci nisu uneseni", Toast.LENGTH_SHORT).show();

        }

    c=db.rawQuery("SELECT SUM(cijena) FROM potrosnjaDB where vozilo="+vozilo+" ;", null);
        if(c.moveToFirst())
        {
            ukupnoCijena.setText(c.getString(0)+ " kn.");
        }
        else {showMessage("Greška", "Podaci nisu pronađeni");}

    c=db.rawQuery("SELECT SUM(kolicina) FROM potrosnjaDB where vozilo="+vozilo+"   ;", null);
        if(c.moveToFirst())
        {
            ukupnoKolicina.setText(c.getString(0)+ " lit.");
        }
        else {showMessage("Greška", "Podaci nisu pronađeni");}

        c=db.rawQuery("SELECT SUM(cijena) FROM potrosnjaDB where datum >= date('now', '-30 days') AND vozilo="+vozilo+"   ;", null);
        if(c.moveToFirst())
        {
            tridesetCijena.setText(c.getString(0)+ " kn.");
        }
        else {showMessage("Greška", "Podaci nisu pronađeni");}

        c=db.rawQuery("SELECT SUM(kolicina) FROM potrosnjaDB where datum >= date('now', '-30 days') AND vozilo="+vozilo+"   ;", null);
        if(c.moveToFirst())
        {
            tridesetKolicina.setText(c.getString(0)+ " lit.");
        }
        else {showMessage("Greška", "Podaci nisu pronađeni");}

        /*c=db.rawQuery("SELECT SUM(cijena) FROM potrosnjaDB ;", null);
        if(c.moveToFirst())
        {
            sveUkupnoC.setText(c.getString(0)+ " kn.");
        }
        else {showMessage("Greška", "Podaci nisu pronađeni");}

    c=db.rawQuery("SELECT SUM(kolicina) FROM potrosnjaDB ;", null);
        if(c.moveToFirst())
        {
            sveUkupnoK.setText(c.getString(0)+ " lit.");
        }
        else {showMessage("Greška", "Podaci nisu pronađeni");} */

}
private void showMessage(String title, String message) {
    Builder builder=new Builder(this);
    builder.setCancelable(true);
    builder.setPositiveButton("OK", null);
    builder.setTitle(title);
    builder.setMessage(message);
    builder.show();
    }

}
If I click radio 1 I want ListView to show data from SQLite for vozilo1, rado2 for vozilo2, etc.

A: Make sure you call adapter.notifyDataSetChanged() every time you change the Model for your ListView.
I notice that in your OnClickListener, you change your vozilo variable (which really should be passed into your populateList() method as an argument, by the way), call populateList(), but never let your adapter know that your list changed.


text:
Q: How can I quantify the business value of normalization? My company is developing an internal application with a SQL server database which was started earlier by another developer.
Now I am Looking at the model,the developer has stopped at 1NF. I proposed going all the way to 3NF but my manager said it would add no business value.
Is there a way to quantify the business values of normalization, specifically going to 3NF?

A: The actual costs are difficult to quantify as they are often diffused.  Often they appear as slower transactions.  For a system used rarely, this may not be significant.  For a system used for an hour a day, that is taking twice as long as is required the cost would be about 100 hrs a year per person using the system.  Slower transactions may also have higher error rates due to users being distracted or interrupted while processing transactions.
Failure to normalize the data often results in in consistent data through-out the application.  Updates to some records may be missed, or incorrect records may be updated.  Inconsistent data can have serious business and/or legal implications.   Such problems can reduce the reputation of the business.
Updates to non-normalized records may take many times longer than with normalized data. (That is time someone is waiting for the system rather than moving to the next task.).  In some cases the update will fail, or lock the table for excessively long periods of time.


text:
Q: Nginx proxy image/javascript hosted externally I'm trying to proxy a javascript and image hosted by a external party with nginx
I'm running my site on https and they only offer the files through http, I have already had contact with them about this but the can't give timeline when they are gone resolve this.
So no I'm trying to proxy_pass those files in my nginx config I have the following location blocks
location /blogcounter/image {
        #rewrite ^/blogcounter(.*) /$1 break;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_pass http://widget.external-domain.tld/$uri$is_args?$args;
}
location /blogcounter.js {
        #rewrite ^/blogcounter(.*) /$1 break;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_pass http://widget.external-domain.tld/$uri$is_args?$args;
}

The widget I want on my page is.

');
</script>

So I want the client request going through my server which has https which makes my server request the file from the external server and servers it back to the client. Currently this is not working yet, is see the request in the access log which also shows a status code 200 but neither the image or javascript file are send back. Can anyone help with what I'm doing wrong?

A: Mapping a client URL like:
https://my-domain.tld/blogcounter/image?image=red_s&blog_id=random_id

to an upstream URL like:
http://widget.external-domain.tld/blogcounter/image?image=red_s&blog_id=random_id

requires no magic URI transformations, so the simplest proxy_pass form is all that is required:
location /blogcounter {
    proxy_pass http://widget.external-domain.tld;
    proxy_set_header ...;
    ...
}

Notice that there are no trailing / as the request URI is passed upstream unmodified.
I have set the location to /blogcounter as I do not know what other locations (if any) your server hosts.
You do not mention the upstream URL for blogcounter.js. The above location block will also map:
https://my-domain.tld/blogcounter.js

to the upstream URL:
http://widget.external-domain.tld/blogcounter.js

See this document for details.


text:
Q: Regular expression handle multiple matches like one, how to fix? I have a regex, and a string that includes some matches for this regex. My regex handle all this matches like it is only one big match (of course I don't want such behaviour), let me show you an example:
My test string (sorry for scribble, but this doesn't matter):
sdfsd -dsf- sdfsdfssdfsfdsfsd -sdfsdf-

my regex in js code:
view.replace(/(\-(.+)\-)/g, '$1');

my result:
sdfsd-dsf- sdfsdfssdfsfdsfsd -sdfsdf-

As you can see each of this strings in the "-" must be enclosed in span, but there is only one span. How I can fix this? (honestly I don't want change my (.+) regex part, which I think might be a problem, but if there is no other way to do this, let me know).
In other words, result must be:
sdfsd-dsf- sdfsdfssdfsfdsfsd -sdfsdf-

Feel free to ask me in the comments, and thanks for your help.

A:
honestly I don't want change my (.+) regex part, which I think might be a problem

Why not, it is actually the source of the problem, you can try the following regex which would work:
/(\-([^-]+)\-)/g

and if you think that dashes - can appear between - and - themselves then you can use the less efficient:
/(\-(.+?)\-)/g

+? causes a lazy match, or in other words after matching the initial -, then .+? matches a single character then it moves control to the following - which tries to match a dash, if it couldn't then .+? reads (consumes) another character from the input and so on until the following - is able to match.

A: You can try:
view.replace(/-([^-]+)-/g, '$1');


text:
Q: != giving incorrect response all. Apologies in advance, because I'm sure this is a facepalm-worthy obvious solution. I'm brand new to python and coding in general, and I'm still muddling around. My problem is this: I'm working on a function with nested loops, where three simple addition questions must be answered. The function looks like this:
def themath():
    rounds = 0
    while rounds <= 3:
        num1 = random.randint(10,99)
        num2 = random.randint(10,99)
        sum = num1 + num2
        print(f"{num1} + {num2} = ")
        print(sum)
        answer = input()

        while answer != sum:
            print("Incorrect. Please try again.")
            answer = input()
        else:
            rounds = rounds + 1
    else:
        print("Good morning! :)")

My problem is that, no matter what I input, even if its the correct answer to the math problem, I keep getting "Incorrect, please try again," and cannot exit the loop. I apologize again if this is a silly question or I haven't explained it well. Thank you in advance for any input!


text:
Q: Can't compare two ranges Can't figure out why std::ranges::equal in the code below does not compile:
struct A { int x; };

using Map = std::map<int, A>;

void some_func()
{
    std::vector<A> v{ {0}, {1}, {2}, {3} };

    auto v2m = [](const A& a) { return std::pair<int, A>(a.x, a); };

    const auto actual = std::ranges::single_view(v[2]) | std::views::transform(v2m);

    Map expected{ {v[2].x, v[2]} };

    //Does not compile.
    bool equals = std::ranges::equal(actual, expected);
}

The compiler errors with MSVC are:
error C2672: 'operator __surrogate_func': no matching overloaded function found
error C7602: 'std::ranges::_Equal_fn::operator ()': the associated constraints are not satisfied

A: Problem 1: A isn't comparable, so you cannot compare it using std::ranges::equal with the default predicate. Solution:
struct A {
    int x;
    friend auto operator<=>(const A&, const A&) = default;
};

Problem 2: Your transform function produces std::pair<int, A> which doesn't match with the elements of map which are std::pair<const int, A>. Solution: use std::pair<const int, A> (or just Map::value_type so that there's less room for mistakes).


text:
Q: Сьезжает моб верстка при открытии на айфонах Есть одностраничник, сьезжает верстка именно при открытии на айфонах(через дев тулз всё ок), на любых браузерах. В чем может быть причина? Один блок просто идет под другой

html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}

body, .content, .success, .ask {
    display: flex;
    flex-flow: column nowrap;
}

#header {
    height: 100px;
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-around;
    align-items: center;
    padding: 5px;
    position: absolute;
}

#header img {
    width: 30%;
}

.success {
    color: black;
    justify-content: center;
    align-items: center;
    min-height: 400px;
    background: url(https://severenity.com/rujjje/img/Bg.jpg);
    background-position: center;
}

.success .title {
    font-size: 55px;
}

.success .description {
    font-size: 18px;
}

.success .description .yellow{
    color: #f1c40f;
}

.success .submit {
    width: 220px;
    height: 65px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 7px;
    background: #f1c40f;
    text-decoration: none;
    color: #3d3d3d;
    font-size: 15px;
    font-weight: 900;
    text-transform: uppercase;
    position: absolute;
    margin-top: 200px;
}

.submit:hover {
    background: #fff200;
    border-bottom: 2px solid #7f8c8d;
    cursor: pointer;
}

.ask {
    padding-top: 50px;
}

.askTitle {
    font-size: 23px;
    color: #3d3d3d;
    text-align: center;
}

.questions {
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;
}
.question {
    display: flex;
    flex-flow: column nowrap;
    justify-content: space-around;
    align-items: center;
    min-height: 120px;
    box-shadow: 0 0 10px rgba(0,0,0,0.2);
    padding: 30px;
    margin: 20px;
}

.question .questTitle, .questionDescription{
    text-align: center;
}

.question .num{
    width: 40px;
    height: 40px;
    color: black;
    background: #34495e;
    border: none;
    border-radius: 2px;
    position: absolute;
    margin-left: -110px;
}

@media only screen and (min-device-width: 290px) and (max-device-width: 500px) {
    #header {
        flex-flow: column nowrap;
        padding: 10px;
    }

    .headerTitle {
        margin: 7px;
        font-size: 1em;
    }

    #header img {
        width:55%;
    }

    .content .success {
        padding: 15px;
    }

    .content .success .title{
        font-size: 35px;
    }

    .content .success .description{
        font-size: 15px;
    }

    .success .submit {
        width: 190px;
        height: 55px;
        margin-top: 213px;
    }

    .askTitle {
        margin: 0;
    }

    .questions {
        flex-flow: column nowrap;
        padding: 15px;
    }

    .questions1, .questions2 {
        padding: 0;
        margin-top: 0;
        margin-bottom: 0;
    }

    .questions .num {
        margin-left: -154px;
    }
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
    <title>Document</title>

Lorem ipsum dolor, sit amet consectetur

Lorem, ipsum dolor.

Lorem ipsum dolor sit.Lorem, ipsum dolor.

Lorem ipsum dolor sit amet.

            Lorem

Lorem, ipsum.

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet consectetur adipisicing elit.

                        <button disabled class="num">1</button>

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet consectetur adipisicing elit.

                        <button disabled class="num">2</button>

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet consectetur adipisicing elit.

                        <button disabled class="num">3</button>

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet consectetur adipisicing elit.

                        <button disabled class="num">4</button>

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet consectetur adipisicing elit.

                        <button disabled class="num">5</button>

Lorem ipsum dolor sit amet.

Lorem ipsum dolor sit amet consectetur adipisicing elit.

                        <button disabled class="num">6</button>

Поехавшая верстка выглядит вот так:

A: Возможно трабла в том, что у тебя у .success указан min-height и flex одновременно. Попробуй завернуть .success в обертку и ей задай min-height, а у самого .success удали.


text:
Q: PHP apache error: Access denied for user 'jobportal'@'localhost' (using password: YES) I tried to access the index page of my website: index.php, via this link:
localhost:80/web/index.php. This brought me to a blank page on chrome that shows the error result:

Warning: Declaration of SugarDateTime::setTime($hour, $minute, $sec = 0) should be compatible with DateTime::setTime($hour, $minute, $second = NULL, $microseconds = NULL) in C:\xampp\htdocs\uat\include\SugarDateTime.php on line 692
  Could not connect to the database. Please refer to simplecrm.log for details.

I checked the "simplecrm.log" file, it showed me the error:

Could not connect to DB server localhost as jobportal. port : Access denied for user 'jobportal'@'localhost' (using password: YES)

I have scoured the internet for answers, especially:

*

*https://www.ostraining.com/blog/coding/error-1045-phpmyadmin/

*MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

*#1045 - Access denied for user 'root'@'localhost' (using password: YES)
But these answers only show the root user, while my issue refers to the "jobportal" user. I did try the solutions given but I still can't solve this issue.
Here is the code in index.php:
include ('include/MVC/preDispatch.php');
$startTime = microtime(true);
require_once('include/entry.php');
ob_start();
require_once('include/MVC/SugarApp.php');
$app = new SugarApp();
$app->startSession();
$app->execute();

A: If you set your database password then write like
$db_name = 'dbname';
$db_pass = 'yourPasss';

Else
$db_name = 'dbname';
$db_pass = ''; //empty

A: Try granting all privilages on the database to user jobportal using the following SQL, like so:
GRANT ALL PRIVILEGES ON your_database.* TO 'jobportal'@'localhost'
IDENTIFIED BY 'your_db_password';

After executing the above, execute the following:
FLUSH PRIVILEGES;


text:
Q: Find the expected value of $|H-T|$
Bob repeatedly throws a (fair) coin. For each throw, there is a $4\%$ chance that Bob decides to stop throwing the coin. He records the number of heads H and the number of tails T before he stops flipping the coin (if he decides to stop flipping the coin on a toss, he doesn't record anything for that toss). Find the expected value of $|H-T|$.

Let $p=1/25$.
I'm not sure whether the expected value of $|H-T|$ after n+1 throws given that it is nonzero after n throws equals the expected value after n throws. Note that the probability that $H-T < 0$ after n flips and the (n+1)st throw is an H equals the probability that $H-T > 0$ and the (n+1)st throw is a T (we can simply replace H's with T's in the corresponding sequences). Also, the probability $H-T < 0$ and the (n+1)st throw is a T equals the probability that $H-T>0$ and the (n+1)st throw is an H. Also, the probability $H-T < 0$ after n throws and the (n+1)st throw is an H equals the probability $H-T<0$ after n throws and the (n+1)st throw is a T. Let $I$ be an indicator random variable equal to $-1$ if $H-T < 0$ and the (n+1)st throw is an H or $H-T > 0$ and the (n+1)st throw is a T and $1$ if $H-T > 0$ and the (n+1)st throw is a T or $H-T < 0$ and the $(n+1)$st throw is an H. I'm not sure about how to proceed from here.
Alternatively, I think it should be possible to find the expected value of $|H-T|$ assuming $n$ tosses were performed directly from the definition, and then compute the desired expected value using the fact that the probability n successful flips were performed (not including the last flip) is $p(1-p)^n$. Now if i is nonzero, then the probability that $|H-T| = i$ equals the probability $H-T = i$ plus the probability $H-T = -i$. In the first case, since $H+T = n, H = \dfrac{n+i}2, T = \dfrac{n-i}2$ while in the second case, $H = \dfrac{n-i}2, T = \dfrac{n+i}2.$ And clearly the probability $|H-T| = 0$ is ${n\choose n/2}$ assuming n is even; if not the probability is zero. So the expected value of $|H-T|$ is just $1/2^n \sum_{i=1}^n 2 {n\choose \dfrac{n+i}2} i,$ where ${n\choose k} := 0$ if $n$ is an integer but k is not. In particular, if $n$ is odd, then the expected value is $\dfrac{1}{2^n} \sum_{i=0}^{(n-1)/2} 2{n\choose \dfrac{n+2i+1}2} (2i+1)$ while if n is even, the expected value is $\dfrac{1}{2^n} \sum_{i=1}^{n/2} 2{n\choose \dfrac{n+2i}2}(2i).$

Question: how can I simplify the latter expression or come up with the expected value using a different method?

By computing a few small values, it seems that the last expression actually equals $\prod_{i=1}^{\lfloor (n-1)/2\rfloor } \dfrac{2i+1}{2i}$. Let us call the latter assumption assumption (*). I'm not sure how to prove this, so I'll just assume this is true from now on.
We have
\begin{align} E(|H-T|) &= p\sum_{n=1}^\infty (1-p)^n \prod_{i=1}^{\lfloor (n-1)/2\rfloor } (2k+1)/(2k))\\
&= p(\sum_{m=0}^\infty (1-p)^{2m+1} \prod_{k=1}^m \dfrac{2k+1}{2k} + \sum_{m=0}^\infty (1-p)^{2m+2} \prod_{k=1}^m \dfrac{2k+1}{2k})
\\
&= p(1-p)(2-p) \sum_{m=0}^\infty (1-p)^{2m} \prod_{k=1}^m \dfrac{2k+1}{2k} \\
&= p(1-p)(2-p) (1-(1-p)^2)^{-3/2}\\
&= (1-p)/\sqrt{p(2-p)},
\end{align}
and so plugging in $p=1/25$ gives that the expected value is $24/7$ under assumption (*).

A: I'm not simplifying OP's expression. Here is an alternative approach to showing that $$E_{n} |H-T| = \prod_{i=1}^{\lfloor (n-1)/2\rfloor } \dfrac{2i+1}{2i}.$$
We'd prove this by induction.
Let $A_n$ denote the act of throwing $n$ coins. We say that $ a_n = k$ if $|H-T| = k$.
Let $ E_n$ denote the expected value of $|H-T|$ when throwing $n$ coins.
For $A_n$, first consider the cases where $ |H - T | =k > 0$.
Restricting to these cases, when we flip an additional coin, the expected value stays the same, namely
$$E_{n+1} ( |H-T| \mid a_n = k ) = \frac{1}{2} (k+1) + \frac{1}{2} (k-1 ) = k = E_n ( a_n = k).$$
Let's first focus on an odd number of coin flips, and what happens when we add an additional coin flip.
$|H-T| $ is odd, so by Linearity of Iterated Expectation,
$$ E_{2n} = \sum_{k=1}^{n} P(a_{2n-1} = 2k-1) \times E_{2n-1} (|H-T| \mid a_{2n-1} = 2k-1 ) \\
= \sum P(a_{2n-1} = 2k-1) E_{2n-1} ( a_{2n-1} = 2k-1 )   \\= E_{2n-1}.$$
Notice that $E_{2n} = E_{2n-1}$ is reflected in the closed form.
Now we focus on the $n=2k$ even number of coin flips, and what happens when we add an additional coin flip.
$|H-T|$ is even. We understand what happens when $|H-T| \geq 2$, so let's investigate when $|H-T| = 0$.
This occurs with probability $P(a_{2k} = 0 ) = \frac{2k \choose k } { 2^{2k}}$.
With the next coin flip, we have $|H-T| = 1$ always, so $E_{2k+1} ( |H-T| \mid a_{2k} = 0 ) = E_{2k} ( |H-T| \mid a_{2k} = 0 ) + 1$.
Thus, by Linearity of Iterated Expectation,
$$ E_{2n+1} = \sum_{k=0}^{n} P(a_{2n} = 2k) \times E_{2n+1} (|H-T| \mid A_{2n} = k )\\
 = P(a_{2n}  =0) +  \sum_{k=0}^n P(a_{2n} = k) E_{2n} ( a_{2n}= k )   \\ = \frac{2k \choose k } { 2^{2k}} + E_{2n}.$$
By induction (check the math), $E_n$ has the closed form as given above.


text:
Q: Sequelize connection over ssh I am not able to connect to a remote mysql server using sequelize but I am able to ssh into the machine and connect to mysql.
How do I make Sequelize connect to mysql server over ssh rather than directly in node?

A: You set up an SSH tunnel to your server, which listens on (for example) port 33060:
ssh -NL 33060:localhost:3306 yourserver

In another window/terminal, you can use the MySQL client (assuming that it's installed locally) to connect to the remote MySQL server over the SSH tunnel:
mysql --port 33060 --host 127.0.0.1

If that works, it's just a matter of changing the port number in Sequelize:
var sequelize = new Sequelize('database', 'username', 'password', {
  host: "127.0.0.1",
  port: 33060
});

If it doesn't work, it might be that the remote MySQL server isn't configured to accept connections over TCP. If that's the case, you should configure your MySQL server to get it to accept TCP connections.


text:
Q: Highlight value on hover I'm trying to highlight text inside .category-value class on hover over div with class month-hover to apply #197ABF color. ie., "Jan" text should be of color #197ABF on hover over div.
I tried applying the below CSS,but not working(as its highlighting only on mouse hover over Jan or Feb).
.month-hover>.category-title:hover{
    color:#197ABF;
}

Plunker link here

A: You forgot the dot (.) before your category-title class:
.month-hover > .category-title:hover {
    color: #197ABF;
}

A: This works if, parent class and then child class. This will change the color of text when hovered. (Missed the .)
.month-hover .category-title:hover{
    color:#197ABF;
}

To change the color of text when div hover is simple,
Full code:

.margin-set{
  margin:35px;
}
.category-title{
  font-size:15px;
}
.category-value{
  font-size:45px;
  color:#197ABF;
}

.month-hover{
    cursor: pointer;
    border: solid transparent 2px;
}
.month-hover:hover {
    border-color: #197ABF;
    color:#197ABF;
}
/*.month-hover>.category-title:hover{
    color:#197ABF;
}
.month-hover >.category-title:hover{
    color:#197ABF;
} */
<!DOCTYPE html>

    <link data-require="bootstrap-css@3.2.0" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
    <link rel="stylesheet" href="bootstrap-5-columns.css" />
        <link rel="stylesheet" href="style.css" />

Jan

2017

Feb

2017

Just added color to the on hover of the div.
Result:

(Blue arrow is where the mouse is at)

A: This could work
.month-hover .category-title:hover{
    color:#197ABF;
}


text:
Q: Where do I put shared constants in a C# application? I have some constant strings that are needed in multiple classes. How can I store and retrieve these constants in a way that meets these required criteria:

*

*No duplication of information.

*No function call to retrieve constants.

*No namespace symbol prior to constant (IE: Constant not Namespace.Constant)

None of the solutions I've found so far meet every criteria:

*

*Duplicate them in every class they are needed in (violates criteria #1).

*Store them in a separate static class that is referenced wherever needed (a bit like a C-style header file, violates criteria #3).

*Put them in one of the classes where they are used and reference that class when they are needed elsewhere (this is seems like a bad idea because it could create circular references, and it violates criteria #3).

*Put them in app.config and retrieve them whenever they are needed (This seems to break style conventions since non-configuration data is stored in a config file, and a change to the config file could break application logic. It also violates criteria #2).

Is there a solution in C# that meets every criteria?

A: I use option #2 often, because #1 is rife with risk of different values, and #3 breaks normally-sought class encapsulation.  If you must have globals. have one Single Source of Truth for them.
You can make the code somewhat cleaner with a using alias:
 using static namespace.StaticClassName;

A: VB.Net has Module Statement that can be used for global variables that can be accessed without using the name of the module, but C# doesn't have anything like that.
In C# I use #2, but with const. That way the value is shown when you hover it in Visual Studio:


text:
Q: How to set  tag in  by javascript? I have a gsp with html code as below

How can I use JavaScript to set  inside  so I can define a url in it?
I had done it like this in JavaScript
$element.html(indic.link(url));

where $element is referring to , indic is a value and url is to be opened when the value clicked. I noticed by this method I have the url open in new tab or can't change the color of the font.

A: You can use this to set  tag inside
var kbd = document.getElementsByTagName('kbd')[0];
kbd.innerHTML = 'Click me';

JSFiddle : https://jsfiddle.net/5caps8f3/


text:
Q: How can I use the spare capacity in a std::vector? What is the safe, portable, idiomatic way to use the spare capacity in a std::vector?
std::vector<Foo> foos;
foos.emplace_back(1);
foos.emplace_back(2);
foos.reserve(10);

At this point, foos owns at least 8 * sizeof(Foo) uninitialized spare memory starting at foos.data() + foos.size(). It seems terribly inefficient to let that memory go to waste. How can I use this spare capacity as scratch space or for other purposes before I fill it with Foo objects by appending to foos? What is the right way to do this without invoking any undefined behavior?

A:
How can I use the spare capacity in a std::vector?

By inserting more elements.

More convoluted answer which may be what you're looking for, but probably more complex than it's worth:
You can allocate memory yourself (std::allocator or whatever; don't forget std::unique_ptr), and implement a custom allocator that uses that piece of memory. You can then use that memory for whatever and later create a vector using the custom allocator. Note that this doesn't let you use the memory that has already been reserved for the vecor; you can only use the memory before it has been acquired by the vector.

A: Yes, memory for unused elements is wasted, but it is unavoidable. It's by design.

The storage of the vector is handled automatically, being expanded and
contracted as needed. Vectors usually occupy more space than static
arrays, because more memory is allocated to handle future growth. This
way a vector does not need to reallocate each time an element is
inserted, but only when the additional memory is exhausted.

It's also good to know some non-standard vector's variants and may use them as replacement for std::vector, they
have specific application scenarios.
If you need a dynamic array and the maximum capacity is know at compile time,then boost::static_vector would be a choice(Use it may avoid the unnecessary memory waste of std::vector since most of std::vector's implementation always reserve capacity with a pow of 2, so if your desired capacity is 10, then 6 elements is likely to
be waste):

static_vector is an hybrid between vector and array: like vector, it's
a sequence container with contiguous storage that can change in size,
along with the static allocation, low overhead, and fixed capacity of
array. static_vector is based on Adam Wulkiewicz and Andrew Hundt's
high-performance varray class.
The number of elements in a static_vector may vary dynamically up to a
fixed capacity because elements are stored within the object itself
similarly to an array. However, objects are initialized as they are
inserted into static_vector unlike C arrays or std::array which must
construct all elements on instantiation. The behavior of static_vector
enables the use of statically allocated elements in cases with complex
object lifetime requirements that would otherwise not be trivially
possible. Some other properties:
Random access to elements Constant time insertion and removal of
elements at the end Linear time insertion and removal of elements at
the beginning or in the middle. static_vector is well suited for use
in a buffer, the internal implementation of other classes, or use
cases where there is a fixed limit to the number of elements that must
be stored. Embedded and realtime applications where allocation either
may not be available or acceptable are a particular case where
static_vector can be beneficial.

And if the dynamic array mostly has a very small size(only some of them would be large but with a small probability), then we may consider using small_vector, a small vector will improve the performance for such a scenario and such container is widely used in large projects.

small_vector is a vector-like container optimized for the case when it
contains few elements. It contains some preallocated elements
in-place, which allows it to avoid the use of dynamic storage
allocation when the actual number of elements is below that
preallocated threshold. small_vector is inspired by LLVM's SmallVector
container. Unlike static_vector, small_vector's capacity can grow
beyond the initial preallocated capacity.


text:
Q: Webscraping Google news page: getting AttributeError: 'NoneType' object has no attribute 'find_all' I'm trying to web-scrape the Google News page for a personal project and retrieve the article headlines to print out onto another page. I've been searching for any typos or mistakes but I'm not sure why my element keeps returning as "None" when I try to print it.
import requests
from bs4 import BeautifulSoup

URL = 'https://www.google.com/search?q=beyond+meat&rlz=1C1CHBF_enUS898US898&sxsrf=ALeKk00IH9jp1Kz5-LSyi7FUB4rd6--_hw:1624935518812&source=lnms&tbm=nws&sa=X&ved=2ahUKEwicqIbD7LvxAhVWo54KHXgRA9oQ_AUoAXoECAEQAw&biw=1536&bih=754'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find('div', id='rso') #grabs everything in column
article_results = results.find_all('div', class_='yr3B8d KWQBje') #grabs divs surrounding each article
for article_result in article_results:
    headliner = article_result.find('div', class_='JheGif nDgy9d')#grabs article header div for every article
    if None in (headliner):
        continue
    headliner_text = headliner.text.strip()
    print()

A: import requests
from bs4 import BeautifulSoup

URL = 'https://www.google.com/search?q=beyond+meat&rlz=1C1CHBF_enUS898US898&sxsrf=ALeKk00IH9jp1Kz5-LSyi7FUB4rd6--_hw:1624935518812&source=lnms&tbm=nws&sa=X&ved=2ahUKEwicqIbD7LvxAhVWo54KHXgRA9oQ_AUoAXoECAEQAw&biw=1536&bih=754'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
headers = soup.find_all('div', class_='BNeawe vvjwJb AP7Wnd')
for h in headers:
    print(h.text)

Refer the output... Is this what you are expecting?


text:
Q: what's wrong with my steps,why there is no output? I'm using Magento, and want to echo 'welcome, my visitor!' on the right part of the default template.  I've performed the following steps, but there's no output.
First, in page.xml
 <block type="core/text_list" name="right" as="right" translate="label">
                <label>Right Column</label>
                <block type="catalog/navigation" name="category.listing" template="catalog/navigation/categories.phtml" />
            </block>

I add
<block type="catalog/navigation" name="category.listing" template="catalog/navigation/categories.phtml" />`

Second, I created the file template/catalog/navigation/categories.phtml containing the following code in it.
   <?php echo 'welcome, my visitor!'; ?>

After doing this, there's no output? How can I fix this? Thank you.

A: You're using back-ticks instead of single- or double-quotes.
It should be:
<?php echo 'welcome, my visitor!'; ?>
Back-ticks are used to execute shell commands: http://php.net/manual/en/language.operators.execution.php


text:
Q: Linux: remove file with Questionmark AND parentheses in the filename How can i rename a file that looks like this:
Some shitty words with spaces and sp?ecial (characters).ext

I tried enclosing in single quotes, i tried enclosing in double quotes. I tried moving
mv Some*.ext test.ext

But anything i do, will result in
mv: cannot stat ... no such file or directory.
None of the tips for getting rid of either the question mark or parentheses work, i guess having both of these in a filename is the ultimate reason to get you stuck.
I cant even delete the whole folder...
Thanks for any help!


text:
Q: How do I read x amount from a buffer For the sake of this question, let's assume nothing is wrong with the server and let's just focus on the client and how it receives the data.
So I have this client / server setup going and this is how it currently flows.
The server sends a packet that's 5000 bytes.
All the packets are structured like this.. The first 4 bytes are reserved for the length of the entire packet, the next byte is reserved for the OpCode.. The remaining bytes represents the actual payload.
Length (4 bytes) | OpCode (1 byte) | Payload (x bytes)
On the client I'm currently doing this
byte[] RawBuffer = new byte[Constants.BufferSize]; //Constants.BufferSize = 1024
int packLen = 0;
int totalReceived = 0;
private byte[] allData;

private void ReceiveCallback(IAsyncResult ar)
{
    var stream = (NetworkStream)ar.AsyncState;
    var received = stream.EndRead(ar);
    Debug.Print($"Data received: {received} bytes");

    //If we haven't assigned a length yet
    if (packLen <= 0)
    {
        //Use "allData" as the final buffer that we use to process later down the line.
        using (var ms = new MemoryStream(RawBuffer))
        using (var reader = new BinaryReader(ms))
        {
            packLen = reader.ReadInt32();
            allData = new byte[packLen];
        }
    }

    Buffer.BlockCopy(RawBuffer, 0, allData, 0, received);
    totalReceived += received;

    if (totalReceived == allData.Length)
    {
        Debug.Print($"We've successfully appended {allData.Length} bytes out of {packLen}");
    }

    stream.BeginRead(RawBuffer, 0, Constants.BufferSize, ReceiveCallback, _stream);
}

That only works if I send 1 packet from the server to the client, but if I send 5 packets for instance it never actually splits them up.
How do I properly split them up so that once it's received the full packet based on the Length header, it prints out "Received packet successfully"