text:
Q: Do I have to set all variables to private in C++ class? In unversity, my tutor told me always use private variables in class and have a setter and getter function, because it provides better encapsulation.  But what is encapsulation?  Is there any resons to do so if I know my code is only going to be developed by myself? It's just simpler to use my_obj.var instead of my_obj.set_var(var)!

A: Encapsulation in the classroom means making an over-engineered 2D point struct. Completely contrived and useless. It does a disservice to the entire concept by teaching it with poor examples.
Encapsulation in the real world is e.g. std::vector which works how you expect and is safe due to not allowing you to tamper with its internals.
In short: no, it's not necessary. It really depends on what you're doing.
In particular, you want encapsulation if your object is handling dynamically-allocated resources directly. So all properly-implemented container types should use encapsulation to prevent you from accidentally breaking it.
But if your type is just a pair of ints or some other raw data, there's really no need.
Specifically, getters and setters should be used if the details of the implementation could potentially change at some later point in the future. E.g. a struct representing a timespan could be represented as seconds:minutes:hours, but could also just be (a lot of) milliseconds. The getters and setters would allow you to turn that into seconds/minutes/etc. without it actually having to be stored that way internally. The operating word here is internal representation.


text:
Q: Which were the graphic updates of DAoC? The graphics of Dark Age of Camelot were updated several times.
What was changed when since the release of DAoC?
I'm refering to any visual change, whether the graphic engine was updated or whether only models/textures changed. (However, graphic fixes/updates of single weapons etc. are irrelevant.)
I tried to find a page with before/after screenshots, e.g. of a character standing in a city, but with no success.
For example: What was changed in Shrouded Isles? IIRC the water was updated. What else? Were the environment/city/character/mob models updated, too? In DAoCWiki it only says:

displayed in an all-new state-of-the-art graphics engine that make it look as advanced as any game on the market

A: Shrouded Isles

*

*water

*shadows

Source: mmorpg.com: Dark Age of Camelot Shrouded Isles Review:

When I first fired up Shrouded Isles, the most immediately obvious change to the original Dark Age of Camelot was in the graphics department. Many of the textures had been updated, and of particular note were the updated shadow and water graphics. The shadows were much more realistic than the original "blob" shadow, and water rippled and reflected.

Source: camelotherald.wikia.com: How does each category in the options menu affect gameplay?:

Shrouded Isles Water: Shrouded Isles based water.

Trials of Atlantis

*

*trees

*terrain/grounds

*water

Source: ofcamelot.net: FAQ - Trials of Atlantis Info:

The main two features of the new engine are the new tree textures and the new ground textures. Both of these effects are present in the old world, but are even more spectacular in the new regions.

Source: en.wikipedia.org: Dark Age of Camelot - Expansions:

also includes new terrain graphics for all areas of the game (including trees)

Source: camelotherald.wikia.com: How does each category in the options menu affect gameplay?:

Use Atlantis Trees: If checked, trees in Shrouded Isles and Classic zones will be replaced with the new Trials of Atlantis-style trees.
  Use Atlantis Terrain: If checked, the terrain will be drawn using new higher resolution textures.
  […]
  Reflective Water: Trials of Atlantis based water.

New Frontiers (Patch 1.70)

*

*whole new frontier zone incl. new keeps (technically it didn't update the old frontier zone, but the access to the old FZ was no longer possible)

Source: camelotherald.wikia.com: New Frontiers
Catacombs

*

*player models incl. faces

*

*(also mobs?)

*textures in dungeons (except for Darkness Falls)

Source: en.wikipedia.org: Dark Age of Camelot - Expansions:

Also includes new player model graphics and new graphics for all the games' dungeons (except Darkness Falls).

New Towns (Patch 1.75)

*

*cities

*outer walls of capital cities

Source: daocpedia.eu: New Towns
Darkness Rising

*

*textures of world models

*textures in capital cities

*textures in Darkness Falls

Source: en.wikipedia.org: Dark Age of Camelot - Expansions:

new graphics for the game world's models (such as barns, haystacks and forts, this includes the Darkness Falls dungeon and the capital cities) which are following the design ideas presented in Mythic's new graphics for the starting cities

New New Frontiers (Patch 1.90)

*

*keeps and towers

Source: en.wikipedia.org: Dark Age of Camelot - Expansions:

significant changes to the layout of keeps and towers

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check if a sql variable is declared? In MS SQL Server. Please don't tell me to ctrl-f. I don't have access to the entire query, but I'm composing the columns that depend on whether certain variable is declared.
Thanks.
Edit:
I'm working with some weird query engine. I need to write the select columns part and the engine will take care of the rest (hopefully). But in some cases this engine will declare variables (thankfully I will know the variable names), and in other cases it doesn't. I need to compose my columns to take these variables when they are declared, and give default values when these variables are not declared.

A: Given the limitations of my understanding of what you're running (I'm deciphering the word problem to mean that your "query engine" is actually a "query generation engine" so, something like an ORM) you could observe what's occurring on the server in this scenario with the following query:
select
    sql_handle,
    st.text
    from sys.dm_exec_requests r
    cross apply sys.dm_exec_sql_text(r.sql_handle) st
where session_id <> @@SPID
    and st.text like '%@<<parameter_name>>%';

The statement needs to have begun execution to be able to catch it. Depending on a multitude of situations, you may be able to pull it from query stats, too:
This will also get you the query plan (if it has one), but note that it will also pull stats for itself as well as the query above so you'll need to be discerning when you look at the outer and statement text values:
select
    text,
    SUBSTRING(
                st.text,
                (qs.statement_start_offset / 2) + 1,
                ((CASE qs.statement_end_offset
                                    WHEN -1 THEN DATALENGTH(st.TEXT)
                        ELSE qs.statement_end_offset
                        END -
                                qs.statement_start_offset) / 2) + 1)
                    AS statement_text,
                    plan_generation_num, creation_time, last_execution_time, execution_count
                    ,total_worker_time, last_worker_time, min_worker_time, max_worker_time,
                    total_physical_reads, min_physical_reads, max_physical_reads, last_physical_reads,
                    total_logical_writes, min_logical_writes, max_logical_writes, last_logical_writes,
                    total_logical_reads, min_logical_reads, max_logical_reads, last_logical_reads,
                    total_elapsed_time, last_elapsed_time, min_elapsed_time, max_elapsed_time,
                    total_rows,last_rows,min_rows,max_rows
                    ,qp.*

    from sys.dm_exec_query_stats qs
    cross apply sys.dm_exec_sql_text(qs.sql_handle) st
    outer apply sys.dm_exec_query_plan(qs.plan_handle) qp
    where st.text like '%@<<parameter_name>>%';


text:
Q: Claims for IdentityServer4 user not included in JWT and not sent to Web Api Following the official IdentityServer4 documentation, I reached the point where I have an MVC client app, IdentityServer4 and a Web Api (resource server running). IS4 homepage displays all claims for the user, and when calling the api with the access token, we again get as a result all the user's claims.
Sample code is available here, although it's probably not necessary, and I'm just missing something obvious.
Anyway, for simplicity's sake let's not get claims from the DB and just assign a random hardcoded one:
public class ProfileService : IProfileService
{
    public Task GetProfileDataAsync(ProfileDataRequestContext context)
    {
        context.IssuedClaims.Add(new System.Security.Claims.Claim("role", "admin"));
        return Task.FromResult(0);
    }
    ...
}

I register the custom Profile service in the startup file and now when I'm logged in on IS4, I see the additional claim.
However, when calling the web api (resource server), this additional claim is not included in the JWT. Code for api call:
    public async Task<IActionResult> CallApiUsingUserAccessToken()
    {
        var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");

        var client = new HttpClient();
        client.SetBearerToken(accessToken);
        var content = await client.GetStringAsync("http://localhost:5001/identity");

        ViewBag.Json = JArray.Parse(content).ToString();
        return View("json");
    }

(All the api does is return the list of User.Claims). My added claim is not in there, and when I debug the code and pick the access token string and decode it on jwt.io, there's no such claim again.
Question is : what am I missing? is the HttpContext.Authentication.GetTokenAsync bad for my use case, and if so - what is the substitute I'm supposed to use?
Edit: Here are the OpenId Connect Options (on the MVC client):
        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            AuthenticationScheme = "oidc",
            SignInScheme = "Cookies",

            Authority = "http://localhost:5000",
            RequireHttpsMetadata = false,

            ClientId = "mvc",
            ClientSecret = "secret",

            ResponseType = "code id_token",
            Scope = { "api1", "offline_access" },

            GetClaimsFromUserInfoEndpoint = true,
            SaveTokens = true
        });

A: I guess the reason is that you haven't assigned any claims to your API. This is why we don't call the profile service at all.
This is a common problem and a little inconsistent since we are always calling the profile service for identity tokens.
We changed this behavior in 1.0.2
https://github.com/IdentityServer/IdentityServer4/releases/tag/1.0.2
Please try again and see if this gives you the expected result.


text:
Q: Set Variable With For Loop (Javascript) I am new on JS and would like to set new variables automatically via For loop, by example:
var mybox0
var mybox1
etc...
var board = document.getElementById('board');
var boxes = [];

for(var i=0; i<9; i++){
    var myBox = document.createElement('div');
    board.appendChild(myBox);
    myBox.id = "box" + i;
    boxes.push(myBox);
}

A: Welcome to JavaScript! Always nice to have another in the fold.
The short answer is that this is not possible in JavaScript. You've really got two choices for this. You've already implemented the first one: arrays. It's a good option and the one I would go with personally.
An alternative, mentioned in the comments to your question, would be to use an object instead. The code would look something like this:
var board = document.getElementById('board');
var boxes = {};

for(var i = 0; i < 9; i++) {
    var myBox = document.createElement('div');
    board.appendChild(myBox);
    myBox.id = "box" + i;
    boxes['mybox' + i] = myBox;
}

You could then reference your variables like this:
boxes.mybox0;
boxes.mybox1;

Instead of this:
boxes[0];
boxes[1];

My opinion of the code inside the for loop is that the array code is more readable than the object code. The code that makes use the generated object is equally readable to the array code. Furthermore, the array is more versatile as you can iterate over it more easily using functions like .map and .forEach.
So, I don't think there is anything to gain from using objects to do this and a bit to lose. Stick with the array.


text:
Q: I don't have a dedicated GPU and I can't install DirectX to play NFS Most Wanted I want to play NFS Most Wanted on the PC and I do not have any Graphic Card. While installing this system asks to install Directx (Even I have already installed it) and displays an Internal system error.
Please somebody guide me about this game and Directx Issues.

A: Every computer built in the last 5 years or so has a 3D capable graphics card.  Need for Speed Most Wanted has modest system requirements, so it's likely that if you have a fairly recent computer, you'll be able to play it.
You can identify the model and type of your graphics card by going into the device manager.  You may also need to update your graphics drivers before you'll be able to play.
As far as your DirectX error goes, I found one guide that gave a hint:

DirectX Error when Installing: When installing the game if you get an error that DirectX9.0c is not installed, even if you've installed DX9.0c already, then find the game's Autorun.exe file (in the base directory of the game CD), right-click on it, select Properties, go to the Compatibility tab, tick the 'Run this program in compatibility mode for' and select 'Windows 2000'. Then double-click on Autorun.exe to begin installation. Make sure to turn off compatibility mode after installing the game.

If this doesn't fix your problem, you're going to have to provide more detail in your question.


