text:
Q: How to require module from gem to use its classes without namespace? Could you please help me?
I am developing gem, it has a module:
#cherry/sdk/high_level.rb
 module Cherry
  module SDK
   module HighLevel
    autoload :CherryUser, 'cherry/sdk/high_level/user'
    autoload :CherryCard, 'cherry/sdk/high_level/card'
   end
  end
 end

Now I use it like this:
 require "cherry/sdk/high_level"
 user = Cherry::SDK::CherryUser.new
 card = Cherry::SDK::CherryCard.new

But I need user to use my gem classes without namespaces, i.e.
 require "cherry/sdk/high_level"
 user = CherryUser.new
 card = CherryCard.new

How can I achieve it?
Also what do you think about autoload?
it was promised to depreciate this ability, but new ruby versions still have autoload method.
Thank you!

A: You can always include modules to get access to their classes inside current class scope:
module Cherry
  module SDK
    module HighLevel
      class CherryUser
      end
    end
  end
end

# require "cherry/sdk/high_level"
include Cherry::SDK::HighLevel
user = CherryUser.new # => #<Cherry::SDK::HighLevel::CherryUser:0x007f9c09185ab8>

About autoload - it's considered bad practice and you should avoid it. Here is quite good article about this: http://urbanautomaton.com/blog/2013/08/27/rails-autoloading-hell/

A: I think if you create classes at the top level and inherit them from your namespaced classes, it should work, i.e.
#cherry_user.rb
class CherryUser < Cherry::SDK::HighLevel::CherryUser
end

require 'cherry_user'
CherryUser.new

Otherwise you might need to define the public interface for your methods in the top-level CherryUser class, that will call the methods you need in your SDK (might be better organization-wise to set up your public API like that)
Also a better practice would be to have
#lib/cherry/user.rb
module Cherry
  class User < Cherry::SDK::HighLevel::CherryUser
  end
end

#lib/cherry.rb
require 'cherry/user'

# in user code
Cherry::User.new

this way bundler will automatically require lib/cherry.rb which will, in turn, load the User code, also there will be less classes added to the global namespace which is generally good


text:
Q: Is there any way to set the default value of all columns in a mysql database at a time? Is there any way to set all the columns(int)  default value at a time, in single query?

A: Yes
ALTER TABLE table_name
    ALTER COLUMN column_name datatype DEFAULT value

An example with int
ALTER TABLE table_name
    ALTER COLUMN column_name int DEFAULT 0;

If you actually wanted to change all the values in the table to a value instead, use:
UPDATE table_name
    SET column_name = value;

And if you wanted to change let's say all entries having old_value to new_value for column_name:
UPDATE table_name
    SET column_name = new_value
    WHERE column_name = old_value;

Please formulate your question more clearly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UIPickerView - using custom views for multi-line rows - need layout advice I have a UIPickerView which will display a list of items for the user.  I'd like each item to be presented as multiple lines of text using a different font size for each line.  A rough mockup is shown below.  This will allow presenting more text than can fit in the single line of the default UIPickerView.

bdesham pointed me towards using the pickerView:viewForRow:forComponent:reusingView in the delegate for the UIPickerView.  This seems to be the way to go as it'll let me provide my own custom view for the individual rows.
My thought was to create a UIView which had 2 UILabel subviews, one for each line of text.  This way I could apply a different font to each line.  I tried the below, but the layout doesn't seem to be working.  I need the lines to be one on top of the other.  The below was my attempt at floating the second line to the bottom via the mask.
#define VIEWTAG_LINE1 1
#define VIEWTAG_LINE2 2

- (UIView*)pickerView:(UIPickerView *)thePickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UIView* v;
    if (view)
        v = view;
    else
    {
        v = [[[UIView alloc] init] autorelease];

        UILabel* l1 = [[[UILabel alloc] init] autorelease];
        l1.tag = VIEWTAG_LINE1;
        [v addSubview: l1];

        UILabel* l2 = [[[UILabel alloc] init] autorelease];
        l2.tag = VIEWTAG_LINE2;
        l2.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [v addSubview: l2];
    }

    UILabel* l1 = (UILabel*)[v viewWithTag: VIEWTAG_LINE1];
    l1.text = [NSString stringWithFormat: @"row %d line 1", row];
    [l1 sizeToFit];

    UILabel* l2 = (UILabel*)[v viewWithTag: VIEWTAG_LINE2];
    l2.text = [NSString stringWithFormat: @"row %d line 2", row];
    [l2 sizeToFit];

    [v sizeToFit];

    return v;
}

This produces the below.  Any suggestions on getting the two UILabel views so they're stacked on top of each other producing the desired multi-line result?

A: You need to set the frames and font of the two labels.
    v = [[[UIView alloc] init] autorelease];

    UILabel* l1 = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 24)] autorelease];
    li.font = [UIFont sytemFontOfSize:22]; // choose desired size
    l1.tag = VIEWTAG_LINE1;
    [v addSubview: l1];

    UILabel* l2 = [[[UILabel alloc] initWithFrame:CGRectMake(0, 24, 320, 16)] autorelease];
    l2.font = [UIFont sytemFontOfSize:14]; // choose desired size
    l2.tag = VIEWTAG_LINE2;
    [v addSubview: l2];

Adjust the labels' height as needed. Adjust the y origin of l2 as needed.

A: If anyone's having this problem with Auto Layout, set translatesAutoresizingMaskIntoConstraints to YES (which is the default value). I was setting it to NO, which was causing all the problems.


text: Q: Blank desktop page I'm running Linux Mint. I just restarted my system after a system update. The login page doesn't wait for a password; it just boots, to a desktop showing only desktop icons. It is not showing the panel, and commands are not responding. It is still popping up Authentication: 'The login keyring did not get unlocked when you logged into your computer'.


text:
Q: Why does this regex not match the second binary gap? Trying a solution for the problem listed here in python, I thought I'd try a nice little regex to capture the maximum "binary gap" (chains of zeroes in the binary representation of a number).
The function I wrote for the problem is below:
def solution(N):
    max_gap = 0
    binary_N = format(N, 'b')
    list = re.findall(r'1(0+)1', binary_N)

    for element in list:
        if len(element) > max_gap:
            max_gap = len(element)

    return max_gap

And it works pretty well. However... for some reason, it does not match the second set of zeroes in 10000010000000001 (binary representation of 66561). The 9 zeroes don't appear in the list of matches so it must be a problem with the regex - but I can't see where it is as it matches every other example given!

A: The same bit can't be included in two matches. Your regex matches a 1 followed by one or more 0s and ends with another 1. Once the first match has been found you are left with 0000000001 which doesn't start with a 1 so isn't matched by your regex.
As mentioned by @JoachimIsaksson, if you want to match both sets of 0s, you can use a lookahead so that the final 1 is checked but isn't included in the match. r'1(0+)(?=1)'.


text:
Q: Substracting End and Start times to find difference in minutes So I need to see if there is at least 10 minutes between times to make my operator true or not so it knows to alert or not below is the code in VB.net
        Dim LessThanTen As Double

    Dim CheckTimeBegin As DateTime = Convert.ToDateTime(txttimebegin.Text)
    Dim CheckTimeEnd As DateTime = Convert.ToDateTime(txttimeend.Text)

    Dim Duration As TimeSpan = CheckTimeEnd - CheckTimeBegin

    If Duration.TotalMinutes < 10 Then
        LessThanTen = True
    Else
        LessThanTen = False
    End If

A: Fixed it
        Dim LessThanTen As Double

    Dim Startt = DateTime.ParseExact(txttimebegin.Text, "h:mm:tt", Nothing)
    Dim Endt = DateTime.ParseExact(txttimeend.Text, "h:mm:tt", Nothing)

    Dim Duration As TimeSpan = Startt - Endt

    If Duration.TotalMinutes < 10 Then
        LessThanTen = True
    Else
        LessThanTen = False
    End If


text: Q: Typing Arrow Pointing Leftwards Then Curving Upwards It seems that the Arrow Pointing Leftwards Then Curving Upwards character doesn't exist. The Arrow Pointing Rightwards Then Curving Upwards already exists. I've searched for how to write that character, but unfortunately none helped. I've came up with this alternative Leftwards Arrow with Tip Upwards. But, actually, I need it curved. How could I type the Arrow Pointing Leftwards Then Curving Upwards in a text editor (e.g OneNote)?


text:
Q: How to compare two lines in a file? Let say I have a file foo.csv:
timestamp,id,ip_src,ip_dst,protocol,msg
08/20-12:01:22.172612 ,1000001,10.0.0.2,10.0.0.1,ICMP,"ICMP test detected"
08/20-12:03:22.172809 ,1000001,10.0.0.6,10.0.0.3,ICMP,"ICMP test detected"
08/20-12:06:22.172940 ,1000001,10.0.0.1,10.0.0.2,ICMP,"ICMP test detected"
08/20-12:06:22.172838 ,1000001,10.0.0.9,10.0.0.2,ICMP,"ICMP test detected"
08/20-12:10:23.173945 ,1000001,10.0.0.8,10.0.0.1,ICMP,"ICMP test detected"
08/20-12:19:23.173982 ,1000001,10.0.0.1,10.0.0.8,ICMP,"ICMP test detected"

I want to how to compare ip_src from the last line and check the line above it until find a line that have same ip address.
Can I do that?
This is my code snippet:
#!/bin/bash
logfile="/var/log/foo.csv"

tail -s 0 -n 1 -f $logfile | while read line; do
    time=`echo $line | cut -f 1 -d ","`
    id=`echo $line | cut -f 2 -d ","`
    src=`echo $line | cut -f 3 -d ","`
    dst=`echo $line | cut -f 4 -d ","`
...

A: I'd flip the file around using tac - then you can note the first value of the third comma-separated field, and print when you see it again:
$ tac "$logfile" | awk -F, 'NR==1 {seen[$3]++; next} seen[$3] {print; quit}'
08/20-12:06:22.172940 ,1000001,10.0.0.1,10.0.0.2,ICMP,"ICMP test detected"

A: Another with awk:
awk -F, '{a[ip] = nr; nr = NR; ip = $3} END {print a[$3]}' foo.csv

This saves the previous line's IP and line number to the array a. After all lines have been processed, the last line number hasn't been updated yet - it's slot is still occupied by the line number of the last occurrence of that IP.

