text:
Q: Invalid Audience Id - Office 365 I am trying to connect with office 365 without going through Azure, so I was able to get the access token by calling the following URL
https://accounts.accesscontrol.windows.net/myDomain.onmicrosoft.com/tokens/OAuth/2
Parameters:
**resource** 00000003-0000-0ff1-ce00-000000000000/myDomain-my.sharepoint.com@myDomain.onmicrosoft.com
**client_id** ab15d15a-9bf6-4f52-b67a-6528398d2ca9@myDomain.onmicrosoft.com
**client_secret** xxxxxxx
**code** xxxxxx
**grant_type** authorization_code

But the problem is when I try to call the Office 365 API like this:

https://myDomain-my.sharepoint.com/_api/v1.0/me/files/getByPath('Shared%20with%20Everyone')/children

I got the following error:

Invalid audience Uri
  '00000003-0000-0ff1-ce00-000000000000/myDomain.sharepoint.com@132436d6-76fe-4a35-95b5-c2a643463cb4'.

Any hints of what is happening?


text:
Q: Whats the point in UrbanAirship? I'm looking into push notifications for an app I'm creating. I've heard lots about UrbanAirship but I can't seem to find a definitive reason why I should use it? As far as I understand it UA is a middle man? This page shows the free version doesn't have a push composer, so a developer will still need a server themselves to create the notification, if their own server is needed then I might as well go directly to APNS?
What is the point and advantage of UA? And if you use it how do you send notifications without your own server?

A: A working implementation of push notifications involves many things, such as:

*

*Keeping track of Device IDs (web service for the device to contact, database to store the IDs)

*Storing metadata associated with each Device ID (ie. so you can refer to a device by a username or a group of devices by a tag)

*Keeping track of which devices have been deactivated (which happens if the user turns of notifications)

*Clearing out bad Device IDs

*Actually forming the raw request to send the message to Apple's servers

*Some sort of service/program to know when you need to send the notifications