text:
Q: Can't show paginations (dots) in OwlCarousel I used owl carousel to create a slideshow, but can't show dots or pagination. I read the documentation and it was stated that it takes key word argument dots: true|false, but when I used dots: true it doesn't show. I also tried pagination: true.
<script>
  $(".slider").owlCarousel({
    loop: true,
    autoplay: true,
    autoplayTimeout: 2000,
    autoplayHoverPause: true,
    dots: true,
  });
</script>

here is a pen for full review. Thanks for help

A: You don't have enough items to trigger the dots. Your loop is 3 and your amount of cards is 3. There is no pagination to show.Also you need to add the class owl-theme to your container with the owl-carousel class and you need a theme file from Owl Carousel, there are a few CDN's and you need any CSS file with theme in the name.
Here's an example with the default theme: https://codepen.io/JHeth/pen/QWyewpy


text:
Q: Full Outer Join With Where Clause I am in need of a way to return all records from both tables BUT have a where condition on ZT1 I have tried both queries below, however Query 1 ignores any row from @TTBL that does not exist in ZT1, while Query 2 ignores the WHERE condition I want to put on the table ZT1 (bc it was changed to an or)
How should my query be written in order to accomplish my desired result of all data from @TTBL AND only data from ZT1 that fall between the date criteria
    Query 1
SELECT
    Employee = COALESCE(ZT1.Employee,Z.Name),
    COUNT(ZT1.sales) AS Salecount,
    SUM(ISNULL(ZT1.[SaleTotal],0)) AS SaleTotal,
    SUM(ISNULL(ZT1.[SaleTotal],0) - ISNULL(ZT1.[TotalB4Discount],0)/NULLIF(ZT1.[SaleTotal],0)) AS ActualSale,
    SUM(ISNULL(ZT1.[SaleTotal],0) - ISNULL(ZT1.[TotalB4Discount],0)) AS ProfitMargin,
    ISNULL(Z.SaleTotal0,0) AS SaleTotal0,
    ISNULL(Z.SaleTotal1,0) AS SaleTotal1
FROM dbo.holdings AS ZT1
FULL OUTER JOIN @TTBL AS Z ON Z.Name = ZT1.Employee
WHERE ZT1.[SaleDate] >= '20170601'
AND ZT1.[SaleDate] <= '20170625'
GROUP BY ZT1.Employee,Z.SaleTotal0,Z.SaleTotal1,Z.Name

--Query 2
SELECT
    Employee = COALESCE(ZT1.Employee,Z.Name),
    COUNT(ZT1.sales) AS Salecount,
    SUM(ISNULL(ZT1.[SaleTotal],0)) AS SaleTotal,
    SUM(ISNULL(ZT1.[SaleTotal],0) - ISNULL(ZT1.[TotalB4Discount],0)/NULLIF(ZT1.[SaleTotal],0)) AS ActualSale,
    SUM(ISNULL(ZT1.[SaleTotal],0) - ISNULL(ZT1.[TotalB4Discount],0)) AS ProfitMargin,
    ISNULL(Z.SaleTotal0,0) AS SaleTotal0,
    ISNULL(Z.SaleTotal1,0) AS SaleTotal1
FROM dbo.holdings AS ZT1
FULL OUTER JOIN @TTBL AS Z ON Z.Name = ZT1.Employee
OR ZT1.[SaleDate] >= '20170601'
AND ZT1.[SaleDate] <= '20170625'
GROUP BY ZT1.Employee,Z.SaleTotal0,Z.SaleTotal1,Z.Name

A: Give this query a shot. I suspect that the "WHERE" clause is effectively turning your full outer join into a right join. When a record doesn't exist in ZT1, your where clauses are obviously going to evaluate false. By enclosing the AND clause in parenthesis for sanity's sake, and adding some sort of OR clause (I assumed that you should have a field named SaleDate in @TTBL, and that you only want to fetch records where the SaleDate is in that range one way or another), you should hopefully see this problem go away. Let me know how it goes.

SELECT
    Employee = COALESCE(ZT1.Employee,Z.Name),
    COUNT(ZT1.sales) AS Salecount,
    SUM(ISNULL(ZT1.[SaleTotal],0)) AS SaleTotal,
    SUM(ISNULL(ZT1.[SaleTotal],0) - ISNULL(ZT1.[TotalB4Discount],0)/NULLIF(ZT1.[SaleTotal],0)) AS ActualSale,
    SUM(ISNULL(ZT1.[SaleTotal],0) - ISNULL(ZT1.[TotalB4Discount],0)) AS ProfitMargin,
    ISNULL(Z.SaleTotal0,0) AS SaleTotal0,
    ISNULL(Z.SaleTotal1,0) AS SaleTotal1
FROM dbo.holdings AS ZT1
FULL OUTER JOIN @TTBL AS Z ON Z.Name = ZT1.Employee
WHERE (ZT1.[SaleDate] >= '20170601'
AND ZT1.[SaleDate] <= '20170625')
OR (Z.[SaleDate] >= '20170601'
AND Z.[SaleDate] <= '20170625')
GROUP BY ZT1.Employee,Z.SaleTotal0,Z.SaleTotal1,Z.Name


text:
Q: Using a list-matrix to supply indices to N-dimensional object I am working on a partial differential equations project where some N-dimensional objects are required. I got stuck in padding one N-dim object with a copy of each of its dimensions. Here is the function:
padreplicate <- function(a, padSize) {
    # Pad an array by replicating values.
    numDims <- length(padSize)
    idx <- vector("list", numDims)
    for (k in 1:numDims) {
        M <-  dim(a)[k]       # 32
        onesVector <-  ones(1, padSize[k])
        idx[[k]] <- c(onesVector, 1:M, M * onesVector)
    }
    # return(a[ unlist(idx[1]), unlist(idx[2]) ])  # this works for 2D
    # return(a[ idx[[1]], idx[[2]] ])              # this also works for 2D
    # return(a[apply(idx, 1, function(x) unlist[x])])  #:( doesn't work
    # a[sapply(apply(idx, 1:length(dim(idx)), function(x) eval(parse(text=x))), unlist)] #:(

    # 2D: "a[idx[[1]], idx[[2]]]"     3D: "a[idx[[1]], idx[[2]]], idx[[3]]]"
    dim_text = paste0("a", "[ ",
                      paste0(sapply(1:length(idx), function(x)
                          paste0("idx", "[[", x, "]]")), collapse = ", ")," ]")
    eval(parse(text=dim_text))               # this works
}

The first argument is the N-dim object; it could be a matrix, a 3D array or higher dimensional array.
An example for a 2D object or matrix would be:
# pad a matrix 4x3 with c(1,1)
set.seed(123456)
mx = matrix(sample.int(9, size = 9*100, replace = TRUE), nrow = 4, ncol = 3)
mx
  #       [,1] [,2] [,3]
  # [1,]    8    4    9
  # [2,]    7    2    2
  # [3,]    4    5    8
  # [4,]    4    1    6
padreplicate(mx, c(1,1))

The padded matrix looks like this:
      [,1] [,2] [,3] [,4] [,5]
[1,]    8    8    4    9    9
[2,]    8    8    4    9    9
[3,]    7    7    2    2    2
[4,]    4    4    5    8    8
[5,]    4    4    1    6    6
[6,]    4    4    1    6    6

For a 3-D array the input array and the padded array.
ar = array(sample.int(9, size = 9*100, replace = TRUE), dim = c(3, 3, 1))
ar
padreplicate(ar, c(1,1,1))

# input 3x3x1 array
, , 1

     [,1] [,2] [,3]
[1,]    3    4    6
[2,]    7    2    9
[3,]    3    4    8

   # padded 5x5x3 array
, , 1

     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    4    6    6
[2,]    3    3    4    6    6
[3,]    7    7    2    9    9
[4,]    3    3    4    8    8
[5,]    3    3    4    8    8

, , 2

     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    4    6    6
[2,]    3    3    4    6    6
[3,]    7    7    2    9    9
[4,]    3    3    4    8    8
[5,]    3    3    4    8    8

, , 3

     [,1] [,2] [,3] [,4] [,5]
[1,]    3    3    4    6    6
[2,]    3    3    4    6    6
[3,]    7    7    2    9    9
[4,]    3    3    4    8    8
[5,]    3    3    4    8    8

These are all correct results.
My question is this: "is there a better way of doing this N-dim padding operation?
EDIT 1
Thanks to Frank, now the N-dimensional padreplicate function:
padreplicate <- function(a, padSize) {
    # Pad an array by replicating values.
    numDims <- length(padSize)
    idx <- vector("list", numDims)
    for (k in 1:numDims) {
        M <-  dim(a)[k]       # 32
        onesVector <-  ones(1, padSize[k])
        idx[[k]] <- c(onesVector, 1:M, M * onesVector)
    }
    do.call( `[`, c(list(a), idx))
}

EDIT 2
Using matrix instead of my function ones. Sorry about that.
padreplicate <- function(a, padSize) {
    # Pad an array by replicating values.
    numDims <- length(padSize)
    idx <- vector("list", numDims)
    for (k in 1:numDims) {
        M <-  dim(a)[k]       # 32
        onesVector <-  matrix(1, 1, padSize[k])
        idx[[k]] <- c(onesVector, 1:M, M * onesVector)
    }
    do.call( `[`, c(list(a), idx))
}


text:
Q: Creating subset using or statement I have a data frame with 6 columns and thousands of rows containing share transactions. I want to identify rows with bad price data. The following function gives me a subset with the rows with good price data:
function in_price_range(df)
    price_good = subset(df, :UnitPrice => X-> (trough_share_price .<= X .<= peak_share_price), skipmissing=true)
    return price_good
end

For a subset for bad data I tried:
function out_price_range(df)
    price_discrepancy = subset(df, :UnitPrice => X-> (X .< trough_share_price || X .> peak_share_price), skipmissing=true)
    return price_discrepancy
end

However, that givers error TypeError: non-boolean (BitVector) used in boolean context
I tried .|| rather than || but that then gives error: syntax: "|" is not a unary operator
How do I fix the code?

A: In Julia, || is
help?> ||
search: ||

  x || y

  Short-circuiting boolean OR.

The short-circuiting part meaning, that if x is true, || will not even bother to evaluate y. In other words, this will make a branch in the code. For example:
julia> 5 < 7 || print("This is unreachable")
true

This is great if you want to write code that is efficient for a case like
if something_easy_to_evaluate || something_costly_to_evaluate
    # Do something
end

In other words, this is control flow! Obviously, this cannot be broadcasted. For that, what you want is the regular or operator |, which you can broadcast with .|. So for example:
julia> a = rand(3) .< 0.5
3-element BitVector:
 1
 0
 0

julia> b = rand(3) .< 0.5
3-element BitVector:
 0
 1
 0

julia> a .|| b
ERROR: syntax: "|" is not a unary operator
Stacktrace:
 [1] top-level scope
   @ none:1

julia> a .| b
3-element BitVector:
 1
 1
 0

The same applies to && vs &; the former is only used for control-flow, the latter is normal bitwise and.


text:
Q: What is the hash function for a normal class and why don't dataclasses have the same hash function? Following is an example where the dataclass "fails" to be hashable but the normal class does produce a hash value fine.
Why does this work given that the normal class has the np.ndarray as well and should be unhashable?
import numpy as np
from dataclasses import dataclass

class X:
    def __init__(self):
        x = np.ndarray([0,1,1,0,110])