A: IIUC, something like this would do the job:
#!/usr/bin/env sh

last_ip_address="$(tail -1 "$1"  | cut -d, -f3)"
echo Last IP address: "$last_ip_address"
last_line="$(cut -d, -f3 "$1"  | grep -n "$last_ip_address" | cut -d: -f1 | tail -2 | head -n 1)"
echo Last line that has it: "$last_line"

Usage:
$./script.sh <FILE>

In your example:
$ ./script.sh foo.csv
Last IP address: 10.0.0.1
Last line that has it: 4

A: try one more solution with only awk.
awk '
{
  a[FNR]=$0
}
END{
split(a[FNR], array,",");
for(i=FNR;i>1;i--){
  split(a[i-1], array1,",");
  if(array[3] == array1[3]){
    print a[i-1];
}
}
}
' Input_file

This will look for all lines above which have same 3rd field as last line of Input_file, so if you want only very 1st match of that 3rd field of last line then add either exit or quit after print a[i-1], let me know if this helps you.


text:
Q: Find common first columns and print the second one if they are matched File1
3.5 22
5. 23
4.2 42
4.5 44

File2
3.5
3.7
5.
6.5

Desired output:
 3.5 22
 5. 23

I prefer to use 'awk'.

A: This oneliner should do the trick:
awk 'NR==FNR{a[$1];next}$1 in a' file2 file1

Explanation
NR==FNR{a[$1];next}: stores the keys presents in file2.
$1 in a: will print the line if the current key from file1 is in a where we stored the keysof file2.
From the docs:

If you refer to an array element that has no recorded value, the value
  of the reference is "", the null ... Such a reference automatically
  creates that array element, with the null string as its value.

Note
As @JonathanLeffler explain in comments $1 in a is used instead a[$1] to avoid creating elements in a when there's no match.
Note 2
As @EdMorton points a[$1]++ wastes processor cycles. We can use just a[$1] to initialize  the associative array.
Original code
awk 'NR==FNR{a[$1]++;next}a[$1]' file2 file1

Thanks Jonathan && Ed.


text:
Q: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse We have a really simple Tycho project:
<properties>
    <tycho-version>0.26.0</tycho-version>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.build.timestamp.format>yyyyMMdd_HHmmss</maven.build.timestamp.format>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.eclipse.tycho</groupId>
            <artifactId>tycho-maven-plugin</artifactId>
            <extensions>true</extensions>
            <version>${tycho-version}</version>
        </plugin>

        <plugin>
            <groupId>org.eclipse.tycho</groupId>
            <artifactId>target-platform-configuration</artifactId>
            <version>${tycho-version}</version>
            <!-- snipped because probably not relevant -->
        </plugin>
    </plugins>
</build>

When we execute the maven goal eclipse:eclipse, we get the following weird comment in the .project files of features and products:

NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse.

(A nonsense exception, because we execute it on the command line, there is no M2Eclipse involved at all.)
We could probably live with that, but the .classpath files look like that:
<classpathentry kind="lib" path="C:/Users/WileCoyote/.m2/repository/p2/osgi/bundle/com.itextpdf/5.5.3/com.itextpdf-5.5.3.jar"/>
<classpathentry kind="lib" path="C:/Users/WileCoyote/.m2/repository/p2/osgi/bundle/org.acme.config/2.0.2.v201506191015/org.acme.config-2.0.2.v201506191015.jar"/>
<!-- etc. -->

And so if imported in another user's workspace, these projects don't work anymore.
Here is an explanation on how to fix the problem, but that's really a no-brainer (remove the broken class path entries from the class path, because features and products don't need them anyway).
What I really want to know is why it happens at all? What is the problem? How do I fix it?


text:
Q: function and class calling I currently have this code from some source and is it possible to call this function on onCreate?
public static Intent getPickImageIntent(Context context) {
    Intent chooserIntent = null;

    List<Intent> intentList = new ArrayList<>();

    Intent pickIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    takePhotoIntent.putExtra("return-data", true);
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
    intentList = addIntentsToList(context, intentList, pickIntent);
    intentList = addIntentsToList(context, intentList, takePhotoIntent);

    if (intentList.size() > 0) {
        Log.d("mytag", "e");
        chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
                context.getString(R.string.pick_image_intent_text));
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
    }

    return chooserIntent;
}

I already tried:
public static Intent getPickImageIntent(Context context);
public Intent getPickImageIntent(Context context);
public static getPickImageIntent(Context context);

but no luck. still have error calling the function.
And is it possible to call a 2nd.class from Main.class? 2nd.class has all the work and Main.class will just pass and retrieve the data, image and text?

A: You didn't provide any detailed info but I will try to assume/guess some of them and try to answer. For a future, please fix Your question and try to be as precise as possible.

And is it possible to call a 2nd.class from Main.class? 2nd.class has all the work and Main.class will just pass and retrieve the data, image and text?

Yes, it is possible. Not exactly calling the class, but calling a method inside the class. If the method is static, You call it like this:
SecondClassName.methodName(parameter1, parameter2); // some method
SecpmdClassName.getPickImageIntent(context);        // method from Your question

If Your method is not static, You need an instance of Your class to call the method e.g:
SecondClassName secondClassInstance = new SecondClassName();
secondClassInstance.methodName(parameter1, parameter2);
secondClassInstance.getPickImageIntent(context); // You can also call a static method

You've mentioned a names like Main.class and 2nd.class. File names in Java needs to be equal to a public class declared inside. If this is Your class name "2nd" than it is incorrect. Classes' names cannot start with a digit - that's why I've used in my example above a "SecondClassName" instead of "2nd".


text:
Q: Reading ArrayList in Concurrent system I have a simple ArrayList and I am feeding this ArrayList from multiple Threads via Java concurrency. Each Thread will only read the same instance of this ArrayList. Is there any chance of error during the reading operation?

A: If the list is fully populated and always accessed in read-only by all the threads, you won't have a problem. If there is a write operation, then you need to synchronize all the accesses to the list, or to use a concurrent list (like CopyOnWriteArrayList).

A: Provided there are no more writes make it immutable using Collections.unmodifiableList and then forget about read issues.


text:
Q: Interpreting results from emmeans comparison I have a glm model with two fixed effects, Treatment and Date, to estimate Temperature from data collected in a time series. Within Treatment there are three different categories: Fucus, Terrycloth or Control, and temperature is measured beneath those canopies. The model is created like so mod1 <- glm(Temp ~ Treatment * Date, data = aveTerry.df )
I am trying to tell if Terrycloth has a similar effect as Fucus canopy (i.e. replicates it).
I found the emmeans package and believe it could help me compare between these levels within treatment by using my model, and have used it as so to find the estimated marginal means terry.emmeans <- emmeans(modAllTerry, poly ~ Treatment | Date) and plotted the comparisons via plot(terry.emmeans.average, comparison = TRUE) +theme_bw()
Giving me this output linked here.

I am looking for some help understanding what this graphical output is, especially what exactly are the comparisons (which are shown by the red arrows). I somewhat understand the that blue boxes are the confidence intervals for the mean value of temperature for each treatment on one day (based on model), but am wondering how is the comparison made? And why do some days only have a one sided arrow?

A: As described in the documentation for plot.emmGrid, the comparison arrows are created in such a way that two arrows are disjoint if and only if their respective means are significantly different at the stated level.
The lowest mean in the set has only a right-pointing arrow because that mean will not be compared with anything smaller, obviating the need for a left-pointing arrow. For similar reasons, the highest mean has only a left-pointing arrow. These arrows do not define intervals; their only purpose is depicting comparisons.
In situations where the SEs of pairwise comparisons vary widely, it may not be possible to construct comparison arrows. If that happens, an error message is displayed.
Confidence intervals are available as well, but those CIs should not be used for comparing means.
More information and examples may be found via vignette("comparisons", "emmeans"). Also, details of how the arrows are actually constructed are given in vignette("xplanations", "emmeans")


text:
Q: Why is there a difference between a for-loop optimization and an optimization via a personalized .fit() method for a keras.Model? I have been trying to create a keras.Model which can fit a Generalized Pareto Distribution (GPD) based on either samples of a GPD or its quantiles. The fit is done by minimizing the difference between the observation and the quantiles of the estimated GPD.
Imports
import tensorflow as tf
from tensorflow import keras
import tensorflow_probability as tfp

The GPD layer
I created a basic GPD layer by subclassing keras.layers.Layer and by keeping the parameters outside of the layer as recommanded for better performances. I am also using the GPD implemented in tensorflow_probability.distributions.GeneralizedPareto (see doc). The two parameters of the GPD are gamma and sigma.
class GPD_layer(keras.layers.Layer):
    def __init__(self):
        super(GPD_layer, self).__init__()
    def call(self, gamma,sigma,num):
        pareto = tfp.distributions.GeneralizedPareto(
            loc=0.0,
            scale=sigma,
            concentration=gamma
            )
        return pareto.quantile(tf.cast(tf.range(start=1/(num+1),limit=1.0,delta=1/(num+1),dtype=tf.float64),dtype=tf.float32))

The GPD model
I created a keras.Model subclass to have a proper model and to be able to train it like a regular keras.Model. Following the guide provided by the Keras team. I made the following subclass :
class GPD_model(keras.Model):
    def __init__(self):
        super(GPD_model, self).__init__()
        self.gpd_layer = GPD_layer()
        self.gamma = tf.Variable(
            initial_value=tf.random_normal_initializer(mean=0.2)(shape=(1,),dtype="float32"),
            trainable=True,
            name="gamma")
        self.sigma = tf.Variable(
            initial_value=tf.random_normal_initializer(mean=1.0)(shape=(1,),dtype="float32"),
            trainable=True,
            name="sigma")

    def call(self, num, training=None, *args, **kwargs):
        if training:
            return self.gpd_layer(gamma=self.gamma,sigma=self.sigma, num=num)
        return self.gpd_layer(gamma=self.gamma, sigma=self.sigma, num=num)

    def train_step(self,data):
        num = data.shape[0]
        with tf.GradientTape() as tape:
            X_gpd = self(num = num,training=True)
            loss = tf.norm(data-X_gpd,ord=1)
        gradients = tape.gradient(loss, [self.sigma, self.gamma])

        self.optimizer.apply_gradients(zip(gradients, [self.sigma, self.gamma]))
        return {"loss":loss}

