text:
Q: AJAX fails loading XML I try to reach out to the IKEA Api to access the availability checker. If I want to ajax the file it wont return anything and the .fail function is called.
$('#availability').submit(function (event) {
let productNumber = $('#productId').val();

if (testString(productNumber, '^[0-9]{3}\.[0-9]{3}\.[0-9]{2}$')) {
    productNumber = productNumber.replace(/\./g, '');
    let target = 'http://ikea.com/de/de/iows/catalog/availability/' + productNumber;

    $.ajax({
        url: target,
        cache: false,
        dataType: 'xml'
    })
        .done(function (data) {
            console.log('succes');

        })
        .fail(function (x) {
            console.log(x);
        });
}

event.preventDefault();

});

A: You don't see any result because your request is being blocked (here is the error that I see in the console):
XMLHttpRequest for http://ikea.com/de/de/iows/catalog/availability/00122822/ required Cross Origin Resource Sharing (CORS).
Redirect was blocked for CORS request
There are several links related to CORS error in StackOverflow. Apparently, this is a security setting in your browser and it is unsafe to turn it off.
I found this link that suggests a workaround:
https://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/


text:
Q: Query for Foreign Key string ID without fetching the actual entity Given the model below, when fetching an entity from the myentity table with JPA, is there a way to prevent the secondary fetch that would get the entity from the anotherentity table, but would provide us with the externalPk String value (which is used as a Foreign Key) itself?
As much as I understand that due to the declared types in Java it wouldn't specifically be possible, I do wonder if there's way to access that information without the extra fetch considering it is indeed right there in that myentity table as an actual varchar column.
If it can help, we use EclipseLink as our JPA provider.
Current model
@Entity
@Table(name = "myentity")
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@IdClass(MyIdClass.class)
public class MyEntity {

    @Id
    @Column(updatable = false)
    private String foo;

    @Id
    @Column(updatable = false)
    private String bar;

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "my_foreign_key", referencedColumnName = "external_pk")
    private AnotherEntity anotherEntity;
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Embeddable
public class MyIdClass implements Serializable {

    private String foo;
    private String bar;
}

@Entity
@Table(name = "anotherentity")
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public class AnotherEntity {

    @Id
    @Column(name = "external_pk", nullable = false, updatable = false)
    private String externalPk;

    @Column
    private String something;
}

A: If the oneToOne relation is not optional, you can append the anotation with optional = false, fetch = FetchType.LAZY like such:
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "my_foreign_key", referencedColumnName = "external_pk")
private AnotherEntity anotherEntity;

You'll then be able to access its key with myEntity.getAnotherEntity().getKey() without loading the relation.
Here's a POC using hibernate

A: If you want to be able to access the my_foreign_key foreign key value without having to call MyEntity.getAnotherEntity().getId() and perform a full fetch of anotherEntity, you should probably map it as a read-only basic mapping within the MyEntity instance:
public class MyEntity {
...
    @Column(updatable = false)
    private String bar;

    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "my_foreign_key", referencedColumnName = "external_pk")
    private AnotherEntity anotherEntity;

    @Column(name = "my_foreign_key",updatable = false, insertable=false)
    private String myForeignKey;
}

As an added benefit, while EclipseLink is pretty good about it on this type of mapping, it can be used in queries to prevent inadvertently forcing a table join unnecessarily. Draw backs though are that you must set this value from the relationship yourself to keep the value in synch with the relationship value - @MapsId might work, but it is meant for relationships involved in ID mappings, so might not be portable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is the word "pants" plural? We wear a shirt, a jacket but a pair of pants.
Why is pants plural?

A: A quick search led me to the excellent site World Wide Words run by Michael Quinion
The site has an entire page on this issue. Here's a brief snippet.