@dataclass(frozen=True, eq=True)
class Y:
    name: str
    unit_price: np.ndarray

a = X()
print(a.__hash__())

b = Y(10, np.array([0,1,2]))
print(b.__hash__())

Ouput:
8787234869218
Traceback (most recent call last):
  File "t.py", line 37, in <module>
    print(b.__hash__())
  File "<string>", line 3, in __hash__
TypeError: unhashable type: 'numpy.ndarray'

A: Because you used:
@dataclass(frozen=True, eq=True)

The rules here are described in the docs:

If eq and frozen are both true, by default dataclass() will generate a
__hash__() method for you. If eq is true and frozen is false, __hash__() will be set to None, marking it unhashable (which it is, since it is mutable). If eq is false, __hash__() will be left
untouched meaning the __hash__() method of the superclass will be used
(if the superclass is object, this means it will fall back to id-based
hashing).

The dataclass generated a hash function that is hashing based on the attributes. Of course, it doesn't actually work because you used a numpy.ndarray.
By default, user-defined objects inherit object.__hash__, which just hashes based on identity, pretty much return id(self) (although not exactly).
The two won't behave the same, in the first case, because you told the dataclass code generator to make an "immutable" type with a corresponding __eq__ that is based on the attributes of the object.  The hash, of course, is consistent with the __eq__ and is based on the values of the attributes. In the second case, the hash (and equality) is based on the identity of the object.
To illustrate these differences:
>>> from dataclasses import dataclass
>>> @dataclass(frozen=True, eq=True)
... class Point1:
...     x: int
...     y: int
...
>>> points = set()
>>> points.add(Point1(0, 0))
>>> Point1(0, 0) in points
True

So notice, a different point object with the same value was in the set.
However, here is how identity based hashing/equality would function:
>>> class Point2:
...     def __init__(self, x, y):
...         self.x = x
...         self.y = y
...
>>> p = Point2(0, 0)
>>> points = set()
>>> points.add(p)
>>> Point2(0, 0) in points
False
>>> p in points
True


text:
Q: Remove everything that doesn't match string line = "Rok rok irrelevant text irrelevant;text.irrelevant,text";
string NewLine = Regex.Replace(line, @"\b[rR]\w*", "");

Right now it replaces every word starting with r/R with a blank space, but I want to make everything a blank space EXCEPT words starting with r/R.

A: Edit
It seems all you want is to extract words starting with r or R and join them with a space. In this case, use a mere \b[rR]\w* regex and the following code:
var result = string.Join(" ", Regex.Matches(line, @"\b[rR]\w*").Cast<Match>().Select(x => x.Value));

See the C# demo.
Original answer
You may use a negative lookahead after a word boundary:
\b(?![rR])\w+
  ^^^^^^^^

Note that the + quantifier is better here since you want to remove at least 1 char found.
Or, in case you also want to remove all non-word chars after the found word, use
\b(?![rR])\w+\W*

See the regex demo #1 and regex demo #2.
If you want to remove any non-word chars before and after a qualifying word, use
var result = Regex.Replace(line, @"\W*\b(?![rR])\w+\W*", " ").Trim();

It will remove all non-word chars before a word not starting with r and R and after it.
Details

*

*\b - a word boundary

*(?![rR]) - a negative lookahead that will fail the match if, immediately to the right of the current location, there is r or R

*\w+ - 1+ word chars

*\W* - 0+ non-word chars.


text:
Q: Plural of 'performance' I wrote the following sentence in my journal article:

The performance of the new and existing methods are compared.

Then MS Word indicated that I had used 'are' in the aforementioned sentence incorrectly.
Is the above sentence incorrect?
If so, which is the correct sentence?

The performances of the new and existing methods are compared.

or:

The performance of the new and existing methods is compared.

A: MSWord grammar checker is correct as far as it goes. You can either use the plural "performances" with "are", or the singular (or uncountable) "performance" with "is".
The real question here is whether "performance" is countable or not.
According to Oxford Learners Dictionaries, this usage of "performance" (meaning 3) can be either countable or uncountable. So that doesn't really clear the matter up!
In your particular situation you could pluralise it, and use "are", but it doesn't quite feel right to me. Presumably it doesn't to you either, or you wouldn't be asking the question! If you say:

The performances of the new and existing methods are compared

then it sounds to my ear as if both the new method and the existing method have multiple performances, which are being compared (presumably Performance n new method being compared with Performance n existing method).
The problem, though, is that you can't compare one "uncountable" item to another, because you'd have to have two of them to compare one against the other, and you can't have two of something that is uncountable. So uncountable "performance" with "is" isn't an option.
Your only other option is to reword the sentence to avoid the situation.
I would suggest:

The performance of the new method is compared to that of the existing method

or possibly

The relative performance of the new and existing method is evaluated.

A: More context is needed.
If you are referring to two different performances (the new one and the existing one), it should be plural, and the verb of which 'performances' is the subject should also be plural.  This, in that case, is the correct sentence:

The performances of the new and existing methods are compared.

On the other hand, there might be one performance that features both methods.  In that case, use this:

The performance of the new and existing methods is compared.

In either case, this is incorrect:

The performance of the new and existing methods are compared.

because the verb and subject do not agree.

A: With all due respect to Peter Shor - I'm under the impression that two different interpretations of the same work were being compared.
You could liken the situation to the first time any story about the character "Sherlock Holmes" was produced for stage or screen to the most recent interpretation, being the series "Sherlock" starring Benedict Cumberbatch in the titular role. There's a world of difference between the settings and the portrayal of many of the central characters, yet the 2010-2016 productions are still clearly recognizable as Sherlock Holmes to someone who has read any of the the original works by Sir Arthur Conan Doyle...
Anyway, back to the original question! I agree with CHEESE that the sentence was no doubt flagged by MS Word as the verb and subject do not agree. Given the lack of context I think that CHEESE delivered a clear and concise answer to the dilemma at hand.
All I can really add as advice is that relying entirely on MS Word* for grammatical help is an abysmal idea in general (although for a personal journal its at least excusable!).  For students it is not, and for "Journalists" even less so.
*Or any relevant analogs including the automatic spell/grammar check software for mobile phones

A: "Performances" in plural may be acceptable for different shows.  Here we are not speaking of an act of performing, but how well a method does (i.e. performs), for which one may speak of "levels of performance". Therefore, in my opinion, "performance" should not be pluralized in such contexts.

A: "is compared" sounds wrong and illogical. Use "are compared", and adjust the sentence to that. Use "performances" and "are".
I see performance is being used like the word efficiency. I've heard of efficiencies (semi-awkward), but performances is confusing unless you're referring to staged shows etc. It's not in the question, but you could switch "is" to "gets" (easier on the ear and uses singular), or switch "performances" to "efficacies" (less confusing).
ADDED:
"is compared" makes me wonder, is compared to what? Those two methods could be compared as a whole to two other methods. That's why plural helps.


text:
Q: discordjs How to get roles by name and not by id I take the array of role ids in this way message.guild.roles.cache.keyArray(); with the keyArray method, is there any way to get the list of id's name and not id?

A:
is there any way to get the list of id's name and not id?

I'm assuming you are trying to make a list of roles, mapped by name instead of ids.
If that's the case, it is pretty easy. <Guild>.roles.cache is a Collection. You can use a method called <Collection>.map() that maps each item to another value into an array.

const Roles = message.guild.roles.cache.map(role => role.name);

console.log(Roles);

// --> ['MyRole1', 'MyRole2', 'MyRole3', 'etc']


text:
Q: Limit sup of functions I know that if $\limsup_{x\to\infty}f(x)&ltL$ then there exist $x_{0}$ such that $f(x)&ltL$ for all $x\geq x_{o}$.
Is the following true:
If $\limsup_{x\to\infty}f(x)&ltL$ then, for any $\epsilon>0$, there exist $x_{0}$ such that $f(x)&ltL+\epsilon$ for all $x\geq x_{o}$.
(If the above is true, does $x_{o}$ depends on $\epsilon$?) Thanks

A: Yes, it is true and $x_0$ is independent of $\epsilon$ - just pick the same $x_0$ as you have in the first statement you said you know is true. Your second statement is a weaker version of your first.

A: Based on this comment is seems that OP had a slightly different question in mind. (But he did not edited the question. And he did not answered, what definition of the limit superior he is using.)
Basically, without knowing what is his definition of $\limsup$ we should be working with, the question cannot be answered. Anyway, I'll mention here several possibilities how $\limsup$ can be defined. I'll also discuss (very briefly) why these definitions are equivalent. Hopefully, this will be helpful for the OP.

Definition 1. Let $S\in\mathbb R$. We say that $S=\limsup\limits_{x\to\infty} f(x)$  if the following two conditions are fulfilled:

*

*For each $\varepsilon>0$ there exists $x_0$  such that $x>x_0 \Rightarrow f(x)<S+\varepsilon$.
$$(\forall\varepsilon>0)(\exists x_0)(x>x_0 \Rightarrow f(x)<S+\varepsilon).$$

*For each $\varepsilon>0$ and $M$ there exists $x>M$ such that $f(x)>S-\varepsilon$.
$$(\forall\varepsilon>0)(\forall M)(\exists x>M) f(x)>S-\varepsilon.$$
Of course, limit superior can also be equal to $\pm\infty$. Definition has to be appropriately modified for these cases; I'll omit this for the sake of simplicity. (I have also ignored the question why such $S$ exists.)
Definition 2. $S=\sup\{L; \text{ there exists a sequence }(x_n)\text{ such that }x_n\to\infty, f(x_n)\to L\}$
Definition 3. $S=\lim\limits_{N\to\infty} \sup\{f(x); x\ge N\}$
All these definition can be modified to get $\limsup_{x\to x_0} f(x)$ instead of $\limsup_{x\to\infty} f(x)$.
Let us show that these definitions are equivalent. I.e., suppose that $S_1$, $S_2$, $S_3$ are the values given by the above definitions. We will assume that $f(x)$ is bounded (for the sake of simplicity), which implies that $S_{1,2,3}$ are finite.
It is easy to see that $\boxed{S_2\le S_3}$, since if $x_n\to\infty$ then $x_n>N$ for large $n$'s and $f(x_n) \le \sup\{f(x); x\ge N\}$.
Using definition 1 we can inductively construct sequence $x_n$ such that $x_n\to\infty$ and $|f(x_n)-S_1|<\frac1n$ (by choosing $\varepsilon=\frac1n$); which implies that $x_n\to S_1$. This implies $\boxed{S_1\le S_2}$.
If $N$ is large enough then, from definition 1, we have $\sup\{f(x); x\ge N\}\le S_1+\varepsilon$. This implies that $S_3\le S_1+\varepsilon$. Since this is true for any $\varepsilon>0$, we get $\boxed{S_3\le S_1}$.

A: Yes, it is true trivially since $L&ltL+\epsilon$.
A stronger statement is (trivially) true also: there exists an $\epsilon>0$ and an $x_0$ such that $f(x)&ltL-\epsilon$ for all $x\ge x_0$. To see this, just pick $\epsilon>0$ such that $\limsup\limits_{x\rightarrow\infty} f(x)&ltL-\epsilon$ and apply your first statement to $L-\epsilon$.


text:
Q: Does 'java -jar' fetch transitive dependencies? If I execute a jar with:
java -jar foo.jar