Training the model
N=1000
gamma_th = 0.4
sigma_th = 2.0

pareto = tfp.distributions.GeneralizedPareto(loc=0,scale=sigma_th,concentration=gamma_th)
X_train = pareto.quantile(tf.cast(tf.range(start=1/(N+1),limit=1.0,delta=1/(N+1),dtype=tf.float64),dtype=tf.float32))

model = GPD_model()
model.compile(
    optimizer=keras.optimizers.SGD(learning_rate=1e-2),
    loss="mae",
    run_eagerly=True
    )
history = model.fit(X_train, epochs=200, batch_size=X_train.shape[0])

This training leads to a value of gamma that becomes negative and that seems to diverge slowly and to the following effect on the loss :

Creating an other method
This is a method of the class GPD_model which is similar to an external training loop.
def manual_fit(self,data, epochs):
        history = {"loss":[],"sigma":[],"gamma":[]}
        num = data.shape[0]
        for step in range(epochs):
            with tf.GradientTape() as tape:
                Y = self(num = num)
                loss = tf.norm(data-Y,ord=1)

            gradients = tape.gradient(loss, [self.sigma,self.gamma])
            self.optimizer.apply_gradients(zip(gradients, [self.sigma, self.gamma]))

            history["loss"].append(loss)
            history["sigma"].append(tf.constant(self.sigma))
            history["gamma"].append(tf.constant(gamma))
            print("\n",str(step+1)+"/"+str(epochs))
            print([f"{k}: {history[k][-1]}" for k in history.keys()])
        return history

This method leads to the expected behavior for the loss, gamma and sigma.

Note that the two optimization methods were performed with the same number of epochs, the same learning rate and the same optimizer. The oscillations at the end are due to the fact that the learning rate is not the best one.
Questions

*

*Why is there such a different behavior between the two methods?

*Does the train_step do something differents than the loops inside .manual_fit()?

*What is causing this ? Is it an issue related to the computation of the gradient? The fact that I'm using a tensorflow_probability.distributions.Distribution? Is it a difference of in the gradient descent method inside .fit() that I don't know?


text:
Q: How to turn off laptop native display with its lid open while using external monitors I'm using a Windows laptop (model: DELL inspiron-13-5379-2-in-1-laptop), and its LED lid has to be in open position, otherwise the laptop is designed not to repond when push power button to turn on.
I'm use the laptop mostly in a home-office setting connected to external monitors, and hope to turn off laptop's native display while keep the lid open.
Is it possible? and How? Hints will be highly appreciated.

A: I don't know if this is true for all models, but many laptops use small magnetic sensors to know when the lid it closed.
Test: Using a paper-clip or other small ferrous object, see if you can fid where it 'sticks' round the screen edges.
Once located, you can place small magnet(s) on the opposite face & the computer will think the lid is closed.

A: There should be an F key that can be used to toggle the various screen options. I have a different Dell laptop, and I use the F8 key together with the Fn (function). The symbol on my F8 key is that of a laptop with a screen behind it.


text:
Q: CQRS Projections by consumer is not designed for API Portfolio Architecture? I don't understand how to make a generic API REST, (like recommendation, no specific API by consumer) in an API Portfolio, but and the other recommendation of CQRS that tell, make projections by consumers, and so an API (GET) by consumers.
I wish a simple solution, and in this case, how to avoid to make only one projection with everything inside.
It's the same problem. How to expose DDD Application Layer, via an API REST, because Applicaiton Layer should return the consumer want, to return only data need with specific format etc...
Thanks

A: Basically, REST is not a goal per se. Furthermore, it's often believed that resource-basednes of REST harms Domain-Driven Design.
As the article referred above states for your case it's perfectly fine to build customer-centric endpoints as in your case.
As for me, I do think that most developers strive to implement REST not because of it's resource-oriented but because it's stateless which facilitates horizontal scalability. And also because stereotypical architecture is something that is easy to catch up.
P.S. Orignal spec states that HATEOAS is required for REST API. Based on my experience I've never seen it implemented in any of those so-called "REST API", and I doubt you'll be the first. So you won't be implementing  REST API in a strcit definition of it anyways :)


text:
Q: Unparseable date: "2018-08-02T14:24:40.040353" I am trying to parse a DateTime from C# to Java. Here is what comes as string from the java call "2018-08-02T14:24:40.040353". When I try to parse it, I get the following error Unparseable date: "2018-08-02T14:24:40.040353"
Here is the method for parsing the date
public static String dateFormater(String dateFromJSON, String
    expectedFormat, String oldFormat) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(oldFormat);
    Date date = null;
    String convertedDate = null;
    try {
        date = dateFormat.parse(dateFromJSON);
        SimpleDateFormat simpleDateFormat = new
        SimpleDateFormat(expectedFormat);
        convertedDate = simpleDateFormat.format(date);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return convertedDate;
}

A: Your date look like a ISO_LOCAL_DATE_TIME, If you are using Java8 you can use java.time API and use the default format of LocalDateTime like this :
String dateString = "2018-08-02T14:24:40.040353";
LocalDateTime ldt = LocalDateTime.parse(dateString);

ldt.toString():
2018-08-02T14:24:40.040353


text:
Q: use search result in replace statement with vim substitute I've got a file with a whole heap of words of the form 'foo' and i want to change them to Literal('foo'). The following :s command :%s/'.*'/Literal('.*')/gci finds the things i want to change but then it replaces them all with Literal('.*') rather than Literal('foo')
Examples:
I get:
'_' -> Literal('.*')
'dog' -> Literal('.*')
I want:
'_' -> Literal('_')
'dog' -> Literal('dog')

A: You almost have it
:%s/\('.*'\)/Literal(\1)/gci

You need to save the match and reference it in the replace.  You were inserting a literal (no pun) .* in the replace.

A: An alternative to casey's answer with explicit capturing is to restrict the match with \zs (start) and \ze (end), to assert that the single quotes are there, but don't include them. Then, you can just refer to the match in the replacement part with &:
:%s/'\zs.*\ze'/Literal(&)/gci


text:
Q: python create hierarchy from parent-child list Given the following list:
a = [
{'parent': 'p1', 'parent_name': 'pn1', 'child': 'c1', 'child_name': 'cn1'},
{'parent': 'p1', 'parent_name': 'pn1', 'child': 'c2', 'child_name': 'cn2'},
{'parent': 'c1', 'parent_name': 'cn1', 'child': 'c3', 'child_name': 'cn3'},
{'parent': 'c1', 'parent_name': 'cn1', 'child': 'c4', 'child_name': 'cn4'},
{'parent': 'c4', 'parent_name': 'cn4', 'child': 'c5', 'child_name': 'cn5'},
{'parent': 'c2', 'parent_name': 'cn2', 'child': 'c6', 'child_name': 'cn6'},
{'parent': 'c3', 'parent_name': 'cn3', 'child': 'c7', 'child_name': 'cn7'}
]

I want to create a hierarchical dict of lists
So far I've made this code which runs fine, but for some reason the children c3 and c4 are repeated twice.
Where did I made a mistake?
def build(key):

    children = [(item['child'], item['child_name']) for item in a if item['parent'] == key]

    data = {}
    for k, name in children:
        data[k] = {'child': k, 'child_name': name, 'children': []}
        for item in a:
            if item['parent'] == k:
                data[k]['children'].append(build(k))

    return data

EDIT:
The code above produce this output:
{'c1': {'child': 'c1',
        'child_name': 'cn1',
        'children': [{'c3': {'child': 'c3',
                             'child_name': 'cn3',
                             'children': [{'c7': {'child': 'c7',
                                                  'child_name': 'cn7',
                                                  'children': []}}]},
                      'c4': {'child': 'c4',
                             'child_name': 'cn4',
                             'children': [{'c5': {'child': 'c5',
                                                  'child_name': 'cn5',
                                                  'children': []}}]}},
                     {'c3': {'child': 'c3',
                             'child_name': 'cn3',
                             'children': [{'c7': {'child': 'c7',
                                                  'child_name': 'cn7',
                                                  'children': []}}]},
                      'c4': {'child': 'c4',
                             'child_name': 'cn4',
                             'children': [{'c5': {'child': 'c5',
                                                  'child_name': 'cn5',
                                                  'children': []}}]}}]},
 'c2': {'child': 'c2',
        'child_name': 'cn2',
        'children': [{'c6': {'child': 'c6',
                             'child_name': 'cn6',
                             'children': []}}]}}

I would need the exact same output but obviously without the duplications (here the children of c1 are repeated twice)

A: c3, for example, is repeated twice because of line 2 below:
data[k] = {'child': k, 'child_name': name, 'children': []}
for item in a: # 'c3' will be found twice in a
  if item['parent'] == k:

Because c3 occurs twice in a, you add its children twice.
I'm not sure why you need to do that loop. To me it looks like it'll work if you remove that loop and just do data[k]['children'].append(build(k)) below data[k] = {'child': k, 'child_name': name, 'children': []}:
data[k] = {'child': k, 'child_name': name, 'children': []}
data[k]['children'].append(build(k))