Before the days of modern tailoring, such garments, whether underwear or outerwear, were indeed made in two parts, one for each leg. The pieces were put on each leg separately and then wrapped and tied or belted at the waist (just like cowboys' chaps). The plural usage persisted out of habit even after the garments had become physically one piece. However, a shirt was a single piece of cloth, so it was always singular.

A: Apparently in the past they were two tube weakly linked, think to current tights. Hence the plural form.

A: It actually makes perfect sense. Think of these examples. "The clown wore a pair of pants where one pant was red and the other pant green".  Also, "The amputee wore his pants with one pant tied up and the other pant covering his good leg". The proper use of the singular and plural is used to make the meaning clear.  Or if you look at panties as a whole with two openings or two short upper leg coverings we use the plural, however, if we only refer to the single toursal opening we say "panty waist", especially when referring to a male who is less masculine or who acts cowardly.  And by the way "sleeves" is upper body equivalent of pants. "The shirt has short sleeves". "He wore short sleeves". In both these examples we used sleeves as a noun. When we use it as an adjective of a singular noun, we use the singular, ". . . short-sleeve shirt".

A: I think it just like the "shoes". You cannot have one "shoe" as well as one "part" of the pants.

A: It's referring to the components that make up the whole.  A pair of pants consists of two pants.  Much like a pair of glasses (usually) has two pieces of glass.


text:
Q: PHP foreach not working XML I don't really understand why this foreach is not working:
 <?php
    $url = "https://maps.googleapis.com/maps/api/place/textsearch/xml?query=hotels+in+newyork&key=AIzaSyAZAkutsge0U-xZVMvwf_Iw_ubdN2bra64";
    $xml = simplexml_load_file($url);

foreach($xml->result->name as $name)
{

    echo $name;
}

it shows only the 1st row!

A: you have to loop $xml->result.
foreach($xml->result as $result)
{
    echo $result->name;
}


text:
Q: Symbol table implementation using hash table in C I am trying to implement a simple symbol table that stores the strings in a hash table according to their hash values. The hash table in my program is an array of pointers to linked lists. we have 6 linked lists corresponding to each hash value.
The problem is that though the program runs, it replaces the old strings with the new string in each iteration.
my code is..
struct node{
    char *string;
    struct node *next;
};
struct node *hashtable[6];

int calchash(char *arr);
main()
    {
    char *line, a='n';
    int val, i;
            do{
            printf("Enter string:\n");
            scanf("%s", line);
            struct node *current;
            struct node *q= (struct node*)malloc(sizeof(struct node));
            q->string = line;
            q->next = NULL;
            val= calchash(line);
            if(hashtable[val] == NULL)
                    {
                    hashtable[val] = q;
                    current =q;}
            else{
                    current->next = q;
                    current = q;
                    }
            printf("Node created\n");
    for(i=0; i<6; i++)
            { printf("Hash value %d :\n", i);
            if(hashtable[i]==NULL)
                    {printf("No STRINGS!\n\n");}
            else
                    {struct node *t = hashtable[i];
                    while(t != NULL)
                            {printf("%s \n", t->string);
                            t = t->next;}
                    printf("\n\n");
                   }
            }

    printf("CONTINUE(y/n):\n");
    scanf(" %c", &a);
    }while(a!='n');
    }

int calchash(char *arr)
    {int i=0, ascii;
    int sum=0;
    while(arr[i] != '\0')
            {ascii = arr[i];
            if(ascii>=48 && ascii<=57)
                    {
                    sum+= 2*ascii;}
            else
                    {sum=sum+ ascii;}
            i++;
            }
    return ((sum*17+5)%6);
    }

And the output is:
Enter string:
az9
Node created
Hash value 0 :
No STRINGS!
Hash value 1 :
No STRINGS!
Hash value 2 :
az9
Hash value 3 :
No STRINGS!
Hash value 4 :
No STRINGS!
Hash value 5 :
No STRINGS!
CONTINUE(y/n):
y
Enter string:
Az9
Node created
Hash value 0 :
No STRINGS!
Hash value 1 :
No STRINGS!
Hash value 2 :
Az9
Hash value 3 :
No STRINGS!
Hash value 4 :
Az9
Hash value 5 :
No STRINGS!
CONTINUE(y/n):
n
Can someone please tell me what changes are needed so as to retain the previous az9 string under hash value 2???

A: if(hashtable[val] == NULL) {
    hashtable[val] = q;
    current =q;
} else {
    current->next = q;
    current = q;
}

should be replaced with:
q->next = hashtable[val];
hashtable[val] = q;
// no need for current

Also, writing through any uninitialised pointer is UB, please allocate sufficient space first. Anything might happen...

A: How does this not crash immediately?  Neither line nor hashtable are initialized.
You will need to make a copy of the string to go into each hash node, probably with strdup.  Currently, all of the nodes point to the same string buffer as line, so when you read a new string into line, all of the nodes will see it.  This is why you must duplicate the string for each node.  I wonder where the buffer ended up though, since you never initialized line...
Also, what is current?  It is local to the loop, and appears unnecessary.  You should just chain new nodes onto the head of the bucket, so you don't need to check if the bucket is empty.
The insert also does not check if the string is already present, so you will insert duplicates.


text:
Q: Google Cloud Functions Python Sessions: "The session is unavailable because no secret key was set" I have created a simple login script that I want to host on Google Cloud Functions.
The application works fine when I run it locally because I then run app.py which uses app.secret_key and starts a Flask app with app.run(...).
However when running on Goolge Cloud Functions the starting point is the function main(request=None). This does not start a Flask App. Because of this a secret_key is not set and I get the error "The session is unavailable because no secret key was set".
How can I solve this problem?
app.py - Only used locally
import os

import flask
from flask import request
from flask_cors import CORS

import main

app = flask.Flask(__name__)

cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route("/", methods=['GET', 'POST'])
def index():
    print("index()")
    return main.main(request)

# - Main start ----------------------------------------------------------------
if __name__ == "__main__":

    # Sessions
    app.secret_key = os.urandom(12)
    app.run(debug=True, host="0.0.0.0", port=8080, ssl_context=('certificates/cert.pem', 'certificates/key.pem'))

main.py - The entry point for the Google Cloud Function
import json
import os

import flask
from flask import session

from src.pages.login import login

def main(request=None):
    print("main()")

    # Logged in?
    if not session.get('logged_in'):
        return login(app)
    else:
        return "logged in!"

    # Finish
    return {"message": "completed successfully"}

if __name__ == '__main__':
    main()

src/pages/login.py
from flask import request, session

def login(app):
    print("login() :: Init")

    # Get :: Process
    process: int = int(request.args['process'])

    # Process == 1
    if process == 1:

        # Fetch username and password
        inp_username: str = ""
        inp_password: str = ""
        try:
            login = request.form

            inp_username = login['inp_username']
            inp_password = login['inp_password']

        except Exception as e:
            print(f"login() :: Process error when getting request form e={e}")

        # Test username and password
        if inp_username == "admin" and inp_password == "admin":
            print("login() :: Welcome")

            # Sessions
            session['logged_in'] = True
            return "Welcome"
        else:
            print("login() :: Wrong password")
            return "Wrong password"

    return '''
    <form method="post" action="?process=1" enctype="multipart/form-data">

Username:

        <input type="text" name="inp_username" value="" />

Password:

        <input type="password" name="inp_password" value="" />

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

    </form>
    '''

A: You are right that the main function acts as the entry point rather than app.py when executing your Flask application on Google Cloud Functions rather than the latter directly. Because the Flask app is not launched using app.run(), the app.secret_key variable is not set.
When using Google Cloud Functions, you may alter your main function to construct and launch the Flask app and configure the app.secret_key.
from flask import Flask, session

app = Flask(__name__)
app.secret_key = 'secret_key'

@app.route('/route')
def your_function():
    session['key'] = 'value'
    data = session.get('key')
    return '=response'

def main(request):
    with app.test_request_context(request.path, headers=request.headers):
        response = app.full_dispatch_request()
    return response


text:
Q: How to get Span Id value into PHP Variable? I am bit confuse how to get Span ID value into PHP Variable. When I tried DOM, Span become will not work.
I want to store the value of Span id "sum".
Please help me in this.
HTMl + PHP Form:

      Fees Particular [A] + [B] = [Payble Fees]
      <input type="text" name="valuesum" class="valuesum" value="<?php $mf = mysqli_fetch_array(mysqli_query($conn,"SELECT * FROM total_fees where class = '$qry[class]'")); $m_f = $mf['total_fees']/10; echo $m_f;?>" > +
      <input type="text" name="valuesum" class="valuesum" value="<?php echo $i; ?>" > =
      Rs.

Script:

A: You have problem here in your HTML, jQuery works fine.
Updated Fiddle

            Fees Particular [A] + [B] = [Payble Fees]
            <input type="text" name="valuesum" class="valuesum" value="<?php $mf = mysqli_fetch_array(mysqli_query($conn,"SELECT * FROM total_fees where class = '$qry[class]'")); $m_f = $mf['total_fees']/10; echo $m_f;?>" > +
            <input type="text" name="valuesum" class="valuesum" value="<?php echo $i; ?>" > =
            Rs.

You can't run mysql query inside input, right way to do it is, first run query
<?php $mf = mysqli_fetch_array(mysqli_query($conn,"SELECT * FROM total_fees where class = '$qry[class]'"));
$m_f = $mf['total_fees']/10;
?>

and then in input put variable in value
<input type="text" name="valuesum" class="valuesum" value="<?php echo $m_f;?>" >

And to store values, first you have to store it into input (check updated fiddle)
<input type="text" name="total" id="total" value="" >

and then post it with form and store into database,


text:
Q: Windows - can't run a node.js app as a background service with npm-windows? I am trying to use node-windows to run my script as a background service.
I installed node-windows with the global flag, and then linked.
service.js:
var Service = require("node-windows").Service;

console.log("entered");

// Create a new service object
var svc = new Service({
  name: "myService",
  description: "my service",
  script:
    "C:\\path-to-my-script\\example.js",
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on("install", function () {
  console.log(" entered install ");
  svc.start();
});

// Listen for the "start" event and let us know when the
// process has actually started working.
svc.on("start", function () {
  console.log(
    svc.name + " started!\nVisit http://127.0.0.1:3000 to see it in action."
  );
});

svc.on("error", function () {
  console.log(svc.name + " error occured");
});

svc.install();

console.log(" completed");

example.js:
var http = require("http");

const hostname = "127.0.0.1";
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World");
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

After node service.js, I receive the following error:
Windows Script Host: There is no script engine for file extension ".vbs"
I already tried the following:

*

*in cmd: assoc .vbs=VBSFile
Still nothing happens.

A: The problem was that the default program for handling .vbs scripts was set to Notepad++, instead of Microsoft Windows Based Script Host. (You can see yours under Settings/Default apps/Choose default apps by file type).
To revert it back , I found this as the only solution.


text:
Q: Keras to_categorical in a self-defined metrics gives error I'm trying to use a self-defined(f-1 scores) metrics, while using to_categorical from keras.utils in a lstm-crf model. I'm testing on the example from keras.contrib conll2000_chunking_crf. However, the y_true I pass in the metrics doesn't have a shape, thus to_categorical does not work. Is there anything I can do to convert y_true to one hot representation within a metrics?
Here is the code for f-1 score, which is pretty much the code used by Keras before being removed.
Here is the shape of train_x,test_x
print(train_x.shape)
print(train_x)
print(train_y.shape)
print(train_y)
(8936, 78)
[[   0    0    0 ...   33    1   34]
 [   0    0    0 ...   50   51   34]
 [   0    0    0 ...   68   69   34]
 ...
 [   0    0    0 ... 5164  102   34]
 [   0    0    0 ...    1 2948   34]
 [   0    0    0 ... 1673 1382   34]]
(8936, 78, 1)
[[[-1]
  [-1]
  [-1]
  ...
  [16]
  [16]
  [22]]

 [[-1]
  [-1]
  [-1]
  ...
  [16]
  [16]
  [22]]

 [[-1]
  [-1]
  [-1]
  ...
  [ 5]
  [16]
  [22]]

 ...

 [[-1]
  [-1]
  [-1]
  ...
  [16]
  [10]
  [22]]

 [[-1]
  [-1]
  [-1]
  ...
  [ 5]
  [16]
  [22]]

 [[-1]
  [-1]
  [-1]
  ...
  [16]
  [ 1]
  [22]]]

Here is the model and the summery:
model = Sequential()
model.add(Embedding(len(vocab),EMBED_DIM,mask_zero = True))
model.add(Bidirectional(LSTM(BiRNN_UNITS, return_sequences=True)))
crf = CRF(len(class_labels), sparse_target=True)
model.add(crf)
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
embedding_1 (Embedding)      (None, None, 200)         1787200
_________________________________________________________________
bidirectional_1 (Bidirection (None, None, 256)         336896
_________________________________________________________________
crf_1 (CRF)                  (None, None, 23)          6486
=================================================================
Total params: 2,130,582
Trainable params: 2,130,582
Non-trainable params: 0
_________________________________________________________________

Here is the code of the metrics:
 def f1(y_true, y_pred):
    def recall(y_true, y_pred):
        """Recall metric.

        Only computes a batch-wise average of recall.

        Computes the recall, a metric for multi-label classification of
        how many relevant items are selected.
        """
        true_positives = K.sum(K.round(y_true * y_pred))
        possible_positives = K.sum(K.round(y_true))
        recall = true_positives / (possible_positives + K.epsilon())
        return recall

    def precision(y_true, y_pred):
        """Precision metric.

        Only computes a batch-wise average of precision.

        Computes the precision, a metric for multi-label classification of
        how many selected items are relevant.
        """
        true_positives = K.sum(K.round(y_true * y_pred))
        predicted_positives = K.sum(K.round(y_pred))
        precision = true_positives / (predicted_positives + K.epsilon())
        return precision
    y_true = to_categorical(y_true)
    precision = precision(y_true, y_pred)
    recall = recall(y_true, y_pred)
    f1_score = 2*((precision*recall)/(precision+recall+K.epsilon()))
    f1_score = K.eval(f1_score)

    return f1_score

Here is the error message I got when trying to compile the model:
model.compile('adam', loss=crf.loss_function, metrics=[f1])
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-54-d498ba26f571> in <module>()
----> 1 model.compile('adam', loss=crf.loss_function, metrics=[f1])

~\Anaconda3\envs\tensorflow\lib\site-packages\keras\engine\training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, **kwargs)
    438                 output_metrics = nested_metrics[i]
    439                 output_weighted_metrics = nested_weighted_metrics[i]
--> 440                 handle_metrics(output_metrics)
    441                 handle_metrics(output_weighted_metrics, weights=weights)
    442

~\Anaconda3\envs\tensorflow\lib\site-packages\keras\engine\training.py in handle_metrics(metrics, weights)
    407                     metric_result = weighted_metric_fn(y_true, y_pred,
    408                                                        weights=weights,
--> 409                                                        mask=masks[i])
    410
    411                 # Append to self.metrics_names, self.metric_tensors,

~\Anaconda3\envs\tensorflow\lib\site-packages\keras\engine\training_utils.py in weighted(y_true, y_pred, weights, mask)
    401         """
    402         # score_array has ndim >= 2
--> 403         score_array = fn(y_true, y_pred)
    404         if mask is not None:
    405             # Cast the mask to floatX to avoid float64 upcasting in Theano

<ipython-input-53-83f49b6ba707> in f1(y_true, y_pred)
     27         precision = true_positives / (predicted_positives + K.epsilon())
     28         return precision
---> 29     y_true = to_categorical(y_true)
     30     precision = precision(y_true, y_pred)
     31     recall = recall(y_true, y_pred)

~\Anaconda3\envs\tensorflow\lib\site-packages\keras\utils\np_utils.py in to_categorical(y, num_classes)
     21         is placed last.
     22     """
---> 23     y = np.array(y, dtype='int')
     24     input_shape = y.shape
     25     if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:

ValueError: setting an array element with a sequence.

I tried to run the following code and I got the desired outcome, so I'm guessing the error occurs on the compile step.
y1 = model.predict(test_x)
f1(test_y,y1)
0.3058861

Any help would be appreciated. Thanks in advance.


text:
Q: How to Copy and paste to another worksheet if value match - Excel VBA I need to copy and paste values from sheet1 Columns(A:B) to sheet2 Columns(A:B), if Sheet1 Column F="NUMBERS"
Input

A 1 NUMBERS
B 2 TEXT
C 3 NUMBERS
D 4 TEXT
E 5 NUMBERS AND TEXT

OUTPUT
A 1
C 3

Currently i use AutoFilter and copy, paste method it sometime gives Error(Because very long Macro).
Sheets("sheet1").Select
ActiveWorkbook.save
Range("A1:J1").Select
Selection.AutoFilter
ActiveSheet.Range("$A:$J").AutoFilter Field:=6, Criteria1:="Numbers"
 Columns("A:B").Select
    Selection.Copy

 Sheets("Sheet2").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

So I need find value and copy paste method (loop based).

A: You can use this Macro to Copy entire Row to another Sheet has Number as value in Column F.
Option Explicit

Sub CopyRowWithSpecificText()

Dim Cell As Range

With Sheets(1)
      For Each Cell In .Range("F1:F" & .Cells(.Rows.Count, "F").End(xlUp).Row)
        If Cell.Value = "Numbers" Then

            .Rows(Cell.Row).Copy Destination:=Sheets(2).Rows(Cell.Row)
        End If
    Next Cell
End With
End Sub

Edited 1:
-If you don't like the Macro to produce blank rows, if any in Sheet 1 among Rows to be copied, then use this code.
    Sub CopyRowsWithNUMBER()

    Dim c As Range
    Dim j As Integer
    Dim Source As Worksheet
    Dim Target As Worksheet

    Set Source = ActiveWorkbook.Worksheets("Sheet1")
    Set Target = ActiveWorkbook.Worksheets("Sheet2")

    j = 1
    For Each c In Source.Range("F1:F20")
        If c = "Numbers" Then
           Source.Rows(c.Row).Copy Target.Rows(j)
           j = j + 1
        End If
    Next c
    End Sub

Edited 2:
Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rngCheck As Range
    Dim CheckCell As Range
    Dim lRow As Long

    Set rngCheck = Intersect(Me.Columns("F"), Target)

    If Not rngCheck Is Nothing Then

        For Each CheckCell In rngCheck.Cells
            If CheckCell.Value = "Numbers" Then
                With Sheets("sheet2")
                    lRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
                    Me.Cells(CheckCell.Row, "A").Copy Destination:=.Cells(lRow, "A")
                    Me.Cells(CheckCell.Row, "B").Copy Destination:=.Cells(lRow, "B")

                End With
            End If
        Next CheckCell
    End If

End Sub

How it works:

*

*Copy & Paste this code in Sheet 1 as standard module.

*As soon you enter Numbers in any cells of Column F, this code will copy data from the Column A & B only for the specific Row/Rows to Sheet 2.

*Destination Column(s) should different than Source.

N.B.

*

*Sheet Name, Column (F) has specific text, and the specific text, Number are adjustable.

*Save the Workbook as Macro Enabled (.Xlsm).


text:
Q: Extract By Mask moving pixels in ArcGIS Desktop? I am creating some statistics based on certain values. The issue I am having is that the extracted values are not the same as the values in the original raster. This creates incorrect output, and I need to ensure that, when joined, both fields are the exact same. After looking on ArcGIS Desktop, i found that the reason is that the pixels are moved by a tiny bit on the extract vs the original.

Hopefully you can see that the pixels are not aligned properly, and I need them to be properly aligned. I have tried the following:

*

*Set extent and Co-ordinate system to the extraction layer (in Extract by Mask)

*Snap the raster to the extraction extent(in Extract by Mask)

I am not sure what else I can do. I understand that this is a glitch as documented http://support.esri.com/en/knowledgebase/techarticles/detail/34448
From the article, setting the extent should fix it, but it does not do anything.

A: It appears that these comments by @MichaelStimson answered your question:

Have you set your Cell Size
  http://help.arcgis.com/EN/arcgisdesktop/10.0/help/index.html#/Cell_Size/001w0000001s000000/
  and Snap Raster
  http://help.arcgis.com/EN/arcgisdesktop/10.0/help/index.html#//001w0000000m000000
  to the raster being extracted from before the extraction? if not the
  origin may be taken from the mask or decided arbitrarily hence the
  difference in pixels... then set the output extent also to the input
  raster or not at all otherwise you'll have two environments
  conflicting. For extract by mask the Snap Raster and Cell Size are
  more important than extent.

and:

Yes, it's an old problem persisted since ArcInfo workstation. When you
  have a raster being extracted by another raster or polygon the extent
  will shrink to that of the clipping geometry and the origin (upper
  left) is taken just outside the extent of the geometry.. by enforcing
  the Snap Raster you tell the geoprocessor to essentially round the
  coordinates to match the snap which, even though offset by a pixel or
  two, will align with the snap raster and as you specify the cell size
  as being the source  the result will align with the source (and avoid
  resampling).


text:
Q: Mule CXF Marshall Response I am using cxf:jaxws-client in Mule 3 and the response I get from my web service call is of type ReleasingInputStream. I have tried adding the http-response-to-message-transformer, but that generates an error - does anyone know how I can retrieve the response as an object as opposed to a ReleasingInputStream?
Many thanks.

A: To solve the issue put the <cxf-client> inside the <outbound-endpoint> section (NOT BEFORE IT), by modifying the following code
    <cxf:jaxws-client
        clientClass="com.xyz.services.WSServices"
            port="WSServicesSoap"
            wsdlLocation="classpath:wsdl-file.wsdl"
            operation="GimmeDataOperation" />
    <outbound-endpoint exchange-pattern="request-response" address="http://localhost:8083/OutboundService" />

which produces a ReleasingInputStream output to
    <outbound-endpoint exchange-pattern="request-response" address="http://localhost:8083/OutboundService" >
        <cxf:jaxws-client
            clientClass="com.xyz.services.WSServices"
            port="WSServicesSoap"
            wsdlLocation="classpath:wsdl-file.wsdl"
            operation="GimmeDataOperation" />
    </outbound-endpoint>

that returns the expected object.

A: I was just having this same problem.  I solved it by adding an ObjectToString transformer to the response side of the outbound endpoint like this:
<mule>
   <object-to-string-transformer name="ObjectToString"/>

   <flow>
      ...
      ...
      ...
      <cxf:jaxws-client clientClass="com.my.ClientClass"
                        port="MyPort"
                        wsdlLocation="classpath:MyWsdl.wsdl"
                        operation="MyOperation" />
      <outbound-endpoint address="http://some.address/path/to/service"
                         exchange-pattern="request-response"
                         responseTransformer-refs="ObjectToString" />
      ...
      ...
      ...
   </flow>
</mule>

A: The whole point of jaxws-client is to receive the unmarshaled Java object, so getting the WS response as a String or ReleasingInputStream should not even be an option.
To make the <cxf:jaxws-client> "work" as one would expect the WS client to work - put the INSIDE of the <outbound-endpoint> you will be getting a correct Java object as a payload.


text:
Q: LINQ GroupBy extremely slow The following code takes 5 minutes to run on 100,000 rows. That seems crazy to me. What am I doing wrong?
        var query =
            from foo in fooStuff.AsEnumerable()
            group foo by foo.Field<Int64>("FooID") into g
            select new
            {
                    FooID = g.Key,
                    FooTier = g.Min(foo => foo.Field<int>("Tier"))
            };

Note: On Mono.

A: You are materializing all the entities when you call AsEnumerable(), so your grouping is being done in memory. Try removing that part so that the grouping is done at the database level:
var query =
        from foo in fooStuff
        group foo by foo.FooID into g
        select new
        {
                FooID = g.Key,
                FooTier = g.Min(foo => foo.Tier)
        };

A: It is not a direct comparision and isn't on Mono, but I have some code which does something similar with a 6MB xml file which I read into a DataSet and it has 30,000 rows and takes 0.5 seconds, so I don't think it is the groupby itself that causes the problem.
To diagnose further, I would suggest

*

*Testing how long it takes to read the information into a list, ie
var fooList = fooStuff.AsEnumerable().ToList();

*Testing how long it takes if you change the query to use fooList instead of fooStuff

*Testing how long it takes if you remove FooTier = g.Min(foo => foo.Tier) from the select

*Separate the .Field<> reflection from the groupby and time each section, ie first read the information from the datatable into a list , eg
var list2 =
(from foo in fooStuff.AsEnumerable()
select new {
    FooID = foo.Field<Int64>("FooID")
    Tier  = foo.Field<int>("Tier")
}).ToList();

Then you can query this list
var query =
from foo in list2
group foo by foo.FooID into g
select new
{
        FooID = g.Key,
        FooTier = g.Min(foo => foo.Tier)
};
var results = query.ToList();

If this query is slow, it would suggest that there is something wrong with mono's implementation of GroupBy. You might be able to verify that by using something like this
    public static Dictionary<TKey, List<TSrc>> TestGroupBy<TSrc, TKey>
     (this IEnumerable<TSrc> src, Func<TSrc,TKey> groupFunc)
    {
        var dict= new Dictionary<TKey, List<TSrc>>();

        foreach (TSrc s in src)
        {
            TKey key = groupFunc(s);
            List<TSrc> list ;

            if (!dict.TryGetValue(key, out list))
            {
                list = new List<TSrc>();
                dict.Add(key, list);
            }
            list.Add(s);
            }

        return dict;
}

And to use it
  var results = list2.TestGroupBy(r=>r.FooID)
      .Select(r=>  new { FooID = r.Key, FooTier = r.Value.Min(r1=>r1.Tier)} );

Note, this is not meant as a replacement for groupby and does not cope with null keys but should be enough to determine if their is a problem with groupby (assuming mono's implementation of Dictionary and List are ok).


text:
Q: Order of execution in Lightning Web Components I have a parent and a child component below is the code:
Parent component HTML:
<template>
    <lightning-tabset>
        <lightning-tab label="Child One">
            <c-child-one record-id={sobjectId}></c-child-one>
        </lightning-tab>
        <lightning-tab label="Child Two">
        </lightning-tab>
        <lightning-tab label="Child Three">
        </lightning-tab>
    </lightning-tabset>
</template>

Parent Component JS:
import {LightningElement, api, wire} from 'lwc';
import getRecordId from '@salesforce/apex/DemoCTRL.getRecordId'

export default class ChildOne extends LightningElement {
    @api recordId;
    sobjectId;

    constructor() {
        super();
        console.log('Constructor Called in Parent');
    }

    //getting dependent record Id
    @wire(getRecordId, {recordId: '$recordId'}) getSobjectId({error, data}) {
        if(data) {
            console.log('Wired Called In Parent');
            this.sobjectId= data;
        }
        else if (error) {
            console.log(error);
        }
    }
}

Child Component HTML:
<template>

                <template for:each={fieldSetData} for:item="field">

{field.fieldLabel}

                </template>

            <template for:each={records} for:item="row">

                    <template for:each={row} for:item="data">
                        {data.value}
                    </template>

            </template>

</template>

Child Component JS:
import {LightningElement, api, wire} from 'lwc';
import {processRecords} from 'c/recordGenerator';
import getFieldSetData from '@salesforce/apex/FieldSetData.getFieldSetData';
import getSobjectRecords from '@salesforce/apex/DeomoCTRL.getRecords';
import VanillaDatatable from '@salesforce/resourceUrl/VanillaDatatable';
import {loadScript, loadStyle} from 'lightning/platformResourceLoader';

export default class ManageSelectedIndicators extends LightningElement {
    @api recordId;
    records;
    fieldSetData;
    @wire(
        getFieldSetData,
        {objectName: 'SOBJECTName', fieldSet: 'FIELSETName'}
    ) wiredFieldSetData({error, data}) {
        console.log('wired called in Child')
        if (data) {
            this.fieldSetData = data;
            this.getData();
        }
    }

    constructor() {
        super();
        console.log('Constructor called in Child');
    }

    connectedCallback() {
        console.log('Connected callback');
    }

    renderedCallback() {
        console.log('Rendered callback');
        // Promise.all([
        //     loadScript(this, VanillaDatatable + '/VanillaDataTables/src/vanilla-dataTables.js')
        // ]).then(() => {
        //     const table = new DataTable(
        //         document.getElementsByClassName('.project-indicator'),
        //         {searchable: true, sortable : true}
        //     );
        // })
        // .catch(error => {
        //    console.log(error);
        // });
    }

    getData() {
        getSobjectRecords ({
            sobjectId: this.recordId
        })
        .then(response => {
            this.records= processRecords(response, this.fieldSetData);
        })
        .catch((error) => {
            console.log(error);
        });
    }

}

Here's the result after the page has loaded:

I'm not sure what's going on here and as a result of that my table is not rendering with data (only table headers are rendered because fieldSetData is populated) and I'm unable to instantiate the new DataTable() JS because the table doesn't exist.
Edit: looks like the sobjectId only gets populated after the child has rendered and hence the records is empty.
Please recommend the best approach to get the record in the parent -> pass it to the child component -> load related records -> render the table -> then call the JS

A: @wire(
    getFieldSetData,
    {objectName: 'SOBJECTName', fieldSet: 'FIELSETName'}
)

This wire in child is getting called even before you get recordId from parent and so you cannot say when will getSobjectRecords be invoked and when its response is returned, whether or not fieldSet information is available or not.
fixes:
Option 1. Render child only when sobjectId is available: (preferred)
    <c-child-one if:true={sobjectId} record-id={sobjectId}></c-child-one>

Option 2.
    @wire(
        getFieldSetData,
        {objectName: 'SOBJECTName', fieldSet: 'FIELSETName', recordId: '$recordId'}
    )

Make above wire dependent on recordId. This will get data only if it gets valid recordId
Added based on comments:
if:true is like normal javascript if condition which checks if value is:

*

*not null

*not undefined

*not blank

*is true if boolean


text:
Q: React Router not redirecting after user was logged in I have small problem with React Router and redirecting. After i have created a admin protected route, I want the user to be redirected to "user dashboard" after login. But my issue is that redirect is not working.
All is happening like this:
My Navigation componente, but this one i think is okay:
import React from 'react';
import { Link, withRouter } from 'react-router-dom';

import { signOut, isAuthUser } from '../../../utils/utils';

const isActive = (history, path) => {
  if (history.location.pathname === path) {
    return { color: '#ff9900' };
  } else {
    return { color: '#ffffff' };
  }
};

const Navigation = ({ history }) => {
  return (

          <Link className='nav-link' style={isActive(history, '/')} to='/'>
            Home
          </Link>
          <Link
            className='nav-link'
            style={isActive(history, '/user/dashboard')}
            to='/user/dashboard'
          >
            Dashboard
          </Link>
          {!isAuthUser() && (

              <Link
                className='nav-link'
                style={isActive(history, '/signup')}
                to='/signup'
              >
                Signup
              </Link>
              <Link
                className='nav-link'
                style={isActive(history, '/signin')}
                to='/signin'
              >
                Signin
              </Link>

          )}
          {isAuthUser() && (
            <Link
              className='nav-link'
              style={isActive(history, '/signout')}
              onClick={() => signOut()}
              to='/'
            >
              Sign Out
            </Link>
          )}

  );
};

export default withRouter(Navigation);

My app.js with Routes
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

import MainLayout from '../src/components/layout/MainLayout/MainLayout';
import Signup from './components/views/Signup/Signup';
import Signin from './components/views/Signin/Signin';
import Home from './components/views/Home/Home';
import PrivateRoute from './components/common/ProvateRoute/PrivateRoute';
import UserDashboard from './components/views/UserDashboard/UserDashboard';

function App() {
  return (
    <BrowserRouter>
      <MainLayout>
        <Switch>
          <Route exact path='/' component={Home} />
          <Route exact path='/signin' component={Signin} />
          <Route exact path='/signup' component={Signup} />
          <PrivateRoute exact path='/user/dashboard' component={UserDashboard} />
        </Switch>
      </MainLayout>
    </BrowserRouter>
  );
}

export default App;

My utils.js with some helper functions
export const signOut = () => {
  if (typeof window !== 'undefined') {
    localStorage.removeItem('jwt');
    return fetch('http://localhost:8000/api/signout', { method: 'GET' }).then(res => {
      console.log('signout', res);
    });
  }
};

export const authenticateUser = data => {
  if (typeof window !== 'undefined') {
    localStorage.setItem('jwt', JSON.stringify(data));
  }
};

//check if user is auth and there is jwt item in localstorage. menu render
export const isAuthUser = () => {
  if (typeof window == 'undefined') {
    return false;
  }
  if (localStorage.getItem('jwt')) {
    return JSON.parse(localStorage.getItem('jwt'));
  } else {
    return false;
  }
};

So those looks okay in my opinion, but still i decided to post those here.
As all things that are most related are in my tow files: UserDashboard and Signin
My Signin.js looks like this:
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import axios from 'axios';

import Layout from '../../layout/Layout/Layout';
import { authenticateUser, isAuthUser } from '../../../utils/utils';

class Signin extends Component {
  state = {
    formData: {
      email: '',
      password: '',
    },
    userRedirect: false,
  };

  onChange = e => {
    const { formData } = this.state;
    //assign form data to new variable
    let newFormData = { ...formData };
    newFormData[e.target.name] = e.target.value;
    this.setState({
      formData: newFormData,
    });
  };

  signIn = user => {
    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    };
    axios
      .post('http://localhost:8000/api/signin', user, config)
      .then(res => authenticateUser(res.data));
    this.setState({
      formData: { email: '', password: '' },
      userRedirect: true,
    });
  };

  onSubmit = e => {
    const { password, email } = this.state.formData;
    e.preventDefault();
    this.signIn({ email, password });
  };

  signInForm = (email, password) => (
    <form onSubmit={this.onSubmit}>

        Email
        <input
          type='email'
          name='email'
          value={email}
          onChange={this.onChange}
          className='form-control'
        ></input>

        Password
        <input
          type='password'
          name='password'
          minLength='6'
          value={password}
          onChange={this.onChange}
          className='form-control'
        ></input>

      <button className='btn btn-primary'>Submit</button>
    </form>
  );

  redirecUser = () => {
    const { userRedirect } = this.state;
    const { user } = isAuthUser();

    if (userRedirect === true) {
      if (user && user.role === 1) {
        return <Redirect to='/admin/dashboard' />;
      } else {
        return <Redirect to='/user/dashboard' />;
      }
    }
  };

  render() {
    const { email, password } = this.state.formData;

    return (
      <Layout
        title='Signin'
        description='Login to your account'
        className='container col-md-8 offset-md-2'
      >
        {this.signInForm(email, password)}
        {this.redirecUser()}
      </Layout>
    );
  }
}

export default Signin;

Here I am rendering all with signInForm and passing all data that i want with signIn(). From this i get user data: _id, email, password, role and token. This is sent to local storage.
Based on that what i get i want admin dashboard or user dashboard.
I have now olny user Dashboard
import React from 'react';
import { isAuthUser } from '../../../utils/utils';

import Layout from '../../layout/Layout/Layout';

const UserDashboard = () => {
  const {
    payload: {
      user: { name, email, role },
    },
  } = isAuthUser();

  return (
    <Layout
      title='User Dashboard'
      description={`Wlecome ${name}`}
      className='container col-md-8 offset-md-2'
    >

User information

{name}

{email}

            {role === 1 ? 'Admin' : 'Registered User'}

Purchase history

History

    </Layout>
  );
};

export default UserDashboard;

I have created PrivateRoute component based on documentation
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import { isAuthUser } from '../../../utils/utils';

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={props =>
      isAuthUser() ? (
        <Component {...props} />
      ) : (
        <Redirect to={{ pathname: '/signin', state: { from: props.location } }} />
      )
    }
  />
);

export default PrivateRoute;

I do get all data in local storage, but after signin user is not redirected
Thanks for any help

A: Since you are trying to redirect from a function in your Signin.js try using history api.
this.props.history.push('/admin/dashboard')

instead of
<Redirect to='/admin/dashboard' />;


text:
Q: Magento 1 Restore coupon for a especific customer I'm trying to restore a coupon for a specific customer, I know their id and the coupon code.
My code is:
$customerId = 98080;

$coupon = Mage::getModel('salesrule/coupon')->load('test-it', 'code');
$coupon->setTimesUsed($coupon->getTimesUsed()-1);

$coupon->save();

$timesUsed = $coupon->getTimesUsed();

$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$query = "UPDATE salesrule_coupon_usage SET times_used = times_used-1 WHERE customer_id='".$customerId."' AND coupon_id='".$coupon->getId()."'";

$result = $write->query($query);

if ($customerCoupon = Mage::getModel('salesrule/rule_customer')->loadByCustomerRule($customerId, $coupon->getRuleId())) {
    $customerCoupon->setTimesUsed($customerCoupon->getTimesUsed()-1);

    $customerCoupon->save();
}

And apparently all is working fine, I check the customer in the database and he doesn't have the discount assigned:
SELECT group_concat(distinct sfo.coupon_code) FROM sales_flat_order sfo
WHERE coupon_code IS NOT NULL
AND customer_email='email@example.com'
GROUP BY customer_email;
// group_concat(distinct sfo.coupon_code) == 0,one-discount,another

And in the code table:
SELECT coupon_code, count(coupon_code) FROM sales_flat_order
WHERE coupon_code ='test-it4'
GROUP BY coupon_code;
//Empty set

At first, all goes well, I can use the code again, but in the last step of the checkout I have the next message:

There was an error processing your order. Please contact us or try
  again later.

I don't know why the logs don't show anything
UPDATE
I have this error in apache2 log:

Integrity constraint violation: 1062 Duplicate entry '331536-98080'
  for key 'PRIMARY''

Where 331536 is the coupon_id and 98080 is the customer_id, but I don't find in which table is this data stored

A: I need to execute:
$query = "DELETE FROM salesrule_coupon_usage WHERE coupon_id='".$ruleId."' AND customer_id='".$customerId."';";

And all works again


text:
Q: Отправка в начало страницы при перезагрузки Нужно добавить скрипт в React приложение, что бы при перезагрузки страницы откидывало в начало страницы. Так в приложении фиксится много багов с анимированием, приложение сделано на react-router. Помогите сделать, буду благодарен)

A: Если именно для перезагрузки то вот так:
  componentDidMount(prevProps) {
      window.scrollTo(0, 0)
  }

Также если перезагрузки не происходит а страница однотипная с меняющимся location то можно привязаться и к нему
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
  window.scrollTo(0, 0)
 }
}