and foo.jar declares a dependency on bar.jar in the Class-Path attribute of its manifest, will the jars defined in the manifest of bar.jar be added to the classpath?
MANIFEST.MFin foo.bar contains:
Class-Path: bar.jar

MANIFEST.MFin bar.bar contains:
Class-Path: baz.jar

Is baz.jar added to the classpath when running java -jar foo.jar ?


text:
Q: Can I make wso2 msf4j work with jersey? WSO2 MSF4J to improve the size adds their own jaxrs-delegate which strips quite a bit of functionality from JAX-RS standard such as UriBuilder or BadRequestException
I've noted a few of the limitations of WSO2's MSF4J implementation https://github.com/wso2/msf4j/issues/290#issuecomment-329673266
So what I tried to do was see if I can replace the WSO2 jaxrs-delegate with Jersey instead.  I excluded it from the core and tried to put in the jersey and jackson dependencies, but in the end it didn't work out.
I was wondering if this is even duable.

A: TL;DR
Set the BOMs (note don't use the latest versions as of the time of this writing)
<dependencyManagement>
<dependencies>
  <dependency>
    <groupId>com.fasterxml.jackson</groupId>
    <artifactId>jackson-bom</artifactId>
    <version>2.8.10</version>
    <type>pom</type>
    <scope>import</scope>
  </dependency>
  <dependency>
    <groupId>org.glassfish.jersey</groupId>
    <artifactId>jersey-bom</artifactId>
    <version>2.26-b03</version>
    <type>pom</type>
    <scope>import</scope>
  </dependency>
</dependencies>
</dependencyManagement>

Add the dependencies
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
  <groupId>javax.ws.rs</groupId>
  <artifactId>javax.ws.rs-api</artifactId>
  <version>2.1</version>
</dependency>
<dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-client</artifactId>
</dependency>
<dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-server</artifactId>
</dependency>

Exclude the delegate from core
<dependency>
  <groupId>org.wso2.msf4j</groupId>
  <artifactId>msf4j-core</artifactId>
  <version>2.1.0</version>
  <exclusions>
    <exclusion>
      <groupId>org.wso2.msf4j</groupId>
      <artifactId>jaxrs-delegates</artifactId>
    </exclusion>
  </exclusions>
</dependency>


text:
Q: Covariant derivative in associated bundle Let $\pi:P→M$ be an arbitrary principal $G$-bundle, $F$ a vector space  and $\pi_F : P × _G F → M$ the associated fiber bundle.
If $U$ is an open subset of $M$, then a smooth map
$ϕ : \pi^{−1} (U)→ F$ is said to be equivariant  if
$ϕ(p · g) = g^{-1} · ϕ(p)$
Given a section $s : V → \pi_F^{-1}(U) $  we can show that there is a  one-to-one and onto correspondence between $ϕ(p)$ and $s$.
Assuming now that $\pi:P→M$ has defined on it a connection form $ω$, we define the covariant exterior derivative
$d^ω ϕ$ of $ϕ$ by
$(d^ω ϕ)_p(v)= (dϕ)_p(v^H)$
Where $dϕ$ is the exterior derivative of $ϕ$ , $v ∈ T_pP$ and $v^H$ is the horizontal part of it.
It also can be show that
$d^ω ϕ=dϕ+ω\cdotϕ$ where $ω\cdotϕ$ means $ω$ acting on $ϕ$
Now given a section on the principal bundle $\sigma : V → \pi^{-1}(U)$
we can show also that
$(\sigma^*d^ωϕ)(T)=d(\sigma^*ϕ)(T)+(\sigma^*ω)(T)\cdot\sigma^*ω$
Identifying  $(\sigma^*d^ωϕ)(T)$ as $\nabla_T S $ where $S=\sigma^*ϕ$ we obtain
$\nabla_T S=dS(T)+(\sigma^*ω)(T)\cdot S$
Now my question is if $ϕ$ is a function a $0$ form then $S$  the pullback of a $0$ form is a function but by definition of covariant derivative we should have
$\nabla_T S=dS(T)$
Only if if we identify $S$ as a section that we would have the extra piece.
Then how can we say that $\nabla_T$ is a covariant derivative?

A: Okay, I still don't completely understand you, but I think I pinpointed the problem.
Using your notation, $S$ is not really a section of the associated bundle, but rather the component representation of such. So the notation $\nabla_T S$ is either incorrect, or just requires a lot of interpretation.
Let $F$ be a real, $k$ dimensional vector space, to see an example. Let us assume, that the latin indices $a$ range from $1$ to $k$.
We actually have some separate things here. We have a principal fiber bundle $(P,\pi,M,G)$ and an associated vector bundle $(E,\pi,M)$ with $E=P\times_\rho F$, where $\rho:G\rightarrow GL(F)$ the representation that defines the associated vector bundle.
The thing is, if $\psi:M\rightarrow E$ is a (smooth) section of $E$, then there exists a unique corresponding equivariant map $\phi:P\rightarrow F$, but for all intents and purposes, they are not the same.
You should instead think about them like this: If ${e_{a}}$ is a local frame of $E$, then we have locally $\psi=\psi^ae_a$, where the components $\psi^a$ depend on two things - they depend on the manifold points $x\in M$, but also on the local frame $e_a(x)$ (at $x$) chosen to represent it, so $$ \psi^a=\psi^a(x,\{e_a(x)\}). $$
But if $E$ is an associated vector bundle to $P$, then, essentially, $P$ is an associated principal bundle to $E$, so $P$ can be identified as the frame bundle of $E$ (because a local frame $e_a$ provides a local trivialization of both $E$ and $P$, so local sections of $P$ can be understood as frames of $E$). Well, not the total frame bundle, but some restriction of the frame bundle to a $G$-subbundle.
So the point is, that because the components $\psi^a$ depend on points of $P$, rather than $M$, it is an $F$-valued (essentially $\mathbb{R}^k$-valued) function on $P$. But it needs to be equivariant. Why? Because if $\Lambda^a_{\ b}(x)$ is a local frame transformation on $E$, then the components transform by $\Lambda^{-1}$. But a local frame transformation (acting on the model fiber $F$) is equivalent to the fibrewise transitive right action of $G$ on $P$, so $$ \psi^a(x,e(x)\Lambda(x))=(\Lambda^{-1})^a_{\ b}(x)\psi^b(x,e(x)).$$
Essentially, invariant fields are sections of $E$, component representations of it are realized basis independently as equivariant functions on $P$. Equivariance guarantees that the components transform "properly" under frame transformations (frame transformation = group action on $P$).

With this discussed, let us concatenate notation:

*

*$\psi$ is the invariant section of $E$.

*$\psi^a$ are components of it taken with respect to a local trivialization of either $E$ or $P$ (they agree).

*$\phi$ is the equivariant function on $P$ satisfying $$ \phi(x,e(x))=(\psi^1(x,e(x)),...,\psi^k(x,e(x))), $$ where $(x,e(x))$ is a point of $P$.
What actually is, is that $$ \nabla_T\psi=(d(\sigma^*\psi^a)(T)+(\sigma^*\omega)^a_{\ b}(T)(\sigma^*\psi^b))e_a, $$ where the frame $e_a$ is the frame that generates the local trivialization/section $\sigma$.
Since this got quite complicated, and the otherwise simple essence gets lost, what your "$\nabla_TS$" is, is an analogue of $\nabla_T X^\mu$ for tangent vectors, when, in fact, what interests you is not $\nabla_T X^\mu$, but $\nabla_TX=\nabla_T(X^\mu\partial_\mu)$.
You got the component representation of the covariant derivative. Which is fine, just the notation confuses you, because $\nabla_T$ should not act on the components, but the invariant section.


text:
Q: Phone number regex in javascript/jquery on (000)000-0000 I'm using jquery.validate.addMethod(), and need a regex for specific phone number format. I somehow knew it before, but since I don't use regex that much, I forgot.
So, this is just a simple question: How do you create a regex for javascript on the following format:
(000)000-0000
The current phoneUS format which jQuery Validate possess is not applicable to the current problem.

A: Something like this:
/^\(\d{3}\)\d{3}-\d{4}$/

A: /^\(\d{3}\)\s?\d{3}-\d{4}$/

This allows for a space after the closing parenthesis as well.


text:
Q: Amazon Redshift dateadd() in CASE statement I'm trying to add the date in a case statement
select the_date,
(case
when the_date like '%years%' then dateadd(year,REPLACE(REGEXP_SUBSTR(condition_, '-?[0-9]+\.? years'),'years',''),the_date)
end)
from customer

But I'm getting the following error:

SQL Error [500310] [42883]: Amazon Invalid operation:
  function pg_catalog.date_add("unknown", text, timestamp with time
  zone) does not exist;

Can anyone help please?

A: You have to cast the second parameter to INT and the third parameter to timestamp (currently it's timestamptz.
This is the DATEADD signature:
DATEADD( datepart, interval, {date|timestamp} )

Your query should look something like:
select the_date,
(case when the_date like '%years%' then
    dateadd(
         year,
         REPLACE(REGEXP_SUBSTR(condition_, '-?[0-9]+\.? years'),'years','')::INT,
         the_date::timestamp
    )
end)
from customer

Alternatively you could use simple + operator with an interval. This way you can preserve the timestamptz data type for the_date:
select the_date,
(case when the_date like '%years%' then
    the_date + (interval '1 year' * REPLACE(REGEXP_SUBSTR(condition_, '-?[0-9]+\.? years'),'years','')::INT)
    )
end)
from customer


text:
Q: Javs GUI Application MIGLayout not displaying My Java GUI application wont display data from the PersonUI.java class with the layout details im using MIGLayout in Netbeans 8.0.
All the files i n the project have no errors it wont display the GUI. May help me with displaying the MIGlayout .
package View;

import Model.Person;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import net.miginfocom.swing.MigLayout;
/**
/**
 *
 * @author Mbano
 */import Controller.PersonBean;
public class PersonUI extends JPanel {
    private JTextField idField = new JTextField(10);
   private JTextField fNameField = new JTextField(30);

 private JTextField mNameField, lNameField, emailField, phoneField;

   private JButton createButton = new JButton("New...");
   private JButton updateButton, deleteButton, firstButton, prevButton, nextButton,
   lastButton;
 private  PersonBean bean = new PersonBean();

   public PersonUI() {
       setBorder(new TitledBorder
      (new EtchedBorder(),"Person Details"));
      setLayout(new BorderLayout(5, 5));
      add(initFields(), BorderLayout.NORTH);
      add(initButtons(), BorderLayout.CENTER);
      setFieldData(bean.moveFirst());
   }

   private JPanel initButtons() {
      JPanel panel = new JPanel();
      panel.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
      panel.add(createButton);
      createButton.addActionListener(new ButtonHandler());
      //...
      panel.add(lastButton);
      lastButton.addActionListener(new ButtonHandler());
      return panel;
   }

   private JPanel initFields() {
      JPanel panel = new JPanel();
      panel.setLayout(new MigLayout());
      panel.add(new JLabel("ID"), "align label");
      panel.add(idField, "wrap");
      idField.setEnabled(false);
      panel.add(new JLabel("First Name"), "align label");
      panel.add(fNameField, "wrap");
      //...
      panel.add(new JLabel("Phone"), "align label");
      panel.add(phoneField, "wrap");
      return panel;
   }

   private Person getFieldData() {
      Person p = new Person();
      p.setPersonId(Integer.parseInt(idField.getText()));
      p.setFirstName(fNameField.getText());
      p.setMiddleName(mNameField.getText());
      p.setLastName(lNameField.getText());
      p.setEmail(emailField.getText());
      p.setPhone(phoneField.getText());
      return p;
   }

   private void setFieldData(Person p) {
      idField.setText(String.valueOf(p.getPersonId()));
      fNameField.setText(p.getFirstName());
      mNameField.setText(p.getMiddleName());
      lNameField.setText(p.getLastName());
      emailField.setText(p.getEmail());
      phoneField.setText(p.getPhone());
   }

   private boolean isEmptyFieldData() {
      return (fNameField.getText().trim().isEmpty()
         && mNameField.getText().trim().isEmpty()
         && lNameField.getText().trim().isEmpty()
         && emailField.getText().trim().isEmpty()
         && phoneField.getText().trim().isEmpty());
   }

   private class ButtonHandler implements ActionListener {
      @Override
      public void actionPerformed(ActionEvent e) {
         Person p = getFieldData();
         switch (e.getActionCommand()) {
         case "Save":
            if (isEmptyFieldData()) {
               JOptionPane.showMessageDialog(null,
               "Cannot create an empty record");
               return;
            }
            if (bean.create(p) != null)
               JOptionPane.showMessageDialog(null,
               "New person created successfully.");
               createButton.setText("New...");
               break;
         case "New...":
            p.setPersonId(new Random()
            .nextInt(Integer.MAX_VALUE) + 1);
            p.setFirstName("");
            p.setMiddleName("");
            p.setLastName("");
            p.setEmail("");
            p.setPhone("");
            setFieldData(p);
            createButton.setText("Save");
            break;
         case "Update":
            if (isEmptyFieldData()) {
               JOptionPane.showMessageDialog(null,
               "Cannot update an empty record");
               return;
            }
            if (bean.update(p) != null)
               JOptionPane.showMessageDialog(
               null,"Person with ID:" + String.valueOf(p.getPersonId()
               + " is updated successfully"));
               break;
         case "Delete":
            if (isEmptyFieldData()) {
               JOptionPane.showMessageDialog(null,
               "Cannot delete an empty record");
               return;
            }
            p = bean.getCurrent();
            bean.delete();
            JOptionPane.showMessageDialog(
               null,"Person with ID:"
               + String.valueOf(p.getPersonId()
               + " is deleted successfully"));
               break;
         case "First":
            setFieldData(bean.moveFirst()); break;
         case "Previous":
            setFieldData(bean.movePrevious()); break;
         case "Next":
            setFieldData(bean.moveNext()); break;
         case "Last":
            setFieldData(bean.moveLast()); break;
         default:
            JOptionPane.showMessageDialog(null,
            "invalid command");
         }
      }
   }
}

package View;
import java.awt.FlowLayout;
import javax.swing.JFrame;
/**
 *
 * @author Mbano
 */
public class AppMain {
    public static void main(String[] args) {
    JFrame f =new JFrame();
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER));
     f.getContentPane().add(new PersonUI());
      f.setSize(600, 280);
      f.setVisible(true);
}
}