Urban Airship takes care of 1-5 for you, which greatly simplifies the whole process. Yes, you if were just sending a message to one device, you could probably find a C# or python or Objective-C library to connect to Apple and form the message but as soon as you need to keep track of a large number of devices, Urban Airship provides a service for free (if under 1 million pushes a month) to take a lot of work off your shoulders.
(And this is just for the basic push service for iPhone, as this is the only service I have used)
To answer your other question, you do still need some 'server' or program to know when to push (#6). I, for example, monitor twitter with a python program for keywords and send out notifications when I see those. My program is not concerned with the details of how to send notifications, the Urban Airship library I use takes care of the interaction with Urban Airship and Apple.

A: If you start your free trial at nextdns, you find urbanairship becomes one of the most common offenders that they block.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to select option if value contains string I need to select option if value contains particular string.
<select>
    <option value="sunday,1523">Sunday</option>
    <option value="monday,1583">Monday</option>
</select>

Need to select option contains 1583 value.
I tried, but not working.
$("select option:contains(1583)").prop("selected","selected")

A: You are searching for Attribute Contains Selector
[name*="value"]

https://api.jquery.com/attribute-contains-selector/

$("select option[value*=1583]").prop("selected", true)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select>
  <option value="sunday,1523">Sunday</option>
  <option value="monday,1583">Monday</option>
</select>

References
https://api.jquery.com/category/selectors/attribute-selectors/

A: Vanilla JS solution using Array.prototype.filter:

var options = Array.from(document.querySelectorAll("select option"))
options.filter(option => option.value.includes("1583"))[0].selected = true;
<select>
  <option value="sunday,1523">Sunday</option>
  <option value="monday,1583">Monday</option>
</select>

A: You can also use JavaScript's built-in includes() method.

let select = document.querySelector("select");

for(let i=0; i<select.options.length; i++){
    if(select.options[i].value.includes('1583')){
    select.options[i].selected = true;
  }
}
<select>
    <option value="sunday,1523">Sunday</option>
    <option value="monday,1583">Monday</option>
</select>

A: Use the Attribute selector [value] that ends with $=

const num = "1583";

$(`option[value$="${num}"]`).prop("selected", true);
<select>
  <option value="sunday,1523">Sunday</option>
  <option value="monday,1583">Monday</option>
</select>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

A: //if contain specific word '1583'
$("select option[value~='1583']").prop("selected", true)

//if contain word '1583'
$("select option[value*='1583']).prop("selected", true)

//if ending with '1583'
$("select option[value$='1583']).prop("selected", true)

Remember, the difference between prop() and attr()
eg:prop("selected", true), attr("selected", "selected")


text:
Q: How to normalize this data This is a minimum data to reproduce the question:
@prefix rs: <http://example.org/rs#>
@prefix bo: <http://example.org/bo#>
@prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
@prefix xsd: <http://www.w3.org/2001/XMLSchema#>

rs:user1 rs:hasRated [rs:by "1.0"^^xsd:float ; rs:item bo:animalFarm] .

rs:user2 rs:hasRated [rs:by "0.9"^^xsd:float ; rs:item bo:animalFarm] .

rs:user3 rs:hasRated [rs:by "0.9"^^xsd:float ; rs:item bo:animalFarm] .

rs:user4 rs:hasRated [rs:by "0.5"^^xsd:float ; rs:item bo:book3] .

rs:user5 rs:hasRated [rs:by "0.6"^^xsd:float ; rs:item bo:book3] .

rs:user6 rs:hasRated [rs:by "0.8"^^xsd:float ; rs:item bo:algorithem1] .

rs:user7 rs:hasRated [rs:by "0.9"^^xsd:float ; rs:item bo:algorithem1] .

rs:user8 rs:hasRated [rs:by "0.3"^^xsd:float ; rs:item bo:book4] .

I want to normalize the average of rating for each item, and also normalize the number of ratings for each item
I can take the average of ratings for each item, and the number of ratings for each item as the following:
PREFIX  bo:   <http://example.org/bo#>
PREFIX  xsd:  <http://www.w3.org/2001/XMLSchema#>
PREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX  rs:   <http://example.org/rs#>
select ?item (AVG(?ratingValue) as ?avg) (COUNT(*) as ?count)
{
    ?user rs:hasRated [ rs:item ?item ;  rs:by ?ratingValue ] .
}
group by ?item

and the result is:

What I would like, if possible, is to have the following:
bo:book3                 (0.55/(0.55 + 0.93333334 + 0.85 + 0.3 ))   (2/(2 + 3 + 2 + 1))

and off course the same for the other items.
my problem is that I don't know how to make the sum, and at the same time do the division.
Your help is highly appreciated .
Update 1
I am asking about the possibility to do that, if not (or if performance is too bad) i got with different solution

A: In SPARQL, the data is either grouped or it isn't.  You can't really "reach out" from the group and get information that's bigger than the group.  That means that to get this, you'll probably need to have a subquery that gets the total values separately.  With the data that you've given:
select ?item
       (avg(?rating_)/?sumAvgRating as ?rating)
       (count(*)/?countRating as ?percentCount)
{
  ?user rs:hasRated [ rs:by ?rating_ ; rs:item ?item ]

  #-- get number of ratings
  { select (count(*) as ?countRating) { ?user rs:hasRated [] }}

  #-- get sum of average ratings
  { select (sum(?avgRating) as ?sumAvgRating) {
      { select (avg(?rating_) as ?avgRating) {
          ?user rs:hasRated [ rs:by ?rating_ ; rs:item ?item ]
        }
        group by ?item
      }
    }
  }
}
group by ?item ?countRating ?sumAvgRating

-----------------------------------------------------------
| item           | rating                  | percentCount |
===========================================================
| bo:book3       | "0.20886075"^^xsd:float | 0.25         |
| bo:book4       | "0.11392405"^^xsd:float | 0.125        |
| bo:algorithem1 | "0.3227848"^^xsd:float  | 0.25         |
| bo:animalFarm  | "0.35443038"^^xsd:float | 0.375        |
-----------------------------------------------------------

I think that to get the data you really want, and to do it without redundant subqueries, you'll need some post-processing on the results. I say that because you're really asking for some computation that involves grouping in two different ways.  To get the total number of ratings, you need a group over all the results (or at least over a group over some grouped results).  To get the averages for each item, you need to group over the items.  To get the sum of the averages, you need to group over the grouped data.  So I don't think that you can do this perfectly without some redundant querying.
But, you can some of the processing within the query.  I think that I'd get the items and their ratings, and the count the ratings and sum the averages for each item, like this:
select ?item (sum(?rating_) as ?sumRating) (count(*) as ?countRating) {
  ?user rs:hasRated [ rs:by ?rating_ ; rs:item ?item ]
}
group by ?item

The reason I do this, rather than averaging the ratings, is that from the count and the sum you can easily reconstruct the average (just divide the sum by the count), and you can get the sum of the sums, and the sum of the counts.  If you do the average too early, then you can't determine what the sum of all the ratings actually was.


text:
Q: The curvature of the connection one form - misunderstanding Let $(P,M,G,\pi,\cdot)$ be a principal bundle. Let $\omega$ be the connection one form for a connection $H\subset TP$. Let $X,Y$ be smooth vector fields on $P$. Then the curvature $\Omega$ of the connection form is
$\begin{align*}
\Omega(X,Y)&=d\omega(hX,hY)\\
\\
&=(hX)\omega(hY)-(hY)\omega(hX)-\omega([hX,hY])\\
\\
&=-\omega([hX,hY]).
\end{align*}
$
What I am having trouble understanding is the second line of the above equations. As far as I am aware, $\omega$ is a $\mathfrak{g}$ valued one form, so shouldn't $\omega(hY)$ and $\omega(hX)$ be considered as either left-invariant vector fields on $G$ or equivalently some vectors in $T_e G$. Either way, I don't know how to interpret $(hX)\omega(hY)$ since $hX$ is a vector field also? It's as if two vector fields are being 'multiplied'?
Obviously I am missing something crucial here and any help would be much appreciated.
Thanks!

A: Since $\omega$ is a vector-valued form, the exterior derivative is taken componentwise - see e.g. here. Thus $hX \omega(hY)$ denotes the componentwise directional derivative of the $\mathfrak g$-valued function $\omega(hY)$ - i.e. after fixing a basis $e_i$ with dual basis $\theta^i$ for $\mathfrak g$, $$hX \omega(hY) = \sum_i hX (\theta^i(\omega(hY))) e_i$$
where $hX$ is now acting naturally as a directional derivative on functions.


text:
Q: I'm trying to have a hide series button on my highchart but it makes the chart disappear When I click on my button the series briefly disappears then the screen appears to refresh then the whole chart disappears, am I missing something simple.  Please see the code below

the part where i display my chart on the screen using a master page
<button id="button" class="autocompare">Hide series</button>

A: I was obviously having a bad day last week.  The reason it was disappearing was due to postback on a control I am using to select a date.
Once I click the show/hide button, the button posts back and causes the screen to refresh.


text:
Q: Flickering MapOverlay after zoom out and zoom in-iOS I have two questions. First of all, once I allocate memory for the coordinates please see the code below, do I have to free memory free(coords)? Second, as you seen below code, I get overlay and add on the map. However, there is a different timestamps feeds coordinates and should update map. Like a radar map changing overlay shape with different time stamps.It is updating very well initially; however, once user zoom out and zoom in, it starts flashing or flickering. I wonder why this flickering happens? Anybody has experienced that problem before?
NSArray *ants = [mapView overlays];
for(bb = 0; bb < [polygonArray count]; bb++){
        int attr=[[idArray objectAtIndex:bb]floatValue];

        coords = malloc(sizeof(CLLocationCoordinate2D) * [[polygonArray objectAtIndex:bb] count]);
        for (int a = 0;a < [[polygonArray objectAtIndex:bb] count]; a++){
            coords[a].latitude = [[[[polygonArray objectAtIndex:bb]objectAtIndex:a]objectAtIndex:0]doubleValue];
            coords[a].longitude = [[[[polygonArray objectAtIndex:bb]objectAtIndex:a]objectAtIndex:1]doubleValue];
        }
        polygon = [[MKPolygon alloc]init];
        polygon = [MKPolygon polygonWithCoordinates:coords count:[[polygonArray objectAtIndex:bb]count]];
        //free(coords);
        [previousPolygons addObject:polygon];

            }
        [mapView addOverlay:polygon];
        }

    }
[mapView removeOverlays:ants];

A: Download Apples

BreadCrumbs Demo

App.
Using this Demo you see the recommended technic to do your task.
I have used that Demo in my App, and it worked like a charm.
The approach with MkPolygon does not work fine withn big polygons, or changing Polygons.

A: I have tested BreadCrumbs Demo on iOS 6.1 (iPad 3) and it flicker. It's a bug of the new MKMapView (sad). I have submitted the bug to Apple.


text:
Q: Disable both IPv4 and IPv6 on a specific interface Using Ubuntu 21.10, SoftEther docs recommend disabling IPv4 and IPv6 on one of the two Ethernet interfaces used for the local bridge network adapter.
Here's my /etc/netplan/01-network-manager-all.yaml...
network:
  version: 2
  renderer: NetworkManager
  ethernets:
    lan:
      match:
        macaddress: a8:20:XX:XX:9f:da
      dhcp4: false
      dhcp6: true
      addresses:
        - 192.168.1.3/24
      routes:
        - to: default
          via: 192.168.1.1
          metric: 100
      nameservers:
        addresses: [192.168.1.1]
        search: []
      set-name: lan
    softether:
      match:
        macaddress: 40:6c:XX:XX:4a:93
      dhcp4: false
      dhcp6: false
      link-local: []
      optional: true
      set-name: softether

then ran sudo netplan generate then sudo netplan apply. As you can see, I renamed the interface for the local bridge to softether.
Also added this to the end of /etc/sysctl.d/99-sysctl.conf
net.ipv6.conf.softether.disable_ipv6 = 1

then ran sudo sysctl -p.
After rebooting, I am still seeing an IPv4 and IPv6 addresses on softether when running ip a...
2: softether: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 40:6c:XX:XX:4a:93 brd ff:ff:ff:ff:ff:ff
    altname enp9s0
    inet 169.254.65.216/16 brd 169.254.255.255 scope link noprefixroute softether
       valid_lft forever preferred_lft forever
    inet6 fd8b:a698:e8f4:3:426c:8fff:fe35:4a93/64 scope global deprecated dynamic mngtmpaddr
       valid_lft 769sec preferred_lft 0sec
    inet6 fd97:65c2:6883:1:426c:8fff:fe35:4a93/64 scope global dynamic mngtmpaddr
       valid_lft 1785sec preferred_lft 1785sec
    inet6 fda2:db11:4cad:2:426c:8fff:fe35:4a93/64 scope global deprecated dynamic mngtmpaddr
       valid_lft 769sec preferred_lft 0sec
    inet6 fdaa:ed5f:f69b:4:426c:8fff:fe35:4a93/64 scope global deprecated dynamic mngtmpaddr
       valid_lft 770sec preferred_lft 0sec
    inet6 fe80::426c:8fff:fe35:4a93/64 scope link
       valid_lft forever preferred_lft forever

The Netplan docs show these examples...
Example to enable only IPv4 link-local: link-local: [ ipv4 ]
Example to enable all link-local addresses: link-local: [ ipv4, ipv6 ]
Example to disable all link-local addresses: link-local: [ ]

So I thought using the last one would give me what I wanted (but it didn't).
Any thoughts about what I'm doing wrong?

A: Looks like the issue was the Netplan renderer of NetworkManager. After switching to networkd, I got the results I was looking for:
2: softether: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 40:6c:XX:XX:4a:93 brd ff:ff:ff:ff:ff:ff
    altname enp9s0

Here's my new /etc/netplan/01-network-manager-all.yaml:
network:
  version: 2
  renderer: networkd
  ethernets:
    lan:
      match:
        macaddress: a8:20:XX:XX:9f:da
      dhcp6: true
      addresses:
        - 192.168.1.3/24
      routes:
        - to: default
          via: 192.168.1.1
          metric: 100
      nameservers:
        addresses: [192.168.1.1]
        search: []
      set-name: lan
    softether:
      match:
        macaddress: 40:6c:XX:XX:4a:93
      optional: true
      # optional-addresses: []
      link-local: []
      set-name: softether
  wifis:
    wlp2s0:
#     match:
#       macaddress: 88:53:XX:XX:f0:75
      dhcp4: yes
      dhcp6: yes
      access-points:
        "Some SSID":
          password: "SOME PASSWORD"
#     set-name: wifi

Unfortunately, I can no longer rename the WiFi interface like I could with NetworkManager as networkd's wifis don't support match.


text:
Q: Como obter uma lista dos valores comuns a duas listas com LINQ? Tenho duas List,
a primeira, que é uma lista que contém todos os estabelecimentos disponíveis na empresa, por exemplo:

Estabelecimento

Sigla - XPTO
Descricao - XPTO List

Estabelecimento

Sigla - RPTO
Descricao - RPTO List

Estabelecimento

Sigla - GTOR
Descricao - GTOR List

A segunda possuí os estabelecimentos que eu posso ter acesso, que neste caso é apenas :

Estabelecimento

Sigla - XPTO
Descricao - XPTO List

Preciso manter na primeira list apenas os estabelecimentos que eu possuo na segunda.
Return da primeira lista seria :

Estabelecimento

Sigla - XPTO
Descricao - XPTO List

Seria a comparação da primeira com a segunda, removendo da primeiro o que eu não tenho na segunda.

A: Julgo que o que pretende é a intercessão entre as duas listas
Use o método Intersect(). Ele retorna um IEnumerable com os elementos que existem simultâneamente em ambas as listas
lista1 = list1.Intersect(list2).ToList();

A classe Estabelecimento deve prover a sua implementação dos métodos GetHashCode() e Equals().
Ou use um "comparador de Estabelecimentos" que implemente a interface  IEqualityComparer<T>
lista1 = list1.Intersect(list2, new EstabelecimentosComparador()).ToList();

A: Se são duas listas com o mesmo tipo de objeto, não seria só você atribuir a lista2 à lista1 não?
todosEstabelecimentos = estabelecimentosComAcesso;


text:
Q: What's so bad about ref parameters? I'm faced with a situation that I think can only be solved by using a ref parameter. However, this will mean changing a method to always accept a ref parameter when I only need the functionality provided by a ref parameter 5% of the time.
This makes me think "whoa, crazy, must find another way". Am I being stupid? What sort of problems can be caused by a ref parameter?
Edit
Further details were requested, I don't think they are entirely relevant to what I was asking but here we go.
I'm wanting to either save a new instance (which will update with the ID which may later be used) or retrieve an existing instance that matches some logic and update that, save it then change the reference of the new instance to point to the existing one.
Code may make it clearer:
protected override void BeforeSave(Log entity)
{
    var newLog = entity;

    var existingLog = (from log in repository.All()
                           where log.Stuff == newLog.Stuff
                                 && log.Id != newLog.Id
                           select log).SingleOrDefault();

    if (existingLog != null)
    {
        // update the time
        existingLog.SomeValue = entity.SomeValue;
        // remove the reference to the new entity
        entity = existingLog;
    }
}

// called from base class which usually does nothing before save
public void Save(TEntity entity)
{
    var report = validator.Validate(entity);

    if (report.ValidationPassed)
    {
        BeforeSave(entity);
        repository.Save(entity);
    }
    else
    {
        throw new ValidationException { Report = report };
    }
}

It's the fact that I would be adding it in only for one child (so far) of the base class that prevents me using an overload (due to the fact I would have to duplicate the Save method). I also have the problem whereby I need to force them to use the ref version in this instance otherwise things won't work as expected.

A: If you take the .NET Framework as a barometer of people's expectations of an API, consider that almost all of the String methods return the modified value, but leave the passed argument unchanged. String.Trim(), for instance, returns the trimmed String - it doesn't trim the String that was passed in as an argument.
Now, obviously, this is only feasible if you're willing to put return-values into your API. Also, if your function already returns a value, you run into the nasty possibility of creating a custom structure that contains your original return value as well as the newly changed object.
Ultimately, it's up to you and how you document your API. I've found in my experience though that my fellow programmers tend to expect my functions to act "like the .NET Framework functions". :)

A: A ref parameter won't cause problems per se.  It's a documented feature of the language.
However it could cause social problems.  Specifically, clients of your API might not expect a ref parameter simply because it's rare.  You might modify a reference that the client doesn't expect.
Of course you can argue that this is the client's fault for not reading your API spec, and that would be true.  But sometimes it's best to reduce surprise.  Writing good code isn't just about following the rules and documenting stuff, it's also about making something naturally obvious to a human user.

A: Can you add an overload? Have one signature without the ref parameter, and one with it.
Ref parameters can be useful, and I'm glad they exist in C#, but they shouldn't be used without thought. Often if a method is effectively returning two values, it would be better either to split the method into two parts, or encapsulate both values in a single type. Neither of these covers every case though - there are definitely times when ref is the best option.

A: An overload won't kill your application or its design. As long as the intent is clearly documented, it should be okay.
One thing that might be considered is mitigating your fears about the ref parameter through a different type of parameter. For example, consider this:
public class SaveArgs
{
   public SaveArgs(TEntity value) { this.Value = value; }

   public TEntity Value { get; private set;}
   public int NewId { get; internal set; }
   public bool NewIdGenerated { get; internal set; }
}

In your code, you simply pass a SaveArgs rather than the TEntity, so that you can modify its properties with more meaningful information. (Naturally, it'd be a better-designed class than what I have above.) But then you wouldn't have to worry about vague method interfaces, and you could return as much data as you needed to in a verbose class.
Just a thought.
EDIT: Fixed the code. My bad.

A: Perhaps use an overloaded function for this 5% case and leave the other function as is.
Unnecessary ref parameters can lead to bad design patterns, but if you have a specific need, there's no problem with doing this.

A: There is nothing wrong with using ref parameters that I can think of, in fact they can be very handy sometimes.  I think they sometimes get a bad rap due to debugging since the value of the variable can change in the code logic and can sometimes be hard to track.  It also makes things difficult when converting to things like WebServices where a "value" only pass will suffice.

A: The biggest issue I have with ref parameters is they make it difficult to use type inference as you must sometimes explicitly declare the type of the variable being used as the ref parameter.
Most of the time I use a ref parameter it's in a TryGet scenario.  In general I've stopped using ref's in that scenario and instead opted for using a more functional style method by way of an option.
For instance.  TryGetValue in dictionary switches from
bool TryGetValue(TKey key, out TValue value)

To
Option<Value> TryGetValue(TKey key)

Option available here: http://blogs.msdn.com/jaredpar/archive/2008/10/08/functional-c-providing-an-option-part-2.aspx

A: The most common use I've seen for ref parameters is as a way of returning multiple values. If that's the case, you should consider creating a class or struct that returns all the values as one object.
If you still want to use a ref but want to make it optional, add a function overload.

A: ref is just a tool. You should think: What is the best design pattern for what I am building?

*

*Sometimes will be better to use an overloaded method.

*Others will be better to return a custom type or a tuple.

*Others will be better to use a global variable.

*And others ref will be the right decision.

A: If your method only needs this ref parameter 5% of the time perhaps you need to break this method down. Of course without more details its hard to say but this to me smells like a case of violating single responsability principal. Perhaps overloading it will help.
As for your question there is no issue in my opinion passing a parameter as a reference although it is not a common thing to run into.

A: This is one of those things that F# or other functional programming languages solve a lot better with returning Tuple values.  Its a lot more cleaner and terse syntax.  In the book I am reading on F#, it actually points out the C# equivelant of using ref as doing the same thing in C# to return multiple parameters.
I have no idea if it is a bad practice or there is some underlying "booga booga" about ref parameters, to me they just feel as not clean syntax.

A: A void-returning function with a single reference parameter certainly looks funny to me.  If I were reviewing this code, I'd suggest refactoring the BeforeSave() to include the call to Repository.Save() - renaming it, obviously.  Why not just have one method that takes your possibly-new entity and guarantees that everything is saved properly?  The caller doesn't do anything with the returned entity anyway.


text:
Q: Implement abstract class with constrained generic in Kotlin Working on Kotlin 1.3.61
Having this code:
abstract class ResourceObserver<T> : Observer<T> where T : Resource<T> {
    override fun onChanged(t: T) {
        when (t.status) {
            Status.LOADING -> { ... }
            Status.ERROR -> { ... }
            Status.SUCCESS -> { onSuccess(t.data) }
        }
    }

    abstract fun onSuccess(data: T?)
}

and trying to implement it
private val foo = object : ResourceObserver<Resource<Bar>> {
    override fun onSuccess(data: Bar?) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

Compiler (Android Studio in this case) gives me this error:
Type argument is not within its bounds.
Expected: Resource<Resource<Bar>>
Found: Resource<Bar>

What is wrong with my obviously erroneous code?

A: The constraint where T : Resource<T> indeed requires that whatever type argument you use for T must also be Resource<T> (with T substituted by the type itself).
According to this constraint, the type argument that you provide for the implementation T := Resource<Bar> is checked for being Resource<T> ≡ Resource<Resource<Bar>> and fails this check.
For this constraint and the subtype to work, Bar would need to be a subtype (implementation) of Resource<Bar>.
Do you really need T to be a Reosurce<T> with the same T? Will it solve your problem if you use an upper bound with a star-projection T : Resource<*> or add another type parameter, as shown below?
abstract class ResourceObserver<T, R> : Observer<T> where T : Resource<R> { ... }

private val foo = object : ResourceObserver<Resource<Bar>, Bar> { ... }

A: This looks like an attempt to use F-bounded polymorphism. For it to work you need to

*

*make Bar extend Resource<Bar>;

*make private val foo = object : ResourceObserver<Bar> { ... } instead of <Resource<Bar>>.
Usually Resource itself will be declared with the similar constraint
class Resource<T : Resource<T>>

so if you forget to do 1 Bar won't compile.


text:
Q: Shortcut to open table schema in new tab by clicking on table name in BigQuery editor I have the following in the BigQuery editor:
SELECT *
FROM `project.dataset.table`

I remember there used to be a shortcut similar to CMD+CLICK on the table name that would open the properties of table in a new tab showing the table schema, details and preview.
Is it gone or how do you do it?
EDIT:
Apparently the feature works again once you "DISABLE EDITOR TABS" at the top of the BigQuery console. Looks like this is a missing feature when editor tabs are enabled.
EDIT2:
Looks like the feature is working again also when editor tabs are enabled.

A: Try to enclose your table with using `` and then use CMD + CLICK.
You can refer to this GCP documentation for the complete list of keyboard shortcuts in Bigquery:  https://cloud.google.com/bigquery/docs/bigquery-web-ui#keyboard_shortcuts

A: Apparently the feature works again once you "DISABLE EDITOR TABS" at the top of the BigQuery console. Looks like this is a missing feature when editor tabs are enabled.


text:
Q: how to Pass the elements in a structure to an unamed pipe? #include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

struct msg
{
    int pid;
    int giffs;
    int curr;
};

main()
{
    struct msg send = {1, 2, 3};
    int p[2], pid, i;
    char inbuff[sizeof(send)];
    char *q;
    pipe(p);
    pid = fork();
    if(pid > 0)
    {
         write(p[1], (char *)&send, sizeof(send));
         printf("%ld \n", sizeof(send));
    }
    else
    {
         read(p[0], inbuff, sizeof(send));
         printf("%s\n", inbuff);
    }
}

The problem is the elements in the structure are not appearing at the read end,
could anyone please check on this. we can pass a string to a pipe, but I need to pass the bunch of integers to the pipe.

A: The bytes get read at the receiving end, but you try to print binary data as a string.
Treat the read bytes as struct msg instead:
else
{
     struct msg received;
     read(p[0], &received, sizeof(received));
     printf("%d, %d, %d\n", received.pid, received.giffs, received.curr);
}

A: #include <stdio.h>
#include <unistd.h>
 #include <fcntl.h>
struct msg {
    int pid;
        int giffs;
        int curr;
};

main()
{

    struct msg send = {1, 2, 3};
    int p[2], pid, i;
    int *inbuff;
    char *q;
    pipe(p);
    pid= fork();
    if(pid > 0) {
            write(p[1], (char *)&send, sizeof(send));
            printf("%ld \n", sizeof(send));
            sleep(1);
    } else {
        read(p[0],(char *) inbuff, sizeof(send));
    for (i=0;i<sizeof(send)/sizeof(int);i++){
            printf("%d\n", *inbuff++);
    }
    }
 }

try this code..........
here make sure you use waitpid() instead of sleep so that parent process waits for child procees to terminate or else you will get inappropriate response...........


text:
Q: Can we approximate any eigenvalue of an infinite matrix via eigenvalues of some sequence of submatrices which approximates the matrix? Let $T:\ell^2\to\ell^2$ be a compact linear operator. Let $[T]=(a_{i,j})_{i,j=1}^{\infty}$ be the representing infinite matrix of $T$ with respect to the canonical base. Let $T_n$ be the finite rank operator defined by the matrix $(a_{i,j})_{i,j=1}^{n}$ embedded into an infinite matrix. Thus $T_n\to T$ in norm.
Can we approximate the eigenvalues of $T$ with eigenvalues of $T_n$? or more specifically, given $\lambda$ an eigenvalue of $T$, is there a sequence $(\lambda_n)$ such that $\lambda_n$ is an eigenvalue of $T_n$ and $\lambda_n\to\lambda$?  Any recommended reference?


text:
Q: In Read uncommitted transaction, select statement hold S lock I changed my select statement transaction to read uncommitted but still it holds shared lock and get involved in deadlock with another update statement,
Select statements are in whatsnew(uid,friend_news_id,actor_news_id) SP
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ;

 set @actor_news_limit = 2;
 set @player_news_limit = 6;

if (select
    n.id

from
    news n
inner join
    news_user_xrf nu
on
    n.id = nu.news_id
inner join
    friends f
 on
    nu.user_id = f.friend_id
 inner join
    user u
 on
    u.id = f.friend_id
 where
    f.user_id = uid
 and
    n.id > friend_news_id
 order by
    n.points desc,n.newsDate desc
 limit 0,1) is null

then

select * from
(select
    n.id,
    'whatshot_friendsnews' as type,
    n.content,
    '0' as actor_id,
    u.id as player_id,
    n.newsType,
    n.like_text,
    n.link,
    n.newsDate,
    u.imgurl,
    u.firstname,
    u.lastname,
    n.points
from
    news n
inner join
    news_user_xrf nu
on
    n.id = nu.news_id

 inner join
    user u
 on
    u.id = nu.user_id

 where
    u.id <> uid

 and
    n.id > friend_news_id
 order by
    n.newsDate desc
 limit 0,3) a order by newsDate;

else

select * from
(select
    n.id,
    'whatshot_friendsnews' as type,
    n.content,
    '0' as actor_id,
    u.id as player_id,
    n.newsType,
    n.like_text,
    n.link,
    n.newsDate,
    u.imgurl,
    u.firstname,
    u.lastname,
    n.points
from
    news n
inner join
    news_user_xrf nu
on
    n.id = nu.news_id
inner join
    friends f
 on
    nu.user_id = f.friend_id
 inner join
    user u
 on
    u.id = f.friend_id
 where
    f.user_id = uid
 and
    n.id > friend_news_id
 order by
    n.points desc,n.newsDate desc
 limit 0,3) a order by newsDate;

end if;

select * from
(select
    n.id,
    'whatshot_actornews' as type,
    n.content,
    na.actor_id,
    "0" as player_id,
    n.newsType,
    n.like_text,
    n.link,
    n.newsDate,
    n.newsImg as imgurl,
    '' as firstname,
    ''  as lastname,
    n.points

from
    news n
inner join
    news_actor_xrf na
on
    n.id = na.news_id
where
    newsType = 2
and
    n.id > actor_news_id
order by
    points desc,
    newsDate desc
limit
    0,3
)  a order by newsDate;

COMMIT ;

END

now i have another update statement where i update same table and this statement wait for X lock but it cannot have it as the whatsnew sp holds S lock on the same table,
    below is Update sp
set SQL_SAFE_UPDATES=0;

update user
set networth = (select sum(p.avgcostprice * p.quantity)
from portfolio p where p.user_id = user.id) +
(select truncate(sum((a.currentvalue - p.avgcostprice)*p.quantity),2)
from actor a inner join portfolio p on a.id = p.actor_id where p.user_id = user.id) +
user.balance;

update user u
  set u.rank = (select count(*) from friends f
 where ifnull(friend_networth,0) > user_networth
and f.user_id = u.id) + 1;

update user u
set u.rank_text = (select concat(u.rank,'/',(select
count(*)+1 from friends f where f.user_id = u.id)));

Now both of these stored procedure gets involved in deadlock, but question is even when i am using read uncommitted why select statement
 holds Shared lock on the rows, it should read( dirty read) from the
 table. here is SHOW ENGINE INNODB STATUS output
=====================================
2014-07-06 03:44:57 2ad677681700 INNODB MONITOR OUTPUT
=====================================
Per second averages calculated from the last 2 seconds
-----------------
BACKGROUND THREAD
-----------------
srv_master_thread loops: 32811 srv_active, 0 srv_shutdown, 89228 srv_idle
srv_master_thread log flush and writes: 122039
----------
SEMAPHORES
----------
OS WAIT ARRAY INFO: reservation count 22814
OS WAIT ARRAY INFO: signal count 21778
Mutex spin waits 6627, rounds 508985, OS waits 15885
RW-shared spins 5876, rounds 176305, OS waits 5659
RW-excl spins 44, rounds 38079, OS waits 1237
Spin rounds per wait: 76.80 mutex, 30.00 RW-shared, 865.43 RW-excl
------------------------
LATEST DETECTED DEADLOCK
------------------------
2014-07-06 02:01:41 2ad677681700
*** (1) TRANSACTION:
TRANSACTION 1925770, ACTIVE 0 sec fetching rows
mysql tables in use 2, locked 2
LOCK WAIT 25 lock struct(s), heap size 3112, 909 row lock(s)
MySQL thread id 28709, OS thread handle 0x2ad677640700, query id 349542 ec2-54-226-145-7.compute-1.amazonaws.com 54.227.116.3 Database1 Searching rows for update
update user u
set u.rank_text = (select concat(u.rank,''/'',(select
count(*)+1 from friends f where f.user_id = u.id)))
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 19303 page no 29 n bits 104 index `PRIMARY` of table `Database1`.`user` trx id 1925770 lock_mode X waiting
Record lock, heap no 31 PHYSICAL RECORD: n_fields 25; compact format; info bits 0
 0: len 8; hex 8000000000000416; asc         ;;
 1: len 6; hex 0000001d214a; asc     !J;;
 2: len 7; hex 6f0000018d08f9; asc o      ;;
 3: len 8; hex 80005af4001478e8; asc   Z   x ;;
 4: len 5; hex 5269736869; asc Rishi;;
 5: len 5; hex 506174656c; asc Patel;;
 6: len 23; hex 7269736869706174656c5f3939407961686f6f2e636f6d; asc rishi_9999@yahoo.com;;
 7: len 30; hex 43414146336348376866544942414a434844466b5a42664937544a554643; asc CAAF3cH7hfTIBAJCHDFkZBfI7TJUFC; (total 201 bytes);
 8: len 8; hex 800000005405f359; asc     T  Y;;
 9: len 9; hex 80000000000007d619; asc          ;;
 10: len 1; hex 01; asc  ;;
 11: len 30; hex 313034383539303739377c3130303030303937303735313938317c313030; asc 1048590797|100000970751981|100; (total 58 bytes);
 12: len 30; hex 68747470733a2f2f67726170682e66616365626f6f6b2e636f6d2f313030; asc https://graph.facebook.com/100; (total 50 bytes);
 13: SQL NULL;
 14: len 4; hex 80000002; asc     ;;
 15: len 4; hex 466f4145; asc FoAE;;
 16: SQL NULL;
 17: len 4; hex 00000000; asc     ;;
 18: len 3; hex 322f35; asc 2/5;;
 19: SQL NULL;
 20: len 8; hex 8000000000000007; asc         ;;
 21: len 4; hex 05c58045; asc    E;;
 22: SQL NULL;
 23: len 8; hex 8000000000000000; asc         ;;
 24: len 8; hex 8000000000000007; asc         ;;

*** (2) TRANSACTION:
TRANSACTION 1925761, ACTIVE 22 sec starting index read
mysql tables in use 4, locked 4
14 lock struct(s), heap size 3112, 4 row lock(s)
MySQL thread id 28723, OS thread handle 0x2ad677681700, query id 349517 ec2-54-91-34-208.compute-1.amazonaws.com 54.91.34.208 Database1 Sending data
call whatsnew(uid,friend_news_id,actor_news_id)
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 19303 page no 29 n bits 104 index `PRIMARY` of table `Database1`.`user` trx id 1925761 lock mode S locks rec but not gap
Record lock, heap no 31 PHYSICAL RECORD: n_fields 25; compact format; info bits 0
 0: len 8; hex 8000000000000416; asc         ;;
 1: len 6; hex 0000001d214a; asc     !J;;
 2: len 7; hex 6f0000018d08f9; asc o      ;;
 3: len 8; hex 80005af4001478e8; asc   Z   x ;;
 4: len 5; hex 5269736869; asc Rishi;;
 5: len 5; hex 506174656c; asc Patel;;
 6: len 23; hex 7269736869706174656c5f3939407961686f6f2e636f6d; asc rishi_9999@yahoo.com;;
 7: len 30; hex 43414146336348376866544942414a434844466b5a42664937544a554643; asc CAAF3cH7hfTIBAJCHDFkZBfI7TJUFC; (total 201 bytes);
 8: len 8; hex 800000005405f359; asc     T  Y;;
 9: len 9; hex 80000000000007d619; asc          ;;
 10: len 1; hex 01; asc  ;;
 11: len 30; hex 313034383539303739377c3130303030303937303735313938317c313030; asc 1048590797|100000970751981|100; (total 58 bytes);
 12: len 30; hex 68747470733a2f2f67726170682e66616365626f6f6b2e636f6d2f313030; asc https://graph.facebook.com/100; (total 50 bytes);
 13: SQL NULL;
 14: len 4; hex 80000002; asc     ;;
 15: len 4; hex 466f4145; asc FoAE;;
 16: SQL NULL;
 17: len 4; hex 00000000; asc     ;;
 18: len 3; hex 322f35; asc 2/5;;
 19: SQL NULL;
 20: len 8; hex 8000000000000007; asc         ;;
 21: len 4; hex 05c58045; asc    E;;
 22: SQL NULL;
 23: len 8; hex 8000000000000000; asc         ;;
 24: len 8; hex 8000000000000007; asc         ;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 19303 page no 29 n bits 104 index `PRIMARY` of table `Database1`.`user` trx id 1925761 lock mode S locks rec but not gap waiting
Record lock, heap no 26 PHYSICAL RECORD: n_fields 25; compact format; info bits 0
 0: len 8; hex 800000000000040b; asc         ;;
 1: len 6; hex 0000001d214a; asc     !J;;
 2: len 7; hex 6f0000018d0878; asc o     x;;
 3: len 8; hex 80005af401790e35; asc   Z  y 5;;
 4: len 3; hex 52616a; asc Raj;;
 5: len 5; hex 506174656c; asc Patel;;
 6: len 22; hex 706174656c3039303972616a407961686f6f2e636f6d; asc patel@yahoo.com;;
 7: len 30; hex 434141463363483768665449424145726535315545495475473766556652; asc CAAF3cH7hfTIBAEre51UEITuG7fUfR; (total 199 bytes);
 8: len 8; hex 8000000054060653; asc     T  S;;
 9: len 9; hex 800000000000098440; asc         @;;
 10: len 1; hex 01; asc  ;;
 11: len 30; hex 313034383539303739377c313432343530303835307c3130303030303937; asc 1048590797|1424500850|10000097; (total 85 bytes);
 12: len 30; hex 68747470733a2f2f67726170682e66616365626f6f6b2e636f6d2f313030; asc graph.facebook.com/10000; (total 50 bytes);
 13: SQL NULL;
 14: len 4; hex 80000001; asc     ;;
 15: SQL NULL;
 16: SQL NULL;
 17: len 4; hex 00000000; asc     ;;
 18: len 3; hex 312f37; asc 1/7;;
 19: len 4; hex 00000000; asc     ;;
 20: len 8; hex 8000000000000018; asc         ;;
 21: len 4; hex 6bdb7e45; asc k ~E;;
 22: SQL NULL;
 23: len 8; hex 8000000000000000; asc         ;;
 24: len 8; hex 8000000000000018; asc         ;;

*** WE ROLL BACK TRANSACTION (2)
------------
TRANSACTIONS
------------
Trx id counter 1929046
Purge done for trx''s n:o < 1929045 undo n:o < 0 state: running but idle
History list length 1711
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0, not started
MySQL thread id 28864, OS thread handle 0x2ad677681700, query id 357530 122.169.237.65 Database1 init
SHOW ENGINE INNODB STATUS
---TRANSACTION 1929043, not started
MySQL thread id 28863, OS thread handle 0x2ad677640700, query id 357529 ec2-54-226-145-7.compute-1.amazonaws.com 54.227.116.3 Database1 creating table
create table temp_ceiling (actor_id int, p_change float, cval float, fval float)
---TRANSACTION 1929042, not started
MySQL thread id 28859, OS thread handle 0x2ad675ee3700, query id 357510 localhost 127.0.0.1 rdsadmin cleaning up
---TRANSACTION 1929045, ACTIVE 0 sec committing foreign key definitions
5 lock struct(s), heap size 1248, 0 row lock(s), undo log entries 8
MySQL thread id 28863, OS thread handle 0x2ad677640700, query id 357529 ec2-54-226-145-7.compute-1.amazonaws.com 54.227.116.3 Database1 creating table
create table temp_ceiling (actor_id int, p_change float, cval float, fval float)
TABLE LOCK table `SYS_TABLES` trx id 1929045 lock mode IX
TABLE LOCK table `SYS_COLUMNS` trx id 1929045 lock mode IX
TABLE LOCK table `SYS_TABLESPACES` trx id 1929045 lock mode IX
TABLE LOCK table `SYS_DATAFILES` trx id 1929045 lock mode IX
TABLE LOCK table `SYS_INDEXES` trx id 1929045 lock mode IX
--------
FILE I/O
--------
I/O thread 0 state: waiting for completed aio requests (insert buffer thread)
I/O thread 1 state: waiting for completed aio requests (log thread)
I/O thread 2 state: waiting for completed aio requests (read thread)
I/O thread 3 state: waiting for completed aio requests (read thread)
I/O thread 4 state: waiting for completed aio requests (read thread)
I/O thread 5 state: waiting for completed aio requests (read thread)
I/O thread 6 state: waiting for completed aio requests (write thread)
I/O thread 7 state: waiting for completed aio requests (write thread)
I/O thread 8 state: waiting for completed aio requests (write thread)
I/O thread 9 state: waiting for completed aio requests (write thread)
Pending normal aio reads: 0 [0, 0, 0, 0] , aio writes: 0 [0, 0, 0, 0] ,
 ibuf aio reads: 0, log i/o''s: 0, sync i/o''s: 0
Pending flushes (fsync) log: 0; buffer pool: 0
946 OS file reads, 122080 OS file writes, 61052 OS fsyncs
0.00 reads/s, 0 avg bytes/read, 4000.00 writes/s, 5000.00 fsyncs/s
-------------------------------------
INSERT BUFFER AND ADAPTIVE HASH INDEX
-------------------------------------
Ibuf: size 1, free list len 0, seg size 2, 0 merges
merged operations:
 insert 0, delete mark 0, delete 0
discarded operations:
 insert 0, delete mark 0, delete 0
Hash table size 612301, node heap has 33 buffer(s)
0.00 hash searches/s, 5.00 non-hash searches/s
---
LOG
---
Log sequence number 502059361
Log flushed up to   502055320
Pages flushed up to 502053286
Last checkpoint at  502053286
0 pending log writes, 0 pending chkp writes
39359 log i/o''s done, 1.00 log i/o''s/second
----------------------
BUFFER POOL AND MEMORY
----------------------
Total memory allocated 316588032; in additional pool allocated 0
Dictionary memory allocated 269802
Buffer pool size   18880
Free buffers       11148
Database pages     7699
Old database pages 2822
Modified db pages  16
Pending reads 0
Pending writes: LRU 0, flush list 0, single page 0
Pages made young 0, not young 0
0.00 youngs/s, 0.00 non-youngs/s
Pages read 886, created 6813, written 73085
0.00 reads/s, 4000.00 creates/s, 0.00 writes/s
Buffer pool hit rate 1000 / 1000, young-making rate 0 / 1000 not 0 / 1000
Pages read ahead 0.00/s, evicted without access 0.00/s, Random read ahead 0.00/s
LRU len: 7699, unzip_LRU len: 0
I/O sum[0]:cur[1], unzip sum[0]:cur[0]
--------------
ROW OPERATIONS
--------------
0 queries inside InnoDB, 0 queries in queue
0 read views open inside InnoDB
Main thread process no. 18631, id 47100585178880, state: sleeping
Number of rows inserted 43271, updated 151830, deleted 2009, read 7297650700
0.00 inserts/s, 14.49 updates/s, 0.00 deletes/s, 167000.00 reads/s
----------------------------
END OF INNODB MONITOR OUTPUT
============================
'

please help


text:
Q: Adding audio to click event I want to add a sound clip to a button on a game I am creating. Currently It doesn't do anything and I don't know why.
At the moment In the script I have...
var audio = $(".mysoundclip")[0];
$(".minibutton").onclick(function() {
    audio.play();
});

In the HTML I have...
<audio id="mysoundclip" preload="auto">
    <source src="http://www.wav-sounds.com/cartoon/bugsbunny1.wav"></source>
</audio>

Then I have CSS for .minibutton.
Any ideas why it won't work?

A: Your jQuery had some simple errors in it.
HTML
<audio id="mysoundclip" preload="auto">
    <source src="http://www.wav-sounds.com/cartoon/bugsbunny1.wav"></source>
</audio>
<button type="button">play</button>

jQuery
var audio = $("#mysoundclip")[0];
$("button").click(function() {
    audio.play();
});

Fiddle: http://jsfiddle.net/iambriansreed/VavyK/

A: Maybe I'm a too suspicous.. but
http://www.sound-effect.com/sounds1/animal/Saf/Tiger1.wav "The requested URL was not found on this server"
If that's just a typo, you should also try to figure out which audio types a browser is capable to play:
myApp.htmlAudio = (function _htmlAudioCheck() {
    var elem = document.createElement('audio'),
        bool = false;

    try {
        if( !!elem.canPlayType ) {
            bool = new Boolean(bool);
            bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"');
            bool.mp3 = elem.canPlayType('audio/mpeg;');

            bool.wav = elem.canPlayType('audio/wav; codecs="1"');
            bool.m4a = ( elem.canPlayType('audio/x-m4a;') ||      elem.canPlayType('audio/aac;'));
        }
    } catch(e) { }

    return bool;
}());

Now we can check like
if( myApp.htmlAudio && myApp.htmlAudio.wav ) {
}

if the browser is able to playback .wav files for instance.
However, I never saw a nested source element for audio elements. That should be named track if anything. But you don't really need that here, you can just have a src attribute on the audio element itself. Example: http://jsfiddle.net/5GUPg/1/


text:
Q: excel - Loop through worksheet I have never used Marcos in Excel before only in Access. What I want to do is loop through the worksheet and where column X and Y are not null extract the information into a new worksheet. But row Y may have more than 1 value and I would like to create a new record for each value in Y with X. each value is separated by a comma.

The result I would Like is
a      C3
a      C4
b      C6
b      C7
b      C10
And so on
Here is my code so far:
Sub Extract()
'
' Extract Macro
'
Dim WkSht As Worksheet, myOtherSheet As Worksheet, myBook As Workbook
Dim r As Integer
Dim Regex
Dim Match
Dim text
Set myBook = Excel.ActiveWorkbook
Set myOtherSheet = myBook.Sheets("New")
Set Regex = CreateObject("VBScript.RegExp")
Regex.Patten = """[^""]*""|[^,]*"
Regex.Global = True

j = 0
For Each WkSht In ThisWorkbook.Worksheets
    If WkSht.Name = "Sheet1" Then
        For r = 1 To 1000
          If WkSht.Rows(r, B).Value <> "" & WkSht.Rows(r, G).Value <> "" Then
          text = WkSht.Rows(r, G).Value
           For Each Match In Regex.Execute(text)
           myOtherSheet.Cells(j, 1).Value = WkSht.Cells(r, B)
           myOtherSheet.Cells(j, 2).Value = Match
           j = j + 1
           Next Match
           Exit For
           End If
           r = r + 1
           Next r
           Exit For
           End If
           Next WkSht

End Sub

Im unable to get this to run, I think my syntax is wrong for the regex, iv only ever used it in c#, Is this the best option for what I am trying to achieve, any help would be greatly appreciated ?

A: to fix the 1004 error, change
Rows(r, B).Value
to
Range(r, B).Value
the Rows property only takes a single index, you are trying to test a cell, so muct use either the Range or Cell object.
also to make programming with RegEx easier, add a reference to the Microsoft VBScript Regular Expressions 5.5 library:
on the Tools>References menu in the VB Editor.
Then you can declare
Dim Regex as RegExp and use Set Regex = New RegExp
This will give you Intellisense which will help you code corerctly.
For a tutorial in using Regular expressions from Excel vba, see

*

*MacroStash: Regular Expression Tutorial for Excel VBA

*Regular Expressions Website
Also, the in Tools>Options Editor tab, check all the boxes like Require Variable declaration and Auto List Members


text:
Q: Post Video on Facebook friend wall in iPhone (Graph API) I integrated Graph API in my iOS Application.Its working fine.
I Need to implement share video on fb. How can we share video in Graph API?
Please give same idea about this. Thanks in advance


text:
Q: #define and how to use them - C++ In a pre-compiled header if I do:
#define DS_BUILD
#define PGE_BUILD
#define DEMO

then in source I do:
#if (DS_BUILD && DEMO)
    ---- code---
#elif (PGE_BUILD && DEMO)
    --- code---
#else
    --- code ---
#endif

Do I get an error that states:

error: operator '&&' has no right operand

I have never seen this before. I am using XCode 3.2, GCC 4.2 on OS X 10.6.3

A: You have to decide first how you want to use your conditional compilation macros. There are normally two popular approaches. It is either
#define A
#define B

#ifdef A
...
#endif

#if defined(A) && defined(B)
...
#endif

or
#define A 1
#define B 0

#if A
...
#endif

#if A && B
...
#endif

I.e. either just define a macro and analyze it with #ifdef and/or #if defined() or define a macro for a numerical value and analyze if with #if.
You are mixing these two approaches in your code sample, which generally makes no sense. Decide which approach you want to use and stick to it.

A: The effect of #define DEMO is that during preprocessing every occurence of DEMO is replaced with nothing ( '' ). The same with #define PGE_BUILD. So, in the second sample you posted you effectively get #elif ( && ) which, you agree, doesn't make much sense for compiler:).

A: You need to add the defined keyword since you want to check that you defined have been defined.
#if defined (DS_BUILD) && defined (DEMO)
    ---- code---
#elif defined (PGE_BUILD) && defined (DEMO)
    --- code---
#else
    --- code ---
#endif

A: You need to provide values for DS_BUILD , PGE_BUILD and DEMO, or you need to use ifdef
#define DS_BUILD 1
#define PGE_BUILD 1
#define DEMO 1

defining like above would work


text:
Q: How to get the SyntaxToken.Kind in current version of Roslyn? I'm trying to update a project which makes heavy use of comparison against SyntaxToken.Kind. This property appears to have disappeared in newer versions of Roslyn and I wondered if there an alternative method or an extension method I could write to get the same functionality?
The code has many references such as:
if (expression.OperatorToken.Kind == SyntaxKind.PlusEqualsToken)

Any ideas?

A: Add a using for Microsoft.CodeAnalysis.CSharp.Syntax, and then use the CSharpKind() extension method.


text:
Q: What happens to the gas in the container in this picture when the container is tilted
So the test question asked what would happen to the gas if this container were tilted on its side. The piston shown here is 10 kg and moves frictionlessly. I said that the pressure inside the container would decrease and and the piston would move out; however the answer key said that there would be no change in pressure or in position of the piston.
My reasoning was that lets say the gas inside the container exerts an arbitrary force of 1000N upwards because of the pressure. Then lets say the 10kg exerts 100N downward, and the atmosphere exerts an arbitrary 900N downward. The system is obviously in equilibrium. However, when turned on the side, the force of gravity no longer acts right or left, so the 1000N against the 900N of atmospheric pressure will accelerate the piston right until the pressures equalize.
Personally, I thought my answer was the intuitive one. Am I right?

A: Yes you are right.
The 10kg piston acts as a force over the area of the piston, increasing the pressure and decreasing the volume of the gas inside.
When the set up is tilted, the force no longer acts on the gas, but sideways, so the pressure equalizes.


text:
Q: Test for open TCP port in bash script I want to delay the script execution until a certain server process is ready, which it is once it accepts incoming TCP connections.
How do I test if a local TCP port is open (I get a SYN/ACK answer)?

A: I would use lsof if available for this purpose. You can grep the output to check for a line of output with a LISTEN condition for the port in question. Some options may have to be passed to prevent converting port names to symbolic, etc, see man lsof for details.


text:
Q: Identify bad data in azure data explorer I have a dataset and I need to filter bad/invalid data for my compute. I tried percentile but that will filter genuine value
Eg: 1, 2,8,10,20,25,55,100,100000,98,99,95
Here, 100000 is corrupted/bad, When I call Max () function, I expect 100 instead of 100000.

A: series_outliers()
datatable(val:int)[1, 2,8,10,20,25,55,100,100000,98,99,95]
| summarize val = make_list(val)
| extend anomaly_score = series_outliers(val)
| mv-expand val to typeof(int), anomaly_score to typeof(real);
//| where anomaly_score between (-1.5 .. 1.5)

val
anomaly_score

1
-0.045592692382452886

2
-0.017097259643419842

8
0

10
0

20
0

25
0

55
0

100
0.0028495432739035469

100000
2846.6965801726751

98
0

99
0

95
0

Fiddle


text:
Q: Есть ли максимальная разница в датах допустимая в запросе? Работаю над запросом, который ищет строки в таблице, где дата last_run + frequency (в минутах), больше, чем текущая дата. Заметил, что, похоже, существует верхняя граница для сравнения дат, которую БД может понять.
Например, этот запрос:
with tests as (
    select 'TEST 1'  as code, 99999999 as frequency, sysdate as last_run
    from dual union all
    select 'TEST 2'  as code, 99999999999 as frequency, sysdate as last_run
    from dual)
select p.*, (p.last_run + p.frequency / 24 / 60) as next_run
from tests p
where (p.last_run + p.frequency / 24 / 60 < sysdate or p.last_run is null)

Ожидаю, что этот запрос ничего не вернет, но вместо этого он возвращает:

CODE
FREQUENCY
LAST_RUN
NEXT_RUN

TEST 2
99999999999
05-OCT-2021 10:15:46 AM
15-APR-4455 08:54:46 PM

Кажется странным, что БД не может распознать, что год 4455 > 2021.
Есть ли какая-то максимально возможная разница в датах, которая мне неизвестна?

Свободный перевод вопроса Is There a Maximum Date Difference Oracle Can Interpret от участника @Peter Sanders

A:
Кажется странным, что БД не может распознать, что год 4455 > 2021.

Может распознать. Дело в том, что год не 4455, а -4455. См. db<>fiddle, показывающий результат с форматом по умолчанию DD-MON-RR, с форматом как в вопросе, и форматом ISO с включенным знаком года (первая S в шаблоне формата).

CODE
FREQUENCY
LAST_RUN
NEXT_RUN

TEST 2
99999999999
2021-10-05 17:16:21
-4454-03-12 03:55:21

Значением 99.999.999.999, которое добавляется к текущей дате, составляет 69444444 дня, что приблизительно 190128 лет. Очевидно, что это значительно превышает максимальную дату 9999-12-31. И действительно, при другом значении, например 9.999.999.999 (одну цифру меньше), которое составляет 6944444 дня или приблизительно 19012 лет, будет ошибка см. db<>fiddle.
Проблема, по-видимому, заключается в том, как БД манипулирует своим внутренним представлением даты при выполнении вычислений. При добавлении большого значения, думаю, что год - который хранится в двух байтах, переполняется и начинается отсчёт заново.
Используя тип даты 13, 190128+2021 = 192149, что составляет (256 * 750) + 149. 750 не помещается в один байт, поэтому получается деление с остатком, которое равно 238. Таким образом, первые два байта вычисленной даты будут равны 149,238. Это фактически соответствует году -4459:
select dump(date '-4459-01-01') from dual;

Typ=13 Len=8: 149,238,1,1,0,0,0,0

Достаточно, чтобы убедится, что именно так и происходит учитывая, что вычисления выходят за пределы ожидаемого диапазона и, вероятно, ещё там выполняются недействительные вычисления високосного года. Суть, однако, в том, что это "развернутое" значение представляет собой действительный год во внутренней нотации.
Те же расчёты с меньшим значением 19012+2021 = 20133, что составляет (256 * 82) + 41. Теперь переполнения нет, поэтому первые два байта вычисленной даты получаются как 41,82. Теперь это не действительный год, поэтому и происходит исключение ORA-01841.
Следовательно, необходимо ограничить значение числом, которое никогда не выйдет за пределы 9999-12-31, или проверить его во время выполнения на 9999-12-31 минус текущая дата, если оно слишком большое, проигнорировать его.

Свободный перевод ответа от участника @Alex Poole


text:
Q: Entity Framework Core - Upsert entities from other database encounters tracking problems I have a flatfile from a different database. I import it and map it to my application's entities. Because the flatfile does not contain ids I cannot be sure the entries I handle are not duplicates of what has already been added to my database earlier or to my context at this moment.
The error message I get is:

The instance of entity type 'Car' cannot be tracked because another
  instance with the same key value for {'Make', 'Model'} is already
  being tracked. When attaching existing entities, ensure that only one
  entity instance with a given key value is attached. Consider using
  'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the
  conflicting key values.

An example:
Data rows from flatfile
Volvo V70 Steve
Volvo V70 John

Having mapped these rows and trying to put them in db
foreach(var row in flatFileRows){
   Car existingCar = null;

   if(dbContext.Cars.Any(c => c.Make == row.Make && c.Model == row.Model)){
      existingCar = dbContext.Cars
     .SingleOrDefault(c => c.Make == row.Make && c.Model == row.Model);
   }
   //I also do the same for existingDriver

   var car = existingCar != null
    ? existingCar
    : new Car()
    {
        Make = row.Make,
        Model = row.Model,
        Drivers = new List<Driver>();
    };

    var driver = new Driver()
    {
        CarId = existingCar != null ? exsitingCar.Id : 0,
        Name = row.Name
    };

   car.Drivers.Add(driver);

   dbContext.Cars.Update(car); //Second time we hit this the error is thrown
}
dbContext.SaveChanges();

Make and Model are set to keys in the schema because I don't want duplicate entries of the car models.
The above example is simplified.
What I want is to check if I already put a car in the db with these attributes and then build according to my schema from that entity. I don't care to track any entries, disconnected or otherwise, because I just need to populate the database.


text:
Q: Drake -- Coredump in Simulation When There is a Contact I have a Kuka arm and some objects set up in my simulation(very similar to manipulation station example), and I have been running into coredump error below whenever there is a contact between the robot and the objects.

"abort: Failure at multibody/plant/multibody_plant.cc:1640 in CalcImplicitStribeckResults(): condition 'info == ImplicitStribeckSolverResult::kSuccess' failed.
  Aborted (core dumped)"

Decreasing the integration step size for the simulator did not help, so I ended up tracing back the error and commented out the condition that is causing the error( "DRAKE_DEMAND(info == ImplicitStribeckSolverResult::kSuccess);" ), which seems to coredump a lot less often.
However, I am guessing that condition is there for a reason, so would commenting the line out cause any other issues in the simulation? What is the proper way to fix the coredump problem?

A: In Drake PR #12503, the ImplicitStribeck code was refactored to reflect the notation in the TAMSI arXiv paper, and in #12361 it was changed to provide a more helpful exception with troubleshooting tips:
https://github.com/RobotLocomotion/drake/blob/v0.15.0/multibody/plant/multibody_plant.cc#L1866-L1878
Can you try out a later version (e.g. 0.15.0), and then try out the troubleshooting instructions there? (You've already tried changing step size in the simulator, but you may want to check on the stiffness of your overall system, etc.)


text:
Q: Applying CTE for recursive queries I am trying to apply CTE and recursive queries.  The database is MariaDB 10.2 or greater.
Business rules are as follows:

*

*An account can either be a holding or a portfolio.

*A holding consists of a given amount of money.

*Holdings can be active and inactive.

*A portfolio contains zero or more accounts, and these accounts can belong to more than one portfolio.

*The total value of each account is multiplied by a "weight" factor when determining the value of a portfolio.

My schema is as follows (note char is used for id type for illustration purposes only, but I will really use int):

CREATE TABLE IF NOT EXISTS accounts (
  id CHAR(4) NOT NULL,
  name VARCHAR(45) NOT NULL,
  type ENUM('holding', 'portfolio') NULL,
  PRIMARY KEY (id))
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS holdings (
  accounts_id CHAR(4) NOT NULL,
  value DECIMAL(6,2) NOT NULL,
  active TINYINT NOT NULL,
  PRIMARY KEY (accounts_id),
  CONSTRAINT fk_holdings_accounts
    FOREIGN KEY (accounts_id)
    REFERENCES accounts (id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS portfolios (
  accounts_id CHAR(4) NOT NULL,
  PRIMARY KEY (accounts_id),
  CONSTRAINT fk_portfolios_accounts1
    FOREIGN KEY (accounts_id)
    REFERENCES accounts (id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

CREATE TABLE IF NOT EXISTS portfolios_has_accounts (
  portfolios_id CHAR(4) NOT NULL,
  accounts_id CHAR(4) NOT NULL,
  weight DECIMAL(4,2) NOT NULL,
  PRIMARY KEY (portfolios_id, accounts_id),
  INDEX fk_portfolios_has_accounts_accounts1_idx (accounts_id ASC),
  INDEX fk_portfolios_has_accounts_portfolios1_idx (portfolios_id ASC),
  CONSTRAINT fk_portfolios_has_accounts_portfolios1
    FOREIGN KEY (portfolios_id)
    REFERENCES portfolios (accounts_id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT fk_portfolios_has_accounts_accounts1
    FOREIGN KEY (accounts_id)
    REFERENCES accounts (id)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

Sample data is as follows:
INSERT INTO accounts(id,name,type) VALUES ('p1','portfolio1','portfolio'),('p2','portfolio2','portfolio'),('p3','portfolio3','portfolio'),('h1','holding1','holding'),('h2','holding2','holding'),('h3','holding3','holding'),('h4','holding4','holding');
INSERT INTO holdings(accounts_id,value,active) VALUES ('h1','50','1'),('h2','40','0'),('h3','70','1'),('h4','40','1');
INSERT INTO portfolios(accounts_id) VALUES ('p1'),('p2'),('p3');
INSERT INTO portfolios_has_accounts(portfolios_id,accounts_id,weight) VALUES ('p1','h1','1'),('p1','p2','0.5'),('p2','h2','2'),('p2','p3','1'),('p3','h3','2'),('p3','h4','0.5');

accounts
id  name        type
p1  portfolio1  portfolio
p2  portfolio2  portfolio
p3  portfolio3  portfolio
h1  holding1    holding
h2  holding2    holding
h3  holding3    holding
h4  holding4    holding

portfolios
portfolios_id
p1
p2
p3

holdings
id value active
h1  50   1
h2  40   0
h3  70   1
h4  40   1

portfolios_has_accounts
portfolios_id   accounts_id weight
p1               h1         1
p1               p2         0.5
p2               h2         2
p2               p3         1
p3               h3         2
p3               h4         0.5

My objectives are to find:

*

*Find all accounts which only contain active holdings.  Given sample data it is p3, h1, h3, and h4.  p2 is not included because it includes h2 which is not active, and p1 is not included because it includes p2.

*The total value of portfolio p1.  Given sample data, it is 170:  1*50 + 0.5*( 2*40 + 1*( 2*70 + 0.5*40 ) )

*The constants which the holdings are multiplied by to result in the total value of portfolio p1.  Given the sample data, they are the following (note that  1*h1 + 1*h2 + 1*h3 + 0.25*h4 = 170)
.
id  weight
h1  1
h2  1
h3  1
h4  .25

How can I accomplish this?

A: Please comment whether these should be done differently, or from a performance perspective, whether they have any major issues?
Objective #1
MariaDB [recursion]> WITH RECURSIVE t AS (
    ->     SELECT accounts_id FROM holdings WHERE active=0
    ->     UNION ALL
    ->     SELECT pha.portfolios_id
    ->     FROM portfolios_has_accounts pha
    ->     INNER JOIN t ON t.accounts_id=pha.accounts_id
    -> )
    -> SELECT a.* FROM accounts a
    -> LEFT OUTER JOIN t ON t.accounts_id=a.id
    -> WHERE t.accounts_id IS NULL;
+----+------------+-----------+
| id | name       | type      |
+----+------------+-----------+
| h1 | holding1   | holding   |
| h3 | holding3   | holding   |
| h4 | holding4   | holding   |
| p3 | portfolio3 | portfolio |
+----+------------+-----------+
4 rows in set (0.00 sec)

Objective #2
MariaDB [recursion]> WITH RECURSIVE t AS (
    -> SELECT pha.*, h.value
    -> FROM portfolios_has_accounts pha
    -> LEFT OUTER JOIN holdings h ON h.accounts_id=pha.accounts_id
    -> WHERE pha.portfolios_id="p1"
    -> UNION ALL
    -> SELECT pha.portfolios_id, pha.accounts_id, pha.weight*t.weight, h.value
    -> FROM t
    -> INNER JOIN portfolios_has_accounts pha ON pha.portfolios_id=t.accounts_id
    -> LEFT OUTER JOIN holdings h ON h.accounts_id=pha.accounts_id
    -> )
    -> SELECT SUM(weight*value) FROM t WHERE value IS NOT NULL;
+-------------------+
| SUM(weight*value) |
+-------------------+
| 170.0000          |
+-------------------+
1 row in set (0.00 sec)

Objective #3
MariaDB [recursion]> WITH RECURSIVE t AS (
    -> SELECT pha.*, h.value
    -> FROM portfolios_has_accounts pha
    -> LEFT OUTER JOIN holdings h ON h.accounts_id=pha.accounts_id
    -> WHERE pha.portfolios_id="p1"
    -> UNION ALL
    -> SELECT pha.portfolios_id, pha.accounts_id, pha.weight*t.weight, h.value
    -> FROM t
    -> INNER JOIN portfolios_has_accounts pha ON pha.portfolios_id=t.accounts_id
    -> LEFT OUTER JOIN holdings h ON h.accounts_id=pha.accounts_id
    -> )
    -> SELECT accounts_id, weight FROM t WHERE value IS NOT NULL;
+-------------+--------+
| accounts_id | weight |
+-------------+--------+
| h1          | 1.00   |
| h2          | 1.00   |
| h3          | 1.00   |
| h4          | 0.25   |
+-------------+--------+
4 rows in set (0.01 sec)

MariaDB [recursion]>


text:
Q: Обновление чата Те, кто шарит, помогите, плс... Хочу сделать по типу чата, но встал вопрос:
окно с сообщениями у меня выводится через iframe и обновляется через refresh каждые 2сек, но когда сидишь в нем, он мигает и это немножко накаляет, как можно избавиться от мигания (обновления) и сделать по другому... Подскажите, и если можно, с примерчиком.
A: Простой вариант: каждые несколько секунд отправляется ajax-запрос на сервер, и только если он возвращает результат «Чат обновлён» — фрейм перезагружается. Мигание всё равно будет, но не каждые две секунды, а только при появлении новых сообщений.
Сложный вариант: опять же ajax-запрос, но в ответе он приносит не просто флажок «обновился/не обновился», а полный текст новых сообщений. Этот текст добавляется в innerHTML фрейма (точнее, того его элемента, который содержит все сообщения; в простейшем случае это body). Только надо при этом отслеживать, чтобы общее число строк во фрейме не превысило разумного максимума (подсчитывать их и удалять старые сообщения, если надо).
A: Простые аякс запросы это дорогое удовольствие с точки зрения ресурсов попробуйте использовать COMET, это по сути тот же аякс, с увеличенным временем ожидания ответа сервера, то есть из-за длительного открытого соединения, данные пересылаются постоянно.
Предлагаю вам почитать о COMET подробнее


text:
Q: The number of surjection from n elemental set to n-1 elemental set. How much is count of surjection from $n$ elemental to $n-1$ elemental set ?
I have start that:
$A=\{x_1,x_2,...,x_n\}$
$B=\{y_1, y_2,...,y_n-1\}$
And number of surjection is $(n-1)^n$ ?
But I dont know how is next step.

A: For a surjection, exactly one $y_k$ must be hit twice, i.e., exactly two of the $x_i$ map to the same value. So we first pick one of $n\choose 2$ pairs from the $x_i$ and declare that they are the ones mapping to the same value. Now if we drop one element of the chosen pair, we are left with the task to find a bijection between two sets of cardinality $n-1$ each. There are $(n-1)!$ such bijections, hence the final answer is
$$ {n\choose 2}\cdot (n-1)! = \frac{n-1}{2}\cdot n!.$$

A: Hint:  $(n-1)^n$ is the total number of functions from $A$ to $B$, but not all of them are surjections.  To have a surjection, one element in $B$ must be the image of two elements in $A$ and all the other elements in $B$ must be the image of exactly one element in $A$.  One way to count the surjections is to count the ways to pick the element of $B$ that is the image of two elements of A, count the ways to pick the two elements in $A$ that go to that element, then count the ways to make a bijection among the rest of the elements.


text:
Q: jqgrid full screen switch, window width and height How would this be possible to switch between full screen and normal view?
for example: tiny mce editor has the same function.
Any ideas in js ?

A: I didn't clearly understand the question
But if you are looking for resizing jqgrid  on browser resize this might be helpful
$(window).bind('resize', function() {
    jQuery("#grid").setGridWidth($('#parentDiv').width()-30, true);
}).trigger('resize');


text:
Q: Взаимодействия между ViewModel-ями Как лучше организовать взаимодействие между ViewModel-ями?
A: Многое зависит от вида связи моделей вида (родитель-потомок или брат-брат). В общем случае часто используют шину сообщений. Модели подписываются на сообщения определенного типа и получают их, когда другие модели посылают их. Хороший пример реализации - это класс Messenger в
MVVM Light Toolkit.


text:
Q: Enhance image by simple interpolation using matlab I'm working on some tomography and is trying to enhance the quality of my data. You can see the raw data here: http://i.imgur.com/270HT.png .
What I want to do is to smooth the image along the X-direction. Basically stretching the image and interpolate the data in between the discrete jumps.
I don't know a lot about image processing, but to my naked eye I can see that matlabs built-in imresize and interp2 function don't do a very good job.
Can someone please help me how to enhance this?

A: I'm not sure whether a usual interpolation is right here. It seems that your image was created from separate column-measurements. If you look at your data it seems that neighboring columns are almost copies of each other. They seem just a bit translated. If you take the brightness of two neighboring columns and plot it, you see

that for the two peaks, which are vessel-like structures in your image, this seems really the case.
So what about calculating the correlation of two neighboring columns to get the offset

You see that the two columns correlate the most if they are shifted by a few pixel.
So here is what I would try first. Calculate the offset of each neighboring column. You get a list of offsets which tells you how much you have to translate a line to make it the best match with its neighbor. Then you smooth this list and use the smoothed version to translate every column.
This should repair columns like the one at x=7 in your raw image.
Furthermore, you could of course stretch your image in x-direction by interpolating this list of offsets. Say you have 10 neighboring columns and their offsets, where they match the most.

Then you could use the intermediate steps by using the same line with different translations. In this way you would get a smooth transition from column to column and you would resize the x-direction.

Edit
This

Then you smooth this list and use the smoothed version to translate every column. This should repair columns like the one at x=7 in your raw image.

needs clarification. When you have the list of offsets, what you want to use for the translation of each column is the difference between this list and its smoothed version. I hope I'm right here, because I didn't try it.

A: You can use different styles of imresize -> For example putting 'lanczos3' as optional argument. (See the manual for this one).
You can also try to sharpen the image after resizing, if you like it more.
However, you will never get something really good, as an interpolation is always a creation of data out of nowhere.


text:
Q: Replacing a value in a arraylist that is type data structure This is probably a very simple question, but I will still ask it.
My arraylist:
ArrayList<FileNameData> fileData;

FileNameData class:
public FileNameData(TCComponentItemRevision rev, TCComponentDataset selectedDataset, String markUp, String fileName)

set Method
public void setFileName(String fName) {
   fileName = fName;
}

I am trying to take the users input for file name and replace the file name already in the array.
I created the following method.
public void setFileName(int index, String fName) {
    fileData.set(index, setFileName(fName));
}

I know to get the file name it is very simple
String fName = fileData.get(index).getFileName();

I know that the set method needs the index and new value, but I am not sure how to get to the setFileName method inside the set?

A: If I get you right, then you want to modify the object that is stored at position index:
public void setFileName(int index, String fName) {
    fileData.get(index).setFileName(fName);
}

Or, with some more lines:
public void setFileName(int index, String fName) {
    // get the fileNameData stored at position index
    FileNameData fileNameData = fileData.get(index);

    // set the new filename
    fileNameData.setFileName(fName);
}

A: If you are trying to get the file a particular file from the ArrayList and change the name of the file, you need to get the correct element from the list.
If you know the index of the old file, it is fairly simple:
file = list.get(index);
file.setName(newName);

You can use the indexOf method of ArrayList. for this the equals and hashcode of the FileData object must be implemented correctly. Assuming that the name of the file uniquely identifies a file:
In the FileData class
public boolean equals(Object other)
{
    return other instanceof FileData
           && this.getFileName().equals(((FileData)other)getName());
}

public int hashCode()
{
    return this.getFileName().hashCode();
}

Then you can find the index of the file with a given name and update it:
FileData file = new FileData();
file.setName(oldName);
int index = list.indexOf(file);
file = list.get(index);
file.setName(newName);

A: If I understand you correctly, you have two classes looking something like this:
class SomeClass {
    ArrayList<FileNameData> fileData;

    public SomeClass(){
        fileData = new ArrayList<FileNameData>();
    }
}

and
class FileNameData {

    String fileName;

    public FileNameData(TCComponentItemRevision rev, TCComponentDataset selectedDataset, String markUp, String fileName){ ... }

    public void setFileName(String fName) {
        fileName = fName;
    }

    public String getFileName() {
        return fileName;
    }
}

So, you'll need to find a way to get the index where the current fileName is storred.
Once you have the index, you can just do the following (should be done in SomeClass, so that class will look like:
class SomeClass {
    ArrayList<FileNameData> fileData;

    public SomeClass(){
        fileData = new ArrayList<FileNameData>();
    }

    public void replaceFileNameAtIndex(int index, String fileName){
           fileData.get(index).setFileName(fileName);
    }
}

One way of finding the index could be:
public int findIndexOfFilleName(String fileName){
     for (FileNameData file : fileData)
        if (file.getFileName().equals(fileName))
            return fileData.indexOf(file);
    return -1; //or some other value indicating not found
}


text:
Q: Declaring an explict object dependency in Spring The basic problem I have here is that I have one xml file that is being used as a utility file and imported into other xml files. It defines a series of objects for connecting to a platform and providing an interface to it. The beans in this file are defined to be lazy-initialised so that if you do not want to connect to the platform you will not but if you start referencing the appropriate bean then everything should get up and running.
The basic problem I have is that one of the beans in this set is not explicity referenced by any of the others but it is required to be constructed as it will call a method on one of the other beans in order to "activate" it. (It is acting as a gate keeper by switching on/off the connectivity based on what it detects as the state of the platform).
Here's a dummy of the sort of XML setup I have:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"
    default-lazy-init="true">

    <!-- Provides the connection to the platform -->
    <bean id="PlatformConnection">
        <constructor-arg ref="PlatformConnectionProperties" />
    </bean>

    <!-- This bean would be overriden in file importing this XML -->
    <bean id="PlatformConnectionProperties"/>

    <!-- Controls the databus to be on/off by listening to status on the Platform
         (disconnections/reconnections etc...) -->
    <bean lazy-init="false" class="PlatformStatusNotifier">
        <constructor-arg ref="PlatformConnection" />
        <constructor-arg ref="PlatformConnectionDataBus" />
    </bean>

    <!-- A non platform specific databus for client code to drop objects into -
         this is the thing that client XML would reference in order to send objects out -->
    <bean id="PlatformConnectionDataBus" class="DataBus"/>

    <!-- Connects the DataBus to the Platform using the specific adaptor to manage the java object conversion -->
    <bean lazy-init="false" class="DataBusConnector">
        <constructor-arg>
            <bean class="PlatformSpecificDataBusObjectSender">
                <constructor-arg ref="PlatformConnection" />
            </bean>
        </constructor-arg>
        <constructor-arg ref="PlatformConnectionDataBus" />
    </bean>

</beans>

Now basically I want to remove the lazy-inits here that are required to get this thing to work properly. The objects referenced by the client XML are the PlatformConnection and the PlatformConnectionDataBus. How can I explicity declare that I want those other beans constructed if they are referenced?

A: You can add an explicit dependency from one bean to another by using the depends-on attribute:
<bean id="a" class="A"/>
<bean id="b" class="B" depends-on="a"/>

If I'm understanding your questin correctly, then I suggest you make all of your bean definitions lazy-init="true", and use depends-on to tie them together, for example:
<bean id="PlatformStatusNotifier" lazy-init="false" class="PlatformStatusNotifier">
    <constructor-arg ref="PlatformConnection" />
    <constructor-arg ref="PlatformConnectionDataBus" />
</bean>

<bean id="PlatformConnectionDataBus" lazy-init="false" class="DataBus" depends-on="PlatformStatusNotifier"/>

So if your client config were to express a dependency on PlatformConnectionDataBus, then that would trigger the initialisation of PlatformConnectionDataBus, which in turn would trigger the initialisation of PlatformStatusNotifier.


text:
Q: LUA, find user input string in table been trying to get this one on my own for a few days but got out of ideas.
Here's how it goes...
expect user input of 1 to x words into  a local variable,
every word has to be compared to a table with multiple strings, one at a time,
if all words are true for one of the strings then do something (it will print other fields of that table ID to the user) or if one of words is missing do another thing (just tell the user the search returned no results)
words have not to be matched completely.

A: hmmm... Sounds like a simple problem, you're probably over-thinking it or expecting there to be some very simple way of doing it, but (unless you want to use some tool like lpeg), there's really just the obvious way:
local function find_words_in_string(str, words)
   for i, word in ipairs(words) do -- Try every word
      if not str:find(word) then -- See if it's in the string
         return false -- Say no if it isn't
      end
   end
   return true
end

If you want to be fancy, you can also implement it as a recursive variadic function:
local function find_words_in_string(str, word, ...)
   if word then
      return str:match(word) and find_words_in_string(str, ...)
   else
      return true
   end
end


text:
Q: Does Reinhardt gain ultimate quicker when blocking opponents? I saw a youtube video where Reinhardt does nothing and somehow his ultimate goes up quickly. Once it's up he kills 3 enemies at once.
I forgot the URL but here is another one.

I wonder why the ultimate goes up quickly?
Maybe because he blocks a lot? His shield gets destroyed a lot of times.

A: No. Reinhardt does not gain ultimate charge for blocking damage. He does, however, gain lots of ultimate charge for dealing damage. For every 11 points of damage he deals, he gains 1% ultimate, according to this answer. This means that if a charge hits, that's up to 27% ultimate charge right there, and 6% for every hammer swing.


text:
Q: blob download counter in .net I need to add a download counter to know how many times my BLOB data is read and displayed from the database (to determine traffic). How and where can I add this counter? Many thanks!
I have a dynamically generated list of links such as
Document filename which direct to a display page.
My display page code looks like:
Protected Sub Page_Load
    Dim DocID As Integer = Convert.ToInt32(Request.QueryString("DocID"))
    Dim connStr As String = conn string here
    Dim SqlCmd1 As String = "SELECT DocID, DocBD, Filename, MIMEType WHERE DocID=@DocID"
    Dim conn As SqlConnection = New SqlConnection(connStr)
    Dim Cmd1 As SqlCommand = New SqlCommand(sqlCmd1, conn)
    With Cmd1.Parameters
        .Add(New SqlParameter("@DocID", DocID)
    End With
        Try
        conn.Open()
        Dim myReader As SqlDataReader = Cmd1.ExecuteReader
        If myReader.Read Then
                Response.ClearContent()
                Response.AddHeader("content-disposition", "inline; filename=" & myReader("Filename"))
                Response.ContentType = myReader("MIMEType").ToString()
                Response.BinaryWrite(myReader("DocBD"))
                Response.End()
        Else
        Label1.Text = "The document you requested doesn't exist in the database. Please contact the document owner"
        End If
        myReader.Close()
   Catch ex As Exception
        Label1.Text = ex.Message()
   Finally
   conn.Close()
   End Try
End Sub

A: Hopefully this will help you out. It's for uploading, but maybe you can use it as a reference for downloading.
public void ProcessRequest(HttpContext context, string uploadPath)
    {
        string filename = context.Request.QueryString["filename"];
        bool complete = string.IsNullOrEmpty(context.Request.QueryString["Complete"]) ? true : bool.Parse(context.Request.QueryString["Complete"]);
        bool getBytes = string.IsNullOrEmpty(context.Request.QueryString["GetBytes"]) ? false : bool.Parse(context.Request.QueryString["GetBytes"]);
        long startByte = string.IsNullOrEmpty(context.Request.QueryString["StartByte"]) ? 0 : long.Parse(context.Request.QueryString["StartByte"]); ;

        string filePath;
        if (UniqueUserUpload)
        {
            if (context.User.Identity.IsAuthenticated)
            {
                filePath = Path.Combine(uploadPath, string.Format("{0}_{1}", context.User.Identity.Name.Replace("\\",""), filename));
            }
            else
            {
                if (context.Session["fileUploadUser"] == null)
                    context.Session["fileUploadUser"] = Guid.NewGuid();
                filePath = Path.Combine(uploadPath, string.Format("{0}_{1}", context.Session["fileUploadUser"], filename));
            }
        }
        else
            filePath = Path.Combine(uploadPath, filename);

        if (getBytes)
        {
            FileInfo fi = new FileInfo(filePath);
            if (!fi.Exists)
                context.Response.Write("0");
            else
                context.Response.Write(fi.Length.ToString());

            context.Response.Flush();
            return;
        }
        else
        {

            if (startByte > 0 && File.Exists(filePath))
            {

                using (FileStream fs = File.Open(filePath, FileMode.Append))
                {
                    SaveFile(context.Request.InputStream, fs);
                    fs.Close();
                }
            }
            else
            {
                using (FileStream fs = File.Create(filePath))
                {
                    SaveFile(context.Request.InputStream, fs);
                    fs.Close();
                }
            }
            if (complete)
            {
                if (FileUploadCompleted != null)
                {
                    FileUploadCompletedEventArgs args = new FileUploadCompletedEventArgs(filename, filePath);
                    FileUploadCompleted(this, args);
                }
            }
        }
    }

    private void SaveFile(Stream stream, FileStream fs)
    {
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
        {
            fs.Write(buffer, 0, bytesRead);
        }
    }


text:
Q: Symfony entity override "The table with name 'sulu_11.me_media' already exists I am overriding entity of bundle.
In my bundle
I am writing an
namespace AppBundle\Entity;

use Sulu\Bundle\MediaBundle\Entity\Media as Base;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @ORM\Table(name="me_media")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\MediaRepository")
 */
class Media extends Base
{

}

And when i run command
php bin/console doctrine:schema:update --force

Error thrown while running command "doctrine:schema:update --force".
  Message: "The table with name 'sulu_11.me_media' already exists."
  ["error" => Doctrine\DBAL\Schema\SchemaException { …},"command" =>
  "doctrine:schema:update --force","message" => "The table with name
  'sulu_11.me_media' already exists."] []
  [Doctrine\DBAL\Schema\SchemaException]                     The table
  with name 'sulu_11.me_media' already exists.

A: Have you added also the configuration for the new entity? You can find that in the documentation http://docs.sulu.io/en/latest/cookbook/extend-entities.html#configuration


text:
Q: Binary search tree cumsum Problem: Given a binary search tree in which the keys are numbers, we'll define the operation 'cumsum' ( shorthand for cumulative sum ) that switches the key of every node in the tree with the sum of all the keys that are smaller or equal to it.
For example,

In this example,
The key 5 in the root is switched to the value 10: the sum of the original key in the root ( which is 5 ) and all smaller keys than it ( which are 2 and 3 ).
The key 3 is switched with the value 5: sum of the original key in this node ( meaning, 3 ) and all the smaller keys than it ( which is 2 ).
The key 12 in the rightmost node is switched with the value 45: sum of the original key in this node ( meaning, 12 ) and all the smaller keys than it ( which are 2,3,5,6,8 and 9 ).
Note that the method needs to be an envelope function that envelopes a recursive function. Also note that the method cumsum does not return a new tree but rather updates the tree itself ( in-place )
My attempt:
def cumsum(T):
    def cumsum_rec(node,L):
        L.append(node.key)
        if node.left != None:
            cumsum_rec(node.left,L)
        if node.right != None:
            cumsum_rec(node.right,L)
        count = 0
        for val in L:
            if val < node.key:
                count += val
        node.key += count

    L = []
    cumsum_rec(T.root,L)

Explanation: I traverse each node in the tree, I save each original node in an auxiliary list denoted as 'L'. When all nodes were traversed, I look for all the nodes keys in the list 'L' that are smaller than the current node and appropriately update the key of the current node to be the sum of the keys of all nodes whose key are smaller or equal to the current node's key .
My implemenation works, for example, for the tree in the example above:
t = Binary_search_tree()
t.insert(5,'A')
t.insert(2,'A')
t.insert(9,'A')
t.insert(3,'A')
t.insert(8,'A')
t.insert(12,'A')
t.insert(6,'A')

which looks:
>>> print(t)
          5
   ______/ |__________
  2                   9
 / |__             __/ |__
#     3           8       12
     / |       __/ |     /  |
    #   #     6     #   #    #
             / |
            #   #

And after performing cumsum operation on it:
>>> cumsum(t)
>>> print(t)
          10
   ______/  |____________
  2                      33
 / |__                __/  |__
#     5             24        45
     / |         __/  |      /  |
    #   #      16      #    #    #
              /  |
             #    #

My question:
Although my implementation works, I was interested in seeing other possible implementations for the sake of learning. Do you have an alternative implementation? one that doesn't require using a list as an input to the recursive function?
Addendum ( implementation of  Binary search tree and Tree_node classes if you're interested ):
def printree(t, bykey = True):
        """Print a textual representation of t
        bykey=True: show keys instead of values"""
        #for row in trepr(t, bykey):
        #        print(row)
        return trepr(t, bykey)

def trepr(t, bykey = False):
        """Return a list of textual representations of the levels in t
        bykey=True: show keys instead of values"""
        if t==None:
                return ["#"]

        thistr = str(t.key) if bykey else str(t.val)

        return conc(trepr(t.left,bykey), thistr, trepr(t.right,bykey))

def conc(left,root,right):
        """Return a concatenation of textual represantations of
        a root node, its left node, and its right node
        root is a string, and left and right are lists of strings"""

        lwid = len(left[-1])
        rwid = len(right[-1])
        rootwid = len(root)

        result = [(lwid+1)*" " + root + (rwid+1)*" "]

        ls = leftspace(left[0])
        rs = rightspace(right[0])
        result.append(ls*" " + (lwid-ls)*"_" + "/" + rootwid*" " + "|" + rs*"_" + (rwid-rs)*" ")

        for i in range(max(len(left),len(right))):
                row = ""
                if i<len(left):
                        row += left[i]
                else:
                        row += lwid*" "

                row += (rootwid+2)*" "

                if i<len(right):
                        row += right[i]
                else:
                        row += rwid*" "

                result.append(row)

        return result

def leftspace(row):
        """helper for conc"""
        #row is the first row of a left node
        #returns the index of where the second whitespace starts
        i = len(row)-1
        while row[i]==" ":
                i-=1
        return i+1

def rightspace(row):
        """helper for conc"""
        #row is the first row of a right node
        #returns the index of where the first whitespace ends
        i = 0
        while row[i]==" ":
                i+=1
        return i

#######################################################################

class Tree_node():
    def __init__(self, key, val):
        self.key = key
        self.val = val
        self.left = None
        self.right = None

    def __repr__(self):
        return "(" + str(self.key) + ":" + str(self.val) + ")"

class Binary_search_tree():

    def __init__(self):
        self.root = None

    def __repr__(self): #no need to understand the implementation of this one
        out = ""
        for row in printree(self.root): #need printree.py file
            out = out + row + "\n"
        return out

    def lookup(self, key):
        ''' return node with key, uses recursion '''

        def lookup_rec(node, key):
            if node == None:
                return None
            elif key == node.key:
                return node
            elif key < node.key:
                return lookup_rec(node.left, key)
            else:
                return lookup_rec(node.right, key)

        return lookup_rec(self.root, key)

    def insert(self, key, val):
        ''' insert node with key,val into tree, uses recursion '''

        def insert_rec(node, key, val):
            if key == node.key:
                node.val = val     # update the val for this key
            elif key < node.key:
                if node.left == None:
                    node.left = Tree_node(key, val)
                else:
                    insert_rec(node.left, key, val)
            else: #key > node.key:
                if node.right == None:
                    node.right = Tree_node(key, val)
                else:
                    insert_rec(node.right, key, val)
            return

        if self.root == None: #empty tree
            self.root = Tree_node(key, val)
        else:
            insert_rec(self.root, key, val)

Thanks in advance for any help!

A: Here's one implementation that doesn't require keeping the extra list; it just adds the numbers up as it goes.
def cumsum(T):
    def cumsum_rec(node, initial):
        if node is None:
            return initial
        left = cumsum_rec(node.left, initial)
        node.key = left + node.key
        right = cumsum_rec(node.right, node.key)
        return right
    cumsum_rec(T.root, 0)

Note that there is no need to do extra comparisons of values (my code has no <), because all of that information is already contained in the structure of the tree.


text:
Q: JPA cascade type i cannot understand how the JPA cascade type works,
i have a Judgement class which has a ManyToOne relationship with another Class User, i have user created first and stored in user table, only when user make a judgement, a new record of judgement will be inserted to the judgement table with that user id(not but reinsert the same user to the user table again). so here is my declare in judgement class:
@ManyToOne(cascade = { CascadeType.REFRESH, CascadeType.MERGE}) @PrimaryKeyJoinColumn
@JoinColumn(name = "user_id")
private User judge;

but it complained
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing  -- com.dyihi.recseva.model.Judgement.judge -> com.dyihi.recseval.model.User

what's wrong here? thanks


text:
Q: NodeJS bidirectional (internal) events I've made a simple class that receives HTTP GET requests and emits the pathname and query in a event.
The idea is that one can do a get request like: 'example.com/lightControl?id=1&state=true' to set a light on.
However, one should also be able to request the current state of the lamp by simply doing a request like: 'example.com/lightControl?id=1'
let http = require('http');
let url = require('url');
let EventEmitter = require("events").EventEmitter;

class Api extends EventEmitter{
    constructor(port){
    super();
    this.startServer(port);
    }
  startServer(port){
    this.server = http.createServer(this.handleRequest);
    this.server.listen(port, function(){
      //Callback triggered when server is successfully listening. Hurray!
      console.log("Server listening on port:", port);
    });
  }
  handleRequest(request, response){
    //console.log("URL",request.url);
    var parsed = url.parse(request.url,true);
    this.emit('request',parsed.pathname,parsed.query);
    response.end('API called: \n\nPath:   ' + JSON.stringify(parsed.pathname) + "\nValues: " + JSON.stringify(parsed.query));
  }
}

Currently my code responds to the request, by stating the pathname and query. But I would like it to respond with the actual status of the light.
The problem however, is that I'm using an event bus. All connected devices can send events and then another device can act upon it, but there is no direct response message. Theoretically, it could send a response event, but then I'll need a way to jump back into the handleRequest function and finish it from where the event was emitted?
I'm thinking that asynchronous and loosely coupled properties of an event bus do not really support such a requirement.
I could go around and do something like this (see below), but that would break the whole principle of a message bus.
handleRequest(request, response){
    //console.log('URL',request.url);
    var parsed = url.parse(request.url,true);
    deviceHandler.setDevice(parsed.pathname,parsed.query);
    var state = deviceHandler.getDeviceState(parsed.pathname);
    response.end('Device: ' + parsed.pathname + ' is now: ' + state);
  }

Is there a way to achieve this using events?
Or do I require another design?