text:
Q: Copy rails projects from one machine to another(Github issue) I'm new to rails and github and found such problem. I have cloned two projects to my first machine(work there sometime – made branches and all this stuff) and now I need to move these projects to my another machine – and I don't know how to do it. I know that I can again clone this projects on my second machine but it didn't save my branches. Can somebody give me any advices. Thanks for the help
P.s. Can I simply copy my projects folders from one machine on flashdrive and paste it to another machine?

A: yes you can simply copy that on flashdrive and paste it to another machine

A: You should also be able to accomplish this using the --bare and --mirror tags with git clone
git clone --mirror https://github.com/exampleuser/repository-to-mirror.git
# Make a bare mirrored clone of the repository

cd repository-to-mirror.git
git remote set-url --push origin https://github.com/exampleuser/mirrored
# Set the push location to your mirror

See this article form github for more info:
https://help.github.com/articles/duplicating-a-repository
And as @NitinJ said, from there you just run
rake db:create:all (or just enter the selected db's you want to create)
rake db:migrate


text:
Q: im getting build error after connecting firebase with my code plugins {
    id 'com.android.application'
    id 'com.google.gms.google-services'
}

Im getting the gollowing error when i add "com.google.gms.google-services" in build.gradle(app).
A problem occurred configuring project ':app'.

org.gradle.internal.metaobject.AbstractDynamicObject$CustomMessageMissingMethodException: Could not find method setVariantDir() for arguments [debug] on task ':app:processDebugGoogleServices' of type com.google.gms.googleservices.GoogleServicesTask.

Thanks.


text: Q: Set run configuration for multiple files at once? Is there a way to set run configuration (e.g. "command line arguments") for multiple files all at once in Eclipse? It would be convenient when running single testing test script, right now any arguments are added script by script.


text:
Q: Uncaught TypeError: Cannot read properties of undefined (reading 'img') at Basket.jsx:19:1 The application has the function of adding products to the basket. On the product page it is possible to choose the color and size, if they are not selected in the basket, they will not be marked. But if you select at least one of the colors or sizes, then when you go to the cart page, an Uncaught TypeError: Cannot read properties of undefined (reading 'img') error appears.
But if you click on the selection more than once when choosing a color or size, then everything is displayed correctly on the basket page. As I understand it, the problem lies in the asynchrony of useState, if not difficult, tell me what can be done in this case, thanks!
The application has the function of adding products to the basket. On the product page it is possible to choose the color and size, if they are not selected in the basket, they will not be marked. But if you select at least one of the colors or sizes, then when you go to the cart page, an Uncaught TypeError: Cannot read properties of undefined (reading 'img') error appears.
But if you click on the selection more than once when choosing a color or size, then everything is displayed correctly on the basket page. As I understand it, the problem lies in the asynchrony of useState, if not difficult, tell me what can be done in this case, thanks!

ProductPage

import s from "./ProductPage.module.scss";
import { useParams, NavLink } from "react-router-dom";
import { useEffect, useState } from "react";

import Prices from "./prices/Prices";
import ChooeseSize from "./choosesize/ChooeseSize";
import ChooeseColor from "./choosecolor/ChooeseColor";
import RelatedItems from "./relatedItems/RelatedItems";

const ProductPage = ({ buttonHandler, sizef, colorf, clr, sz }) => {
  let { id } = useParams();

  let [fetchedData, updateFetchedData] = useState([]);

  let { name, price, old_price, img, size, color, related_products } =
    fetchedData;

  let api = `[some api]`;

  useEffect(() => {
    (async function () {
     let data = await fetch(api).then((res) => res.json());
      updateFetchedData(data);
    })();
  }, [api]);

  return (

{name}

        <NavLink to={"/"}>Главная</NavLink> -{" "}
        <NavLink to={"/shop"}>Магазин </NavLink> - {name}

      <Prices price={price} old_price={old_price} context="page" />
      <ChooeseSize size={size} sizef={sizef} />
      <ChooeseColor color={color} colorf={colorf} />

        <button
          onClick={(e) =>
            buttonHandler({
              id: id,
              img: img,
              name: name,
              size: sz,
              color: clr,
              price: price,
            })
          }
          className={s.btnopenshop}
        >
          Добавить в корзину
        </button>

  <RelatedItems related_products={related_products} />

  );
};

export default ProductPage;

Basket

import s from "./Basket.module.scss";
import BasketItem from "./BasketItem/BasketItem";
import { NavLink } from "react-router-dom";

const Basket = ({ basket }) => {
return (

Корзина

    <NavLink to={"/"}>Главная</NavLink> -{" "}
    <NavLink to={"/basket"}>
       Корзина
    </NavLink>

  {basket?.map((basket) => (
    <BasketItem
      key={basket.id}
      img={basket.img}
      name={basket.name}
      price={basket.price}
      size={basket.size}
      color={basket.color}
    />
  ))}

    <button className={s.checkout}>Оформить заказ</button>

   );
 };

export default Basket;

BasketItem

import s from "./BasketItem.module.scss";
import axios from "axios";
import { useEffect, useState } from "react";

const BasketItem = ({ img, name, price, size, color }) => {
  return (

{name}

{size}

  <div style={{ backgroundColor: `${color.color}` }} className={s.color}>
    {color}

1

{price}

  );
  };

 export default BasketItem;


text:
Q: Не отображаются обновленные данные Vue при изминении свойства с датой На входе - имеем свойство 'today', вычисляемое свойство 'CURRENT_YEAR' и метод 'prevYear'.
На выходе - при нажатии на стрелку влево вызывается метод который изменяет свойство (в нашем случае год) и в последствии чего шаблон должен обновиться и вывести новое значение из вычесляемого свойства.
Но не получается добиться результата... Возможно из-за того, что объект Date устроен функциями и Vue не видит этих изменений. Может кто-то уже сталкивался с этой проблемой и знает как все же добиться обновления?
Vue.component('schedule-component', {
    data: function () {
        return {
            today: new Date()
        }
    },
    computed: {
        CURRENT_YEAR: function () {
            return this.today.getFullYear();
        }
    },
    methods: {
        prevYear: function () {
            this.today.setFullYear(this.today.getFullYear() - 1);
        }
    },
    template:
        `

                 <--
                {{ CURRENT_YEAR }}

`
});

Сам год обновляеться и код работает, но проблема в том, что Vue не хочет отображать изминения (возможно из-за того, что объект Date устроен так, что Vue попросту не видит обновление в данных ибо Date построен на функциях и у него нету таковых свойств, за которыми можно было бы наблюдать), по этому и спрашиваю у вас, может вы знаете как решить это.

A: Я думаю, что Вы правы, в своем предположении

const schedule = Vue.component('schedule-component', {
  data: function() {
    return {
      today: new Date()
    };
  },
  computed: {
    CURRENT_YEAR: function() {
      return this.today.getFullYear();
    }
  },
  methods: {
    prevYear: function() {
      const newValue = this.today.setFullYear(this.CURRENT_YEAR - 1);
      this.today = new Date(newValue);
    }
  },
  template: `

                 <--
                {{ CURRENT_YEAR }}

`
});

const app = new Vue({
  components: {
    schedule
  },
  el: '#app',
  template: `

    <schedule></schedule>

`
});


text:
Q: Check if file content exists with powershell Apoligies in advance if my question isn't clear or not formatted correctly. This is my first time ever posting here.
I have a simple powerhshell script that copies files from one folder to another, if the file doesn't already exist in the destination folder. However, my current issue is that while the files have different names, they can have the exact same content. I want the script to be able tell if the file content already exist in the destination folder and if so, don't do anything. IF the file content doesn't already exist in the destination, then it copies the file. Any help is appreciated.
$date = get-date
$path = "path1"
$destination = "path2"
Foreach($file in (Get-ChildItem $path)) {
If($file.LastWriteTime -gt $date.date)
{
    #Test to see if the file already exists in the destination.
    if (!(Test-path (join-path $destination $file.name)))
    {
       Copy-Item -Path $file.fullname -Destination $destination
    }
}

}

A: I am going to have to go with what Kory Gill posts.
Use get-filehash to test the hashes of the files to see if they match or not..even if their file names are different.  It hashes the contents.  Keep in mind that any difference will create a different hash.  Any space or character that is in one file and not the other will produce a completely different hash.  But, if you are looking for exact matches this works best.  use -Algorithm sha256 since sha1 and md5 or declared not secure (possible to get collisions), though it might be hard with Sha1 to get a collision still today unless you are really trying.
if((Get-FileHash -Path <file1> -Algorithm SHA256).Hash -ne (Get-FileHash -Path <file1> -Algorithm SHA256).Hash)
{
    "Copy the file"
}


text:
Q: Why won't my objects print? New to the site as well as c#. This is my first time using c# and I can't get my objects to print properly. (example Million, Max 55. Cardenas, Jose, 22). I am pretty sure the error is in my accessors but I can't seem to get it right.
  using System.IO;
  using System;

  class PersonApp
   {
  static void Main()
   {
    Random random = new Random();
    Person p1 = new Person();
    Person p2 = new Person();

    p1.Fname = "Max";
    p1.Lname = "Million";
    p1.Id = random.Next(1,100);

    p2.Fname = "Jose";
    p2.Lname = "Cardenas";
    p2.Id = random.Next(1,100);

    Console.WriteLine(p1,p2);
  }
}

   using System.IO;
   using System;

   public class Person
   {
     private string Fname;
     private string Lname;
     private int Id;

  public Person(){
    Fname = string.empty;
    Lname = string.empty;
    Id = 0;
  }

   public string Fname
    {
    get
    {
        return Fname;
    }

    set
    {
        Fname = value;
    }
   }

    public string Lname
   {
    get
    {
        return Lname;
    }

    set
    {
        Lname = value;
    }
   }

   public int Id
  {
    get
    {
        return Id;
    }

    set
    {
        Id = value;
    }
   }

   }

A: You have a few issues in your code.
First, you can't pass multiple values to Console.WriteLine like this:
Console.WriteLine(p1, p2);

Do one at a time:
Console.WriteLine(p1);
Console.WriteLine(p2);

Second, you can't name your private backing field and the public property used to get/set it the same. You can name them whatever you want... typically the private variable starts with a lower case or an underscore, but that's up to you.
Once you fix those, you'll still get unusual output, which is actually the full namespace of your class. That's the result of ToString() being implicitly called when you pass p1 to Console.WriteLine.
Override the ToString() method in your class:
public class Person
{
    private string Fname;
    private string Lname;
    private int Id;

    private override string ToString()
    {
        return string.Format("{0}, {1} {2}", Lname, Fname, Id);
    }

    ...
    ...
}

A: You need to access property of the method to get the values printed
Wrong code :
   Console.WriteLine(p1,p2); // You are trying to print Objects and this is wrong. !!

Correction : Use accessory's get to print the output.
   Console.WriteLine(p1.Fname); // Print first name "Max"

Likewise
   Console.WriteLine(p1.Lname); // print Last name
   Console.WriteLine(p1.Id);  // Print ID

Also your class need to be corrected
  using System.IO;
  using System;

  public class Person{

        private string fname;
        private string lname;
        private int id;

        public string Fname
        {
            get
            {
                return fname;
            }

            set
            {
                fname = value;
            }
        }

        public string Lname
        {
            get
            {
                return lname;
            }

            set
            {
                lname = value;
            }
        }

        public int Id
        {
            get
            {
                return id;
            }

            set
            {
                id = value;
            }
        }
    }

Now you can use it like
        Person a = new Person();
        a.Fname = "k";
        a.Lname = "Do";
        a.Id = 1024;

        Console.WriteLine(a.Fname+" "+a.Lname+" "+a.Id);

A: You can't expect C# to know the format you want the object output in. You have to concatenate the strings yourself to produce the output.
The neatest way to do this is expose a readonly property on Person that formats it how you want, something like this:
public string DisplayName {
    get {
        return Lname + ", " + Fname + " " + Id;
    }
}


text:
Q: Mod-Rewrite in a subdirectory I'm a beginner to mod_rewrite.
I am trying to build a website for a club, and I think using mod_rewrite would pretty up the urls a bit.
Anyway, the page currently is under development, so I have placed it in a subdirectory.
To access my page I would browse to mydomain.com/minisite/club/alpha.
Within this directory, my index.php page asks for an id in which to return a page. so mydomain.com/minisite/club/alpha/index.php?id=1 would return the first page.
I would like the page to appear as .mydomain.com/minisite/club/alpha/page/1/.
Please refer to any useful documentation that I could read to better understand mod_rewrite,
Mark

A: In the alpha folder (where index.php is located), create a .htaccess with the following contents:
RewriteEngine On
RewriteRule ^page/(.*?)/*$ index.php?id=$1

This allows you to browse to both .../page/1 aswell as .../page/1/

A: Add this rule to your .htaccess file in the root directory of your folder. If you already have rules there, add this rule at the top.
#if these 2 lines already exist skip them
RewriteEngine on
RewriteBase /

#this rule should before other RewriteCond/RewriteRules in your .htaccess
RewriteRule ^minisite/club/alpha/page/([0-9]+) minisite/club/alpha/index.php?id=$1 [L,NC]

Here are some resources for .htaccess: Introduction to htaccess,  htaccess Tricks, Apache Docs on Htaccess


text:
Q: Search Gerrit for commits previously rejected by a reviewer Question
How do you search for commits which have ever received CodeReview-2 in the past from a given reviewer?
Context
Basically I want to do a retrospective on every commits I've ever rejected so that I can share those the comments to more people.
It's very easy to get the commits I'm currently rejecting using the search terms reviewer:self label:CodeReview-2.
But once the owner of the commit fixes the issue with a new patchset and I put a +2 on it, I won't be able to search for that commit anymore.
So I'm looking for something like had-label:CodeReview-2.

A: At our local installation we get an email from gerrit at each scoring.
Thus, as a workaround, you can search for emails from gerrit containing "< your login > has posted comments on this change." and "Code-Review-2".


text:
Q: onCreateView pager adapter Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.setAdapter(androidx.viewpager.widget.PagerAdapter)' on a null object reference
I'm trying to implement sliding tab layout using android material design. But it gives me NullPointerException. Here is my code so far:
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private List<Slide> listSlides;
private ViewPager slidePager;
private TabLayout indicator;

 public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {

    homeViewModel =
            ViewModelProviders.of(this).get(HomeViewModel.class);
    View root = inflater.inflate(R.layout.fragment_home, container, false);

     listSlides = new ArrayList<>();
     listSlides.add(new Slide(R.drawable.a, "slide title"));
     listSlides.add(new Slide(R.drawable.b, "slide title"));

     final SliderPagerAdapter adapter = new SliderPagerAdapter(getContext(), listSlides);

     homeViewModel.getText().observe(this, new Observer<String>() {
         @Override
         public void onChanged(@Nullable String s) {
             slidePager.setAdapter(adapter);
         }
     });

    return root;

}

}
public class SliderPagerAdapter extends PagerAdapter {
private Context mText;
private List<Slide> mList;

public SliderPagerAdapter(Context mText, List<Slide> mList) {
    this.mText = mText;
    this.mList = mList;
}

@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {

    LayoutInflater inflater = (LayoutInflater) mText.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View slideLayout = inflater.inflate(R.layout.slider_item,null);

    ImageView slideImg = slideLayout.findViewById(R.id.slide_img);
    TextView slideText= slideLayout.findViewById(R.id.slide_title);

    slideImg.setImageResource(mList.get(position).getImage());
    slideText.setText(mList.get(position).getTitle());

    container.addView(slideLayout);
    return slideLayout;

}

@Override
public int getCount() {
    return mList.size();
}

@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
    return view == object;
}

@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
    container.removeView((View) object);
}

}

A: You didn't instantiate the slidePagerso when you try to setAdapter, it is in fact a null object. You should call a findViewById on the ViewPager.


text:
Q: Use php array in javascript I have an array like:
foreach ( $attachment_ids as $attachment_id ) {
   $array = wp_get_attachment_url( $attachment_id );
}

I need to use that array in a javascript later in the page but outside of the foreach.
Is that possible? I have tried using json encode:
foreach ( $attachment_ids as $attachment_id ) {
       $array = json_encode(wp_get_attachment_url( $attachment_id ));
    }

And then in the script:
<script>
var json = <?php echo json_encode(); ?>
</script>

But it does not work probably, i guess it's because it's outside the foreach?
//Simon

A: Build the array in the loop, then encode and echo it
$array = array();

foreach ( $attachment_ids as $attachment_id ) {
     array_push($array, wp_get_attachment_url( $attachment_id ));
}

<script>
var json = <?php echo json_encode($array); ?>
</script>


text:
Q: How to draw from sample until at least one of each sample value is obtained and then stop I am working on a homework problem where a cereal company is running a promotion where 1 of 4 free toys is included in each box. The goal is to collect all 4 toys through buying one box at a time.
There are two scenarios:
1.Each toy is equally likely
2.The toys have selection probabilities 0.10, 0.25, 0.25, and 0.40.
I want to design a function that takes each toy number and each toy's selection probability as inputs, simulates buying boxes of cereal by sampling from the toy numbers until at least one of each toy is obtained, then stops and reports how many boxes were purchased.
The end goal is to use this function in a Monte Carlo simulation study to find out on average how many boxes consumers will have to buy to collect all the toys, and the proportion of consumers that will have to buy at least 14 boxes to collect all the toys.
I've tried to create a loop (while, repeat) which samples until a vector contains all the toy values but the loops have run infinitely. I suspect there is a problem with the condition I am feeding the loop.
box_buyer <- function (purchase_options, probabilities) {

  boxes <- numeric()

  while (!purchase_options %in% boxes) {

    append(boxes, sample(purchase_options, 1, probabilities, replace = TRUE))

  }

  return(length(boxes))

}

box_buyer(c(1, 2, 3, 4), c(1/4, 1/4, 1/4, 1/4))

I am expecting a function that returns the number of boxes that were purchased. Currently what I get is an infinite loop that gives the error: "the condition has length > 1 and only the first element will be used" repeated until I terminate R.
How can I get the loop to sample until at least one of each toy is obtained and then stop and return the number of boxes purchased? Any help is appreciated.

A: I don't think this loop will be very efficient, because you need to restart the random number generator every time it steps through the loop. I would suggest, instead, taking a large sample of c('A', 'B', 'C', 'D') with the desired probabilities, then seeing when you first got each element, and taking the max of those. This could fail if you happened not to draw any of one type, but with a large enough sample that becomes vanishingly improbable. Here's an implementation of my suggestion.
set.seed(1)

probs <- c(.1, .25, .25, .40)
samp <- sample(c('A', 'B', 'C', 'D'), size = 1000, replace = TRUE, prob = probs)

max(c(min(which(samp == 'A')), min(which(samp == 'B')), min(which(samp == 'C')), min(which(samp == 'D'))))
[1] 6
samp[1:6] # we get the final missing item on draw 6
[1] "D" "D" "C" "A" "D" "B"

A: As @qdread mentioned in the comment you have to include "any". Also you have to reassign boxes in each loop iteration or else it just stays as a numeric empty vector:
box_buyer <- function (purchase_options, probabilities) {

  boxes <- numeric()

  while (any(!purchase_options %in% boxes)) {

    boxes <- append(boxes, sample(purchase_options, 1, probabilities, replace = TRUE))

  }

  return(length(boxes))

}


text:
Q: If a variety over a real closed field has finitely many points they are singular Let $F$ be a real closed field. Let $X$ be a positive-dimensional algebraic variety over $F$.
If $X$ finitely many $F$-points are they all singular?

A: Sure. Suppose for contradiction that $P$ is a smooth point. Let $n$ be the dimension of $X$. Consider a projection $X \to \mathbb A^n$ that induces an isomorphism from the tangent space of $X$ at $P$ to the tangent space of $\mathbb A^n$.
This map is etale in a neighborhood of $P$, so it is locally standard etale, i.e. $X$ is locally of the form $\operatorname{Spec} F [x_1,\dots, x_n,y, g^{-1}]/f$ where $f$ and $g$ are polynomials in $x_1,\dots, x_n$, with $f$ monic in $y$ and $\frac{df}{dy}$ a unit.
Let $\overline{x}_1,\dots, \overline{x}_n, \overline{y}$ be the coordinates of $P$. Then since $\frac{df}{dy}(P) \neq 0$, and wlog it is possitive, for $\delta>0$ small we have $f(\overline{x}_1,\dots, \overline{x}_n, \overline{y}+\delta)>0$ and $f(\overline{x}_1,\dots, \overline{x}_n, \overline{y}-\delta)<0$. Then for $\epsilon$ small we have $f(\overline{x}_1+\epsilon,\dots, \overline{x}_n, \overline{y}+\delta)>0$ and $f(\overline{x}_1+\epsilon,\dots, \overline{x}_n, \overline{y}-\delta)<0$ so by the intermediate value theorem there is $y'$ satisfying $y-\delta < y' < y+\delta$ with $f(\overline{x}_1+\epsilon,\dots, \overline{x}_n,y')=0$.
Since this works for infinitely many $\epsilon$, there are infinitely many points, contradicting our assumption.
(I used the definition of real closed field as fields satisfying the intermediate value theorem for polynomials, which is, for example, the 8th one on Wikipedia.)


text:
Q: Git Desktop error " ! [remote rejected] master -> master (permission denied)" After forking a repo (Repo A) to Repo B, I've cloned a copy onto my PC using Git Desktop. I've then rolled back Repo B to an older commit using CLI and now want to push the change using Git Desktop. I keep getting a permission denied error.
I have added the lines for Windows 10 as per how to log out of one Github account and use another account? however it makes no difference, still having the same issue.
Running git push from the CLI and entering my credentials, I still get "! [remote rejected] master -> master (permission denied) error: failed to push some refs to'"

A: First, make sure you are pushing to your fork (repoB), a repo that you own.
Second, make sure the master branch is not protected against push.
And make sure to use a git push --force, if you have reset your branch to an older commit.
The OP confirms in the comments:

The repo was created with a new account and I'm still logged into the desktop with my personal account

The idea for pushing to a fork remains to push to a repo that you own. The account must match.


text:
Q: Explain the statement I meet the following statement in a code. Can somebody explain it to me, please?
My problem is mostly with the number 0.80. Where do we get it? I know that Math.random generates numbers between 0-0.99.
if (Math.random() > 0.80) { ... }

A: They are trying to create a if statement that gets executed randomly about 20% of the time.
the 0.80 is just a 'magic number' for their particular application. For example changing it from 0.80 to 0.50 would result in the if statement getting executed about 50% of the time.


text:
Q: Dynamically generated dropdown list breaks web service call I have an ASPX dropdown list, that is used in a web service call to generate a graph.
If I manually enter the drop down list entries, the code executes fine, however if I dynamically generate the dropdown list from the SQL server the web service call fails.
Here is how I am generating the dropdown list:
//Populate Customers DDL

string constr = ConfigurationManager.ConnectionStrings["Indigo2.Properties.Settings.ConstrNW"].ConnectionString;
DataTable customers = new DataTable();

    using (SqlConnection con = new SqlConnection(constr))
    {
        try
                {
                    SqlDataAdapter adapter = new SqlDataAdapter("SELECT DISTINCT custid from [Indigo].[dbo].[invoices] WHERE custid='ACC001'", con);
                    adapter.Fill(customers);
                    //ddlCustA.DataSource = customers;
                    //ddlCustA.DataTextField = "custid";
                    //ddlCustA.DataValueField = "custid";
                    //ddlCustA.DataBind();
                }
                catch (Exception ex)
                {
                    // Handle the error
                }

    }

Here is the HTML
<asp:DropDownList ID="ddlCustA" runat="server" Height="17px" Width="100px" AutoPostBack="True">
</asp:DropDownList>

This is where I call the Web Service
    //Code for graph (all in document ready)
    $("#btn_line_chart").on('click', function () {
        var CustA = $("#ddlCustA").val();
        var CustB = $("#ddlCustB").val();
        var getYear = $("#ddlYear").val();

        var jsonData = JSON.stringify({
            custA: CustA,
            custB: CustB,
            year: getYear
        });

        $.ajax({
            type: "POST",
            url: "WebService1.asmx/getLineChartData",
            data: jsonData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess_,
            error: OnErrorCall_
        });

        function OnSuccess_(reponse) {
            var aData = reponse.d;
            var aLabels = aData[0];
            var aDatasets1 = aData[1];
            var aDatasets2 = aData[2];

            var data = {
                labels: aLabels,
                datasets: [{
                    label: "My First dataset",
                    fillColor: "rgba(220,220,220,0.2)",
                    strokeColor: "rgba(220,220,220,1)",
                    pointColor: "rgba(220,220,220,1)",
                    pointStrokeColor: "#fff",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "rgba(220,220,220,1)",
                    data: aDatasets1
                },
                {
                    label: "My Second dataset",
                    fillColor: "rgba(151,187,205,0.2)",
                    strokeColor: "rgba(151,187,205,1)",
                    pointColor: "rgba(151,187,205,1)",
                    pointStrokeColor: "#fff",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "rgba(151,187,205,1)",
                    data: aDatasets2
                }]
            };

            var ctx = $("#myChart").get(0).getContext('2d');
            ctx.canvas.width = 750; // setting width of canvas
            ctx.canvas.height = 400;  // setting height of canvas

            var lineChart = new Chart(ctx, {
                type: "line",
                data: data,
                bezierCurve: false
            });
        }
        function OnErrorCall_(repo) {
            alert("Woops something went wrong, pls try later !");
        }
    });

If I manually choose the dropdown list options (like below), it works fine.
    <select id="ddlCustA">
        <option>ACC001</option>
    </select>

When the dropdown list is generated from the SQL server, the web service call fails with the folowing error:

HTTP500: SERVER ERROR - The server encountered an unexpected condition
  that prevented it from fulfilling the request. (XHR)POST -
  https://localhost:44338/WebService1.asmx/getLineChartData

Any help greatly appreciated.
UPDATE: It seems to be a timing issue. If I add an alert just before the web service calls the ddlCustA variable, ddlCustA shows as "Undefined"
alert($("#ddlCustA").val());

A: In case it helps anyone else, my solution was the way I was calling the object from Javasctipt. The below code fixed it.
 var CustA = document.getElementById('<%= ddlCustA.ClientID %>').value


text:
Q: Temporary bug allowing moderators to see individual votes from all users Moderators can see individual votes from all users on their site right now, i.e. what you see here for your own account.
While this does make it easier for use to find voting rings that managed to stay under the radar, this power is normally reserved for staff members and should remain that way; IIRC accessing that URL for other users used to give a 404 - Not Found for me (which it still does when not logged in, or on sites where I'm not a moderator).

A: This bug was indeed introduced while working on allowing to view close and delete vote history. We're rolling back that change, afterwards it should be fixed. Apologies for the inconvenience!
Update: We've audited traffic logs and have no evidence to suggest that user vote pages were abused while this bug was in production.


text:
Q: Uncaught Error: Element type is invalid: expected a string react-leaflet I integrated react-leaflet on my project create with create-react-app scripts. I follow this example.
Everything works, but when I try use GeoJsoncomponent imported as:
import { Map, TileLayer, Popup, GeoJson } from 'react-leaflet'

I have the following warning.

warning.js:35 Warning: React.createElement: type is invalid --
  expected a string (for built-in components) or a class/function (for
  composite components) but got: undefined. You likely forgot to export
  your component from the file it's defined in. Check your code at
  index.js:47.

and error

Uncaught Error: Element type is invalid: expected a string (for
  built-in components) or a class/function (for composite components)
  but got: undefined. You likely forgot to export your component from
  the file it's defined in. Check the render method of Leaflet

and I can't see the region on maps.
How can fix this?
Thanks
.

A: According to react-leaflet recent changes ,
You should try to import GeoJSON instead of GeoJson.
It was changed in order to match the recent leaflet library change.


text:
Q: Will overwriting Data extensions cause issues in using it in journey builder through the contact data model (not journey data)? I am in a situation where I am having to choose whether I should Add/Update or Overwrite in a Daily Batch File Import into a Data Extension which I plan to use in Decision Paths in Journey through the contact data model (not journey data). Is it true that if my import type into this DE is Overwrite, it will cause issues as the _CustomObjectKey will change?
Also, can someone explain what _CustomObjectKey is? Does each DE record have a unique _CustomObjectKey or is it one per key per DE? How can we find the out _CustomObjectKey?

A: The hidden field _CustomObjectKey is an auto-incrementing value on each data extension. If you set the import type to overwrite it will have new _CustomObjectKey values.
For example, you have 3 records in a data extension. The _CustomObjectKey of those 3 records will be 1, 2, 3. You overwrite those records with 4 new records. Those _CustomObjectKey values will be 4, 5, 6, 7 even though it looks like the data extension only have 4 records. Each time you overwrite or add new records, that _CustomObjectKey value will automatically increment.
More information here: https://help.marketingcloud.com/en-US/documentation/exacttarget/subscribers/data_extensions_and_data_relationships/
With that said, I would recommend that you do not overwrite your data extension if you are planning to use Decision Splits in that journey. You can either:

*

*Use the import type of Add/Update

*Or import into a "staging" data extension and query into the data extension you use for your journey.


text:
Q: Unable to refresh the router menu in Angular 4 I'm unable to have the router menu update itself when doing a router.navigateByUrl in Angular 4.
What I'm doing is really basic, I'm just trying to hide the login/logout menu when the user isn't/is authenticated. Below is my app.component.html:

  {{ appName }}

    Login
    Logout

<router-outlet></router-outlet>

And here is my app.component.ts:
import { Component } from '@angular/core';
import { AuthService } from './services/auth.service';
import { Router } from '@angular/router';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    isLogged: boolean;

    // inject auth
    constructor(private auth: AuthService, private router: Router) { }

    ngOnInit() {
        this.isLogged = this.auth.isLogged;
        console.log('[app] islogged:' + this.auth.isLogged);

        // redirect according to whether user logged in
        if (this.isLogged)
            this.router.navigateByUrl('/total');
        else
            this.router.navigateByUrl('/login');
    }
}

As you can tell, Login and Logout are two separate components. To show which part of the code is responsible for this issue, below is the LogoutComponent::ngOnInit():
ngOnInit() {
    // logout
    this.auth.logout();

    // redirect to /login
    this.router.navigateByUrl('');
}

The last command is able to redirect to the / but the menu isn't updated according to the template posted in the first code.
Edit:
This is the service used to login/logout users:
import { Injectable } from '@angular/core';

@Injectable()
export class AuthService {
    isLogged: boolean = false;
    token: string;

    constructor() { }

    login(token: string) {
        // save token on login
        this.isLogged = true;
        this.token = token;
    }

    logout() {
        // delete token on logout
        this.isLogged = false;
        this.token = '';
    }
}

A: change it based on the route as,
this.router.navigate(['/login']);

While the above will solve your navigation issue.In addition to that, the actual problem lies with the way you update isLogged variable in your app.component.html
According to the way you have right now, it wont get updated whenever it is updated in other components. So you should have the shared service with a variable subject, which would watch for changes.
Something like this,
export class AppMessageQueuService {
    authenticatedUserData: Subject<LoginInfo>;
    constructor() {
        this.authenticatedUserData = new Subject<LoginInfo>();
    }
}


text:
Q: Characteristic function of a random variable: what is the argument/input? The characteristic function (c.f.) of a random variable, $X$, is defined as:
$$
\varphi_X(t) = \mathbb{E}[e^{i\langle t,x \rangle}]
$$
For example, the c.f. of a Poisson random variable, $X$ is:
$$
\varphi_X(t) = e^{-\lambda(1-e^{it})}
$$
I know c.f.'s are an extension of moment-generating functions, and can therefore be used to compute moments. And it is also easy to find the c.f. of the sum of independent random variables (take the product of the individual c.f.'s).
My question is: how do we interpret the argument/input ($t$) of a c.f. ?
There is a similar question here.
However, I do not understand the answer that says it is a "'sensor setting' chosen to investigate whether the given PDF has some inbuilt periodicity at $t$".


text:
Q: Converting functions to a Class The following code shows an alert if the user is using IE11 and sets a cookie that expires after 24 hours:
var cookieExists = document.cookie.indexOf('ie11_cookie') >= 0;

// Function for checking if IE11 or bellow
function isIE() {
  return window.navigator.userAgent.match(/(MSIE|Trident)/);
}

// Function for setting a cookie
function createCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

// If the user is using IE11 and no cookie exist, show the alert and set a cookie
if (isIE() && !cookieExists) {
  window.alert("Your browser is outdated!");
  // Setting a cookie with an expiry date of 1 day
  createCookie('myCookie', 'ie11_cookie', 1);
}

The script works but now I'm trying to convert it to a class.
I've tried this:
var cookieExists = document.cookie.indexOf('ie11_cookie') >= 0;

class ieAlert {
  // Method for checking if IE11 or bellow
  isIE() {
    return window.navigator.userAgent.match(/(MSIE|Trident)/);
  }
  // Method for setting a cookie
  createCookie(name,value,days) {
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
  }
}
// If the user is using IE11 and no cookie exist, show the alert and set a cookie
if (ieAlert.isIE() && !cookieExists) {
  window.alert("Your browser is outdated!");
  // Setting a cookie with an expiry date on 1 day
  createCookie('myCookie', 'ie11_cookie', 1);
}

module.exports = ieAlert;

But if I run the code, I get the following error in console:

Uncaught TypeError: ieAlert.isIE is not a function

I also don't want to use any ES6 syntax as the script should work in IE11 and I'm not using Babel.
What am I doing wrong? What would be the right solution?

A: If you don't want to call a function on an instance of the class, but on the class itself, you should use the static keyword to define your isIE function as static.
var cookieExists = document.cookie.indexOf('ie11_cookie') >= 0;
class ieAlert {
  static isIE() {
    return window.navigator.userAgent.match(/(MSIE|Trident)/);
  }
  // …
}
// …
if (ieAlert.isIE() && !cookieExists) {
  // …
}


text:
Q: My while statement is getting infinite loop? #include "stdafx.h"
#include <iostream>
#include <string>

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

using namespace std;

//this program will let the user input their assignment score and see their letter grade
int main() {

    int score;

    cout << "Input your score: ";

    //to make the while loop
    int x = 1;

    while (x == 1) {

        cin >> score;

        if (score >= 90){
            cout << "\nA";
            break;
        }

        else if (score >= 80) {
            cout << "\nB";
            break;
        }

        else if (score >= 70) {
            cout << "\nC";
            break;
        }

        else if (score >= 60) {
            cout << "\nD";
            break;
        }

        else if (score >= 0) {
            cout << "\nF";
            break;
        }

        else
            cout << "\nInvalid input";
    }
}

I'm trying to write a program that let the user input their score for an assignment and display their resulting letter grade. If the user input is not a valid score, it prints "Invalid input" and should ask for user input again. However, when I actually run the program and type in an invalid value, it goes into an infinite loop of printing "Invalid input". Why is this? Thanks in advance.

A: When the user enters invalid input, cin >> score fails and leaves an error flag set on the stream.
Subsequent read operations just don't do anything until you clear that flag with std::basic_ios::clear().
Furthermore, since the read failed, score has some unspecified value (as you did not initialise it), and apparently on your test runs that unspecified value happens not to match any of those continues, so you never hit a break.
Instead of just:
std::cin >> score;

Try this:
if (!(cin >> score)) {
   // If reading into an int failed, we come here
   cout << "Invalid value! Try again" << endl;

   // Clear error flag
   cin.clear();

   // Restart the loop
   continue;
}

You may also need to ask the stream to eat up newlines in the input buffer. If you get the "Invalid value!" message twice, look up on SO how to do that.

A: you set x=1 and check if x==1. For the compiler it seems that it could be an infinite loop because it's unsure if a break would happen, that's why it's only a Warning and not an Error. For that behaviour you don't even need to vast the variable x , you could use while(true) too.


text:
Q: Angular2 HttpClient get requests that respond with application/javascript are parsed as JSON but I want them to be `eval`'d The tl;dr of my question: Is there a way to setup Angular's HttpClient to have this same behavior as it does in the jQuery and CGI example? Is there a way of using the Angular HttpClient to not interpret the response as JSON, but instead just eval(response_data)?
When running ng serve and making a request in the application using HttpClient#get, like this...
return this.httpClient.get('/assets/values.json')
return this.httpClient.get('/assets/values.js')

... the Angular development web server returns a response with an appropriate Content-Type header, of which the value for the above get requests are, respectively:
Content-Type: application/json
Content-Type: application/javascript

If I put JavaScript in the values.js file, I get a syntax error, "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data" -- which to me is an obvious indication that the application/javascript is not being executed in the browser. It's being interpreted through the automatic execution of the JSON.parse function. The file should not be interpreted as JSON, and this is not the behavior I want.
The behavior that I want is to execute the JavaScript response, similar to what happens when a CGI server response is returned:
Content-Type: text/javascript

x=1;

If I run a web app that calls jQuery.get('/values.js'), and a CGI backend script returns the above response, then x has the value 1 in my browser's window (the JavaScript global) object. This is the (somewhat unclear behavior) of jQuery, but I am guessing it has to do with using the Content-Type header. Seemingly, jQuery#ajax is called with a dataType: "script" property on the options.
EDIT: Before you ask "why am I doing it like this? Try doing this instead..." The reason I'm using assets like this is to create an environment exactly like that which I am building this app for. The GUI app is going to run in an environment with a CGI backend, and the API Response Format described in the backend is specified. I cannot change it. I would like to design my frontend app using mock behavior so that I don't have to deploy the app every time I want to test it. The frontend application being developed using ng serve is an ideal environment because of its auto-refreshing developer experience, and to make it even more useful for me (I think) I want this behavior.

A: Use a different HttpClient#get configuration object, so that Angular does not interpret the response as JSON and it will not return the return value of JSON.parse when it's configured as below:
const options = {
  observe: 'body' as const,
  responseType: 'text' as const,
};
return this.httpClient.get('/assets/values.js', options)

When the HttpClient#get returns, the value will be an Observable with the response body as a parameter of the data returned.
You can subscribe to the Observable and call eval like this .subscribe(data => eval(data)) to get the same behavior as jQuery.


text:
Q: Possible oneliner for this Ruby on Rails code I have a file object which is of type Rails ActionDispatch::Http::UploadedFile.
I need to overwrite user assigned filename with a generic name while preserving the extension of the file. This is how I have the code implemented currently. Is there are a way better and elegant way of writing this in Ruby.
extension = File.extname(file_name.original_filename)
file_name.original_filename = "hello#{extension}"

A: file.original_filename.sub!(/.*\./, "hello.")

this works because .* is greedy and will swallow everything up to the last . it finds.  That just happens to be the the one before the extension.
Or to do an exact replacement, you can just do:
file_name.original_filename = "hello" + File.extname(file_name.original_filename)

technically, still a oneliner lol.

A: Edit: I misunderstood. (I thought new_name included an extension that was to be replaced by "old_fname"'s extension.) As @Bassel says (thanks, Bassel), it should simply be:
old_fname = "/a/b/c.hello"
new_fname = "/d/e/f"

new_fname += File.extname(old_fname)


text:
Q: Check that a list of variables have each been set I have an array filled with the names of variables like this:
var myVariables = [variable1,variable2,variable3,variable4];

Is there a simple way besides and each to test if all of these variables have been assigned a value (elsewhere in my code)?

A: I would suggest using Array.some, with that approach there is a chance you won't have to iterate the entire array:
const hasEmpty = myVariables.some(v => typeof v === 'undefined');

A: You could use the Array.prototype.some() method :

The some() method tests whether some element in the array passes the
  test implemented by the provided function.

It could be more efficient than forEach method as it stops iterating (short circuit in a some way) as soon a element matches the condition.
For example to check that all elements are > 0, use some() with the reverse condition, that is : <=0.
var isFailed = [0, 1, 2, 3, 4].some(x => x <= 0);

For example, here, as soon the first iteration, some() exits and return false.

A: return myVariables.indexOf(undefined) === -1;

A: If one of your variable is not defined, this will throw a ReferenceError such as mentionned in top comments by Felix Kling. Otherwise if it has the value undefined then you can check if your array contains undefined values.
don't throw Reference Error
If you execute the code below you will get a ReferenceError since variable1 has never been defined.

const myArray = [variable1]

But this next code will just create an array with an undefined value in it, since the variable is declared:
let variable1
const myArray = [variable1]

check if undefined is included
With ES 2016 includes():
const isAllDefined = !myVariables.includes(undefined)
// use this boolean where you need it


text:
Q: .NET GetThumbnailImage is not keeping metadata I have a web service that creates an thumbnail of any image uploaded, but all the thumbnails are rotated by 90 degrees. I know this is because of the metadata not being shared with the new image.
How do I set the meta data of the new image to match that of the original picture?
The code is simple:
        // Load image
        Image origImage = Image.FromFile(tempFilePath);

        // Compute thumbnail size
        Size thumbSize = GetThumbnailSize(origImage);

        // Get thumbnail
        Image thumbImage = origImage.GetThumbnailImage(thumbSize.Width, thumbSize.Height, null, IntPtr.Zero);

I tried using things like the code below, but of course it doesn't work.
thumbImage.SetPropertyItem(origImage.GetPropertyItem(0x0112));

After fighting for a while I gave up on trying to set the meta data on the thumbnail so I did the following to fix the rotation:
try
        {
            switch (BitConverter.ToInt16(origImage.GetPropertyItem(0x0112).Value, 0))
            {
                case 1:
                    thumbImage.RotateFlip(RotateFlipType.RotateNoneFlipNone);
                    break;
                case 3:
                    //rft = RotateFlipType.Rotate180FlipNone;
                    thumbImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
                    break;
                case 6:
                    //rft = RotateFlipType.Rotate90FlipNone;
                    thumbImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
                    break;
                case 8:
                    //rft = RotateFlipType.Rotate270FlipNone;
                    thumbImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    break;

            }
        } catch(Exception e){
            Console.WriteLine(e);
        }

Now all my thumbnails are formatted correctly I just hope it doesn't come back to bite me when I add support for Android devices to my service.

A: How about something like:
foreach(PropertyItem propItem in origImage.PropertyItems)
{
  thumbImage.SetPropertyItem(propItem)
}

A: I tested like bellow and it works for me.
thumbImage.Save("without-metadata.jpg", ImageFormat.Jpeg);

thumbImage.SetPropertyItem(origImage.GetPropertyItem(0x0112));
thumbImage.Save("with-metadata.jpg", ImageFormat.Jpeg);

var withoutImage = Image.FromFile("without-metadata.jpg");
// false, of course
Debug.WriteLine("Has 0x0112 property?: {0}", withoutImage.PropertyIdList.Any(o => o == 0x0112));

var withImage = Image.FromFile("with-metadata.jpg");
// true, of course
Debug.WriteLine("Has 0x0112 property?: {0}", withImage.PropertyIdList.Any(o => o == 0x0112));

Could you link an image file that doesn't work?