A: Check the console for any exceptions. Try
new MigLayout("debug")

to see your Layout in debg mode.
You could also set different background colors to the differen JPanels, to see what size they have.


text:
Q: Python ImportError: No module named 'funds' I cloned a repo from github
I keep getting this error when I try running the code:
Traceback (most recent call last):
  File "test.py", line 1, in <module>
    import api.py
  File "C:\xampp\htdocs\projects\mf\mf-platform-bse\mf-platform-bse\api.py", line 10, in <module>
    from models.transactions import TransactionBSE, TransactionXsipBSE, TransResponseBSE, Transaction, PaymentLinkBSE
  File "C:\xampp\htdocs\projects\mf\mf-platform-bse\mf-platform-bse\models\transactions.py", line 4, in <module>
    from funds import SchemePlan, FundScheme
ImportError: No module named 'funds'

Here is my folder structure inside the models folder


text:
Q: How can I create a button with Tkinter that uses two commands, which one of them updates a label? I am trying to create a Tkinter button that runs two commands, one primary function and the other one which updates a label when the button is pressed. I have been able to make it run with both the functions but it does not update the label. Any advice on this problem? I have included the code that I have tried. Thank you in advance.
from tkinter import *
from tkinter import ttk

csv_team_count = 0
team_spaces_left = 4 - csv_team_count

def add_a_team():
    print("testing")
    global csv_team_count
    csv_team_count += 1

root = Tk()
root.title("Sports Event Organiser!")
root.geometry("600x500")

my_notebook = ttk.Notebook(root)
my_notebook.pack()

#creates frames for the notebook.
frame1_overview = Frame(my_notebook, width=600, height=500, bg="#5797ff")
frame2_teams = Frame(my_notebook, width=600, height=500, bg="#5797ff")
frame1_overview.pack(fill="both", expand=0,)
frame2_teams.pack(fill="both", expand=0)
my_notebook.add(frame1_overview, text="Overview",)
my_notebook.add(frame2_teams, text="Teams")

teams_updater_var = StringVar()
teams_updater_var.set("Spaces Left: "+str(team_spaces_left))

def teams_updater():
    teams_updater_var.set("Spaces Left: "+str(team_spaces_left))

def combined_TeamS_addT():
    teams_updater()
    add_a_team()

label_team_spaces_left = Label(frame2_teams,
    textvariable=teams_updater_var,
    font=('Helvatical bold',15),
    bg="#5797ff",
    fg="white",
).pack(pady = 5)

button_team_add = Button(frame2_teams,
    text="Add A Team",
    bg="white",
    height = 1,
    command=(combined_TeamS_addT)
).pack(pady = 10)

root.mainloop()

A: Updated Code:
from tkinter import *
from tkinter import ttk

csv_team_count = 0
team_spaces_left = 4 - csv_team_count

def add_a_team():
    global csv_team_count
    csv_team_count += 1
    print("testing")

root = Tk()
root.title("Sports Event Organiser!")
root.geometry("600x500")

my_notebook = ttk.Notebook(root)
my_notebook.pack()

#creates frames for the notebook.
frame1_overview = Frame(my_notebook, width=600, height=500, bg="#5797ff")
frame2_teams = Frame(my_notebook, width=600, height=500, bg="#5797ff")
frame1_overview.pack(fill="both", expand=0,)
frame2_teams.pack(fill="both", expand=0)
my_notebook.add(frame1_overview, text="Overview",)
my_notebook.add(frame2_teams, text="Teams")

teams_updater_var = StringVar()
teams_updater_var.set("Spaces Left: "+str(team_spaces_left))

def teams_updater():
    global team_spaces_left
    if 0 < team_spaces_left <= 4:
        team_spaces_left = 4 - csv_team_count
    else:
        team_spaces_left = 0
    teams_updater_var.set("Spaces Left: "+str(team_spaces_left))

def combined_TeamS_addT():
    add_a_team()
    teams_updater()

label_team_spaces_left = Label(frame2_teams,
    textvariable=teams_updater_var,
    font=('Helvatical bold',15),
    bg="#5797ff",
    fg="white",
).pack(pady = 5)

button_team_add = Button(frame2_teams,
    text="Add A Team",
    bg="white",
    height = 1,
    command=(combined_TeamS_addT)
).pack(pady = 10)

root.mainloop()


text:
Q: Add Android Feature
I am new to android development. I want to implement something like this image shown that whenever image is clicked on action bar, a pop up type of thing is shown. I want to know what feature of android is this and how can it be implemented.

A: The Navigation Drawer pattern is officially described in the Android documentation!

Check out the following links:

*

*Design docs can be found here.

*Developer docs can be found here.


text:
Q: Different citation style per bibliography using either biblatex or bibtex + natbib + multibib I have a report with three bibliographies where I want different citation styles:

*

*Main part: author-year citations

*Appendix A: numbers citations, needed to fit many citations in a table.

*Appendix B: author-year citations again.

Appendices A or B could be swapped but it does not make a difference to the problem.
I have tried to achieve this with both biblatex, and natbib + multibib. I could not make it work at all with biblatex, while with natbib + multibib I came somewhat close but with faults at the third citatation/refsection, please see a mwe for natbib + multibib below.
The problem for both approaches seems to be that there can only be one 'baseline' citation style. Preferably you would like to define styles with a trick similar to \def\@mb@citenamelist{...} such as \setcitestyletwo{...}, but this seems not possible. Compiling with pdfLaTeX or LuaLaTeX does not make a difference.
Is there a way to make this setup work in any way?
Best, Robert
\documentclass{article}

% needs to have the numbers option, otherwise the second cite will never display numbers
\usepackage[numbers]{natbib}

% https://tex.stackexchange.com/questions/66778/citation-alias-with-multibib-and-natbib
\def\@mb@citenamelist{cite,citep,citet,citealp,citealt,citeptwo,citettwo,citepthree,citetthree}

\usepackage[resetlabels]{multibib}
\newcites{two}{Second-Literature}
\newcites{three}{Third-Literature}

\begin{document}
\section{First}
\setcitestyle{authoryear,round}
Authoryear style cites: \citet{Knuth:1990}

\bibliographystyle{apalike}
\bibliography{testlib}

\section{Second}
\setcitestyle{numbers,square}
Numbers style cites: \citeptwo{Lamport:94} wrote latex.

\bibliographystyletwo{unsrtnat}
\bibliographytwo{testlib}

\section{Third}
\setcitestyle{authoryear,round}
(Desired) Authoryear style cites: \citetthree{Lamport:94alt} wrote latex, but is wrongly cited using the numbers format instead of year!

\bibliographystylethree{apalike}
\bibliographythree{testlib}

\end{document}

%%%% With the contents of testlib.bib as:
@Book{Knuth:1990,
    author    = {Knuth, Donald E.},
    title     = {The Texbook},
    year      = {1990},
    isbn      = {0-201-13447-0},
    publisher = {Addison\,\textendash\,Wesley},
}

@Book{Lamport:94,
    author    = {Lamport, Leslie},
    title     = {latex: A Document Preparation System},
    year      = {1994},
    isbn      = {0-021-52983-1},
    publisher = {Addison\,\textendash\,Wesley},
}

@Book{Lamport:94alt,
    author    = {Lamport, Leslie},
    title     = {latex: A Document Preparation System},
    year      = {1994},
    isbn      = {0-021-52983-1},
    publisher = {Addison\,\textendash\,Wesley},
}

Resulting in:


text:
Q: How is Euler fluids equation considered unsolved? Apart from the Navier-Stokes equation, the Euler equation is described by Clay Math Inst. as unsolved or not well understood. My question is, is there a special case of Euler fluids equation that they are talking about?
P.S: I'm no specialist in this but please I need an answer coherent to someone slightly above a layperson. Thanks


text:
Q: How to get a jQuery UI Autocomplete working I know, there's about 20 questions here that mention jQuery UI Autocomplete. I've read a bunch and I'm still stuck...
I am trying to learn how to implement jQuery UI's Autocomplete feature and I'm working off of this tutorial since it seems closest to my needs and how I need to handle the PHP/MySQL end.
I've been going back and forth between that tut and the documentation and I can't seem to get it working.
I'm trying to set up (what I think is) a simple autocomplete, getting a single field from a db query.
Here's the jQuery code I have at the moment:
$('input.urlSearch').autocomplete({
    source: '../scripts/branchAdmin.php',
    minLength: 3
});