text:
Q: Difficulties getting automated posts to work properly In my web app I have the following facebook-related code being executed when a user submits a page in my application:
<SCRIPT>
function SCRIPTRUN3() {
 FB.login(function(response){
   if (response.authResponse) {
     console.log('Welcome!  Fetching your information.... ');
     FB.api('/me', function(response) {
       console.log('Good to see you, ' + response.name + '.');
    var workedOK = 'YES';
     });
    if (workedOK != 'YES') {
        SCRIPTRUN4();
        var workedOK = 'NO';
    };
    SCRIPTRUN5();
   } else {
     console.log('User cancelled login or did not fully authorize.');
};
   }, {scope: 'publish_stream'});
</SCRIPT>

which calls:
<SCRIPT language="JavaScript">
function SCRIPTRUN5() {
   var body = "<Computed Value>";
   FB.api('/me/feed', 'post', { message: body }, function(response) {
   if (!response || response.error) {
            alert('Error occured: ' + response.error.message);
   } else {
     alert('An announcement was successfully posted to your Facebook wall.');
   }
 });
}
</SCRIPT>

When the code execute I get the following error message:
"Error occured: An active access token must be used to query information about the current user."
Followed by:
"An announcement was successfully posted to your Facebook wall."
Am I executing incorrect code? Too much code? Not enough code? I am trying to post an announcement to the user's facebook wall when they post a document on my site.
Any help would be much appreciated. I am really in the dark with this facebook coding.
Thanks!

A: You need to pass access_token parameter when calling FB.api, you can find it in authResponse object.


text:
Q: ionic2 microsoft Graph API Get not working i am adding Microsoft Graph API to an app, and Get is not working. I am not even sure that it send a request. The URL i got was from Microsoft Graph Explorer.
I am able to get authenticated correctly via ADAL, and get a token back. Here is the code:
import {Http, Headers} from "@angular/http";
import {Injectable} from "@angular/core";
//import 'rxjs/add/operator/map'
//import 'rxjs/add/operator/catch'
import 'rxjs/Rx';

@Injectable()
export class EmailRESTService {

data: any;
token = localStorage.getItem("token");

constructor(private http: Http) {
    this.data = null;
}

load() {

  console.log('Inside EmailREST Promise: ');
  this.http.get('https://graph.microsoft.com/v1.0/me', {
    headers: new Headers ({"Authorization": "Bearer " + this.token})
  }).subscribe(data => {
      if(data.status == 200){
        this.data = data.json();
      }

      if(data.status!= 200){
        console.log('SOmething worng in Subscribe');
      }
    });
  }
}

I am getting this output:
console.log('Inside EmailREST Promise: ');

but no output after that. I have tried many suggestions/codes from the net without success.
Is this a matter of using ADAL Auth on the wrong API endpoint (Azure Graph API vs Graph API)? i tried using this URL:
    https://graph.windows.net/me?api-version
for Azure Graph API without success
Thanks in advance.

A: Thank you everyone for your feedback. i appreciate it.
I managed to get a token for Azure AD graph API and call that library. however, this gives me access to user/group operations, not email and other operations, which i need.
I was just on the phone with Microsoft and they advised me to use MSAL, not ADAL. MSAL javascript package is under preview. And they have no cordova package out yet. Only native devices. I will see how that works for me. Even though i installed the package using npm in my project, and using their tutorial here: https://github.com/AzureAD/microsoft-authentication-library-for-js i am still getting some errors on real time  of "can't find variable Msal", i believe this is not an Msal issue per se, but an import issue. And again, i can't strees this enough" Azure AD graph API" is not the same as "graph API", and the former will only give you access to user operations. So be careful and don't waste your time on it if you are looking to get email functionality

A: Based on the code, you were acquire the token for the Azure AD Graph. However, in the code, you were calling the Microsoft Graph(https://graph.microsoft.com/v1.0/me) instead of Azure AD Graph.
To can the user info via Azure AD Graph, you can refer the rest below:
GET:https://graph.windows.net/myorganization/me?api-version=1.6
authorization: bearer {access_token}

Or you can call the Microsoft Graph via get the corresponding token as Dan Kershaw mentioned in the comment.


text:
Q: SSAS Cube Errors, Not Deploying I'm getting two errors which are very vague.
Internal error: The operation terminated unsuccessfully.
Server: The operation has been cancelled.

This occurs when I try to deploy the cube to the server.
Does anyone know how to fix this error?
Thanks,
Ethan
EDIT:
I just processed each dimension individually and all but one processed successfully.
I also have this one warning message that is suspicious
Errors in the OLAP storage engine: The attribute key cannot be found when processing: Table: 'dbo_DimPractice', Column: 'Phone', Value: '(111) 111-1111 '. The attribute is 'Phone'.

A: So The problem was that there were duplicate phone numbers with different phone numbers. I fixed this by changing the key on the attribute column to include the other attributes.
After fixing that, I had the same warning come up for my time dimension and I did the same thing for it, and then it deployed successfully.

A: Re-apply the service account if it was working earlier & restart the service of SSAS it will starts working.


text:
Q: How would Auth work between Django and Discourse (working together) I need a modern looking forum solution that is self hosted (to go with a django project)
The only reasonable thing I can see using is discourse, but that gives me a problem... How can I take care of auth between the two? It will need to be slightly deeper than just auth because I will need a few User tables in my django site as well.
I have been reading about some SSO options, but I am unclear on how to appraoch the problem down the road. here is the process that I have roughly in my head... Let me know if it sounds coherent...

*

*Use Discourse auth (since it already has social auth and profiles and a lot of user tables.

*Make some SSO hook for django so that it will accept the Discourse login

*Upon account creation of the Discourse User, I will send (from the discourse instance) an API request that will create a user in my django instance with the proper user tables for my django site.
Does this sound like a good idea?

A: That sounds plausible. To make sure a user is logged in to both, you may put one of the auths in front of the other. For example, if discourse is in front of Django, you can use something like the builtin RemoteUserMiddleware.
In general, if they are going to be hosted on different domains, take a look at JWT. It has been gainining ground to marry different services and the only thing you need is to be able to decode the JWT token, which a lot of languages have nowadays in the form of libraries.


text:
Q: R Diff function: Treat the first value of every group so I´m having a little question regarding R´s diff function. Do I have a dataframe df of the following form:
ID  Var1   Difference
1    5        0
1    6        1
1    7        1
1    7        0
2    0        NA
2    2        2
2    4        2
2    7        3

whereas the Difference column was obtained by:
df %>% group_by("ID") %>%
       mutate(Difference = c(0, diff(Var1,
       lag = 1, differences = 1)))

However I´m not happy with the first value as 0 and especially, that the first value is reported as NA for every group. Instead I would like to have:
ID  Var1   Difference
1    5        5
1    6        1
1    7        1
1    7        0
2    2        2
2    2        0
2    4        2
2    7        3

so the first value of every group in Difference should be equal to the Var1 value and the diff function should also take this value into account and calculate the second Difference value per group, taking into account this value.
Thanks in advance

A: Try:
library(dplyr)                                                                                2L, 2L, 3L)), class = "data.frame", row.names = c(NA, -8L))
diffmod <- function(x) {
  c(x[[1]], diff(x))
}

df %>% group_by(ID) %>%
  mutate(Difference = diffmod(Var1),) %>% ungroup()

# A tibble: 8 x 3
     ID  Var1 Difference
  <int> <int>      <int>
1     1     5          5
2     1     6          1
3     1     7          1
4     1     7          0
5     2     0          0
6     2     2          2
7     2     4          2
8     2     7          3

A: We could also use lag and get the difference (-)
library(dplyr)
df %>%
   group_by(ID) %>%
   mutate(Difference = Var1 - lag(Var1, default = 0))

data
df <- structure(list(ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), Var1 = c(5L,
6L, 7L, 7L, 0L, 2L, 4L, 7L)), row.names = c(NA, -8L), class = "data.frame")

A: Using your logic you could do:
df %>%
 group_by(ID) %>%
 mutate(Difference = diff(c(0,Var1), lag = 1, differences = 1))
# A tibble: 8 x 3
# Groups:   ID [2]
     ID  Var1 Difference
  <int> <int>      <dbl>
1     1     5          5
2     1     6          1
3     1     7          1
4     1     7          0
5     2     0          0
6     2     2          2
7     2     4          2
8     2     7          3


text:
Q: "three times as much as" vs. "three times more" 1. She earns three times as much as I.
2. She earns three times more than I.
Are these two sentences grammatically correct?

A: I disagree with Usernew. I interpret both to mean that if you take home £1000 per month, "she" takes home £3000 (for simplicity, ignoring tax)
While "as much as" does mean "the same quantity as" when used alone:

I love you as much as you love me.
These two people have equal amounts of love

In your example it is being modified by the "three times"
She earns      three     times     as much as     I.
Her income  =    3         x          (1x)        "Your income"

Both options for as much as / more than are fine. However I would change the end of the sentence slightly:

She earns three times as much as / more than me.

or

She earns three times as much as / more than I do.

From your comment on another answer:

My wife and I work the same hours but I earn twice as much.

This is grammatical and means that if your wife brings home £1000 per month, you bring home £2000

A: Thanks to JamesWebster for correcting the big mistake.
As far as I can tell, She earns as much as I means that you both earn the same amount of money.

I recommend reading this news article published on The Guardian.

"As much as" means as same quantity as as provided by thefreedictionary

She earns three times more than I.

It means that she earns 3x of what you earn.
So, if you earn $100, she earns $400.

She earns three times as much as I.

This means that if you have $100, she earns $300.
If you earn X dollars, "three times more than x" means 3x + x -- "more than" means "add".
"Three times as much" means 3x.
Yahooanswers
thegrammarexchange

A: n times as much definitely differs from n times more. Try making them equivalent when buying or selling a house, in computer code, or in a court of law and you'll be wrong every time. You'd better hope that the pharmacist preparing your meds understands the difference.
If you think they are the same, try the reverse and write a given math statement as English. Problem 1.: write "3n + n = x."    answer, 3 times n plus (more than) n is x.
Problem 2.: write "3n = x."                 answer, 3 times n is x.
This is NOT a case where a majority can agree and make the two equivalent. If you have no way to express exactly what you mean the statements are useless. The problem is not with an ambiguity in the English language.  I've had hundreds of student ask me what they will ever use math for, and here you have the answer.


text:
Q: Array Objects with queries What I'm trying to do is create an array that contains a list of the titles with the title name, id of the database row, then the names of the champion and contenders. For the values of the champion and contenders I'm needing to do an additional query to retrieve the roster name of the person. If the value was 0 for the champion it needs to add Vacant to the array for that spot and if its 0 for the contender then it uses TBD for the array. Here's what I'm working with so for which includes the query and the print_r output.
My question is I"m not sure where/how I need to be running an additional query with those values of the champion and contenders for each of the titles.
    /**
     * Get titles champions
     *
     * @return  object/NULL
     */
    function getTitlesChampions()
    {
        $this->db->select('titlesList.id');
        $this->db->select('titlesList.titleName');
        $this->db->select('titlesChampions.championID');
        $this->db->select('titlesChampions.contender1ID');
        $this->db->select('titlesChampions.contender2ID');
        $this->db->select('titlesChampions.contender3ID');
        $this->db->from('titlesChampions');
        $this->db->join('titlesList', 'titlesList.id = titlesChampions.titlesListID');
        $query = $this->db->get();
        if ($query->num_rows() > 0) {
            echo "<pre>";
            print_r ($query->result());
            echo "</pre>";

        }
    }

