text:
Q: Mod Rewrite rule to redirect all pdf request to another location I'm trying to clean up our website.  I'm using ISAPI Rewrite.  I have figured out the regex I need to select the files in question.
^(?!.*?web_content.*?).*?\.pdf
I want to redirect all pdf requests to look in web_content/pdf/.  So The pseudo rule I want is

redirect all requests to pdfs that aren't already being requested from
  web_content/pdf.  Drop off the original folder path.
  /somefolder/this/mycool.pdf ==> /web_content/pdf/mycool.pdf

My question is how would I actually create the Mod rewrite rule? I don't know how to correctly do the replacement command.  I also hope this rule wont affect external pdf links on our site.

A: This should work:
RewriteEngine On

RewriteCond %{REQUEST_URI} !^/web_content/pdf/
RewriteRule ^(.+\.pdf)$ /web_content/pdf/$1 [L]

Helicon ISAPI_Rewrite v3 is pretty much the same as Apache's mod_rewrite (except few advanced things), therefore almost all rules that work on Apache will work here as well.


text:
Q: AutoMapper problem with custom convert from source to destination I'm using AutoMapper to map my db models with my api models. But I have a problem with custom mapping. I'll try to explain my problem:
So I have the db and api models like this:
public class ApiModel
{
    public List<ApiSubModel> Colors { get; set; }
}

public class DbModel
{
    public string Type { get; set; }
    public string Settings { get; set; }
}

Generally the DbModel Settings property is the serialized version of the ApiModel . So I want to achieve that with a custom convert when creating the maping:
Startup.cs:
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies())

Mapper profile class:
internal class DbToApiMapping : Profile
    {
        public DbToApiMapping()
        {
            CreateMap<ApiModel, DbModel>()
                .ConvertUsing((source, dest, context) => new DbModel
                {
                    Type = context.Items["Type"].ToString(),
                    Settings = JsonConvert.SerializeObject(source)
                });

            CreateMap<DbModel, ApiModel>()
                .ConstructUsing((source, context) =>
                {
                    var res = JsonConvert.DeserializeObject<ApiModel>(source.Settings);
                    return new ApiModel
                    {
                        Colors = res.Colors
                    };
                });

        }

    }

For the first map I use it like this:
var settings = modelMapper.Map<DbModel>(req.Settings, opt => opt.Items["Type"] = "Setpoint");

For the second map I use it like that:
var ss = modelMapper.Map<ApiModel>(settings.Settings);

The error I get when try to map is as follows:
Message:
AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping.

Mapping types:
Object -> ApiModel
System.Object -> CommonLibrary.Models.ApiModel

I'm sure that I'm doing something wrong...but I can't quite catch what to look exactly. For the second mapping I tried with .ConvertUsing() method, but the error is the same.
Can someone help with this one.
Thanks in advance
Julian
---EDIT---
As suggested in the comments I tried without the DI. Here is the code:
class Program
    {
        static void Main(string[] args)
        {
            var config = new MapperConfiguration( cfg =>
            {
                cfg.CreateMap<ApiModel, DbModel>()
                .ConvertUsing((source, dest, context) => new DbModel
                {
                    Type = context.Items["Type"].ToString(),
                    Settings = JsonConvert.SerializeObject(source)
                });
                cfg.CreateMap<DbModel, ApiModel>()
                .ConstructUsing((source, context) =>
                {
                    var res = JsonConvert.DeserializeObject<ApiModel>(source.Settings);
                    return new ApiModel
                    {
                        Colors = res.Colors
                    };
                });
            });

            var modelMapper = config.CreateMapper();

            var apiObj = new ApiModel
            {
                Colors = new List<ApiSubModel>
                {
                    new ApiSubModel
                    {
                        SomeProp = "Test",
                        SubModel = new ApiSubSubModel
                        {
                            IntProp = 3,
                            StringProp = "Alabala"
                        }
                    }
                }
            };
            DbModel dbRes = modelMapper.Map<DbModel>(apiObj, opt => opt.Items["Type"] = "Setpoint");

            var dbObj = new DbModel
            {
                Type = "Setpoint",
                Settings = "{\"Colors\":[{\"SomeProp\":\"Test\",\"SubModel\":{\"IntProp\":3,\"StringProp\":\"Alabala\"}}]}"
            };

            var apiRes = modelMapper.Map<ApiModel>(dbObj);
            Console.WriteLine(dbRes.Settings);
            Console.WriteLine(apiRes.Colors[0].SomeProp);
            Console.WriteLine(apiRes.Colors[0].SubModel.StringProp);
            Console.ReadLine();
        }
    }

    public class ApiModel
    {
        public List<ApiSubModel> Colors { get; set; }
    }

    public class DbModel
    {
        public string Type { get; set; }
        public string Settings { get; set; }
    }

    public class ApiSubModel
    {
        public string SomeProp { get; set; }
        public ApiSubSubModel SubModel { get; set; }
    }

    public class ApiSubSubModel
    {
        public int IntProp { get; set; }
        public string StringProp { get; set; }
    }

It IS working, but there is something strange, when I want to debug the program and put a break point after var apiRes = modelMapper.Map<ApiModel>(dbObj); and try to debug the value of apiRes it says apiRes error CS0103: The name 'apiRes' does not exist in the current context

A: I tweaked your code a bit and now it works(although I had to use my own JSON and my own SubApiModel) but you can ask me about it in the comments if you're unsure
My models
public class ApiModel
    {
        public List<ApiSubModel> Colors { get; set; }
    }

    public class ApiSubModel
    {
        public string Name { get; set; }
    }

    public class DbModel
    {
        public DbModel(string type, string settings)
        {
            Type = type;
            Settings = settings;
        }

        public string Type { get; set; }
        public string Settings { get; set; }
    }

and my JSON
{
  Colors:
  [
     {
        "Name": "AMunim"
     }
   ]
}

and this is my mapping configuration:
.CreateMap<DbModel, ApiModel>()
                .ConstructUsing((source, context) =>
                {
                    var res = JsonConvert.DeserializeObject<ApiModel>(source.Settings);
                    return res;
                });

This basically deserializes the whole JSON and since it has a property Color which is a list of ApiSubModels, I can simply convert the whole string to Object(of type ApiModel).
This is my complete testing code
using AutoMapper;
using Newtonsoft.Json;
using StackAnswers;
using StackAnswers.Automapper;
using System.Numerics;

DbModel dbModel = new DbModel("very important type", "{Colors: [{\"Name\": \"AMunim\"}]}");
MapperConfiguration config = new(cfg =>
{
    cfg.CreateMap<DbModel, ApiModel>()
                .ConstructUsing((source, context) =>
                {
                    var res = JsonConvert.DeserializeObject<ApiModel>(source.Settings);
                    return res;
                });
});

Mapper mapper = new(config);

ApiModel apiModel = mapper.Map<DbModel, ApiModel>(dbModel);

Console.WriteLine(apiModel.Colors.Count);
Console.WriteLine(apiModel.Colors.FirstOrDefault()?.Name);
Console.Read();

and the output:
EDIT
You can register your profiles/Mappings individually and force DI to use that i.e. register that
var config = new MapperConfiguration(c => {
    //profile
    c.AddProfile<DbToApiMapping>();
    //mappings
    c.CreateMap<DbModel, ApiModel>()
                .ConstructUsing((source, context) =>
                {
                    var res = JsonConvert.DeserializeObject<ApiModel>(source.Settings);
                    return res;
                });

});
//now register this instance
services.AddSingleton<IMapper>(s => config.CreateMapper());

Now when you request this service you will get the instance with configuration applied in your ctor
public class BadClass
{
    private readonly IMapper _mapper;
    BadClass(IMapper mapper)
    {
         _mapper = mapper;
    }

    public void HandleFunction()
    {
       //here you can use this
       ApiModel apiModel = _mapper.Map<DbModel, ApiModel>(dbModel);

    }
}

A: I managed to find my mistake, and I have to admit it is a silly one, but took me a lot of time to figure. The problem is in the line var ss = modelMapper.Map<ApiModel>(settings.Settings);
See I have the Profile like this:
CreateMap<DbModel, ApiModel>()
                .ConstructUsing((source, context) =>
                {
                    var res = JsonConvert.DeserializeObject<ApiModel>(source.Settings);
                    return new ApiModel
                    {
                        Colors = res.Colors
                    };
                });

It expects the source to be a DbModel object, but in fact I pass a property of this object which is in fact a string. And I do not have defined that kind of mapping, that is why I get the error.
The right usage have to be: var ss = modelMapper.Map<ApiModel>(settings);
So thanks for all your suggestions!
Regards,
Julian

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I loop to keep making new object instances of a class? while (x < 6) {
    x = x-1;
    Dog kfl = new Dog();
}

Does this loop creates 6 new different objects and assigns them to reference variable kfl or ...?