And here's the PHP code:
if (isset($_GET['term'])) {
    $searchTerm = mysqli_real_escape_string($_GET['term']);

    require_once('dbConnect.php');

    $fetch = mysqli_query("SELECT url FROM branches WHERE url LIKE '%" . $searchTerm . "%'");
    $returnArr = array();

    while($row = mysqli_fetch_array($fetch, MYSQLI_ASSOC)) {
        $rowArr['url'] = $row['url'];

        array_push($returnArr,$rowArr);
    }

    mysqli_close($dbc);

    header('Content-Type: application/json');
    echo json_encode($arr);
}

Here's the HTML for the textbox
<td id="newBranchUrl" class="branchData">
    <input type="text" id="txtNewBranchUrl" class="urlSearch" />
</td>

The "url" field in the query is really a short string of states and in the case of two-word states (e.g. North Carolina) there's a dash between the words.
When I start typing in the textbox nothing happens - whether I type test I know is or is not in the db. I'm not seeing any network activity in the console, either (using Chrome).
The tut sure makes it look simple! What am I doing wrong here?


text:
Q: Inserting dataframe from Python into Snowflake When I try to insert dataframe into a table in snowflake using the writes_pandas function, only null values appear in the table. I was trying to create a table that does not contain null values, but when I made code that inserts dataframe into Snowflake, it reported an error that NULL values cannot be inserted into a table that stores NOT NULL values. Can someone maybe help me solve the problem? I checked, the dataframe in Python is not null.
import os
import csv
import pandas as pd
import snowflake.connector
import glob
from snowflake.connector.pandas_tools import write_pandas

ctx = snowflake.connector.connect(
   user='****',
   password='****',
   account='****'

)
cs= ctx.cursor()

def split(filehandler, keep_headers=True):
    reader = csv.reader(filehandler, delimiter=',')

    """
        Function split the file on row # basics
    """

    # Variable declartion:
    row_limit = 1000
    output_name_template = 'output_%s.csv'
    output_path = r'C:\Users\Nenad\Desktop\Data\mix'

    current_piece = 1
    current_out_path = os.path.join(
        output_path,
        output_name_template % current_piece
    )
    current_out_writer = csv.writer(open(current_out_path, 'w'), delimiter=',')
    current_limit = row_limit
    if keep_headers:
        headers = next(reader)
        current_out_writer.writerow(headers)
    for i, row in enumerate(reader):
        if i + 1 > current_limit:
            current_piece += 1
            current_limit = row_limit * current_piece
            current_out_path = os.path.join(
                output_path,
                output_name_template % current_piece
            )
            current_out_writer = csv.writer(open(current_out_path, 'w'), delimiter=',')
            if keep_headers:
                current_out_writer.writerow(headers)
        current_out_writer.writerow(row)

if __name__ == "__main__":
    print("file split Begins")
    split(open(r"C:\Users\Nenad\PycharmProjects\untitled15\bigtable_py.csv"))
    print("File split Ends")

os.chdir(r'C:\Users\Nenad\Desktop\Data\mix')
file_extension=".csv"
all_filenames = [i for i in glob.glob(f"*{file_extension}")]
sql = "USE role ACCOUNTADMIN"
cs.execute(sql)
sql = "SELECT CURRENT_ROLE()"
cs.execute(sql)

for file in all_filenames:
 df=pd.read_csv(file, delimiter=',')
 cs.execute("USE DRAGANA")
 write_pandas(ctx, df, 'TABLES')

A: write_pandas() seems to have issues interpreting the dtypes of fields in DataFrame. SQLalchemy performs a much better job. I suggest using a snowflake sqlalchemy and get a sqlalchemy engine.
Using
DataFame.to_sql() solved most issues I personaaly had.


text:
Q: Duplicates Query Can someone help me with this query please:
I have data where customers have multiple records (in a single table, this is a flat file read into a table) e.g.
Name  Policy
Fred  SSS
Fred  SST
Joe   SSS

I need to pull out all records where Policy='SSS' but where that customer only has a 'SSS' policy. So only Joe would be returned from above

A: select name
from yourtable
group by name
having count(policy)=1 and max(policy)='SSS'

A: SELECT Name
FROM tableName a
WHERE Policy = 'SSS'
GROUP BY Name
HAVING COUNT(*) = (SELECT COUNT(*) FROM tableName b WHERE a.Name = b.Name)

SQLFiddle Demo


text:
Q: Converting IFRAME contents to image I fetch a URL into an IFRAME, and now would like to capture a thumbnail of the result to later show the user the links they have followed.
void receiveHtml(Event e) {
  ...
  iframe.convertToImage... // <----- ????? How to do this?
}

IFrameElement iframe = query('#iframehtml') as IFrameElement;
...
iframe.on.load.add(receiveHtml);
...
iframe.src = url; // E.g. url='http://someplace.com/dir/'

Is there a way in DART to capture the iframe document to an image?  (which I can then shrink to a thumbnail and store for later).

A: You can't do this on the client-side, at least not without the iframe being in the same origin ("the same website"). Otherwise, it would be a security risk, because it opens the door to many possibilities like screenshotting a bank website with the user's bank account details.
However, you could do this on the server side, but it does not get much easier.
One thing you could do is to install webkit2png and let it make screenshots of websites. You could just call it something like this:
import 'dart:io';

main() {
  Process.run('python', ['/path/to/webkit2png', 'http://google.com']).then((result) {
    // Here you can open and do whatever you want with the screenshots.
    // The files are placed in the current directory.
    print(new File('somescreenshot.png').readAsBytesSync());
  });
}


text:
Q: How do I access EC2 instance ID in ASP.NET Core? I have an ASP.Net Core application hosted in an AWS Load Balance setup with x number of instances.
I what to display which EC2 instance actually serving the request on the bottom of the web page.
Is there a Nuget package or an convenient API solution to achive this ?
There is a question on Stackoverflow since 2009:  Find out the instance id from within an ec2 machine that provides a solution using wget to call http://169.254.169.254/latest/meta-data/instance-id to get the instance-id
I was hoping for a Nuget package or an API like solution to achieve this.
Update - Solution
The AWSSDK.Core (The Amazon Web Services SDK for .NET - Core Runtime) has the Amazon.Util.EC2InstanceMetadata class which has the InstanceId propery which allows clean cut access to the information I needed.
Thanks for pointing me in the right direction rodrigo-m.

A: The EC2Metadata helper class for ASP.NET was announced in this AWS Developer Blog in 2013. The article describes how this utility class provides easy access to EC2 instance metadata:

A few months ago we added a helper utility to the SDK called
  EC2Metadata. This is a class that provides convenient access to EC2
  Instance Metadata. The utility surfaces most instance data as static
  strings and some complex data as .NET structures. For instance, the
  following code sample illustrates how you can retrieve the current EC2
  instance's Id and network interfaces...

The article also provides examples for its use:
string instanceId = EC2Metadata.GetData("/instance-id");
Console.WriteLine("Current instance: {0}", instanceId);

With this class, consider using the following approach for retrieving and storing the EC2 instance ID in your ASP.NET Core application:

*

*Using the AWS SDK for .NET Version 3 API, call the EC2 Instance Metadata class. The EC2Metadata class exposes the InstanceId property, which returns the instance Id of the current instance.

*Store the instance metadata in the application scope of your application, so that it can be initialized once, at application start time, then referenced as needed for display to the client, or in application logs. See Introduction to session and application state in ASP.NET Core.
Using the application scope, you only need to retrieve this data once at application initialization. This application scope data will persist for the life of the application.


text:
Q: setting css - content as empty string changes the background I display the post titles which is an unordered list in my title bar. Css for header is set as,
.header{
    background: #f0f0f0;
    box-shadow: 0 2px 2px -2px #777;
    *zoom: 1;
    width: auto;
}
.header:before, .header:after {
    display: table;
}
.header:after {
    clear: both;
}

But the background color (or) shadow box is not displayed with the above properties. It comes with white bg color like this,

Then i added an extra property as
.header:before, .header:after {
  content: '';
}

The background color got applied as (i desired),

How does setting content as empty string before/after affect the background color of the header?

A: sudo-elements :before and :after are nothing without content, these element are visible in page iff they have content and are hidden otherwise

A: You can set all the properties you want to the pseudo elements before and after, but they won't occupy space without the attribute 'content' being set. And sorry for not commenting but i still don't have enough rep.


text:
Q: Change Button text When Status Is approved in table I am binding the table using ng-repeat in angularjs here is my table

        Sr. no.

        Title

        Image

        Category

        PostedOn

        Created By

        Status

        Change Status

      {{$index+1}}
      {{obj.Title}}

        {{obj.CategoryName}}

        {{obj.CreatedDate}}

        {{obj.FirstName}}({{obj.UserType}})

        {{obj.IsActive ? 'Approved ' : 'Pending'}}

        <button class="btn btn-primary waves-effect waves-light" ng-click="ToActiveBlog(obj.Id)" ng-bind="btnactivate" type="submit" value="Activate"></button>

In second last td I am setting the value approved and pending.
  {{obj.IsActive ? 'Approved ' : 'Pending'}}

Below td there is a button

  <button class="btn btn-primary waves-effect waves-light" ng-click="ToActiveBlog(obj.Id)" type="submit" value="Activate"></button>

Which has an activate text on it
How can I set the button text "Inactivate" when my status is approved in angularjs?

A: You can use string interpolation in same way
 <button ng-click="ToActiveBlog(obj.Id)">{{obj.IsActive ? 'inactivate' : 'Activate'}}</button>

A: Use ng-value attribute instead of value attribute in the button element. This is specially for Angularjs set value for input elements.

    <button class="btn btn-primary waves-effect waves-light" ng-click="ToActiveBlog(obj.Id)" ng-bind="btnactivate" type="submit" ng-value="obj.IsActive ? 'Activate' : 'Inactivate'"></button>

or else using ng-if

The ngIf directive removes or recreates a portion of the DOM tree
  based on an {expression}. If the expression assigned to ngIf evaluates
  to a false value then the element is removed from the DOM, otherwise a
  clone of the element is reinserted into the DOM.

    <button class="btn btn-primary waves-effect waves-light" ng-click="ToActiveBlog(obj.Id)" ng-bind="btnactivate" type="submit" value="Activate"></button>

    <button class="btn btn-primary waves-effect waves-light" ng-click="ToActiveBlog(obj.Id)" ng-bind="btnactivate" type="submit" value="Inactivate"></button>

A: Please try the following, i think it should work. As i did not had the access to post comment hence im posting it as an answer

    <button class="btn btn-primary waves-effect waves-light" ng-click="ToActiveBlog(obj.Id)"  type="submit" value={{obj.IsActive ? 'Approved ' : 'Pending'}}>
  </button>


text:
Q: Gradle API throws error Could not determine java version from '11' I try to compile from my code a library using Gradle API.
I have an updated version of Gradle on my machine.
------------------------------------------------------------
Gradle 6.2.1
------------------------------------------------------------

Build time:   2020-02-24 20:24:10 UTC
Revision:     aacbcb7e587faa6a8e7851751a76183b6187b164

Kotlin:       1.3.61
Groovy:       2.5.8
Ant:          Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM:          11 (Oracle Corporation 11+28)
OS:           Windows 10 10.0 amd64