Array
(
[0] => stdClass Object
    (
        [id] => 1
        [titleName] => Undisputed Heavyweight Title
        [championID] => 1
        [contender1ID] => 1
        [contender2ID] => 1
        [contender3ID] => 1
    )

[1] => stdClass Object
    (
        [id] => 2
        [titleName] => Outlaw Title
        [championID] => 1
        [contender1ID] => 0
        [contender2ID] => 0
        [contender3ID] => 0
    )

[2] => stdClass Object
    (
        [id] => 3
        [titleName] => Tag Team Titles
        [championID] => 1
        [contender1ID] => 0
        [contender2ID] => 0
        [contender3ID] => 0
    )

)

A: Best practice is a set of additional joins and subqueries, but given the (assumed) state of your schema, having a secondary function might be easiest.
For each result that is found, you will iterate through and assign a Name by calling getRosterName(). That function will return and add additional information to the Champions object.
/**
 * Get titles champions
 *
 * @return  object/NULL
 */
function getTitlesChampions()
{
    $this->db->select('titlesList.id');
    $this->db->select('titlesList.titleName');
    $this->db->select('titlesChampions.championID');
    $this->db->select('titlesChampions.contender1ID');
    $this->db->select('titlesChampions.contender2ID');
    $this->db->select('titlesChampions.contender3ID');
    $this->db->from('titlesChampions');
    $this->db->join('titlesList', 'titlesList.id = titlesChampions.titlesListID');
    $query = $this->db->get();

    if ($query->num_rows() > 0) {

        $result = query->result();

        foreach($result as $row)
        {
            // Iterate through
            $row->championName      =   $this->getRosterName($row->championID);
            $row->contender1Name    =   $this->getRosterName($row->contender2ID);
            $row->contender2Name    =   $this->getRosterName($row->contender2ID);
            $row->contender3Name    =   $this->getRosterName($row->contender3ID);
        }

        // Return it
        return $result;

    }
    return null;
}

/*

/* Returns the name */
function getRosterName($rosterId = null)
{

    if($rosterId && $rosterID > 0)
    {
        $this->db->select('RosterName');
        $this->db->where('rosterId', $rosterId);
        $query = $this->db->get('roster'); // Or whatever your `roster` table is named.
        return $query->row()->firstName; // Or whatever the name is you want returned
    }
    return null;
}

I don't know anything about your schema, so this is a shot in the dark.
Good luck.


text:
Q: How do I access dictionary keys that contain hyphens from within a Django template? We have a system built on a custom database, where many of the attributes are named containing hyphens, ie:
user-name
phone-number

These properties cannot be accessed in templates as follows:
{{ user-name }}

Django throws an exception for this. I'd like to avoid having to convert all of the keys (and sub-table keys) to use underscores just to work around this. Is there an easier way?

A: A custom template tag is probably the only way to go here if you don't want to restructure your objects. For accessing dictionaries with an arbitrary string key, the answer to this question provides a good example.
For the lazy:
from django import template
register = template.Library()

@register.simple_tag
def dictKeyLookup(the_dict, key):
   # Try to fetch from the dict, and if it's not found return an empty string.
   return the_dict.get(key, '')

Which you use like so:
{% dictKeyLookup your_dict_passed_into_context "phone-number" %}

If you want to access an object's attribute with an arbitrary string name, you could use the following:
from django import template
register = template.Library()

@register.simple_tag
def attributeLookup(the_object, attribute_name):
   # Try to fetch from the object, and if it's not found return None.
   return getattr(the_object, attribute_name, None)

Which you would use like:
{% attributeLookup your_object_passed_into_context "phone-number" %}

You could even come up with some sort of string seperator (like '__') for subattributes, but I'll leave that for homework :-)

A: Unfortunately, I think you may be out of luck.  From the docs:

Variable names must consist of any letter (A-Z), any digit (0-9), an
  underscore or a dot.

A: OrderedDict dictionary types support dashes:
https://docs.python.org/2/library/collections.html#ordereddict-objects
This seems to be a side effect of the implementation of OrderedDict.  Notice below that the key value pairs are actually passed in as sets. I would bet that the implementation of OrderedDict doesn't use the "key" passed in the set as a true dict key thus getting around this issue.
Since this is a side-effect of the implementation of OrderedDict, it may not be something you want to rely on.  But it works.
from collections import OrderedDict

my_dict = OrderedDict([
    ('has-dash', 'has dash value'),
    ('no dash', 'no dash value')
])

print( 'has-dash: ' + my_dict['has-dash'] )
print( 'no dash: ' + my_dict['no dash'] )

Result:
has-dash: has dash value
no dash: no dash value


text:
Q: Speed up access to python programs from Golang's exec packaqe I need suggestions on how to speed up access to python programs when called from Golang.  I really need fast access time (very low latency).
Approach 1:
func main() {
...
...
        cmd = exec.Command("python", "test.py")
        o, err = cmd.CombinedOutput()
...
}
If my test.py file is a basic print "HelloWorld" program, the execution time is over 50ms.  I assume most of the time is for loading the shell and python in memory.
Approach 2:
The above approach can be speeded up substantially by having python start a HTTP server and then gaving the Go code POST a HTTP request and get the response from the HTTP server (python).  Speeds up response times to less than 5ms.
I guess the main reason for this is probably because the python interpretor is already loaded and warm in memory.
Are there other approaches I can use similar to approach 2 (shared memory, etc.) which could speed up the response from my python code?.  Our application requires extremely low latency and the 50 ms I am currently seeing from using Golang's exec package is not going to cut it.
thanks,

A: Approach 1: Simple HTTP server and client
Approach 2: Local socket or pipe
Approach 3: Shared memory
Approach 4: GRPC server and client
In fact, I prefer the GRPC method by stream way, it will hold the connection (because of HTTP/2), it's easy, fast and secure. And it's easy moving python node to another machine.


text:
Q: 'Name not unique in this context' with design time CreateDataSet when fkInternalCalc fields present I have a datamodule with several TClientDataSets with fields and field definitions, no provider.
My recent design time changes to all of these:

*

*Set active=false

*Add field and fielddef for integer field TT_APIVERSION

*Right-click 'Create dataset'

If there are one or more fields with FieldKind = fkInternalCalc, I get a 'Name not unique in this context' error.
Changing them to fkCalculated 'solves' the issue (but I had to check my OnCalcField handlers to make sure they also worked for State = dsCalcFields)
This is code that has gone through several Delphi versions, current is Alexandria 28.0.44500.8973
We have done modifications like this before, the datasets had Active=true when I started, and the form contained PersistDataPacket.Data blobs.
Is this a (new) Delphi bug or is there something about fkInternalCalc fields that I'm missing?

A: Remove all fields defined as fkInternalCalc from the FieldDefs collection before any call to CreateDataset (so also right-clicking 'Create dataset').
I'm not sure if it's a bug or a feature, but CreateDataset tries to add fkInternalCalc fields to FieldDefs collection without checking whether it previously existed.
If you have all the FieldDefs and corresponding Fields created, you can as well delete all items from FieldDefs collection, field definitions will be recreated.


text:
Q: set and display a specific datalist option in a dynamically loaded datalist with jquery I have a datalist that is created on the fly based on the user's selection from a group select menu.  After the group is selected, the datalist is created. The datalist allows users to choose from a "dropdown" list or just start typing in the input box and have the list filtered accordingly.  It is structured like this:

    <input type="text" name="ProjTitle" id="ProjTitle" placeholder="~ select project ~" list="projectList" autocomplete="off" value="">
    <datalist id="projectList">
        <select id="projectOptions">
             <option data-projid="390" value="Project 1">Project 1</option>
             <option data-projid="391" value="Project 2">Project 2</option>
             <option data-projid="392" value="Project 3">Project 3</option>
        </select>
    </datalist>

In the default use case, the user double-clicks on the input box, a drop down appears, a project is selected (clicked) and the rest of the page (a report) is populated.  This all works great.
In the alternate use case for the page, the groupid and a particular projid are passed to the page via a stored browser value.
In this case, the presence of the 'groupid' triggers the group selector just fine and the datalist element is populated just as if the user had made the group choice.  All good so far.
What I'm having difficulty doing is interacting with the datalist via jquery to select the item matching the projid that is passed AND displaying the resulting title of the project in the input control.  The title of each project is the "value" of each option.
From lots of other references I've found, the way to select an item in a datalist is to actually set the value of the associated input like this:
$('#ProjTitle').val("Project 1");

This doesn't work in my case, because the value being passed to the page is the projid that is in the data-projid value for each option and not the project title that is the "value" of each option.
One approach I thought of using for this was to select (using jQuery) all of the datalist options and then use $.each() to loop over the items and find the matching projid.  If I could do this, I would then get the valueof that option and pass it to ('#ProjTitle').val().
However, when I use jQuery to select the options like this:
let $options = $(document).find('option');

$options is empty.
Are the options for a datalist not accessible with jQuery for some reason? in the Firefox developer tools the options are greyed out as if they are hidden.  If they can not be accessed directly, how can I get the "value" of the option that matches the projid?
What other approach could I use to set the selected value of the datalist (based on the projid)?
Edit
I am suspicious that the dynamic loading of the content is in play here.  The code to set the datalist is inside the $(function() { }) block of javascript so execution occurs after page load.  Nonetheless, if I add console.log($('#ProjectList')); (or '#ProjectSelect') to the javascript I get the following in Firefox Developer Tools:
Normally, I'd be able to access all the nodes for the element.

A: I think the comments in the demo are sufficient to explain things, but feel free to ask any questions if you need a more details.

/* Assume this is the id passed to your page: */
const projid = 392

/*
  Select the option element with a matching data-projid attr
  and store the actual value for the selected option.
*/
const val = $(`[data-projid="${projid}"]`).val()

/*
  Select the input that is a direct descendant of the
  #projectSelect element and set the value for it
  to the project name
*/
$('#projectSelect > input').val(val)

    <input type="text" name="ProjTitle" id="ProjTitle" placeholder="~ select project ~" list="projectList" autocomplete="off" value="">
    <datalist id="projectList">
        <select id="projectOptions">
             <option data-projid="390" value="Project 1">Project 1</option>
             <option data-projid="391" value="Project 2">Project 2</option>
             <option data-projid="392" value="Project 3">Project 3</option>
        </select>
    </datalist>