A: This depends on what x is. Also, the way you set up your loop, it will run infinitely if x starts at less than 6 or not execute if x starts at 6 or higher.
Assuming int x = 0;
while (x < 6) {
    x = x-1;

Should either by replaced with
int x = 6;
while (x > 0) {
    x--;

Or
int x = 0;
while (x < 6) {
    x++;

When you are defining the instance kfl, you are creating new objects, but they are all assigned to the same variable, so you are rewriting them.
If you want to assign instances with similar variables, a good way is to assign them to an array, and define a new instance for each element of the array. For example,
Dog dogs[] = new Array[5]; // Sets array to 5 elements total

for (int i = 0; i < dogs.length; i++) {
    dogs[i] = new Dog();
}

The reason for loops are used here instead of while loops are that for loops are meant to be used for iteration. While loops are meant to be used as a continual conditional - like an if statement except constantly repeating. Hence, you would use a while loop when you don't know how many times a block of code should iterate and a for loop when you do know how many times.

A: It will create around 5 + Integer.MIN_VALUE of Dog Objects. After each iteration they previous object will be eligible to be garbage collected. After the while loop all of the Dog objects will be no longer referenced because it will be out of scope.
This means in the end you will have no reference to any of the created Dog objects.
Edit: I took x as x=5. Since it has to be < 6 to satisfy the while constraint.

A: Object creation depends on the value of x. If the value of x is less then 6, then it will create an infinite number of objects. In the other case, if the value of x is greater then 6, then the loop will not execute, so the number of objects will be 0.


text:
Q: How to link shared libraries in custom path directly without specifying RPATH? I am on Ubuntu 16.04, and I am required to use an external library (MCR). It puts all of it's shared libraries inside the MATLAB/bin/glnxa64/ folder. I only need the libmx.so in there but there are libraries in there that has the exact same name as the ones in /usr/lib but they are actually different (because the file size is different), for example libtiff.so.5.
This becomes a problem because when I use the find_library function in CMake to add MATLAB/bin/glnxa64/ into RPATH in order to link to libmx.so for my application, since my application also depends on another external library (OpenCV) that was linked to the libtiff.so.5 in /usr/lib when it was built, when I compile my application it shows an compilation error of

/usr/lib/libopencv_imgcodecs.so.3.3.0: undefined reference to
  `TIFFReadDirectory@LIBTIFF_4.0'

It is because my application is trying to link to the libtiff.so.5 in MATLAB/bin/glnxa64/ instead of /usr/lib because RPATH has a higher priority than the default directories. What is the best way to solve this?
I tried renaming the libtiff.so.5 in MATLAB/bin/glnxa64/ to something like libtiff_old.so.5. This solves it but is very ugly.
Is there anyway I can alternate the search priority so RPATH goes after the default directories? Or is there something I can do in CMake so my application can directly link to libmx.so without having to add MATLAB/bin/glnxa64/ into RPATH to mess things up?

A: Well, first it would be good to see your cmake file, but alas..
You can try using this, the <...> is your base directory for the MATLAB install, which might be /usr/local/ or /opt.
find_library (MATLAB_RUNTIME libmx
    PATHS <...>/MATLAB/bin/glnxa64/
    NO_DEFAULT_PATH )


text:
Q: How to determine if a matrix $B$ is spanned by $V$? Given a matrix $B$, how do I determine if it is spanned by $V$?
For example:
Let $B = \begin{bmatrix}
1 & 2\\
0 & 3
\end{bmatrix}$
$V = \mathrm{span} \left\{
\begin{bmatrix}
1&0 \\
0&1
\end{bmatrix},\begin{bmatrix}
1&2 \\
0&0
\end{bmatrix},
\begin{bmatrix}
0&0 \\
3&0
\end{bmatrix}
\right \}$
What is the linear combination in $V$, that is used to produced $B$?

A: Hint: You want to check whether the equation
$$
\pmatrix{1&2\\ 0&3} = a_1 \pmatrix{1&0\\0&1} +
a_2 \pmatrix{1&2\\0&0} +
a_3 \pmatrix{0&0\\3&0}
$$
has a solution for $a_1,a_2,a_3$.  Remember that two matrices are equal if and only if all of their entries coincide.
Noting that the bottom-right entry of the matrix must be $0$, we can see that any solution must satisfy $a_3 = 0$.


text:
Q: php ldap terminal services profile path I've written a php page to change user's names when they get married etc using ldap, however I've just noticed that ldap_get_entries does not return the TS Profile path (msTSProfilePath). Does anyone know how I can get this so I can change it to the new name? (we are changing the user's homedirectory to the new name which includes the TS Profile). Searched here & google, both return 0 results
example code:
$server = "eng-ads-01s.eng.company.co.uk";
$dn = "DC=eng,DC=company,DC=co,DC=uk";$user = "CN=User Name,OU=Users,OU=Helpdesk,OU=Group IT,DC=company,DC=co,DC=uk";
//user password
$psw = "Password";
$ds=ldap_connect($server);
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($ds, LDAP_OPT_REFERRALS,0);
$r=ldap_bind($ds, $user , $psw);
// performing search
$sr=ldap_search($ds, $dn, $search);
$data = ldap_get_entries($ds, $sr);
print_r($data);

$data doesn't return the TS profile path even though it's in AD


text:
Q: Visual Studio 2012 won't let me log out of TFS so I can enter new username/password I've been trying to disconnect or remove my credentials from a machine because of a conflict. However, whilst connecting to the remote TFS server I was asked for credentials, I cannot find a way to log out of the TFS and log in with new credentials to resolve. How can I drop the credentials or simply log into TFS as a different user. This is driving us crazy as we have a mapping conflict issue.
Currently the login to TFS and on VS is different from that of the machine. Is there a way I can just start again.

A: Check the Credential Manager:
Control Panel\All Control Panel Items\Credential Manager
There should be an entry for your TFS and your account. Just delete it and you should be asked again for credentials when connecting VS with TFS.

A: In my case the solution of Navanod didn't work.
What worked for me was adding the TFS-username to the TFS Server URL separated by the at-sign (@).
As follows:

A: The easiest way that I found for logging out of TFS from within Visual Studio is:

*

*In Visual Studio select: View -> Other Window -> Web Browser

*Type in your TFS Server URL in the URL Field (This means using VS, browse to your TFS url: MyName.visualstudio.com)

*Sign out

Now if you try to connect to your TFS Server, VS would prompt you for Username and Password.


text:
Q: Fisher exact test run on multiple columns and results printed to a separate table I am working with a data frame containing case control status, participant ID and genotype data for a SNP per column.
caco   ID     x132267464     x132270331   ...
1      10125  0/1            0/0          ...
2      10202  0/2            0/0          ...
...

I wish to run a fisher exact test on the case control (caco) and the genotype data for each snp, once the fisher test is run I want to save the P value to a separate table.
So a fisher test for caco v x132267464, the p value and odds ratio printed to row 1 of the result table, then caco v x132270331 with the p value and odds ratio printed to row 2 and so on.
Any help would be much appreciated

A: Actually managed to solve the problem my code looks like this
c <- 3
i <- 1
p <- 1
data <- data.frame()

while (i < 123 ) {

  TAB <- table(acadfull$caco, acadfull[,c])
  ANS <- fisher.test(TAB, conf.int=T)

  c <- c+1
  i <- i+1
  p <- p+1

  if (i==123)
  break

}

write.csv(c(snp,pos,data),"indel_results", row.names=F)


text:
Q: How do we disable Azure Api Management developer portal (both legacy and new) I worked with a team today who wanted to disable the developer portal and the signup.
The best we could come up with was to disable the legacy developer portal by adding delegation to a static site as per https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-setup-delegation
I did some testing and the new developer portal can be disabled by removing all the providers including username and password from the identities blade. This means going to the new portal returns "Developer portal has not been published yet." I think I read that the new portal would be optional somewhere.
Does anyone know a the correct way to disable the legacy and new developer portals?

A: From what I have found in my own research, Azure API Management does not have a way to disable either the legacy or new dev portals. There is a roadmap item for an Unpublish feature for the new dev portal at the following address:
https://github.com/Azure/api-management-developer-portal/projects/4#card-28534235
As this link will likely not last very long, here is a screenshot of the referenced roadmap item:

As an alternative to removing the identity providers, you can use the Azure APIM Management REST API to toggle the "properties.enabled" portal setting. Instructions are available at this link: https://blog.bitscry.com/2019/11/07/disabling-signup-in-the-azure-api-management-developer-portal/
Note that when this setting is changed to enabled = false, both sign up and sign in are disabled on the legacy dev portal (I don't know if the new dev portal respects this setting).
What can also be done in the legacy dev portal is to modify the Sign In and Sign Up templates to remove their respective forms, preventing anyone from being able to perform either action. Removing the relevant widgets from the respective pages in the new dev portal may also be feasible (or possibly delete the Sign In and Sign Up pages complete and remove from the Navigation list).


text:
Q: java - discrepancy when passing parameter of different type and update in below code although I am updating StringBuilder roar3 inside roar(String roar1, StringBuilder roar3) method but how it affects roar2 in main() method? Same thing does not affect int x or y in intUpdate(int  x, int y) also not for String roar1.
public class TestReference {

    public void roar(String roar1, StringBuilder roar3) {
        roar1.concat("!!!");
        roar3.append("!!!");
    }

    public void intUpdate(int  x, int y) {
        x=1;
        y=2;
    }

    public static void main(String[] args) {
        String roar1 = "roar";
        StringBuilder roar2 = new StringBuilder("roar");
        new TestReference().roar(roar1, roar2);

        System.out.println(roar1 + " " + roar2);

        int x=-1,y=-2;
        new TestReference().intUpdate(x, y);

        System.out.println(x + " " + y);
    }
}


text:
Q: Regex for word exclusion in python I have a regular expression '[\w_-]+' which allows alphanumberic character or underscore.
I have a set of words in a python list which I don't want to allow
listIgnore = ['summary', 'config']

What changes need to be made in the regex?
P.S: I am new to regex

A: >>> line="This is a line containing a summary of config changes"
>>> listIgnore = ['summary', 'config']
>>> patterns = "|".join(listIgnore)
>>> print re.findall(r'\b(?!(?:' + patterns + r'))[\w_-]+', line)
['This', 'is', 'a', 'line', 'containing', 'a', 'of', 'changes']

A: This question intrigued me, so I set about for an answer:
'^(?!summary)(?!config)[\w_-]+$'

Now this only works if you want to match the regex against a complete string:
>>> re.match('^(?!summary)(?!config)[\w_-]+$','config_test')
>>> (None)
>>> re.match('^(?!summary)(?!config)[\w_-]+$','confi_test')
>>> <_sre.SRE_Match object at 0x21d34a8>

So to use your list, just add in more (?!<word here>) for each word after ^ in your regex. These are called lookaheads. Here's some good info.
If you're trying to match within a string (i.e. without the ^ and $) then I'm not sure it's possible. For instance the regex will just pick a subset of the string that doesn't match. Example: ummary for summary.
Obviously the more exclusions you pick the more inefficient it will get. There's probably better ways to do it.


text:
Q: How to get posts filtered by ratings in Mongoose POST SCHEMA
const mongoose = require("mongoose");

const postSchema = new mongoose.Schema(

{
    photos: {
      type: [String],
    },
    title: {
      type: String,
      required: true,
      trim: true,
      minlength: 30,
      maxlength: 100,
    },
    body: {
      type: String,
      required: true,
      trim: true,
      minlength: 30,
      maxlength: 1000,
    },
    city: {
      type: String,
      required: true,
      trim: true,
    },
    price: {
      type: Number,
      required: true,
      min: 50,
    },
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    ratings: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Rating",
      },
    ],
  },
  { timestamps: true }
);

module.exports = mongoose.model("Post", postSchema);

RATING SCHEM
const mongoose = require("mongoose");

const ratingSchema = new mongoose.Schema(
  {
    user: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
      required: true,
    },
    post: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Post",
      required: true,
    },
    numStars: {
      type: Number,
      required: true,
      min: 1,
      max: 5,
    },
    comment: {
      type: String,
      required: true,
      trim: true,
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("Rating", ratingSchema);

ENDPOINT: http://localhost:4001/api/posts/search
My question here is how can I filter posts based on city, price and ratings (numStars) in Mongoose? Because I don't have total ratings for each post and it is kind of confusing me.
I would really appreciate your help.
Thanks everyone!
cheers,


text:
Q: Get the "maximum value entered by user"? I need to get the maximum value out of this code, but it's really screwy. Anyone got any suggestions?
import java.util.Scanner;
public class Test{
    public static void main(String args[])
    {
        Scanner scan = new Scanner(System.in);

         final int sentinel = 0;
         int number;
         int maxval = 0;
         int count = 0;

         System.out.println ("Enter a number: ");

         number = scan.nextInt();
         while (number != sentinel)
         {
            count++;
            System.out.println("Enter another number");
            number = scan.nextInt();
            maxval = number;
         }

         if (number > maxval)
         {
            maxval = number;
            System.out.println ("The max value is " + maxval);
         }
    }
}

A: you overwrite the maxval variable every time you get a new number. You have to do something like this
 while (number != sentinel)
 {
     count++;
     System.out.println("Enter another number");
     number = scan.nextInt();
     if (number > maxval && number != sentinel) //So you don't overwrite it when you get the sentinel character
        maxval = number;
 }
 System.out.println ("The max value is " + maxval);

A: Try this, it's a bit simpler and fixes the main problem in your code: that the comparison number > maxval has to be inside the main loop:
    Scanner scan = new Scanner(System.in);

    final int sentinel = 0;
    int maxval = 0;
    int number = 0;

    do {
        System.out.print("Enter a number: ");
        number = scan.nextInt();
        if (number > maxval)
            maxval = number;
    } while (number != sentinel);

    System.out.println("The max value is " + maxval);


text:
Q: Python, SUM list of dictionaries by matching key value I have found similar solutions to what I am looking to do, and it works to an extent. However not exactly as I need. Your assistance is appreciated.
Problem: I want to make a new list/dictionary per OrderID and its TradeVolume. You can have multiple Trades but only one OrderID. If an OrderID has more than one trade associated to it, I want to sum the TradeVolume.
I have a list of unique orderIDs that I made from a JSON response:
order_ids = [39663397, 39982478]

Trimmed for example purposes.
Here is the JSON that I will be running through
   trades = [{'TradeNumber': 39784054, 'OrderNumber': 39982478, 'TradeVolume': 1.0}, {'TradeNumber': 39784055, 'OrderNumber': 39982478, 'TradeVolume': 1.0}]

Expected Result:
{'OrderNumber': 39982478, 'TotalTradeVolume': 2.0}

Current output:
{'OrderNumber': 39982478, 'TotalTradeVolume': 1.0},
{'OrderNumber': 39982478, 'TotalTradeVolume': 2.0}

As you can see, on the first pass its adds it as expected. But with the second pass, I expect it to update the value already in the list, and not add a new one. The sum is correct in the second item.
Here is my code snippet that does the work:
for orderid in order_ids:
sum = 0
for trade in trades:
    if orderid == trade['OrderNumber']:
        sum = sum + trade['TradeVolume']

        if orderid not in total_per_order:
            print('not in,  adding...')
            total_per_order.append({'OrderNumber': orderid, 'TotalTradeVolume': sum})
        else:
            print('already here, updating...')
            total_per_order.update({'TotalTradeVolume': sum})

From running this in debug mode, it never seems to find that the OrderNumber is already in the new list I created. Pretty certain this is where my mistake is.
Thanks for your help!

A: How about this:
total_per_order = []
for orderid in order_ids:
    total_per_order.append({
        'OrderNumber': orderid,
        'TotalTradeVolume': sum(t['TradeVolume'] for t in trades if t['OrderNumber'] == orderid)}

Result; total_per_order =:
[{'OrderNumber': 39663397, 'TotalTradeVolume': 0},
 {'OrderNumber': 39982478, 'TotalTradeVolume': 2.0}]

A: To solve for your expected result, you also can bring the if statement at the bottom of your code to a higher level:
total_per_order = []
for orderid in order_ids:
    sum = 0
    for trade in trades:
        if orderid == trade['OrderNumber']:
            sum = sum + trade['TradeVolume']

if orderid not in total_per_order:
    print('not in,  adding...')
    total_per_order.append({'OrderNumber': orderid, 'TotalTradeVolume': sum})
else:
    print('already here, updating...')
    total_per_order.update({'TotalTradeVolume': sum})

Result:
not in,  adding...
[{'OrderNumber': 39982478, 'TotalTradeVolume': 2.0}]


text:
Q: uneven growth rate of progression in animation Look at flowing code:
from kivy.app           import App;
from kivy.uix.widget    import Widget;
from kivy.animation     import Animation;
from kivy.uix.button    import Button;
from time               import time;
import json;

but = Button();
anim = Animation(size_hint = (.75 , .75), duration = 1);
anim += Animation(size_hint = (.5 , .5), duration = 1);
anim += Animation(size_hint = (.25 , .25), duration = 1);
anim += Animation(size_hint = (.0 , .0), duration = 1);

progress_array = [];
time_array = [];

start_time = time();

def progr_fun(*args):
    global time_array, progress_array;
    time_array.append((time() - start_time));
    print((time() - start_time));
    progress_array.append(args[2]);
    print(args[2]);

anim.bind(on_progress = progr_fun);

anim.start(but);

class testApp(App):
    def build(self):
        return but;

if __name__ == '__main__':
    testApp().run();

f_obj = open('hello', 'w');
json.dump([progress_array, time_array], f_obj);
f_obj.close();

Its program, that makes easy animation for button. Animation consists of several parts (its important). There is callback on_progress that collects time data and progression. This data saved at the end of program.
I'm using another script to build plot by time and progression and get something like that:
enter image description here
As you can see in different parts of animation progression growing unevenly.
Why is this happening? How to fix it?

A: It is odd behavior, but I think the cause is a different time interval used to step through the different parts of the animation. I believe those intervals, while changing for the different phases, are within the resolution of the kivy clock.
I'm not sure why those intervals change. I believe that is done in the C-code underneath the kivy Clock.
The + operator for Animation objects produces a Sequence subclass of Animation, and that seems to trigger the difference. A workaround is to construct your own sequence, Something like this:
    self.anim1 = Animation(size_hint=(.75, .75))
    self.anim2 = Animation(size_hint=(.5, .5))
    self.anim3 = Animation(size_hint=(.25, .25))
    self.anim4 = Animation(size_hint=(.0, .0))

    self.anim1.bind(on_progress=self.progr_fun, on_complete=self.start2)
    self.anim2.bind(on_progress=self.progr_fun, on_complete=self.start3)
    self.anim3.bind(on_progress=self.progr_fun, on_complete=self.start4)
    self.anim4.bind(on_progress=self.progr_fun)
    self.anim1.start(self.but)

def start2(self, *args):
    self.anim2.start(self.but)

def start3(self, *args):
    self.anim3.start(self.but)

def start4(self, *args):
    self.anim4.start(self.but)

A: One more possible solution - make your own progress rate using time.time(). Its can looks like that:
but = Button();
anim = Animation(size_hint = (.75 , .75), duration = 1);
anim += Animation(size_hint = (.5 , .5), duration = 1);
anim += Animation(size_hint = (.25 , .25), duration = 1);
anim += Animation(size_hint = (.0 , .0), duration = 1);

def start_fun(*args):
    global start_time;
    start_time = time();

def progr_fun(*args):
    global time_array, progress_array, start_time , anim;
    my_progress = (time() - start_time) / anim.duration;
    print(my_progress);

anim.bind(  on_progress = progr_fun,
            on_start = start_fun);

anim.start(but);

But this variant not so accurate. You can get something like that at the end of animation:
1.0635101795196533
1.0677716732025146
1.0720353722572327


text:
Q: cakePHP - Call to a member function findById() on a non-object I am new to cakePHP, please advice.
The database name is admin_accounts. Here is data.

The class file
<?php
App::uses('AppModel', 'Model');

class AdminAccount extends AppModel {

}
?>

The controller file
<?php
    class AdminAccountsController extends AppController{

    public function profile($id = null){
        if(!$id){ throw new NotFoundException(__('No profile')); }

        $adminAccount = $ $this->AdminAccount->findById($id);
        if (!$adminAccount) {
                throw new NotFoundException(__('No profile'));
        }
        $this->set('admin_account', $adminAccount);
    }

    }
?>

When I call the profile, it gave me this error
Warning (4096): Object of class AdminAccountsController could not be converted to string   [APP/Controller/AdminAccountsController.php, line 15]
Notice (8): Object of class AdminAccountsController to string conversion [APP/Controller/AdminAccountsController.php, line 15]
Notice (8): Undefined variable: Object [APP/Controller/AdminAccountsController.php, line 15]
Notice (8): Trying to get property of non-object [APP/Controller/AdminAccountsController.php, line 15]
Fatal error: Call to a member function findById() on a non-object in /home/crayzest/public_html/cake/app/Controller/AdminAccountsController.php on line 15

What did I do wrong?

A: Firstly remove the extra $ sign .
And , secondly load the Model before you use findById() function.
Write This before findbyId() statement
$this->loadModel('AdminAccount');


text:
Q: Appending parameters to PHP URL is not returning anything, but hard coded works perfectly Alright, so here goes nothing.
the URL: http://tandemenvoy.michaeldvinci.com/forum/repliesJSON.php?rID=2 returns me absolutely nothing. if I hard code the SQL query to
"SELECT * FROM replies WHERE replyID = 2"

I get the correct JSON formatted request, but when I try passing it as a parameter in the URL. is just displays nothing -
now the reason I'm doing this is because I'm working on an iOS app that is transversing multiple tables and I need it to only display the matching 'replyTopic's to the 'categoryID's and I'm guessing if I can just append the categoryIDs to the end of the url with the correct query, it'll be a heck of a lot easier
repliesJSON.php:
<?php

$con=mysqli_connect("localhost","","","");

if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$rID = $GET_['rID'];

$sql = "SELECT * FROM replies WHERE replyID = '".$rID."' ";

if ($result = mysqli_query($con, $sql))
{
    $resultArray = array();
    $tempArray = array();

    while($row = $result->fetch_object())
    {
        $tempArray = $row;
        array_push($resultArray, $tempArray);
    }

    echo json_encode($resultArray);
}

mysqli_close($con);
?>

A: $rID = $GET_['rID'];

should be
$rID = (int)$_GET['rID'];

The main error was the typo in your get var.
I additionally casted your getvar as integer because you are not using any prepare statments.

A: Because your Mysql statement is wrapped in double quotes, PHP will parse it for variables, meaning that '".$rID."' is outputted as '2' (with the single quotes still there) because PHP ignores the double quotes and concatenates the single quotation marks and the number 2.
Simply changing: WHERE replyID = '".$rID."' to: WHERE replyID = '$rID'  will fix this problem.
Edit:
you can also leave out the single quotes altogether as @steven has mentioned:
WHERE replyID = $rID


text:
Q: DevEnv to build BizTalk Visual Studio 2013 solution from command line I'm running the following:
D:\GitRecompile>"c:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe" MyFolder\MyApp.sln /build "Debug"

It gives no error, no results, nothing.  Almost like I just hit enter from the command line.
I'm trying to do a batch rebuild of several BizTalk Projects from the command line to make sure all code was checked-in corretly.
I also tried:
D:\GitRecompile>c:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild MyFolder\MyApp.sln /p:Configuration=Debug

It ran, but got a lot of errors, such as xxx.xsd.cs could not be found. BizTalk creates the .cs from the .xsd at build time; so it seems like the build should have created those files.


text:
Q: Clock.schedule_interval iteration not working in Kivy (Python) I am using the Clock module in kivy.clock. I have 5 different images that need to be constantly checked for coordinates from LEAP Motion. The current code works perfectly, however I am unable to figure out why, when iterated, only the last scheduled event occurs. (The count function correctly reads the number of pictures)
    # for i in range(0, count):
    #     Clock.schedule_interval(lambda dt: self.animate(picture[i], (i - 2) * 300), 1.0 / 60.0)

    Clock.schedule_interval(lambda dt: self.animate(picture[0], -600), 1.0 / 60.0)
    Clock.schedule_interval(lambda dt: self.animate(picture[1], -300), 1.0 / 60.0)
    Clock.schedule_interval(lambda dt: self.animate(picture[2], 0), 1.0 / 60.0)
    Clock.schedule_interval(lambda dt: self.animate(picture[3], 300), 1.0 / 60.0)
    Clock.schedule_interval(lambda dt: self.animate(picture[4], 600), 1.0 / 60.0)


text:
Q: Sending last day of month into a function in R May be this isn't a nice way to do this but I have to run over every last day of month into a function for last 4 years and rbind the output of all the dates into one data.frame.
I already have my dataframe DF in my environment.
MY FUNCTION
Part 1 I need Dynamic Date Insertion here to loop over dates automatically.
myfunct <- function (date) {

abc <- subset(DF, HIRE_DATE <= date || LAST_WORKING_DATE <= date )
abc <- subset(abc, TDATE <= date)

augact <- abc %>%
  group_by(ID_Merged) %>%
  slice(which.max(TDATE))

augact <- subset(augact, ASSIGNMENT_STATUS == "ACTIVE")

hc_cnt <- nrow(augact)
x <- data.frame(date, hc_cnt)

return(x)
}

Part 2
Row Binding the output into one.
x <- myfunct("2021-01-31")
y <- myfunct("2021-08-31")
dfmerged <- rbind(x,y)

Please remember I want to automatically send the last day of the every month. May be there's some package that can do this.
rbind output us as follow
        date hc_cnt
1 2021-01-31   2946
2 2021-08-31   3039

A: I meant this as a comment, but since it is really another answer, it should be visible...
To obtain a Date vector listing the last date of each month from Date start to Date end, using base R only, you can do:
last_of_month <- function(start, end) {
  ## Round "YYYY-MM-DD" down to "YYYY-MM-01"
  start <- as.Date(format(start, "%Y-%m-01"))
  seq(start, end + 1, by = "1 month")[-1L] - 1
}

last_of_month(as.Date("2020-01-15"), as.Date("2021-11-18"))
#  [1] "2020-01-31" "2020-02-29" "2020-03-31" "2020-04-30" "2020-05-31"
#  [6] "2020-06-30" "2020-07-31" "2020-08-31" "2020-09-30" "2020-10-31"
# [11] "2020-11-30" "2020-12-31" "2021-01-31" "2021-02-28" "2021-03-31"
# [16] "2021-04-30" "2021-05-31" "2021-06-30" "2021-07-31" "2021-08-31"
# [21] "2021-09-30" "2021-10-31"

A: May be I can help you. You can get list of all ends of months by hand:
library(data.table)

date_start <- as.Date("2020-01-01")
date_end <- Sys.Date()

all_dates <- .Date(date_start:date_end)
ends_of_months <- all_dates[which(month(all_dates) != month(lead(all_dates)))]


text:
Q: Setting innerHTML/html() on DOM-elements within nested loop - IE performance I am working on some horrible legacy code where a JSON-object is fetched from the server. The object is a list of IDs that correspond to DOM-Nodes. Each list-item contains new HTML-Code-Snippets to be inserted for that node. Basically it looks like this:
var $table = $("#theTable");
var tableData = getData();

for (var row in tableData) {

     // find the TR
     var $row = $table.find('tr[data-id=' + row + ']');

     // update many sub-elements of the TR (~100-1000 nodes)
     for (var el in row) {
           var $el = $row.find("td[data-element='" + el + "']");
           if ($el.length) {
                 $el[0].innerHTML = row[el];
           }
     }
}

Obviously it is bad practice to select nodes or call .innerHTML/.html() within a loop, but at this point there is no other choice. This results in very bad performance especially in IE. I tried to hide/detach the node, before doing the updates, reattaching/showing it again when everything is done, but it did not improve performance what so ever - it just got worse.
Is there any way to easily speed this up?


text:
Q: Merging layers in Spline Design Is there a way to merge different objects together in the current state of the spline.design web 3D tool?
Boolean merges will result in multiple objects in the resulting code export which is what I'm trying to avoid. In Figma this functionality can be achieved by merging multiple layers using the Flatten option.
Could not find any options in the tool and no reference in the official documentation.

A: yes! select the layers you want to merge by holding shift and then on the right side panel you'll see "boolean modifier" which should give you the option to merge geometries. heres a link to splines more in depth review of boolean operations: https://docs.spline.design/abc1708f70ad41be88116076d5b916d2


text:
Q: jquery user screen selection I am working on a script that takes a users on screen selection (when they physically highlight text in the browser) and is supposed to manipulate that text.
This is what I am trying to do.
Take the selected text, search for the selected text in an original string and then wrap the text that is found in the original string with a certain HTML tag (, , )
I am using the jQuery.textselect plugin.
The part I can't figure out is how to manipulate the original text once the user selection has been found.
Example:
If this text is shown on the screen: "HELLO WORLD"
The original text is HELLO WORLD, the user selects HELLO, then the script searches through the original text for the user selection and will wrap HELLO with  tags and then output the new original text... make sense?
Sorry for the confusion and thanks for the help!

A: This is the closest I could get. It's not ideal for a few reasons (if you highlight Hello, it will highlight ALL the hellos). The text select plugin isn't particularly standardized, and I couldn't identify a way to know WHERE in the text, besides pixel positioning, the event was taking place, since the e variable is an event object, rather than a $(this)-style DOM element.
$(function() {
  $(document).bind('textselect', function(e) {
        $('body').html($('body').html().replace(e.text,""+e.text+""));
    });
});

jQuery isn't quite ideally suited for this, as it tends to cater to manipulation of DOM elements, rather than text manipulation.
EDIT: A more precise option, but that limits you to having this effect for a single DOM element:
$(function() {
  $(document).bind('textselect', function(e) {
      var $this = $(e.target);
      $this.html($this.html().replace(e.text,""+e.text+""));
    });
});

This is an excellent question.


text:
Q: Symbol lookup errors in (Qt?) dynamically linked libraries I'm using Ubuntu 15.10
Problem:
For some days now I have been getting Errors like this when opening some applications:
/usr/lib/x86_64-linux-gnu/libpoppler-qt5.so.1: undefined symbol: _ZN6QDebugD1Ev

Some applications affected are

*

*texstudio shows
/usr/lib/x86_64-linux-gnu/libpoppler-qt5.so.1: undefined symbol: _ZN6QDebugD1Ev

*IPython's qtconsole shows
/usr/lib/python3.5/site-packages/PyQt5/QtCore.so: undefined symbol: _ZNK12QStorageInfo11displayNameEv

*konsole (KDE's terminal emulator - I'm using Unity though) shows
/usr/lib/x86_64-linux-gnu/libKF5ItemViews.so.5: undefined symbol: ...

*granatier (a KDE game), KSysguard and KAddressbook also show errors in KF5 libraries

*also fail

*VLC seems to be affected too since it says there is something wrong with Qt 4 (see below)

Qt
all of this errors seem to come from Qt linked libraries ("Qt" appears in most filenames and most symbol names). AFAIK KDE ist baed on Qt, which would explain why all KDE applications fail.
It seems to affect both Qt 4 and 5
Possible Origin
The day this problems appeared I had enabled wily-proposed packages in the Ubuntu "Software &  Updates" System application. I interrupted the upgrade and tried this to roll it back.
After this I had a similar problem with ssl but it went away eventually.

A: Ok, so it seems the source of the problem was that I had Qt linked libraries like libQt5Core.so.5 in /usr/local/lib. When I remove them everything worked again.
I've read that the package manager doesn't put any libraries there, so it was probably me who did a dumb mistake.


text:
Q: LinkedList update fails c programming I'm trying to implement simple LinkedList in C, using two structs. Then, my goal is to print the data that is stored in the linkedlist's head.
My code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "LineParser.h"
#include <limits.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define SYS_OPEN  5
#define SYS_CLOSE 6
#define SYS_READ  3
#define SYS_WRITE 4
#define SYS_lseek 19

#define STDOUT 1
#define STDIN  0
#define STDERR 2

char buf[2048];

typedef struct pair {
    char *name;
    char *value;
} pair;

typedef struct pList {
    pair *curPair;
    struct pList *next;
} pList;

pList *head;

void addLink(pList *link);

void addLink(pList *link) {
    if (head == NULL) { //head empty
        head = link;
    } else {
        pList *curLink = head;
        while (curLink->next != NULL) {
            curLink = curLink->next;
        }
        curLink->next = link;
    }
}

void print() {
    printf("%s", head->curPair->name);
}

void dummyFunc() {
    pair *p = (pair *)malloc(sizeof(pair));
    p->name = "User1";
    p->value = "123";
    pList *link = (pList *)malloc(sizeof(pList));
    link->curPair = p;
    link->next = NULL;
    addLink(link);
    head = (pList *)malloc(sizeof(pList));
    head->curPair = p;
    head->next = NULL;
    print();
}

int main(int argc, char *argv[]) {
    char argVals[3];
    argVals[2] = '\0';
    //init the list
    head = NULL;

    while (1 == 1) {
        fgets(buf, 2048, stdin);
        if (strcmp(buf, "dummy") == 0) {
            dummyFunc();
        }
    }
}

Then, when the print function is executed (called from dummyFunc) the program gets a segfault, implying that the changes that occurred in dummyFunc didn't actually effect head.

A: There is something you are not telling use, because it is highly unlikely if (strcmp(buf, "dummy") == 0) matches. You would need to have input exactly dummy without a trailing newline for the comparison to return 0 and for dummyFunc() to be called!
Furthermore, why do you overwrite head with a new allocated node instead of calling addLink as you did just before? This is causing a memory leak but no segmentation fault, unless malloc() is configured to fail.


text:
Q: special condition in average cost function written here that absolute minimum of a cost function will occur at it's critical point when $\overline {C}'(x)=0$
since $\overline {C}(x)=\frac {C(x)} {x}$
thus, the derivative is
$$\overline {C}'(x) = \frac {xC'(x) - C(x)} {x^2}$$
in this case Marginal cost(derivative of main function) will equal to Average cost (function at x / x)
but i don't have idea how to stomach this. i mean if this phenomenon is occurs at critical point doesn't it mean Marginal cost(first derivative) is equal to zero at this point?(since x is critical points)
and above function will turn into
$$0= \frac {0 - C(x)} {x^2}$$ and it will force $C(x)$ to become zero , and this don't make any sense, i hope someone tell me where did i go wrong

A: The minimum average cost occurs when $\bar C'(x)=0$ i.e. when the marginal cost $C'(x)$, which is the derivative of the cost function and not the average cost function, equals the average cost $\bar C(x)$.

A: Firstly, $C'(x)$ and $\overline{C}'(x)$ are not the same functions. $\overline{C}'(x)$ = $0$ = $ xC'(x) - C(x)$. if you just want to find absolute minimum of cost function then you can solve $C'(x) = 0$ to find x.


text:
Q: Capitalization of "site" in the Data Explorer's footer There's a small capitalization inconsistency in the footer between the main site and the Data Explorer.
On SE the footer has the word "Site" capitalized while it's written "site" using small case in the Data Explorer.

A: The Data Explorer is open source, and even though I'm not able to run it on this machine, I'm comfortable making minor textual changes. I've created a pull request to fix this and some old links which were still HTTP. I hope it gets merged somewhere in the next 6-8 weeks...


text:
Q: Which option is correct? Can you tell which option is correct? And why it is necessary to use or not to use this or that article?

I have pizza.

or

I have a pizza.

A: They are actually both correct.
I will list two scenarios, one for each one, to show how they are correct.
1.
Bob: I'm so hungry! Does anyone have food?
Bobby: I have pizza.

2.
Bob: Finally, it's lunch time. Guess what I have?
Bobby: I don't know, what do you have? A sandwich?
Bob: I have a pizza!
Bobby: Ooh lucky!

As you can see, they both make sense in each scenario, and if you put on in the other scenario, they will still work. It's a matter of what you mean. I have a pizza means that you have one pizza. I have pizza means you have pizza. One is more specific than the other.
Hope this helps!


text:
Q: Both SAM and cdk can make stack, SAM include cdk ? or cdk include SAM? I want to make two bucket(x,y) in S3 and make a lambda.
My goal is uploading files to S3(x) and it triggers lambda then lambda create and put file in S3(y)
Currently, I am developing lambda function on SAM.
Deploying lambda function by SAM
And I made two S3 buckets by cdk.
Then manually adding trigger and Iam policy to lambda to access S3
However I want to do this all automatically.
So my idea is ,

*

*SAM can make two S3 bucket as stack and I don't need cdk anymore ?

*cdk can include SAM development environment?

*Any other way??
What is the best practice for this purpose??

A: My `solution is

*

*Local development with SAM

*AWS deployment is carried out by cdk only, SAM doesn't work anything for deployment.
My folder structure is below
cdk / bin
      lib
      cdk.json
      etc
      samproj/helloworld/app.py
             /samconfig.toml
             /template.yaml
             /etc

For local developing, in samproj directory, do something like this, tutorial.
sam local invoke "HelloWorldFunction" -e events/event.json

And for AWS deployment by cdk project .
Just make lambda directly from samproj/helloworld directory in Stack.
export class CdkVrBaseStack extends Stack {
    const lambda_ = new lambda.Function(this, 'TestLambda', {
      functionName: 'testLambda',
      runtime: lambda.Runtime.PYTHON_3_9,
      code: lambda.Code.fromAsset('samproj/helloworld'),
      handler: 'index.handler',
      timeout: cdk.Duration.seconds(300),


text:
Q: Will Ringworld be taken over by the sunflowers? In Larry Niven's novel Ringworld, there is a scene over the field of "sunflowers" that badly burn Speaker.
Won't those plants eventually take over the whole of Ringworld? Or do they have some sort of natural enemy?

A: They could...but not completely.
Tor.com on Sunflowers (on the 40th Anniversary of Ringworld)

Even so, sunflowers will never take over the entire structure's land area. Sunflowers need carbon dioxide to live and this comes from microbes and animals. There are no geological processes on the Ringworld to hold and recycle carbon dioxide, except the Spill Mountains.
So, while sunflowers can eventually take over much of the Ringworld they need to let at least microbes survive. This doesn't mean that there wouldn't be animals, and that they wouldn't be sentient. After all, since the sunflowers don't have any way to maintain the Ringworld, they need to leave some sentients around who can maintain the place.

A: As explained in World of Ptavvs, the sunflowers are under the control of the Tnuctip, something that Kzanol is too dim to figure out but that Greenberg does.  So whether they have a natural enemy is only one part of the question, and to an extent besides the point.  They are artificial, and have a control interface.  An enterprising hominid species simply needs to find it and hit the off switch.
As for "natural" enemies: A hominid who doesn't know their control interface but that finds them a threat to itself, its family, or its species, is their enemy.  Never underestimate the ability or the will, to just kill off stuff wholesale, of the group that is responsible for the Holocene Extinction.
And sunflowers do appear to be a genetically engineered monoculture.  Our enterprising hominids, adept at such biological warfare as the use of myxomatosis to kill rabbits, just needs to find the right strain of Sunflower Root Rot, or Bulb Blight.  A sunflower will have a spot of difficulty attacking a disease that is transmitted below ground.
Then there's the minor point that they are obviously vulnerable when the shadow squares are hiding the sun.  Our enterprising hominids know how make mirrors and dig tunnels, moreover.
They also know how to farm, and the joy of hyperintensive agriculture.  Give them a nice source of ultra-tough reflective stuff, and before you know it they'll be sewing together shiny protective suits made of harvested sunflower leaves and doing to sunflowers what they do to bananas, tea, wheat, cotton, rice, olives, and oranges.
Sunflowers have a good defence against predation; but that does not mean that they are invulnerable, or that they lack predators.  Or that they stand much of a chance against hominids that have decided that We like your species; we think that we'll like you on the wall over the fireplace, stuffed.
Nor should we ignore the possibility that they could acquire a parasite plant or two.  "What? You'll send lots of juicy sunlight my way in a vain attempt to kill me and you'll kill off all of my competitors?  Why, thank you very much, M. Host Plant!"  Think of it as evolution in action.  ☺


text:
Q: SEO on Laravel 5.4 I am implementing a website for generating analytics for various institutes in the USA.
I now need to implement SEO on my website. I have edited all the URL's to have them SEO friendly.
Now my question is, how to find the keywords,meta tags for my laravel website and how to include them in my website.
On my home page ? or any where else ?

A: Create a layout.blade.php and @yield the section named title and meta. When the user requests the page, it will pass through controller from which you can fetch the Title and meta description tag from your post_meta table or some table in which you store your Meta description.I am working on one CMS based on Laravel and I am doing same. To make it easy for you to understand, here is the simple example!
Example Route.php (Your User Friendly URLs)
Route::get("page/{page_id}","PageController@show");

Example Controller Function
public function show($page_id)
{
    // Fetching Meta Tag Content from Table and Passing it to View
    $page_meta = Page::getMeta($page_id);

    return view('pages.show')->with('meta_description',$page_meta);
}

Example Layout.blade.php (Your Layout file)
<html>
    <head>
        @yield('title_and_meta')
    </head>
    <body>
        @yield('body_content')
    </body>
</html>

Example Page view (Your view file that will be shown to user!)
@extends('your_layout')

@section('title_and_meta')
    <title>Your Page title</title>
    <meta name="description" content="{{ $meta_description }}" />
@endsection

@section('body_content')
    // Content here!
@endsection

Surely, you can use the Variables Passed from Controller in the views! You can pass the Array Containing Title, Meta Description, Meta Author, Meta Keywords (Deprecated) and more Page meta Stuff and show it in the view!
This is how you make your Laravel Project SEO Friendly. My Content Management System is not yet Ready otherwise I can give you the URL of my GitHub Project from which you can understand it better!Hope this helps! Let me know if you have any more Questions!


text:
Q: Is there a way to compare the format in which a line of a text file was written in Fortran? I'm developing a Fortran program that must obtain some data from a text file and generate another text file using specific data from the first one.
The input file have many lines written in several specific formats which I know of. Although I know the formats, the lines in this file are generated in a "random way".
It would be much easier to generate the output file if I could compare the format in which each line was written, then I would know exactly what data I can get from that line of the input file to use it in the output file.
What I need is something like, for example, knowing that the format of the line read and stored in the LINHA variable is described in the FORMATO variable, do something like:

IF (FORMATO = '(1X, 15,3F8.1,2 (5A, 1X))') THEN
  READ (LINHA, '(6X, F8.1)') my_variable
END IF

Because there might be another format such as
'(6A, 2F8.1, F8.6,2 (6A))'

in which, if I use the same READ statement, I will read an F8.1 variable in my_variable, however this value is not the correct one.

A: A (not so elegant) work-around that I can think of is to read the entire line using the advance = no option of read() and parse each character in the line separately. While doing so, you may count white spaces or other specific characters that you know of and then identify the different formats from there.
It would be helpful if you could give more specifications of the nature of the task.

A: The best option is to read without format, keeping each line in a character array. Then read the line variable as an internal file with the required format using the variable IOSTAT in order to check if the format is the correct.
INT max_size = 80
CHARACTER(LEN=max_size) :: line
READ(*,*) line
READ(line,'(1X, 15,3F8.1,2 (5A, 1X))',IOSTAT=ios) var1, var2, ...

A: Problem solved using a mixture of some of the suggestions posted.
I read each of the lines of the input file in an internal variable (RLINFILE) in the format '(A165)'. After that, I read all the contents of the string that I put in this internal variable in several dummy variables, using the format I knew of the lines from where I wanted to get some information (read all the information of the line in the desired and get IOSTAT = 0 guarantee that this is the correct line), so if the result of the reading is ok (IOSTAT = 0), it is because the line I just read was the correct one for the information I wanted, so I store the contents of some of the dummy variables that represent the values that interest me. In the code, the solution looked something like this:
OPEN(UNIT=LU1,FILE=RlinName,STATUS='OLD')
ilin = 0
formato = '(14X,A,1X,F7.1,1X,F7.1,5X,A,1X,A,1X,A,5X,A,I5,1X,A,I3,3F8.1,A,A,A,1X,A,2(1X,F8.2),1X,A,1X,A)'
DO WHILE (.TRUE.)
  READ(LU1,'(A165)',END=300) RLINFILE
  READ(RLINFILE,formato,IOSTAT=linhaok) dum2_a1,dum2_f1,dum2_f2,dum2_a2,dum2_a3,dum2_a4,dum2_a5,dum2_i1,dum2_a6,dum2_i2,dum2_f3,dum2_f4,dum2_f5,dum2_a7,dum2_a8,dum2_a9,dum2_a10,dum2_f6,dum2_f7,dum2_a11,dum2_a12
  IF(linhaok.EQ.0) THEN
    ilin = ilin+1
    rlin_lshu(ilin) = dum2_a4
    rlin_nbpa(ilin) = dum2_i1
    rlin_ncir(ilin) = dum2_i2
    rlin_ppij(ilin) = dum2_f3
    rlin_pqij(ilin) = dum2_f4
    rlin_tapn(ilin) = dum2_a7
  END IF
END DO
300 CLOSE(UNIT=LU1)

A: The description of the problem you are trying to solve is a bit vague to me, but the simplest solutions that comes to my mind, given the description of the problem, is to modify the original code that generates the input data file, to write the used Fortran READ format before the data line in the input file. This way, you can read the format as a string and use it in the subsequent data IO in your second code.
If you describe the specific task your tryting to accomplish in more details, perhaps more experienced Fortranners could help.


text:
Q: Passing an array as a parameter of a function inside a for loop I am trying to pass an array of objects in a onclick function inside a for loop. The scope of the array is inside the for loop only, So I cannot do like this.
A sample of my code is as follows:
for (var j = 0; j < globalVariables.countryColl.length; j++) {
    var testArray = $.map(empCatgry2Arr, function (e, i) {
                        return {
                            Id: e.ID,
                            company: e.Company,
                            dept: e.Department
                        }
                    });
                    html += "
" +
                        "" + globalVariables.countryColl[j].Title + "	" +
                        '' + empCatgry2Count + '	' +
"
";
}
html += "

";
$("#tablediv").append(html);

But when I inspect the page, the HTML looks like : "1	"
Initially I was trying to pass the whole empCatgry2Arr array, I have used the map function only to use required key-values.

A: When you render Javascript, your program must render the source code the same way as if you were writing the code yourself.
The way to pass a new array to a javascript function is to place it inside square brackets and supply the initial values in a comma-delimited list.
var html = 'etc....onclick="ShowEmployeeDetails([' + testArray.join() + '])">' + empCatgry2Count + etc...';

A: Create an element and bind the click event something like this, I used some mock data, on click you may see the console log where it logs the dynamically passed data!

function ShowEmployeeDetails(param) {
  console.log(param);
}

const html = $('

');

for (var j = 0; j < 3; j++) {

    const num = j+1;
    let obj = {"id": num};

    const row = $('

').appendTo(html);
    // first td
    $('	').attr({ class: 'fc-green'}).text("Title" + num).appendTo(row);

    // second td
    const td2 = $('	').text("ShowEmployeeDetails on click" + num).appendTo(row);

    // bind the click event to the element and then append the element to row
    td2.on('click', ShowEmployeeDetails.bind(null, obj));
    td2.appendTo(row);
}
$("#tablediv").append(html);
td {
border: 1px solid;
padding: 5px;
}


text:
Q: Interface logic when a class has parent/child logic I would like to put my interfaces into a separate assembly, but I'm having trouble implementing the interfaces.
public interface IModelObject {...}

public interface IViewmodel
{
    IModelObject ModelObject { get; }
}

public interface ITreeNodeViewmodel: IViewmodel {...}

public interface ITreeViewmodel
{
    ITreeNodeViewmodel Root { get; set; }
}

Now in the implementation:
public class NodeViewmodel:ITreeNodeViewmodel {...}
public class TreeViewmodel:ITreeViewmodel
{
    NodeViewmodel Root { get; set; }

    ITreeNodeViewmodel ITreeViewmodel.Root { get => Root; set => Root = (NodeViewmodel)value; }
    ITreeNodeViewmodel ITreeViewmodel.Root => Root;
}

You can see that the design requires that the TreeViewmodel.Root should be constrained to the  NodeViewmodel type. I can explicitly implement the interface and have one smelly explicit cast in the setter.
Is there a better way to enforce a type constraint on this property and still satisfy the interface?

A: You can create generic interfaces that extend your other interfaces like so
public interface ITreeViewmodel<T> where T: ITreeNodeViewmodel
{
    T Root { get; set; }
}

A: There is quite a strong likelihood that you'll end up with this kind of object structure:
public interface IModel
{ }

public interface IViewModel<M> : IModel
    where M : IModel
{
    M Model { get; }
}

public interface ITreeNodeViewModel<M> : IViewModel<M>
    where M : IModel
{ }

public interface ITreeViewModel<M, T>
    where M : IModel
    where T : ITreeNodeViewModel<M>
{
    T Root { get; }
}

public class TreeNodeViewModel<M> : ITreeNodeViewModel<M>
    where M : IModel
{
    public M Model { get; private set; }
}

public class TreeViewModel<M, T> : ITreeViewModel<M, T>
    where M : IModel
    where T : ITreeNodeViewModel<M>
{
    public T Root { get; private set; }
}

I just thought I'd post it as I think it'll be the natural progression of your object model once you start working with it.

A: Given the requirements you're working with, your implementation looks good.  If you don't want a "smelly cast", you could try something along the lines of:
set
{
   if (value is NodeTreeItemViewmodel goodRoot)
   {
      Root = goodRoot;
   }
   else
   {
      throw new ArgumentException("Root must be a NodeTreeItemViewmodel
 instance");
   }
}

This takes more code, but will at least give you clearer feedback if something goes wrong.


text:
Q: Own etcd cluster for Kubernetes I want to build my own Kubernetes cluster across two locations (300 km distance) and integrate it into GitLab.
Let me list my ideas. My question is if I have a mistake in my thinking somewhere and ask to solve it.

*

*Since I can only set up VMs and have no rights directly on the hosts, I want to install an etcd-cluster on 5 VMs (3+2). I would install etcd with apt on Ubuntu 18.04. For this I don't need Kubernetes at first.

*An odd number of instances only applies to etcd and not to control planes?

*Does it make any sense to set up separate VMs for the control planes or can I reuse the 3+2 VMs of the etcd cluster? Otherwise I would already have 10 VMs.

A: Unless you have a big kubernetes cluster with thousand of services and many nodes, you can setup a separated etcd cluster and remember if you want to setup the etcd cluster in two locations, check the coreos documentation, because etcd is very sensitive to latency
If you choose to use an external etcd cluster, you don't need an odd number for the control planes, you only need an odd number with etcd, because etcd machines are in cluster.
Control planes doesn't communicate between them, only with etcd

A: I have learned a few things and would like to share them with you.
etcd is pronounced like "@ cee dee".
I have decided now to not use apt (etcd 3.2 on Ubuntu 18.04) for installation but to download the latest version (3.3.18) with wget. The first hit on Google worked.
Installation
cd /opt/
sudo wget https://github.com/etcd-io/etcd/releases/download/v3.3.18/etcd-v3.3.18-linux-amd64.tar.gz
sudo tar xvf etcd-v3.3.18-linux-amd64.tar.gz
cd etcd-v3.3.18-linux-amd64/
sudo mv etcd etcdctl /usr/local/bin/
sudo mkdir -p /var/lib/etcd/
sudo mkdir /etc/etcd/
sudo groupadd --system etcd
sudo useradd -s /sbin/nologin --system -g etcd etcd
sudo chown -R etcd:etcd /var/lib/etcd/

Reset
Remove all data in the member folders:
sudo rm /etc/etcd/*.etcd/member/ /opt/etcd-v*-linux-amd64/default.etcd/member/ /var/lib/etcd/member/ -fr

Or change argument --initial-cluster-token XYZ (every five members the same) and start etcd with parameter --force-new-cluster.
When you restart your existing cluster or add more members: change from --initial-cluster-state new to --initial-cluster-state existing.
Drop all data (keys with values) from etcd cluster:
sudo ETCDCTL_API=3 etcdctl del "" --prefix

Configuration
sudo -u etcd etcd \
--name aaa \
--data-dir /var/lib/etcd/ \
--listen-peer-urls http://localhost:2380,http://localhost:7001,http://192.168.4.101:2380,http://192.168.4.101:7001 \
--listen-client-urls http://localhost:2379,http://localhost:4001,http://192.168.4.101:2379,http://192.168.4.101:4001 \
--initial-advertise-peer-urls http://192.168.4.101:2380 \
--initial-cluster aaa=http://192.168.4.101:2380,bbb=http://192.168.4.102:2380,ccc=http://192.168.4.103:2380,eee=http://192.168.4.105:2380,ddd=http://192.168.4.104:2380 \
--initial-cluster-state new \
--initial-cluster-token 2020-02-07T14:53 \
--advertise-client-urls http://192.168.4.101:2379

sudo -u etcd etcd \
--name bbb \
--data-dir /var/lib/etcd/ \
--listen-peer-urls http://localhost:2380,http://localhost:7001,http://192.168.4.102:2380,http://192.168.4.102:7001 \
--listen-client-urls http://localhost:2379,http://localhost:4001,http://192.168.4.102:2379,http://192.168.4.102:4001 \
--initial-advertise-peer-urls http://192.168.4.102:2380 \
--initial-cluster aaa=http://192.168.4.101:2380,bbb=http://192.168.4.102:2380,ccc=http://192.168.4.103:2380,eee=http://192.168.4.105:2380,ddd=http://192.168.4.104:2380 \
--initial-cluster-state new \
--initial-cluster-token 2020-02-07T14:53 \
--advertise-client-urls http://192.168.4.102:2379

sudo -u etcd etcd \
--name ccc \
--data-dir /var/lib/etcd/ \
--listen-peer-urls http://localhost:2380,http://localhost:7001,http://192.168.4.103:2380,http://192.168.4.103:7001 \
--listen-client-urls http://localhost:2379,http://localhost:4001,http://192.168.4.103:2379,http://192.168.4.103:4001 \
--initial-advertise-peer-urls http://192.168.4.103:2380 \
--initial-cluster aaa=http://192.168.4.101:2380,bbb=http://192.168.4.102:2380,ccc=http://192.168.4.103:2380,eee=http://192.168.4.105:2380,ddd=http://192.168.4.104:2380 \
--initial-cluster-state new \
--initial-cluster-token 2020-02-07T14:53 \
--advertise-client-urls http://192.168.4.103:2379

sudo -u etcd etcd \
--name ddd \
--data-dir /var/lib/etcd/ \
--listen-peer-urls http://localhost:2380,http://localhost:7001,http://192.168.4.104:2380,http://192.168.4.104:7001 \
--listen-client-urls http://localhost:2379,http://localhost:4001,http://192.168.4.104:2379,http://192.168.4.104:4001 \
--initial-advertise-peer-urls http://192.168.4.104:2380 \
--initial-cluster aaa=http://192.168.4.101:2380,bbb=http://192.168.4.102:2380,ccc=http://192.168.4.103:2380,eee=http://192.168.4.105:2380,ddd=http://192.168.4.104:2380 \
--initial-cluster-state new \
--initial-cluster-token 2020-02-07T14:53 \
--advertise-client-urls http://192.168.4.104:2379

sudo -u etcd etcd \
--name eee \
--data-dir /var/lib/etcd/ \
--listen-peer-urls http://localhost:2380,http://localhost:7001,http://192.168.4.105:2380,http://192.168.4.105:7001 \
--listen-client-urls http://localhost:2379,http://localhost:4001,http://192.168.4.105:2379,http://192.168.4.105:4001 \
--initial-advertise-peer-urls http://192.168.4.105:2380 \
--initial-cluster aaa=http://192.168.4.101:2380,bbb=http://192.168.4.102:2380,ccc=http://192.168.4.103:2380,eee=http://192.168.4.105:2380,ddd=http://192.168.4.104:2380 \
--initial-cluster-state new \
--initial-cluster-token 2020-02-07T14:53 \
--advertise-client-urls http://192.168.4.105:2379

You can put this into service:
/etc/systemd/system/etcd.service (create if not exist) (example for first member aaa)
[Unit]
Description=etcd key-value store
Documentation=https://github.com/etcd-io/etcd
After=network.target

[Service]
User=etcd
Type=notify
Environment=ETCD_DATA_DIR=/var/lib/etcd
Environment=ETCD_NAME=%m
ExecStart=/usr/local/bin/etcd \
--name aaa \
--data-dir /var/lib/etcd/ \
--listen-peer-urls http://localhost:2380,http://localhost:7001,http://192.168.4.101:2380,http://192.168.4.101:7001 \
--listen-client-urls http://localhost:2379,http://localhost:4001,http://192.168.4.101:2379,http://192.168.4.101:4001 \
--initial-advertise-peer-urls http://192.168.4.101:2380 \
--initial-cluster aaa=http://192.168.4.101:2380,bbb=http://192.168.4.102:2380,ccc=http://192.168.4.103:2380,eee=http://192.168.4.105:2380,ddd=http://192.168.4.104:2380 \
--initial-cluster-state new \
--initial-cluster-token 2020-02-07T14:53 \
--advertise-client-urls http://192.168.4.101:2379
Restart=always
RestartSec=10s
LimitNOFILE=40000

sudo systemctl daemon-reload
# sudo systemctl enable etcd  # for auto start after reboot
sudo systemctl restart etcd

If someone can make an example with encryption, i.e. with client certificates, I would be grateful.
Chrony
It is also important that all five machines have the same time. Otherwise you will see a lot of errors in your logs. For this I used chrony.
sudo timedatectl set-timezone Europe/Berlin
sudo timedatectl set-local-rtc 1 --adjust-system-clock
sudo timedatectl set-local-rtc 0
sudo systemctl stop systemd-timesyncd.service && sudo systemctl disable systemd-timesyncd.service
sudo apt update && sudo apt --yes install chrony

/etc/chrony/chrony.conf
# I use HTTP connect proxy and can't connect to external ntp servers:
local
bindcmdaddress 0.0.0.0
allow 192.168.0.0/16
cmdallow 192.168.0.0/16
# server 192.168.4.101 prefer iburst  # himself
server 192.168.4.102 prefer iburst
server 192.168.4.103 prefer iburst
server 192.168.4.104  prefer iburst
server 192.168.4.105  prefer iburst
# ...
makestep 1 -1

# Show time etc.:
sudo timedatectl
# Show ntp network members:
sudo chronyc sources

Please remember to supply the worker nodes with the same time as well.
Checks
sudo etcdctl cluster-health
member eee6e5e8935fd1c9 is healthy: got healthy result from http://192.168.4.105:2379
member bbb7b0aca4c13cdc is healthy: got healthy result from http://192.168.4.102:2379
member aaac5ad73f7d224f is healthy: got healthy result from http://192.168.4.101:2379
member ccc20379b7c3a64e is healthy: got healthy result from http://192.168.4.103:2379
member ddd76f34bf32390e is healthy: got healthy result from http://192.168.4.104:2379
cluster is healthy

sudo etcdctl member list
eee6e5e8935fd1c9: name=eee peerURLs=http://192.168.4.105:2380 clientURLs=http://192.168.4.105:2379 isLeader=false
bbb7b0aca4c13cdc: name=bbb peerURLs=http://192.168.4.102:2380 clientURLs=http://192.168.4.102:2379 isLeader=false
aaac5ad73f7d224f: name=aaa peerURLs=http://192.168.4.101:2380 clientURLs=http://192.168.4.101:2379 isLeader=true
ccc20379b7c3a64e: name=ccc peerURLs=http://192.168.4.103:2380 clientURLs=http://192.168.4.103:2379 isLeader=false
ddd76f34bf32390e: name=ddd peerURLs=http://192.168.4.104:2380 clientURLs=http://192.168.4.104:2379 isLeader=false


text:
Q: Как передать параметр из метода Chrome API во вне? Метод получает response. Все ок.
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
alert(response);
});

Как передать параметр response во вне метода?
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
response = response;
});

alert(response); //тут response is not defined :(


text:
Q: How to use fontawsome icon as image? I receive this three information related to fontawesome icon.
How can I set this fontawesome icon as a profile image to a user in UWP C#?
background_color = rgb(220, 224, 231)
class = fa-alicorn
color = rgb(74, 74, 74)

A: Have a look at this article and try to follow the steps mentioned there. Here is a snippet taken from there:
<Page …>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel
        Orientation="Horizontal"
        HorizontalAlignment="Center">
        <HyperlinkButton Margin="0,0,32,0">
            <StackPanel Orientation="Horizontal">
                <FontIcon
                    FontFamily="{StaticResource FontAwesomeFontFamily}"
                    Glyph="{StaticResource FontAwesomeFlagString}"
                    FontSize="14" Margin="0,0,8,0"/>
                <TextBlock Text="Flag"/>
            </StackPanel>
        </HyperlinkButton>
        <Button>
            <StackPanel Orientation="Horizontal">
                <FontIcon
                    FontFamily="{StaticResource FontAwesomeFontFamily}"
                    Glyph="{StaticResource FontAwesomePaperPlaneString}"
                    FontSize="14" Margin="0,0,8,0"/>
                <TextBlock Text="Send"/>
            </StackPanel>
        </Button>
    </StackPanel>
</Grid>


text:
Q: server unexpectedly closed network connection Putty after useradd After adding user
[root@ctxsv-gl4j ~]# useradd -m mtteam
[root@ctxsv-gl4j ~]# passwd mtteam
Changing password for user mtteam.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.
[root@ctxsv-gl4j ~]#

putty: to login with 'mtteam' the one just created it, I got this message:

server unexpectedly closed network connection

note: login with 'root' it works well

I want the user not login as root than login su -mtteam.
this is from /var/log/secure
Nov  8 09:05:23 ctxsv-gl4j sshd[5630]: pam_succeed_if(sshd:account): requirement "user ingroup tpt-it" not met by user "mtteam"
Nov  8 09:05:23 ctxsv-gl4j sshd[5630]: pam_succeed_if(sshd:account): requirement "user ingroup builders" not met by user "mtteam"
Nov  8 09:05:23 ctxsv-gl4j sshd[5630]: pam_succeed_if(sshd:account): requirement "user ingroup wheel" not met by user "mtteam"
Nov  8 09:05:23 ctxsv-gl4j sshd[5630]: pam_succeed_if(sshd:account): requirement "user ingroup gl_ctx_ssh" not met by user "mtteam"
Nov  8 09:05:23 ctxsv-gl4j sshd[5631]: fatal: Access denied for user mtteam by PAM account configuration
Nov  8 09:05:23 ctxsv-gl4j sshd[5630]: Failed password for mtteam from xxx.xxx.x.xxx port 62495 ssh2
Nov  8 09:05:40 ctxsv-gl4j sshd[5649]: Accepted password for root from xxx.xxx.x.xxx port 62523 ssh2
Nov  8 09:05:40 ctxsv-gl4j sshd[5649]: pam_unix(sshd:session): session opened for user root by (uid=0

)

A: Man, read the errors that you posted yourself. mtteam needs to member of those groups or it won't work. (Or change the PAM configuration)

A: Check if exists and not commented AllowUsers in /etc/ssh/sshd_config, if yes add this user there.
Also run
 grep mtteam /etc/passwd

and see if it has a valid shell (/bin/bash for example).


text:
Q: How to prevent changing pivot table primary id when syncing many to many relation in Laravel I'm using the pivot table primary id so it shouldn't change by syncing.
The sync method in many to many table will delete all records in pivot table and reinsert it.
Here's my solution:
        $variationUnits = collect($variationUnits);

        foreach ($variationUnits as $variationUnit) {
            if ($variation->units->contains($variationUnit['unit_id'])) {
                $variation->units()->updateExistingPivot($variationUnit['unit_id'], $variationUnit);
            }
            else {
                $variation->units()->attach([$variationUnit]);
            }
        }

        foreach ($variation->units as $variationUnit) {
            if (! $variationUnits->pluck('unit_id')->contains($variationUnit->id)) {
                $variation->units()->detach($variationUnit->id);
            }
        }

Is there any built-in feature to do that? if not, how can I improve it?


text:
Q: How to prevent conflict between dropdown and other links in bootstrap? I have two navbars on the left side of my page.
Until I put some links into the right navbar everything worked fine.
However once text was added into the right navbar, problems with the dropdown menus occured.
Links in the dropdown and the rightmost navbar seem to conflict, as I can't click on the submenus of my principal navbar anymore.
I tried looking for some property to bring the dropdown to the foreground but couldn't find anything useful.

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<link rel="stylesheet" type="text/css" href="..\styles\1navbar.css">
<title>  - PROCEDURE </title>

    HOME

MENU 1

MENU 1

MENU 1

MENU 1

MENU 1

MENU 1

MENU 1

MENU 1

 PROCEDURE

    reter   ter
    tealter     tabindexert

    radtre  tabindexertt
    er

And the CSS (I cleaned it up as well as I can)
/* ________________________________________________________________________________________ */

/* Pour Fixer la bar de navigation à gauche */

.navbar-fixed-left {
  width: 140px;
  position: fixed;
  border-radius: 0;
  height: 100%;
}

.navbar-fixed-left + .container {
  padding-left: 160px;
}

/* On using dropdown menu (To right shift popuped) */
.navbar-fixed-left .navbar-nav > li > .dropdown-menu {
  margin-top: -50px;
  margin-left: 140px;
}

/* Fin du CSS pour la bar de navigation à gauche */

.navbar-nav > li > .dropdown-menu {
background-color: white;
}

/* ________________________________________________________________________________________ */

/* Links in NavMenu */

nav ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 140px;
}

nav li a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
    font-weight: bold;
}

#navliTOP{
    padding-top: 100px;
}

A: this should solve your problem
.navbar-fixed-left {
z-index:1;
}

/* ________________________________________________________________________________________ */

/* Pour Fixer la bar de navigation à gauche */

.navbar-fixed-left {
  width: 140px;
  position: fixed;
  border-radius: 0;
  height: 100%;
z-index:1;
}

.navbar-fixed-left+.container {
  padding-left: 160px;
}

/* On using dropdown menu (To right shift popuped) */

.navbar-fixed-left .navbar-nav>li>.dropdown-menu {
  margin-top: -50px;
  margin-left: 140px;
}

/* Fin du CSS pour la bar de navigation à gauche */

.navbar-nav>li>.dropdown-menu {
  background-color: white;
}

/* ________________________________________________________________________________________ */

/* Links in NavMenu */

nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 140px;
}

nav li a {
  display: block;
  color: #000;
  padding: 8px 16px;
  text-decoration: none;
  font-weight: bold;
}

#navliTOP {
  padding-top: 100px;
}

  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

  <link rel="stylesheet" type="text/css" href="..\styles\1navbar.css">
  <title> - PROCEDURE </title>

          HOME

MENU 1

MENU 1

MENU 1

MENU 1

MENU 1

MENU 1

MENU 1

MENU 1

 PROCEDURE

          reter ter tealter tabindexert
 radtre tabindexertt er


text:
Q: Cylindrical Harmonics - Can't Find Bessel Equation I'm solving Laplace's equation in a region with cylindrical symmetry (i.e. no polar angle dependence). Thus, from the outset, Laplace's equation becomes,
$$
\nabla^2\,f(\rho,z)=\frac{1}{\rho}\frac{\partial}{\partial\rho}\left(\rho\frac{\partial f}{\partial\rho}\right)+\frac{\partial^2 f}{\partial z^2}=0
$$
Doing the standard method (for this particular linear DFQ), we try to look for solutions of the form $f(\rho,z)=P(\rho)Z(z)$. Substituting this into Laplace's equation and dividing by $P(\rho)Z(z)$, we get
$$\frac{1}{\rho P}\frac{d}{d\rho}\left(\rho P'\right)+\frac{Z''}{Z}=0$$
Since this must hold for every $\rho$ and $z$, the two must be equal to a constant (which are inverses of each other of course). For convenience (i.e. the standard next step), I'll set them equal to the following:
$$\frac{Z''}{Z}=k^2$$
$$\frac{1}{\rho P}\frac{d}{d\rho}\left(\rho P'\right)=-k^2$$
The equation for $Z$ is trivial. The equation for $P$, however, becomes
$$\rho P''+P'+k^2\rho P=0$$
Here is my question: The form of the equation for $P$ that I've gotten seems, after looking online, unusual. When I look for linearly independent solutions through the Frobenius method (power-series solution search), I get coefficients that have squares of double factorials, and I've never seen those arising before in Bessel functions. Moreover, I can't seem to match my differential equation with a particular form of the Bessel differential equation at all. What has gone wrong? Should I expect non-Bessel function solutions?
\

A: I've solved my problem. I was obtaining the series representation of the Bessel function of the second kind (zero order), which I had never seen before. However, it can easily be put into the form of the standard Bessel equation by doing the following.
Define $x=k\rho$. The equation then takes the form,
\begin{align*}
\rho P''+P'+k^2\rho P&=\frac{x}{k}\left(\frac{dx}{d \rho}\right)^2\frac{\partial^2 P}{\partial x^2}+\frac{dx}{d \rho}\frac{\partial P}{\partial x}+k^2\frac{x}{k}P\\
&=k\left(x\frac{\partial^2 P}{\partial x^2}+\frac{\partial P}{\partial x}+xP\right)\\
&=\frac{k}{x}\left(x^2\frac{\partial^2 P}{\partial x^2}+x\frac{\partial P}{\partial x}+(x^2-0^2)P\right)\\
&=0
\end{align*}
The first term $k/x$ is never zero, and this equality has to hold for all $x$, so the second term must vanish. We've now found a new (identical) differential equation that $P(x)$ satisfies, rather than $P(\rho)$.
$$x^2\frac{\partial^2 P}{\partial x^2}+x\frac{\partial P}{\partial x}+(x^2-0^2)P=0$$
This is the standard Bessel equation of order zero. The most general solution to this is
$$P(k\rho)=c_1J_0(k\rho)+c_2 Y_0(k\rho)$$


text:
Q: How do I defeat the Gatekeeper as a Tank? (The 'Fortitudo' option?) I've completed all 8 Elite dungeons, and have Blue QL 10 Talismans in every slot! Obviously, the next step is Nightmare modes! But in order to run those, I have to first defeat The Gatekeeper. I'm primarily set up as a Tank (Blade/Chaos if it's important).
How do I defeat this mode? I've figured out that I need to keep him faced away from the green dude that's going to kill him for me, but he seems to periodically one shot me and I just can't avoid it. What am I missing? Are there further phases or mechanics to the fight?

A: Here is a video that shows the Gatekeeper fight as a tank;

As you mention you need to ensure that 'A friend' (the green dude) is behind the Gatekeeper, so that when he performs his 'Burning Light' attack your friend isn't destroyed.
I think the ability you have been one shot by is the 'Gaia Core' ability which can be seen in the above video being cast at approximately 1 minute 3 seconds - this ability seemingly hits for far more health than you'll ever have (1099681 in some combat logs) as filth damage, and needs to be interrupted.
As the fight progresses the Gatekeeper will spawn minions, which also need to be tanked, but don't need killing.

A: When fighting the Gatekeeper in with a melee stance, you need to have 2 impaired active melee abilities. I would suggest not using an active healing ability because you will not have enough time. It is important to use your healing drinks instead and to use them very early in the fight because you have a 90 second cooldown and you will have an opportunity to use 2 healing potions if you have high health as in above 11,000. Attack rating does not help with the amount of damage you deal as compared to the Gatekeepers hit rate against you. If you are using blade and fist weapon, I would reccomend 3 strong active melee abilities for your first three slots, and then use Steel Echo (blue), Trial by Swords, Martial Discipline (Blue), and Stunning Swirl as an elite ability. If you are using a quantum brace you need to aquire the auxilary weapon toolkit to upgrade your weapon to one level higher from common to rare. If you do not have the 8th slot open for an auxilary weapon I would suggest completing the quest.

A: The Gatekeeper fight seems to have been changed a bit. At the start you will get a buff called "Heal Suppressor" that cannot be cleansed or cleared. It suppresses all heals from active abilities, passive abilities, leeching and even gadgets. The only thing that works is healing potions.
This means you should ignore advice about heals like Immortal Warrior, Forged in Fire, or Leeching mentioned in older guides. Instead focus on abilities that boost your block, evasion and protection. Apart form that the old guides are still valid: Dodge the column attack and impair Gaia Core. Quickly get aggro from the adds when they spawn (you don't need to kill them, they do very little damage to you) to protect your green friend. The Gatekeeper will knock you down and reset aggro at one point so be prepared to get it back as fast as you can (rocket jump, flamethrower or mass provocation works fine).
You will probably want to drink a barrier potion at the start to prevent some damage and then a healing potion when 90 seconds have passed. This is the build I used to pass the fight:
Actives

*

*Grip Whip to attack Gatekeeper (boosts block)

*Escalation (to draw aggro from adds when they spawn)

*Dragon's Breath (to aggro adds after being knocked down)

*Illusion (boosts evasion)

*Chaotic Pull (impair)

*Helter Skelter (impair)

Passives

*

*Hardcase (boosts protection)

*Cool, Calm & Collected (reduces damage after successful block)

Stats

*

*Attack rating: 99

*Health: 10204

*Block rating: 368

*Evade rating: 91


text:
Q: I can see only a single point when i change gluLookAt i'm trying to show a 3D matrix made up of 7600700 points and i want to obtain a parallelepiped that is black on the surface and red inside. I have the parallelepiped and it's black on the surface and red inside and i use three different windows to show three different plans which section the parallelepiped and pressing a key it is possible to move along a direction (in one window along the x, in another along the y and in the third along the z) watching one section at a time. Moving along z and x doesn't give me any problem, i can see the sectioning plans correctly, but when i try to show something in the third window (the one that allows me to move along the y coordinate sectioning the parallelepiped with the xz plan) i get different things. If i write
gluLookAt (85.0f, 340.0f, 131.5f, 85.0f, 85.0f, 131.5f, 0.0f, -1.0f, 0.0f)

i only get a single point, but if i write
gluLookAt (340.0f, 85.0f, 131.5f, 85.0f, 85.0f, 131.5f, 0.0f, -1.0f, 0.0f)

or
gluLookAt (85.0f, 85.0f, 526.0f, 85.0f, 85.0f, 131.5f, 0.0f, -1.0f, 0.0f)

i get a plan. My parallelepiped is made up of 170 values for the x, 170 values for the y and 263 values for the z so i usually set the three parameters of gluLookAt in this way: i double the coordinate along which i will move and i halve the other two coordinates. Here's a piece of my code:
void fill_array_3() {

g_vertex_buffer_data_3=new GLfloat[3*p_mat_size_tot];
int i=0;
int k=0;

for(int y=0;y<170;y++) {
 for(int z=0;z<263;z++) {
  for(int x=0;x<170;x++) {
g_vertex_buffer_data_3[i]=(GLfloat)x+0.5f;
g_vertex_buffer_data_3[i+1]=(GLfloat)y+0.5f;
g_vertex_buffer_data_3[i+2]=(GLfloat)z+0.5f;
i+=3;
  }
 }
}

void display_3(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

glLoadIdentity();

gluLookAt (85.0f, 340.0f, 131.5f, 85.0f, 85.0f, 131.5f, 0.0f, -1.0f, 0.0f);
glPushMatrix();
glRotatef(step15, 1.0f, 0.0f, 0.0f);
glRotatef(step16, 0.0f, 1.0f, 0.0f);
glScalef(step17, step17, step17);
glTranslatef(0.0f, 0.0f, step18);
glTranslatef(step19, 0.0f, 0.0f);
glTranslatef(0.0f, step20, 0.0f);

glMatrixMode(GL_MODELVIEW);

glEnableClientState( GL_VERTEX_ARRAY );
glEnableClientState( GL_COLOR_ARRAY );
glVertexPointer( 3, GL_FLOAT, sizeof(Point), &points3[0].x );
glColorPointer( 3, GL_FLOAT, sizeof(Point), &points3[0].r );
glPointSize( 3.0 );
glDrawArrays( GL_POINTS, step21*170*263, 170*263);
glDisableClientState( GL_VERTEX_ARRAY );
glDisableClientState( GL_COLOR_ARRAY );
glFlush();
glPopMatrix();
glutSwapBuffers();
}

void reshape_3(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glFrustum (-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 5000.0f);
glMatrixMode (GL_MODELVIEW);
}

int main(int argc, char** argv)
{

[...]

fill_array_1();
fill_array_2();
fill_array_3();
fill_array();

glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);

glutInitWindowSize(600,600);
glutInitWindowPosition (1100, 100);
window_3 = glutCreateWindow(argv[0]);
glutSetWindowTitle("Vista y");
init();
glutDisplayFunc(display_3);
glutReshapeFunc(reshape_3);
glutKeyboardFunc(keyPressed_3);

glutMainLoop();
return 0;
}

Thank you for your help!!!

A: With
gluLookAt (85.0f, 340.0f, 131.5f, 85.0f, 85.0f, 131.5f, 0.0f, -1.0f, 0.0f)

your viewing direction is (0, 85-340, 0), which is collinear to your up vector of (0,-1,0). gluLookAt will just fail, because your inputs don't describe a distinct camera orientation.


text:
Q: Error 504 in COUNTIFS while referencing other file Trying to calculate the following formula:
=COUNTIFS('file:///home/user/PycharmProjects/my_project/My insights/Train/CSV/Train_tags.csv'#$Train_tags.L$1:L$1048576, "1")

But it fails with error 504, despite being successfuly calculated with COUNTIF.
I need COUNTIFS (and not COUNTIF) because I want to stack more conditions.
Searched for COUNTIFS docs, searched for other issues but haven't seen anything related.
Any idea why it fails?

A: For anyone struggeling with this, I upgraded my LibreOffice version from 5 to 6 and it just worked. Probably a bug in version 5.


text:
Q: CURSOR IN PROCEDURE PL/SQL i have successfully created procedure for checking my stock item, here's the syntax :
create or replace procedure check_stock
AS
CURSOR check_stock IS
select category.category_name, item.item_name, item.stock from category join item on category.category_id = item.category_id;
begin
for stock in check_stock
LOOP
DBMS_OUTPUT.PUT_LINE(stock.category_name||' '||stock.item_name||' '||stock.stock);
END LOOP;
End;

now i want to create the same procedure but i need to input the item name so the output is the stock of that item name i have inputted, can someone show me the way/syntax using the syntax i've given above ? thanks

A: create or replace procedure check_stock ( v_item_name in Integer )
AS
CURSOR check_stock IS
select category.category_name, item.item_name, item.stock from category join item on category.category_id = item.category_id where item.item_name = v_item_name ;
begin
for stock in check_stock
LOOP
DBMS_OUTPUT.PUT_LINE(stock.category_name||' '||stock.item_name||' '||stock.stock);
END LOOP;
End;

A: You need to use one IN and one OUT parameter :
SQL> SET SERVEROUTPUT ON
SQL> CREATE OR REPLACE PROCEDURE check_stock(
                                             i_item_name in  item.item_name%type,
                                             o_stock     out category.stock%type
                                            ) AS
  CURSOR check_stock IS
  SELECT c.category_name, i.item_name, i.stock
    FROM category c
    JOIN item i
      ON c.category_id = i.category_id
   WHERE i.item_name = i_item_name;
BEGIN
  FOR stock IN check_stock
  LOOP
    DBMS_OUTPUT.PUT_LINE(stock.category_name || ' ' || stock.item_name || ' ' || stock.stock);
    o_stock := nvl(o_stock,0) + stock.stock;
  END LOOP;
END;
/

but this way, you get the last value of stock from the cursor for multiple returning rows. It's unclear which value for stock value. So, I considered the summing up the returning stock values.


text:
Q: How to correctly set up websocket proxy using http-proxy-middleware in react app I created a react app with create-react-app, and tried to set up websocket proxy with http-proxy-middleware.
Here is the configure.
const { createProxyMiddleware } = require('http-proxy-middleware');
let remote_url = 'http://127.0.0.1:8088/';
module.exports = function (app) {
  app.use(
    '/name',
    createProxyMiddleware({
      target: remote_url,
      changeOrigin: false,
      ws: true,
      secure: false,
      //logLevel: 'debug',
      pathRewrite: {
        '^/name': '/name',
      },
    }),
  );
  app.use(
    '/api',
    createProxyMiddleware({
      target: remote_url,
      changeOrigin: false,
      ws: false,
      pathRewrite: {
        '^/api': '/api',
      },
    }),
  );
}

And this is the test script I put into browser's console to test
// Create WebSocket connection.
const socket = new WebSocket('ws://127.0.0.1:3000/name');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

When the web-dev-server starts, it prints the following log
[HPM] Proxy created: /  -> http://127.0.0.1:8088/
[HPM] Proxy rewrite rule created: "^/name" ~> "/name"
[HPM] Proxy created: /  -> http://127.0.0.1:8088/
[HPM] Proxy rewrite rule created: "^/api" ~> "/api"

The http proxy on /api works fine. However, the ws proxy on /name seems not working, and the connection just hangs for a while till it fails. The front-end project is started using CRA's web-dev-server, and the apis are served from a spring-boot project.
If I build the fronted project into the backend spring-boot project, and let the spring-boot project host all these static files. In this case, the websocket can connect, and the test script works fine.


text:
Q: Cannot use Mongoose in a child process? I am trying to utilize the Mongoose library to interact with my database from within a child process like such:
process.on('message', function(m) {
    var User = require('./models/user');
    var mongoose = require("mongoose");
    var query = User.findOne({'local.email': 'email@email.com'});
    query.exec(function (err, user) {
        if (err) messages.push("Failed");
        messages.push("User is: " + JSON.stringify(user, null, 4));
    });
    process.send(messages);
});

This did not work, however, as nothing is printed. I am sure this isn't a problem with logging; what I have discovered is that it only happens when Mongoose is used within a child process. Can anyone explain why this is/how I can fix it?


text:
Q: Реализация поиска с помощью searchController'a Привет! Несколько дней никак не могу сделать поиск по таблице. Есть порядка 27 секций (A-Z, 0-9, А-Я), в каждой секции, соответственно, в алфавитном порядке ячейки.
Выглядит все примерно так:

Массив секций выглядит вот так:
let titlesForSections: [String?] = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "K", "L",
                                "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
                                "Y", "0 - 9", "А - Я"]

Массив ячеек имеет формат
let cellsForSections = [["AA", "AB", "AC"], ["BA"], ["CA", "CB"]]

Ну и так далее.
Не понимаю как сделать функцию для сортировки этого двумерного массива по тексту из searchController.searchBar. Помогите, пожалуйста.
func updateSearchResults(for searchController: UISearchController) {
    var sortedArray = ???
    tableView.reloadData()
}

A: Предполагаю, что нужно обновлять все массивы
let searchText = searchController.searchBar.text
var sortedCells: [[String]]  = []
for array in cellsForSection {
    sortedCell.append(array.filter({(cellString) -> Bool
        return cellString.contatins(searchText)
    })
}


text:
Q: Rails not found in specific rails project folder I've installed rails using rvm. I've loaded rvm using ~/.bahsrc.
rails is working fine.
which rails
/home/user/.rvm/gems/ruby-2.1.0/bin/rails

but in that rails project folder which command says
/home/dinesh/.rvm/gems/ruby-2.0.0-p353@something/bin/rails

How's this happening? How to make my rails work in that folder?

A: If you are in the root of a rails project you may use
./script/rails --version # (or whatever rails command you want to call)
to be sure to use the rails version that corresponds to your project. Usually rails magic will apply inside a rails project and "happen" to find the correct version of rails, but there seems to be a number of things that can go wrong about that.


text:
Q: Perfomance issue with rake task: Would adding worker dyno resolve the issue? In our application we are using rake task for sending mails to around 11 000 users. Each email sending is executed as a delayed job as given following.
@Users.each do |a|
    a.delay.send_email(body,text)
end

It was working perfect two weeks back and suddenly slowed down. Means it was about to send all that emails in single day but currently it takes time.
We have tried to follow this performance issue but couldn't find anything so far.
1. We investigated the code, tried with single delayed job. Commented out the part taking from db etc. But it is doing in the same time
2. Tried the email sending part commented out. But time taken was same to execute the delayed job.
Later on noticed about the heroku worker process dyno. We have purchased 1 Worker and 2 Webs currently. Is that the reason it is getting delayed. If so how it was previously working? Adding more workers would increase the performance?