This library can be compiled in the IDE (IntelliJ).
It's also successfully compiled in the CMD using compileJava target.
I use the following code:
 public void buildFolderWithCode(Path rootPath) throws RuntimeException {
        // Root path check
        if (!Files.exists(rootPath)) {
            throw new RuntimeException(String.format("The directory \"%s\" for Gradle build does not exist.", rootPath.toString()));
        }

        ProjectConnection connection = null;
        try {

            connection = GradleConnector.newConnector()
                    .forProjectDirectory(new File(rootPath.toString()))
                    .connect();

            BuildLauncher build = connection.newBuild();

            //select tasks to run:
            build.forTasks("compile");

            //include some build arguments:
            build.withArguments("--no-search-upward", "-i", "--project-dir", rootPath.toString());

            //configure the standard input:
            build.setStandardError(System.err);
            build.setStandardOutput(System.out);

            //kick the build off:
            build.run();
        } catch (Exception ex) {
            throw new RuntimeException(String.format("Failed to build with gradle in path \"%s\" (Check the inner exception for further details).", rootPath.toString()), ex);
        } finally {
            if (connection != null) {
                connection.close();
            }
        }

And I get the error:
java.lang.IllegalArgumentException: Could not determine java version from '11'.
How can I pass it JAVA_HOME? This environment variable is set on the machine...
I also tried compileJava at the target to no avail...


text:
Q: Actor not processing messages for quite some time In my akka application , i am using a main actor as controller which receives commands and delegates it to processor actor .Processor actor upon finishing (which takes around 2 mins to finish each task) , passes the message to controller and then controller actor , sends message to Database actor for persistence. Both processor actor and db database actor are managed using router each with say 5 routees. I am using default dispatcher and all other akka configuration are default only .Now below is the scenario.
The controller actor is receiving around 100 messages which are passed to processor actor , i can see from the log that the processor has finished processing some messages (around 5) and passed on completion message to controller actor. But database actor starts executing after some 5 mins. During this 5 mins , however the processor actor is processing its pending messages. So its not like the application is idle.
When the volume of message is less , the flow from controller -> processor -> controller -> db actor is  almost instantaneously and there is hardly any lag.
I dont want this lag after processing , DB execution should happen as soon as processing is finished. But seems threads are busy executing processor task.How can i overcome this situation , ideally i want the turn around time of my task execution to be less , but due to above behavior i am not able to achieve it.

A: By default, all Akka actors use the same executor which is limited to use 64 threads maximum. From https://doc.akka.io/docs/akka/current/general/configuration-reference.html :
# This will be used if you have set "executor = "default-executor"".
      # If an ActorSystem is created with a given ExecutionContext, this
      # ExecutionContext will be used as the default executor for all
      # dispatchers in the ActorSystem configured with
      # executor = "default-executor". Note that "default-executor"
      # is the default value for executor, and therefore used if not
      # specified otherwise. If no ExecutionContext is given,
      # the executor configured in "fallback" will be used.
      default-executor {
        fallback = "fork-join-executor"
      }

and fork-join-executor config:
# This will be used if you have set "executor = "fork-join-executor""
      # Underlying thread pool implementation is java.util.concurrent.ForkJoinPool
      fork-join-executor {
        # Min number of threads to cap factor-based parallelism number to
        parallelism-min = 8

        # The parallelism factor is used to determine thread pool size using the
        # following formula: ceil(available processors * factor). Resulting size
        # is then bounded by the parallelism-min and parallelism-max values.
        parallelism-factor = 1.0

        # Max number of threads to cap factor-based parallelism number to
        parallelism-max = 64

        # Setting to "FIFO" to use queue like peeking mode which "poll" or "LIFO" to use stack
        # like peeking mode which "pop".
        task-peeking-mode = "FIFO"
      }

The problem could be related to blocking calls in processor actors. Akka assigns separate threads from a pool of 64 to handle these blocking calls in processor actors and waits for one of them to complete message processing to be able to handle messages for other actors. This might cause the time lag that you observe between actors.
A key aspect on which Akka is based is that systems should remain responsive at all times. If you used the same dispatcher/thread pool for the blocking DB operations or processing messages as your main Akka routing infrastructure, it is possible that all the Akka threads could be occupied by the processing actors or DB operations, and your system would effectively be deadlocked until one of the blocking operations is completed. This might not be a problem for a simple system on a single JVM that only performs this task, but when it is scaled, it might cause a lot of problems.
In cases like yours where you cannot avoid blocking, a dedicated dispatcher for blocking operations should be used. This link talks about this aspect(though it is titled for Akka-Http, it can be generalized). You can create two types of dispatchers to handle the two different blocking operations. I also, think that you should throttle your blocking requests as to not overwhelm your system(use dispatchers for throttling). You could also implement buffers within your actors to deal with backpressure situations.
EDIT
The controller mailbox has 100 messages and 5 messages are taken and delegated to processor actors. Each processor actor takes 2 mins of time and sends the response back to the controller and the response gets queued in the controller's mailbox. But before processing these messages, the controller needs to process messages which were added before these messages effectively increasing the service time for processing the messages for controller. The lag is the culmination of this whole process. As soon as the controller got the response message, it delegated to the actor.I think that the processing time increases as the messages increase.
Let me know if it helps!!


text:
Q: Cannot read property 'findDOMNode' of undefined when using stopPropagation - reactJs I need to do event bubbling through the deep nested components ,  I tried to do some thing like below
   import {ReactDOM,render, unmountComponentAtNode} from 'react-dom';

  .........
  .........

  componentDidMount() {
    ReactDOM.findDOMNode(this).addEventListener('click', (event) => {
    event.stopPropagation();
  }, false)
}

I got the following error
bundle.js:45 Uncaught TypeError: Cannot read property 'findDOMNode' of undefined

A: ReactDOM is default export, import findDOMNode instead of ReactDOM.
Try this:
import {findDOMNode ,render, unmountComponentAtNode} from 'react-dom';
...
componentDidMount() {
    findDOMNode(this).addEventListener('click', (event) => {
    event.stopPropagation();
  }, false)
}

OR
import ReactDOM from 'react-dom';
...
componentDidMount() {
    ReactDOM.findDOMNode(this).addEventListener('click', (event) => {
    event.stopPropagation();
  }, false)
}


text:
Q: Getting the application directory for File I/O in C# I am trying to pass in a file path to a StreamReader without writing the full path because I will be uploading this to a web server.  For some reason I can't seem to get this to work.  Here's the code snippet that giving me some problems:
StreamReader reader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + @"\files\randomlist.txt");

This works when I run it locally in Visual Studio, but it doesn't work when I upload it to my website.  The full path of the file I am trying to read is:
C:\Users\Jason\Documents\Visual Studio 2013\WebSites\WordFriends\files\randomlist.txt

So my question is, how can I write the path such that it works on my web server?  Or if you have an alternative solution, please let me know.  Also, could someone also explain why just doing this doesn't work?
StreamReader reader = new StreamReader(@"files\randomlist.txt");

Thanks,
Jason

A: Try using this instead. The call to Server.MapPath returns the physical path corresponding the virtual path you provide, assuming "files\randomlist.txt" is the correct virtual path.
StreamReader reader =
    new StreamReader(HttpContext.Current.Server.MapPath(@"files\randomlist.txt"));

A: Using Server.MapPath("~") would give the root directory of your website.
It's not recommended to concatenate pants with +, use Path.Combine(a, b) instead.


text:
Q: How to check if script was executed via command line or double-clicked? How can I determine if a script was invoked from a command line or via double-click in file manager (Nautilis)?
If the former, I still have a command prompt when the script finishes, but if it was double-clicked (or executed via a .desktop file), the script executes in a window and then disappears. I want the window to remain open with a command prompt.
I figure the script could make this check and either do nothing - if invoked from a command line - or exec bash at the end if invoked via double-click or .desktop.
Haven't been successful using methods to check if interactive or not or tty.

A: You can check if the parent process is the shell. For example:
#! /bin/bash

if [[ $(readlink -f /proc/$(ps -o ppid:1= -p $$)/exe) != $(readlink -f "$SHELL") ]]
then
    echo "Starting the shell..."
    exec "$SHELL"
else
    echo "Not starting a shell."
fi

ps -o ppid:1= -p $$ prints the PID of the parent process (ppid) of the current process (-p $$). A readlink on /proc/<pid>/exe should print the path to the executable, which would be the shell if you ran it in a shell, or something else otherwise.

Another possibility is the SHLVL variable, which indicates how nested the current the shell instance is. If run within a shell, the script should have SHLVL 2 or greater. When run by double clicking, or from a desktop launcher, it should be 1:
#! /bin/bash

if (( SHLVL > 1 ))
then
    echo "Starting the shell..."
    exec "$SHELL"
else
    echo "Not starting a shell."
fi

A: You can check if the shell script was run on a terminal by analyzing the output of tty command.
#! /bin/bash

if [[ $(tty) =~ "not a tty" ]]
then
    echo "Not running on terminal"

else
    echo "Running on terminal"
fi

A: I checked the differences between the environment when running a script from the terminal and the environment when running a script by double-clicking it in Files;
When you run a script by double clicking in Files the $VTE_VERSION variable is unset, so you can hook to it to decide whether to replace the current Bash instance with an interactive one or not.
That is, just put this at the end of your script:
#! /bin/bash
# ...
[ ! -z $VTE_VERSION ] && exec bash

To make this work also in case the script is run from a desktop file, change the desktop file's Exec= line from say:
Exec=/path/to/script

To:
Exec=sh -c '/path/to/script; exec bash'

This way /path/to/script will be executed and sh will be replaced by Bash upon /path/to/script's completion.

A: When double clicked from Nautilus you won't have the entire environment setup like you do in a regular terminal session. I use this boilerplate code to prevent crashes: Desktop shortcut to Bash script crashes and burns . You can adapt it to your needs:
# $TERM variable may be missing when called via desktop shortcut
CurrentTERM=$(env | grep TERM)
if [[ $CurrentTERM == "" ]] ; then
    notify-send --urgency=critical "$0 cannot be run from GUI without TERM environment variable."
    exit 1
fi


text:
Q: Shut Out of XP - No Admin Password or CDR I inherited an old WinXP/Linux dual-boot machine from the stoneage. Because it has Linux, the regular boot process is replaced with the Fedora boot loader; I cannot, therefore, press F8 strategically to tell my PC to boot from CD.
Even if I could, it's a moot point; the CDR doesn't seem to recognize any CDs. To make things worse, there's no option to network boot.
The original user is probably long gone; I don't know the password for any of the Administrator group users. I can login using my corp account, but that's unprivileged on this machine.
Since I'm not an admin, I can't do crazy things, like looking at boot.ini. Or deleting files. I only have 500MB free on my C drive. I'm pretty sure I can't boot from a USB, since I didn't see any settings for this in my BIOS.
How can I get admin access for my user?
Edit: Things I've tried:

*

*Boot from CD (CD not recognized)

*Launch CD from XP (CD not recognized)

*Install Daemon Tools Lite so I can install from an ISO -- don't have admin privileges

*XP password recovery tool -- requires admin privileges

*Adding an admin user -- no access to Control Panel > Users since I'm not an admin

*Logging in as both the admin users on the system (trying some standard passwords)

*Using Fedora to chntpw (the Fedora version installed is ancient -- 2.7)

A: The best way is to get your adminstrator to fix it - most tools to change a password rely on being able to boot off a cd.In any case check if its ok, before you do anything
On the other hand, you should be able to, if you had access to the bios, to select the boot device from there, and maybe USB boot it. You might also be able to boot fedora into single user mode
This may vary depending on your version, but according to fedora documentation
On an x86 system using GRUB, use the following steps to boot into single-user mode:

*

*At the GRUB splash screen at boot time, press any key to enter the GRUB interactive menu.

*Select Fedora with the version of the kernel that you wish to boot and type a to append the line.

*Go to the end of the line and type single as a separate word (press the Spacebar and then type single). Press Enter to exit edit mode
This should log you into a root account on fedora where you can do stuff.
Hopefully if this is a new enough version you could then change the windows password with chntpw - which is the same tool used here in the nt offline password changer utilty, which should give you full access to windows.

A: I solved this by plugging in an external DVD drive via USB. Thankfully, my BIOS was recent enough to recognize it; I deleted all the old Windows/Linux partitions and installed Windows anew. Phew.


text:
Q: How to design a custom color space? I have picked some colors from the CIE LAB color space and want to blend the colors linearly construct a new color space. I first consider the 2D case as a starting point.
Firstly, I choose a set of values for the a and b components in the following way:
acolors = {LABColor[0.5, -1.28, 0.], LABColor[0.5, -0.855158, 0.], LABColor[
 0.5, -0.535583, 0.], LABColor[0.5, -0.285656, 0.], LABColor[
 0.5, -0.086842, 0.], LABColor[0.5, 0.01467, 0.], LABColor[
 0.5, 0.049943, 0.], LABColor[0.5, 0.093202, 0.], LABColor[
 0.5, 0.145433, 0.], LABColor[0.5, 0.207967, 0.], LABColor[
 0.5, 0.282634, 0.], LABColor[0.5, 0.371987, 0.], LABColor[
 0.5, 0.479711, 0.], LABColor[0.5, 0.61135, 0.], LABColor[
 0.5, 0.77577, 0.], LABColor[0.5, 0.98835, 0.], LABColor[
 0.5, 1.28, 0.]}

bcolors = {LABColor[0.5, 0., -1.28], LABColor[0.5, 0., -0.945977], LABColor[
 0.5, 0., -0.678795], LABColor[0.5, 0., -0.460215], LABColor[
 0.5, 0., -0.278078], LABColor[0.5, 0., -0.123975], LABColor[
 0.5, 0., 0.00228], LABColor[0.5, 0., 0.041005], LABColor[
 0.5, 0., 0.088123], LABColor[0.5, 0., 0.145079], LABColor[
 0.5, 0., 0.214], LABColor[0.5, 0., 0.297526], LABColor[
 0.5, 0., 0.400353], LABColor[0.5, 0., 0.529412], LABColor[
 0.5, 0., 0.696892], LABColor[0.5, 0., 0.926912], LABColor[
 0.5, 0., 1.28]}

The corresponding chromaticity diagram for these colors is given below:

Now I wish to Interpolate them linearly to fill the plane L = 0.5.
This is what I have tried:
ac = ImageCrop@
  Image@Graphics[
    Raster[{Range[100]/100}, ColorFunction -> (Blend[acolors, #] &)],
    AspectRatio -> 1];

bc = ImageRotate[
  ImageCrop@
   Image@Graphics[
     Raster[{Range[100]/100}, ColorFunction -> (Blend[bcolors, #] &)],
      AspectRatio -> 1], Pi/2];

And then,
ColorConvert[Blend[{ac, bc}], "LAB"]

However, I find that the L values in the blended image are not the same (0.5) as it should be.
How can I resolve this issue and connect the color points in the color space to have a color plane with L = 0.5?


text:
Q: Replicating a website for offline use I am showing a website within a WebView in an Android app. Since this is a particular page which my app has to access frequently, I would like to offer a cached version of it for when the user has no connectivity. So if the user has an internet connection, the website would be accessed from the internet and a copy would be made. IF you access again but have no connectivity, the cached version should be shown.
My app is for API version 9 and above.
My question is, how would you go and download all assets from a particular page?

A: The webview is already doing that for you once the user visits that view. The page is loaded and cached. You can set the webview to cache on the sd card like this:
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

link to docs
If this default behaviour isn't enough for you you can look into fetching the content with a httpclient and storing that information. But then you'll have to adapt your webview to go look there first and you'll have to make sure you download all the resources that webpage needs.

A: So these are two questions you are asking. The one bit regarding WebView and cache was already answered.
Regarding this bit "My question is, how would you go and download all assets from a particular page?", check these links :

*

*How to create web crawler in java?

*Simple web crawler on android

*How to save file from website to sdcard
First link is a crawler implementation in Java, the second link is basically that code being used (somewhat badly) on Android, the third link should give you enough info as how to download files.
Hope this helps


text:
Q: Accessing the gallery images automatically uisng ionic I m trying to build a gallery application using Ionic, For reading images  I used ImagePicker, to select images in the device. But this will prompt the user to pick images.
I m trying to access the the image files automatically without picked up by the user, Can please somebody help on this.


text:
Q: Rails 7 using custom js in specific pages Having adapted the hotwire mechanism for rails 7, problems arise for custom JS that are dependency-less.  in this case, a JS that is not mapped to a given source.
Added to importmap.rb:
pin_all_from "app/javascript/plugin", under: "plugin"

which does render
    <script type="importmap" data-turbo-track="reload">{
  "imports": {
    "application": "/assets/application-37f365cbecf1fa2810a8303f4b6571676fa1f9c56c248528bc14ddb857531b95.js",
    "@hotwired/turbo-rails": "/assets/turbo.min-e5023178542f05fc063cd1dc5865457259cc01f3fba76a28454060d33de6f429.js",
    "@hotwired/stimulus": "/assets/stimulus.min-900648768bd96f3faeba359cf33c1bd01ca424ca4d2d05f36a5d8345112ae93c.js",
    "@hotwired/stimulus-loading": "/assets/stimulus-loading-1fc59770fb1654500044afd3f5f6d7d00800e5be36746d55b94a2963a7a228aa.js",
    "controllers/application": "/assets/controllers/application-368d98631bccbf2349e0d4f8269afb3fe9625118341966de054759d96ea86c7e.js",
    "controllers/hello_controller": "/assets/controllers/hello_controller-549135e8e7c683a538c3d6d517339ba470fcfb79d62f738a0a089ba41851a554.js",
    "controllers": "/assets/controllers/index-2db729dddcc5b979110e98de4b6720f83f91a123172e87281d5a58410fc43806.js",
    "plugin/auto-complete": "/assets/plugin/auto-complete-813c8033519c4886434d3f867f4159971e0d46aca097d6706580f5042f78d4ec.js"
  }

Also note that I made the mistake of running ./bin/rails javascript:install:esbuild
which leads to unnecessary pollution of the header and do not know how to un-do this (indictions not provided with the gem)
<script type="esms-options">{"nonce":null}</script>
<script src="/assets/es-module-shims.min-b8099fffdbd758070d4801321d43b389c5b6174a50782f9f4cb57061533b7ac2.js" async="async" data-turbo-track="reload"></script>

could this be a factor in impeding the eventual loading of the script?
Apparently, a declaration is required to have it load: <%= javascript_import_module_tag "plugin" %>.  While the preference is to load it on the action that requires it, this was added to the application.html.erb file.
To no avail.
The script runs only if the raw script is included in the action's view.
Is there a more succinct manner to load such a script as necessary?
Update
The suggestion provided by @alex appears in the right direction, however, a greater issue exists for the browser, with a fresh application creation, pushing the situation into a different question.
FF version required an ImportMap enabling under about:config which then rendered the same situation as Chrome:

The same error arises when substituting the pin_all_from command with
pin("plugin/auto-complete")
Chrome:

Thus the building tool is working in an unexpected manner under pin_all_from and pin with
<% content_for :head do %>
  <%= javascript_import_module_tag "plugin/autocomplete" %>
<% end %>

A: As a fix you can use path directly created by pin_all - one you can see in page source code.
In your case - /assets/plugin/auto-complete


text:
Q: Can Owin also handle responses in its pipeline As I understand Owin now it is a pipeline of modules you can define that handles incoming requests. Any module can return a response or pass the request to the next module. So that makes it very easy to add logging or authentication or whatnot, very cool.
But what if I would like to log responses? Can you create a module that runs for every response, irrespective of where the response came from in the pipeline? If it is possible, can you provide an example or link, I can't seem to find this scenario on the web.

A: Turn out it is quite simple and logical, This blogpost shows an example on how to time the request. Since a module either passes the request on to the next module or RETURNS a response it is just a question of registering a module as the first and processing the returnvalue with ContinueWith:
public Task Invoke(IDictionary<string, object> environment)
{
    return _next(environment).ContinueWith(result =>
    {
        Logger.LogResult(result);
        return result;
    });
}


text:
Q: Currency question If a client has the following requirements (below), is there any reason not to request from SF to allow multiple currencies? Are there alternatives to this feature that allow multiple currencies?
Thanks
Need to use American Dollars but with option to change to
•   Canadian Dollars
•   NIS
•   Euro
•   British Pound

A: You should probably read about the implications of turning multi-currency on before doing so, once done, it can't be undone.
Unless you implement your own currency management, I'm not sure what other option there would be if the client requires multi-currency. Depends on your use case.

A: SFDC Multi-currency is a very useful feature and is commonly seen in orgs that sell their products in different currencies. I've worked in two orgs that used multi currencies and dated exchange rates (Advanced Currency Management) and the feature works well.  You have to remember to change exchange rates every quarter/half/fiscal year if you want to match your ERP system.
ACM is well integrated with Opportunities and Opportunity Products and you get a lot of stuff for free.
Third party appexchange products will have support for SFDC multicurrency so any roll your own strategy won't be compliant with your ecosystem.
There are some implications for multi-currency when using VF pages. Here are some to consider (there are workarounds)
apex:outputField limitation (ACM)

A merge field that references the Salesforce field that is associated with this output field. For example, if you want to display an output field for an account's name field, use value="{!account.name}". You cannot associate this output field with a currency merge field if that field value is calculated using dated exchange rates.

Plus this Known Issue


text:
Q: Code goes not recognize Verfiy Function after Clicking on Submit I am trying to use the JQuery Ui function "Verfiy();" to verify that the name, age, country and date fields have been filled before allowing the form to submit.
The verify function should be called when the user hits 'submit', however when I use the following code the webpage is directed to the 'thankyou' page whether the fields have been completed or not. It does not show an error message.

...

Free JavaScripts provided

by The JavaScript Source

...

 <input type="submit" value="Submit" onClick="verify()"/>

 <input type=reset value="Clear Form">

...

Any insight would be greatly appreciated.
Andrew

A: Here you go, just a little tweak in your markup.
<input type="submit" value="Submit" onClick="return verify()"/>


text:
Q: Brave Tracing currentSpan is null I am injecting Tracing object through constructor in a service and trying to get tracing.tracer().currentSpan() which is coming as null. tracing.tracer() object is initiazed with  spanHandler.
I am running it through the test case:
@RunWith(SpringRunner.class)

If I run the individual test case from eclipse currentSpan is initialized properly but when i build the application through mvn clean install currentSpan is coming as null. Here is the code, I am not sure how the currentSpan is initiazed and cant find much about it on internet.
@Service
public class Test {

   Tracing tracing;

   Test(Tracing tracing) {
       this.tracing = tracing;
   }

   //tracing.tracer().currentSpan() is null
}

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
class TestJUnit {

}