text:
Q: Nodejs Bookshelf. How to use BETWEEN filter I want to filter DB table by timeStamp of element.
Table got rows :
ID, URL, timetable.
How to filter data by timestamps in some range?
Like usual in SQL ... BETWEEN firstTime AND lastTime
I tries something like:
  if (first_date && last_date) {
        Pages.forge()
            .where("Date", '>=' , first_date)
            .where("Date", '<=' , last_date)
            .fetchAll()
            .then(function (pages) {
                res.send(persons.toJSON());
            }).catch(function (error) {
                console.log(error);
                res.send('An error occured');
            });

A: model.query({where: {"Date", '>=' , first_date}, orWhere: {"Date", '<=' , last_date}})
      .fetch()
      .then(function(model) {
        // ...
      });

you must use where and or where for example:between means any of two conditions but here you set to both condition true .

A: If you add .query() to call chain you will be able to use knex syntax inside.
To your example:
      Pages.forge()
          .query(function(knex) {
              knex.whereBetween('Date', [first_date, last_date]);
          })
          .fetchAll()
          .then(function (pages) {
              // do something with pages
          }).catch(function (error) {
              // do something with error
          });


text:
Q: bindings: can someone help me to get this right? i am sharpening me react skills and by doing this i stumbled across this sweet line of code.
export default class SearchBar extends Component {

  constructor(props) {
    super(props);
    this.state({term:''});

    this.onInputChange = this.onInputChange.bind(this);
  }

  onInputChange(event) {
    this.setState({ term: event.target.value});
  }
}

Here the jsx part
render() {
  return(<input
    value={ this.state.term }
    onChange={ this.onInputChange }
  />)
}

Can you please help/tell or show me sources, where i can really understand what is going on in the line?
this.onInputChange = this.onInputChange.bind(this);

it kind of confuse me. thanks for your affords. and
kind regards

A: You can go through this blog to understand why binding is needed.
And for binding the methods, I would suggest you to install stage-1 Babel preset and use arrow functions. Arrow functions automatically binds this, so we don't need to use the bind() function.
For more clarity, you can read this blog.
With the arrow function you code will look like this:
export default class SearchBar extends Component {

  constructor(props) {
    super(props);
    this.state({term:''});
  }

  onInputChange = (event) => {
    this.setState({ term: event.target.value});
  }
}

render() {
  return(
    <input
      value={this.state.term}
      onChange={this.onInputChange}
    />
  )
}

Now you don't need to add bind statement every time a new function is added.


text:
Q: Not Ready: File Not Uploaded when adding to Facebook Custom Audience I am attempting to add users to a Facebook Custom Audience using version 2.1 of their API.
I'm using this Python script to create a new audience, and add users to it.
import json, requests

# set up params
account_id = 'an ads account ID'
audience_name = 'a new name'
token = 'a valid access token'

# create a new audience ID for posterity
url =  "https://graph.facebook.com/act_" + account_id + "/customaudiences"
response = requests.post(url, {"name": audience_name, "access_token": token})
resp_dict = json.loads(response.content)
audience_id = resp_dict["id"]

# output new audience name and ID
print("For audience name of:", audience_name)
print("Created audience ID of:", audience_id)

# add email addresses to the audience
the_file = open("the.payload", "r")
payload = the_file.read()
the_file.close()

url = 'https://graph.facebook.com/v2.1/' + audience_id + '/users'
params = {"access_token": token, "payload": payload}
response = requests.post(url, params=params)

# output results
print("Response status code:", response.status_code)
print("Response content:", response.content)

A sample of the contents of "the.payload"  is:
{"data":["a8649fb702fb0a67e21ed5120a589cf4d15dd59e2eebb1ad606485731b124100","4842b7883df3c9048abbff1fddb3fd634bed474450f8b2b9102c4bf76fc33381"],"schema":"EMAIL_SHA256"}

Except, in my file, instead of having just 2 valid email addresses that have been formatted as SHA256, and written per hex, as per their docs, I have 1100 of them.
When I run this script, I receive:
('For audience name of:', 'the name I gave')
('Created audience ID of:', u'a valid ID number')
('Response status code:', 200)
('Response content:', '{"audience_id":"a valid ID number","num_received":1100,"num_invalid_entries":0,"invalid_entry_samples":[]}')

However, more than an hour later, "Not Ready, File not uploaded" shows in the UI for 100% of uploads done using this method.

Can anyone tell me how to correct my code to add users to custom audiences successfully? I've reviewed Facebook's docs extensively, but I believe I'm following their format.

A: This turned out to be an issue with my hashing algorithm.
After posting this, I received a copy of an email hashing algorithm that was proven to work. It was this:
import hashlib
email = "somebody@somewhere.com"
email = email.strip().lower()
email = hashlib.sha256(email).hexdigest()

I compared the hash produced here to my own hash, and it wasn't coming out the same. After correcting it by stripping whitespace and not reusing a hasher in a loop, this problem resolved.
So, Not Ready can result from a hashing issue behind the scenes, or an upload containing too few valid & matching email addresses.


text:
Q: Android Spinner remove OnItemSelectedListener Others has the problem as doesn't working, I have the problem it is working ( and it shouldn't )
I have a data model, which is saved, and need to loaded back to GUI, Activity. It has a few spinner value.
The data is place to a common accesible class, a reference holder.
The activity's onCreate it will check if is on edit mode or not with:
editMode = getIntent().getBooleanExtra(EDIT_MODE_KEY, false);

It will load the UI elements from xml, and start selecting, filling values.
At editing mode, and at creation mode it should select values what has the data model.
At runtime ( after onResume() )  has some workflow: is something is selected at spinner1, than should refresh the spinner2 adapter content and so on.
It doesn't worked the plain .setSelection(positiontoSelect); so I have added a delayed post, now is working.
My problem is: I would like remove for temp the selection listener, call the selection and add back the listener.
Here is the code, which should be modified:
          if (editedTimezonePosition > -1) {
                final int positiontoSelect = editedTimezonePosition;
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        OnItemSelectedListener listener = spSelectTimezone.getOnItemSelectedListener();
                        spSelectTimezone.setOnItemSelectedListener(null);
                        spSelectTimezone.setSelection(positiontoSelect);
                        spSelectTimezone.setOnItemSelectedListener(listener);
                    }
                }, 250);
            }

setting to null the listener has no effect:  I am getting callback to my listener method.
If you have any idea how to fix it, please share it!

A: You could put a counter variable in your onItemSelected method.  If it is 0 (meaning the first time the method has been called), do nothing but increment the variable.  If it is greater than 0, execute the rest of your code.
private int mSpinnerSelectionCount=0;

public void onItemSelected(AdapterView<?> parent, View view,
    int pos, long id) {
        if(mSpinnerSelectionCount == 0){
            mSpinnerSelectionCount++;
        } else {
            // Your normal selection code here
        }
    }


text:
Q: PHP Generate json file and disable cache I have a script that creates a new json file every time I upload a new version of my app.
The problem is that browsers and mobile apps seems to cache that json file.
I use file_put_contents to create that json file.
Is there a way to disable cache specifically for that json file when someone read it from outside?
EDIT1:
Answer the question assuming I cannot change my clients

A: Pseudo code,
Original JSON file:
{
  "param":"value",
  "param1" "value",
  ... etc..
}

JSON.PHP file
<?php

$thatMuch = (60 * 60 * 24); // 24hrs
$cacheTime = (time() + $thatMuch);

$json = file_get_contents($originalJsonFile);

header('Pragma: public');
header('Cache-Control: maxage='.$thatMuch);
header('Expires: ' . gmdate('D, d M Y H:i:s', $cacheTime) . ' GMT');
header('Content-Type: application/json; charset=utf-8');
echo($json);
exit;

If You output that JSON as it is, than file_get_contents is ok, otherwise, You do what You need to do.. use json_encode(), change last header directive to something else, etc.
Also, You could *(if You haven't done so, already) remove .php extension lookup via .htaccess so that .php is not needed in path, therefore, the original path/url will remain exact the same.
Something like this *(root dir .htaccess)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+)$ /$1.php [QSA,L]
</IfModule>

And this would be enough I guess...

A: How do You serve that file to the endusers? Are You serving that file directly? If You do, try to serve that JSON file via/by PHP as well, with proper headers before output, where filename.json.php will take place instead of filename.json or just as Paul proposed, much easier.


text:
Q: Trying to load json through Vue Axios I'm trying to include a local JSON file from the static directory called blogs.json which has a load of blogs inside it.
I'm currently loading the blogs via Vue Axios which is a module I'm including in Nuxt JS.
Currently, the blogs are being loaded from the json file perfectly fine, however there is a noticeable few ms delay before the blogs are loaded, I'm trying to figure out a better approach to load the json file and populate the blogs array listed inside data()
This is my current code:
<script>
import PageBanner from '~/components/PageBanner';

export default {
  head: {
    title: 'Site Title: Blog',
    meta: [
      { hid: 'description', name: 'description', content: 'Site description' }
    ]
  },
  components: {
    PageBanner
  },
  data () {
    return {
      blogs: [],
      isLoading: true
    }
  },
  created () {
    this.axios.get("/articles/blogs.json").then((response) => {
      this.blogs = response.data
      this.isLoading = false
    })
  }
}
</script>

This works just fine, but how could I modify this to load the json more quickly?

A: Just import it, do this and it should work God willing:
<template>
    <div>
        <!-- There should be no delay -->
        {{blogs}}
    </div>
<template>
<script>
import PageBanner from '~/components/PageBanner';

import blogsFromJson from '~/articles/blogs.json'; // Or wherever it is found

export default {
  head: {
    title: 'Site Title: Blog',
    meta: [
      { hid: 'description', name: 'description', content: 'Site description' }
    ]
  },
  components: {
    PageBanner
  },
  data () {
    return {
      blogs: blogsFromJson, // Just set it here
      isLoading: true
    }
  },
  /* No need for this anymore
  created () {
    this.axios.get("/articles/blogs.json").then((response) => {
      this.blogs = response.data
      this.isLoading = false
    })
  }
  */
}
</script>


text:
Q: How can SysVinit scripts restart after their dependencies restart SysVinit scripts can declare dependencies with Required-Start and Required-Stop:
### BEGIN INIT INFO
# Provides:          my-containerized-service
# Required-Start:    docker
# Required-Stop:     docker
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
### END INIT INFO

After symlinking this script into /etc/rc3.d it will automatically start up after docker when the system comes up. But if I manually restart docker, my-containerized-service is stopped, but it does not get restarted. Is there some way to register an event that listens for docker restarts and then starts up my service.


text:
Q: To set Neutral Permission discord.py rewrite See, let me explain, suppose if I want to allow a user to send a message in the channel, and he is denied to send the message. I want to set his permission to neutral. But, this code allows the user to send a message. Even he is having Muted role.
@commands.command(hidden=False)
@commands.has_permissions(kick_members=True)
@commands.bot_has_permissions(manage_channels=True, manage_permissions=True)
async def unblock(self, ctx, member : discord.Member, *, reason:str=None):
    """To allow the blocked user to send messages that channel."""
    guild = ctx.guild

    if member.permissions_in(ctx.channel).send_messages == True: await ctx.send(f"{ctx.author.mention} {member.name} is already unblocked. They can send message")
    else: await ctx.channel.set_permissions(member, send_messages=True, reason=f"Action requested by {ctx.author.name}({ctx.author.id}) || Reason: {reason}")

A: You can do this by simply doing None
# Always allowed
= True

# Neutral
= None

#Always denied
= False

Also you don't need == True, you can just delete that so it's
if member.permissions_in(ctx.channel).send_messages:


text:
Q: Java for each makes problems I had some trouble using a for each loop for an List at my android project. The error is made by an iterator (or I should better say "the error is made by me - not knowing how to use the iterator"^^). The List is looped through in order to draw bullet objects on a canvas. When one of the bullets leaves the screen I delete this object.
Using a "normal" for-loop solved the error:
for (int ii = 0; ii < bulletList_P1.size(); ii++)
                bulletList_P1.get(ii).draw(canvas);

this implementation brings errors:
for (Bullet bullet : bulletList_P1)
                bullet.draw(canvas);

I found THIS here on stackoverflow. The difference to my problem is that in this case new objects are created - my question is now how to deal with this situation when objects get removed (deleted from list).
How massive will be the difference of performance using one or the other implementation?

A: You cannot typically modify a Collection while you are iterating over it.  Strategies around this typically fall into:
i. Copy/Clone the original collection purely to iterate over it, while you change the original collection.
for (Bullet bullet : new ArrayList<Bullet>(bulletList_P1))
    bullet.draw(canvas);

(or even better yet, use the Guava library's ImmutableList.copyOf method)
ii. Collect up your mutations during the iteration and have a separate phase to apply the mutations.  For your example, you might create a set of bullets that have left the screen during the draw phase.  Then use a removeAll to remove the errant bullets at the end.
ArrayList<Bullet> removals = new ArrayList<Bullet>();
for (Bullet bullet : bulletList_P1)
    if (!bullet.draw(canvas))
        removals.add(bullet);
bulletList_P1.removeAll(removals);

iii. Use an iterator and use the remove method of the iterator to modify the collection as you iterate over it.
for (Iterator<Bullet> iterator = bulletList_P1.iterator(); iterator.hasNext(); ) {
    Bullet bullet = iterator.next();
    if (!bullet.draw(canvas))
        iterator.remove();
}


text:
Q: How can I get my php hits from yesterday only? How can I get my php hits from yesterday only when I am getting my total hits using this php sql call. Here is the code:
    SELECT *, COUNT(visitor_tracking.model_id) as model_count FROM user, visitor_tracking WHERE visitor_tracking.model_id = $user_id GROUP BY $user_id ORDER BY model_count DESC LIMIT 1

when the data day is being inserted this way. here is the code:
2013-12-11 14:23:45
and my database name is timestamp.
How can I get the php hits only from yesterday?

A: You need to use between. For example, something like this should work:
SELECT *, COUNT(visitor_tracking.model_id) as model_count
FROM user, visitor_tracking
WHERE visitor_tracking.model_id = $user_id AND
    `timestamp` BETWEEN '2013-12-11 00:00:00' AND '2013-12-11 23:59:59'
GROUP BY $user_id ORDER BY model_count DESC LIMIT 1

BTW, I'm not sure you need the DESC LIMIT 1 in that query because of the use of COUNT, but I could be wrong.

A: WHERE created_time < 'yesterday date 00:00:00'
AND created_time > DATE_ADD( CURDATE( ) , INTERVAL -1
DAY )
I hope it helps


text:
Q: How to create a scatter excel graph with y-axis above and above and below x-axis I am trying to create an excel scatter plot/line graph that shows y-axis values above and below the x-axis. I am trying to recreate the graph in the link below for the data I have.

I have tried playing around with the primary and secondary axis, but I have not been able to get the secondary axis below the y-axis. It seems like the example graph has one primary axis where the "positive values" for static pressure are in decimal increments and the "negative values" for number of responses are whole numbers. Does anyone have any idea how I can accomplish this? Is it just two excel graphs pasted together with the same x-axis? Any help is much appreciated! Thank you.

A: What looks like a horizontal axis may not actually be one. Advanced charting tricks in Excel often use helper series to mimic things. In the screenshot below, the Scatter chart has two data series and a helper series that is formatted with a thin black line, markers in the shape of a + character and labels using values from cells. The labels on the actual X axis have been formatted to "None".
There. An X axis in the middle of the chart with custom labels, even.
Likewise, the vertical axis labels can be constructed with a helper series that has all values at X = 0  and Y values calculated to plot where desired, then use labels to mock up the scale. If the scale is wildly different from the actual data plots, you may need to use a conversion factor to ensure the data points end up where they should.
Looking at your example screenshot, it could also be that two charts have been carefully stacked and aligned to appear as one with a middle X axis.


text:
Q: How to filter nested objects on a should query? I have my mappings as below and I am doing a bool should query on name and other properties as shown below but what I need is that I want to filter CustomerPrices by CustomerId on response.
Each products have same CustomerIds so for eaxample;
product1 -CustomerPrice( CustomerId :1234 -Price:4)
           CustomerPrice( CustomerId :567-Price:5)
            .
            .
 Product2 - CustomerPrice(CustomerId :1234 -Price:8)
            CustomerPrice(CustomerId :567-Price:10)
           .
           .

So according to that when I query Product1, response should have only customerPrice for customerId:1234
{
  "Product": {
    "properties": {
      "CustomerPrices": {
        "type": "nested",
        "properties": {
          "Price": {
            "store": true,
            "type": "float"
          },
          "CustomerId": {
            "type": "integer"
          }
        }
      },
      "Name": {
        "index": "not_analyzed",
        "store": true,
        "type": "string"
      }
    }
  }
}

I tried following query but this is not filtering nested objects. I guess it filters product objects as it makes sense because all products have customerId:1234
   "query":{
        "bool":{
          "should":[
            {
              "multi_match":{
                "type":"best_fields",
                "query":"product 1",
                "fields":[
                  "Name^7"]
              }
            },
            {
              "multi_match":{
                "type":"best_fields",
                "query":"product 1",
                "operator":"and",
                "fields":[
                  "Code^10",
                  "ShortDescription^6"]
              }
            },
            {
              "nested":{
                "query":{
                  "term":{
                    "CustomerPrices.CustomerId":{
                      "value":1234
                    }
                  }
                },
                "path":"CustomerPrices"
              }
            }]
        }
      },

A: I've spent some time on your question since it was interesting how this can be achieved and the only solution I found for now is relying on the inner_hits which gives the exact nested object the match was on. I've also deactivated the _source which isn't used anymore.
So given your mapping and having 2 products like:
PUT product/Product/product1
{
  "CustomerPrices": [
    {
      "CustomerId": 1234,
      "Price": 4
    },
    {
      "CustomerId": 567,
      "Price": 5
    }
  ],
  "Name": "John"
}

PUT product/Product/product2
{
  "CustomerPrices": [
    {
      "CustomerId": 1234,
      "Price": 8
    },
    {
      "CustomerId": 567,
      "Price": 10
    }
  ],
  "Name": "Bob"
}

When running the following query: (Used must just to see 1 result, works with should as well)
GET product/_search
{
  "_source": false,
  "query": {
    "bool": {
      "must": [
        { "match": { "Name": "Bob"}}
      ],
      "filter": [
        {
          "nested" : {
            "path" : "CustomerPrices",
            "score_mode" : "avg",
            "query" : {
              "bool" : {
                "should" : [
                  { "match" : {"CustomerPrices.CustomerId" : 1234}}
                ]
              }
            },
            "inner_hits": {}
          }
        }
      ]
    }
  }
}

I was able to get the result where only "Price" from customer with id 1234 was present:
{
  "took": 5,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0.2876821,
    "hits": [
      {
        "_index": "product",
        "_type": "Product",
        "_id": "product2",
        "_score": 0.2876821,
        "inner_hits": {
          "CustomerPrices": {
            "hits": {
              "total": 1,
              "max_score": 1,
              "hits": [
                {
                  "_index": "product",
                  "_type": "Product",
                  "_id": "product2",
                  "_nested": {
                    "field": "CustomerPrices",
                    "offset": 0
                  },
                  "_score": 1,
                  "_source": {
                    "CustomerId": 1234,
                    "Price": 8
                  }
                }
              ]
            }
          }
        }
      }
    ]
  }
}

Couldn't find an official way of returning partial results of the document by only having the matched nested object. Maybe something that we need to inform elasticsearch guys about to consider for some next releases. Hope it helps you.


text:
Q: How to verify my domain with Apple in a React App Does someone know how to verify a domain with Apple using React.js at the url mydomain.com/.well-known/apple-developer-merchantid-domain-association.txt
I tried to create the .well-known folder in public folder and put the apple-developer-merchantid-domain-association.txt file inside. I'm able to access the file (just access, not download) but the verification still fail on Apple website. Does someone has an other solution ?
I also made a custom route like this
<Route path="/.well-known/apple-developer-merchantid-domain-association.txt" render={() => (
                                    <link rel="apple-developer-merchantid-domain-association.txt file" href="%PUBLIC_URL%/.well-known/apple-developer-merchantid-domain-association.txt" />
                                )}

A: What I did on my react app, hosted on heroku with Stripe (which provides Apple Pay) :

*

*In ./client : Create an "applepay" directory and copy/past the "apple-developer-merchantid-domain-association" file.

1

*In your client package.json file, find the "scripts" list, where you should at least read "build": "react-scripts build".
Add "mkdir -p ./build/.well-known && cp ./applepay/apple-developer-merchantid-domain-association ./build/.well-known/".
It will create during the build an new directory (mkdir) and copy (cp) the verification file inside it.

"scripts": {
    ...,
    "build": "react-scripts build && mkdir -p ./build/.well-known && cp ./applepay/apple-developer-merchantid-domain-association ./build/.well-known/",
    ...,
},

*Push online your updated code, make sure it is an httpS domain, your apple pay merchant id file should be detected.
If you use Stripe you'll get :

2
I hope it helped!


text:
Q: VS Code - printed file paths when selecting Run Python File in Terminal When in VC Code, I right-click and select "Run Python File in Terminal," I get two long folder paths (see below) that I am sure have a reason to exist.
That said, when I right-click and select "Run Python File in Terminal," what what is the reason why I see there two long file paths? And is there a reason why I would want to leave them there? If not, is there a way to just see the current folder "Python_Deep_Dive_Part_1>" and then the output of the python file (e.g. "Hello World").

A: The first file path is the absolute path to your selected Python interpreter and the second is the absolute path to the location of the file you're executing. Both paths are absolute as there is no guarantee that your terminal is open to the same directory it started in and VS Code doesn't provide a way for the extension to know what the current directory is.

A: I have solved for first part and still searching for summarization to file.py
VSCcode > settings.json:
"python.pythonPath": "py"


text:
Q: Matplotlib: How to use two colors in a single line? I am getting a list of close data which is both negative and positive. When I plot a line I want to show positive value as a green segment and negative value as a red segment. I have data in the following df format:
                                A       price     B         side  size  signal  \
time
2019-06-12 03:54:26.668990  4603.35936  7990.0  4583.96620  Buy    20    True
2019-06-12 03:54:26.668990  4603.24884  7990.0  4583.96620  Buy    38    True
2019-06-12 03:54:26.668990  4603.26808  7990.0  4583.96620  Buy    69    True
2019-06-12 03:54:26.668990  4603.32670  7990.0  4583.96620  Buy    25    True
2019-06-12 03:54:26.668990  4603.32670  7990.0  4583.96620  Buy   450    True
...                                ...     ...         ...  ...   ...     ...
2019-06-12 12:07:48.793863  3997.85136  8043.5  4375.44562  Buy    22   False
2019-06-12 12:07:48.793863  3997.87648  8044.0  4375.44562  Buy  1300   False
2019-06-12 12:07:48.793863  3997.87616  8044.0  4375.44562  Buy     6   False
2019-06-12 12:07:48.793863  3997.89530  8044.0  4375.44562  Buy  1000   False
2019-06-12 12:07:48.793863  3997.90046  8044.0  4375.44562  Buy   280   False

If the signal is True show green else red. I found this example but I am struggling to understand it.
The code I have tried so far is below
first=combine[:200000] #DF
x = first.index
y = first.price.values
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
from  matplotlib.colors import LinearSegmentedColormap
cmap=LinearSegmentedColormap.from_list('rg',["r", "g"], N=256)
print(cmap)

I am unable to figure out how to use Signal value to color segments

A: If you want to change the line color in units of data sections in a line chart, you need to convert the data used for the line chart to (x1,y1),(x2,y2). Then create a list to set the color for that section. For each data, specify the plotting function; the time series on the x-axis will be updated last. It may be possible to deal with the time series as it is, but I think it is easier to deal with it as a vector and then deal with it as a time series later. This is a hint for this answer. What I am modifying from this answer is the way the last value is specified since the data used is a pandas series.
import pandas as pd
import numpy as np
import io

data = '''
time A       price     B         side  size  signal
"2019-06-12 03:54:26.668990"  4603.35936  7990.0  4583.96620  Buy    20    True
"2019-06-12 03:54:26.668990"  4603.24884  7990.0  4583.96620  Buy    38    True
"2019-06-12 03:54:26.668990"  4603.26808  7990.0  4583.96620  Buy    69    True
"2019-06-12 03:54:26.668990"  4603.32670  7990.0  4583.96620  Buy    25    True
"2019-06-12 03:54:26.668990"  4603.32670  7990.0  4583.96620  Buy   450    True
"2019-06-12 12:07:48.793863"  3997.85136  8043.5  4375.44562  Buy    22   False
"2019-06-12 12:07:48.793863"  3997.87648  8044.0  4375.44562  Buy  1300   False
"2019-06-12 12:07:48.793863"  3997.87616  8044.0  4375.44562  Buy     6   False
"2019-06-12 12:07:48.793863"  3997.89530  8044.0  4375.44562  Buy  1000   False
"2019-06-12 12:07:48.793863"  3997.90046  8044.0  4375.44562  Buy   280   False
'''

df = pd.read_csv(io.StringIO(data), delim_whitespace=True)

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
fig, ax = plt.subplots()

y = df['price']
x = np.arange(len(y))

# x:numpy.array, y:pandas.Series
segments_x = np.r_[x[0], x[1:-1].repeat(2), x[-1]].reshape(-1, 2)
segments_y = np.r_[y[0], y[1:-1].repeat(2), y[:-1]].reshape(-1, 2)
# print(segments_x, segments_y, sep='\n')
colors = ['green' if x == True else 'red' for x in df['signal']]
segments = [[x_, y_] for x_, y_ in zip(segments_x, segments_y)]
# print(segments)

for s,c in zip(segments, colors):
    ax.plot(s[0],s[1],color=c)

ax.set_xticks(x)
ax.set_xticklabels(df['time'].tolist(), rotation=90)

plt.show()


text:
Q: Django " AttributeError: 'function' object has no attribute 'as_view' " I am trying to make an index page with class based views that will have menu bar and with that menu bar it will redirect to new pages and takes forms as post requests. But whatever i do i always get the same error.
Here is the error ;
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "C:\Users\berat.berkol\anaconda3\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
    self.check(display_num_errors=True)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check
    databases=databases,
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
    return check_resolver(resolver)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
    return check_method()
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 408, in check
    for pattern in self.url_patterns:
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Users\berat.berkol\anaconda3\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module
    return import_module(self.urlconf_name)
  File "C:\Users\berat.berkol\anaconda3\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\berat.berkol\SystemConsole\SystemConsole\urls.py", line 25, in <module>
    path('', UserUpdateView.as_view(), name='home'),
AttributeError: 'function' object has no attribute 'as_view'

And my project's urls.py ;
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from userupdate.views import UserUpdateView

app_name='userupdate'
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/',include('django.contrib.auth.urls')),
    path('', UserUpdateView.as_view(), name='home'),
]

and my views.py ;
from django.shortcuts import render
from datetime import timedelta
from django.utils import timezone
from django.views.generic import TemplateView
from django.views.decorators.csrf import csrf_protect
from django.utils.decorators import method_decorator
from django.urls import reverse
import requests
from userupdate.forms import UserPassForm
from userupdate.forms import LoginForm
from django.views.generic import View
from django.contrib.auth.views import LoginView
from django.contrib.auth.mixins import LoginRequiredMixin

@csrf_protect
class UserUpdateView(LoginRequiredMixin,View):
    emplate_name='home.html'
    def get(self, request, *args, **kwargs):
        return render(request,'home.html')
    #@method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(UserUpdateView, self).dispatch(self, request, *args, **kwargs)

@csrf_protect
class LoginUser(LoginView):
    template_name = 'home.html'  # your template
    from_class = LoginForm()  # your form

    def get_success_url(self):
        '''Here the part where you can implement your login logic'''
        now = timezone.now()
        # Get current day date object
        # like: 12/02/2019 00:00:00
        today = now.replace(minute=0).replace(second=0).replace(microsecond=0)
        # Get the client from the user object
        client = self.request.user.cli
        # Get all the user today's logins and count them
        client_logins = models.ClientLogins.objects.filter(
            client=client,
            date__gte=today,
            date__lte=today + timedelta(days=1)
        ).count()
        if client_logins < 1:  # Or: if not client_logins:
            # create a login tracker record
            models.ClientLogins.objects.create(
                client=client,
                date=now  # Store the date where the user logged in the website
            )
            return reverse_lazy('home')
        # Or redirect to: settings.LOGIN_REDIRECT_URL
        request.session.get_expire_at_browser_close()
        return super().get_success_url()

@csrf_protect
class passResetView(View):

    def get(self,request):

        form=UserUpdateForm()

        return render('basarili')

    def post(self,request):
        passResetuser=self.model.objects.get(pk=2)

        form=UserUpdateForm(request.POST,instance=passResetuser)

        if form.is_valid():
            username=form.cleaned_data('username')
            password=form.cleaned_data('password')
            number=form.cleaned_data('number')
            message=form.cleaned_data('message')

        context={'form':form}
        return render(request,'home.html',context)

I don't know if it's required but here is my app's urls.py ;
from django.urls import path, re_path
from django.contrib.auth.views import LoginView
from userupdate.views import HomeView
from django.contrib.auth import views as auth_views

app_name='userupdate'
urlpatterns = [
    path('', views.UserUpdateView.as_view(template_name='home.html'), name='home'),
    path('login/',
       LoginView.as_view(
           template_name='login.html'),
           name="login"),
    #path('passResetView',views.passResetView.as_view(template_name="home.html"),name='passResetView'),
    path('passreset/',
       passResetView.as_view(
           template_name='passreset.html'),
           name="PasswordReset"),

]

I haven't configured the form pages yet so ignore them for now.
I will build them with the FormView.
By the way I tried the TemplateView also but i didn't help its makes the same error.

A: You can't use @csrf_protect on a class-based view, or at least not directly. This decorator will return a function, and that function of course has no .as_view() method.
You can work with the @method_decorator [Django-doc], which will decorate the class:
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_protect

@method_decorator(csrf_exempt, name='dispatch')
class UserUpdateView(LoginRequiredMixin,View):
    template_name = 'home.html'

    # …
That being said, it is often not a good idea to make a CSRF exempt, since that makes your view vulnerable to Cross-Site Request Forgery [wiki].