text:
Q: experimental sequence of number I'm doing a small numerical experiment. I got, from the first simulations, the following sequence of numbers. I'm trying to imagine a mathematical law behind this sequence. It could be a geometric progression?
1.333333333
1.75
2.491107286
3.835656425
6.219456109
10.44686695
17.99815841
31.6031634
56.31814911
101.5516622
...

A: Your data looks like a simple exponential growth. To a rough approximation:
 y = A*exp(x/t) + y0

 y0 0.95321
 A  0.26613
 t  1.68515

...which makes it a geometric progression with an added constant term.


text:
Q: How to automatically bring up CAN interface in Ubuntu 17.10 In previous versions of Ubuntu I have been using this script to automatically bring up an network interface for a USB to CAN bridge device, whenever the device is plugged in:
$ cat /etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback

allow-hotplug can0
iface can0 can static
    bitrate 250000
        up /sbin/ip link set $IFACE down
    up /sbin/ifconfig $IFACE txqueuelen 20000
    up /sbin/ip link set $IFACE type can bitrate 250000 restart-ms 10
        up /sbin/ip link set $IFACE up

This script does not work any more because Ubuntu 17.10 is not using ifupdown and consequently /etc/network/interfaces file is no longer used. My question is, how do I rewrite this script using the new netplan configuration system?
In particular, what is critical for functioning of my script above is the line allow-hotplug can0 which detects when the can0 interface becomes available (shortly after plugging the device into USB port). Can I do this using the new configuration system?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve AssemblyCompanyName from Class Library I would like to get the AssemblyCompany attribute from a WinForm project inside of my C# class library.  In WinForms, I can get to this information by using:
Application.CompanyName;

However, I can't seem to find a way to get at that same information using a class library. Any help you could provide would be great!

A: You could use the FileVersionInfo class to get CompanyName and much more.
Dim info = FileVersionInfo.GetVersionInfo(GetType(AboutPage).Assembly.Location)
Dim companyName = info.CompanyName
Dim copyright = info.LegalCopyright
Dim fileVersion = info.FileVersion

A: Assembly assembly = typeof(CurrentClass).GetAssembly();
AssemblyCompanyAttribute companyAttribute = AssemblyCompanyAttribute.GetCustomAttribute(assembly, typeof(AssemblyCompanyAttribute)) as AssemblyCompanyAttribute;
if (companyAttribute != null)
{
    string companyName = companyAttribute.Company;
    // Do something
}

A: To get the assembly in which your current code (the class library code) actually resides, and read its company attribute:
Assembly currentAssem = typeof(CurrentClass).Assembly;
object[] attribs = currentAssem.GetCustomAttributes(typeof(AssemblyCompanyAttribute), true);
if(attribs.Length > 0)
{
    string company = ((AssemblyCompanyAttribute)attribs[0]).Company
}

A: The dotnet 5 version:
typeof(CurrentClass).GetCustomAttribute<AssemblyCompanyAttribute>().Company

A: You can also get it using LINQ :
public static string GetAssemblyCompany<T>(){
    string company = (from Attribute a in (typeof(T).Assembly.GetCustomAttributes())
        where a is AssemblyCompanyAttribute
        select ((AssemblyCompanyAttribute)a).Company).FirstOrDefault();

    return company;
}

A: This is a great way to get what you are looking for in a single line:
string company = ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(AssemblyCompanyAttribute), false)).Company;


text:
Q: Git merge and preserve original committer how can i preserve original commiter, when i merging changes made by another developer?
(Something like git merge --preserve-comitter)
cherry-pick is almost good, but it seems does not preserve informations about branches
Here is an image of history made by cherry-pick

Here is an image of history made by merge

A: The history made by merge, shows exactly what you want and need:

*

*the commit that was merged (nicely indented and correctly attributed to Jemerin)

*the commit that merged it (nicely marked as 'merge' commit and correctly attributed to Vendelin)

If you want to see 'simple' flattened log, you could use git log with options (-no-merges)


text:
Q: Elasticsearch Troubleshooting Field Data I am trying to verify the root cause for this error in our environment.
ES Version
elasticsearch-1.7.1
RemoteTransportException[host.com][inet[/internalIP:9300]]
[indices:data/read/search[phase/query]]]; nested:
QueryPhaseExecutionException[[logstash-v2-2016.01.30][3]:
query[filtered(+firstname:Steve +lastname:Harvey)-
>BooleanFilter(+cache(event_time_utc:[1423086205000 TO
1454622205000]))],from[0],size[5],sort[<custom:\"event_time_utc\":
org.elasticsearch.index.fielddata.fieldcomparator.LongValuesComparatorSource@24f48
98c>!]: Query Failed [Failed to execute main query]]; nested:  ElasticsearchException[org.elasticsearch.common.breaker.CircuitBreakingException:
[FIELDDATA] Data too large, data for [event_time_utc] would be larger than
limit of [17997024460/16.7gb]]; nested: UncheckedExecutionException[org.elasticsearch.
common.breaker.CircuitBreakingException: [FIELDDATA] Data too large, data for
 [event_time_utc] would be larger than limit of [17997024460/16.7gb]]; nested:
 CircuitBreakingException[[FIELDDATA] Data too large, data for
[event_time_utc] would be larger than limit of [17997024460/16.7gb]]; "

You can see above that the Data too large for field event_time_utc. I am executing a curl command to investigate the issue. The data returned isn't helping.
Curl Command
 [curl -k -XGET 'https://USERNAME:PASSWORD@host.com:9200/logstash-v2-2016.01.30/_stats/fielddata/?fields=event_time_utc&pretty'][1]

My Questions are:

*

*What stat should would help me when figuring out this breaker is
about to be tripped?

*How am i to determine which fields are going
to trip this breaker?

*How are other monitoring this threshold.

Output
{
  "_shards" : {
    "total" : 10,
    "successful" : 10,
    "failed" : 0
  },
  "_all" : {
    "primaries" : {
      "fielddata" : {
        "memory_size_in_bytes" : 80336,
        "evictions" : 0,
        "fields" : {
      "event_time_utc" : {
        "memory_size_in_bytes" : 40168
      }
    }
  }
},
"total" : {
  "fielddata" : {
    "memory_size_in_bytes" : 92592,
    "evictions" : 0,
    "fields" : {
      "event_time_utc" : {
        "memory_size_in_bytes" : 46296
      }
    }
  }
}
  },
  "indices" : {
    "badge_v2-2016.01.30" : {
      "primaries" : {
        "fielddata" : {
          "memory_size_in_bytes" : 80336,
          "evictions" : 0,
        "fields" : {
        "event_time_utc" : {
          "memory_size_in_bytes" : 40168
        }
      }
    }
  },
  "total" : {
    "fielddata" : {
      "memory_size_in_bytes" : 92592,
      "evictions" : 0,
      "fields" : {
        "event_time_utc" : {
          "memory_size_in_bytes" : 46296
            }
          }
        }
      }
    }
  }
}


text:
Q: What is the .NET equivalent of "ProducesResponseType" from Net Core? I have to do a "backward" from an API made with NET CORE to .NET
I'm facing a problem changing [ProducesResponseType] from Net Core in a valid equivalent of .NET
I have for example this code:
[ApiExplorerSettings(GroupName = "groupName")]
[ProducesResponseType(typeof(something), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(void), StatusCodes.Status400BadRequest)]
[ProducesResponseType(typeof(void), StatusCodes.Status401Unauthorized)]
[ProducesResponseType(typeof(void), StatusCodes.Status500InternalServerError)]
[HttpPost("thing", Name = "creatingThisThing")]
public async Task<IHttpActionResult> PostThing([FromBody]dynamic value)
        {
           /// Other Stuff

I understand I can avoid using the group name and I can adapt the route like this:
[HttpPost]
[Route("", Name = "creatingThisThing")]
/// etc

But I'd like to know what can I use to "replace" the previously mentioned.
Hope I was clear enough.

A: I used [ResponseType(typeof(SomeClass))] from System.Web.Http.Description successfully with .NET 4.6.1.


text:
Q: Await on observable subscription Angelar2 In my Angular2 application, i use the canActivate to allow access to pages.
A part of this is to check with the server that the token has not been tampered with, so before i can decide weather a user can be granted access, i need to call my api.
This means subscribing to an Observable and awaiting an answer.
I need to return true or false, but since i make an asyns call, i cannot return based on my response.
I realize i cannot await since it is single threaded, but i need to somehow block until i have an answer back from the api.
my canActivate looks as follows:
canActivate() {
   this.guardClient.checkToken("token")
  .subscribe(response => {
    let responseText = response.text().replace(/"/g, '');
    if ( responseText === 'Ok')
    {
      return true;
    }
    if(responseText === 'denied') {

      this.router.navigate(['login']); // redirecting to login
      return false;
    }
  });
}

Can someone tell me how to solve this problem??

A: When looking at the CanActivate interface in angular 2 I see the following:
export interface CanActivate {
    canActivate(route: ActivatedRouteSnapshot, state:     RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean;
}

As you can see, you can just return an Observable as well, and not just a boolean.
This means your code could be rewritten something like this.
canActivate() {
 return this.guardClient.checkToken("token")
   .map(response => {
     let responseText = response.text().replace(/"/g, '');
     if ( responseText === '  Ok')
      {
       return true;
      }
     if(responseText === 'denied') {
        this.router.navigate(['login']); // redirecting to login
        return false;
   }
 });
}

This will make Angular wait for the observable to resolve before deciding if the route can be shown or not.
Notice that this method should be pretty fast to avoid slow loads.


text:
Q: return or display valid options in Rule::in when fail validate in laravel in my controller i have this validator
...
$request->validate([
        'id' => ['bail', 'required', 'string'],
        'live' => [Rule::in(['yes', 'no'])],
    ]);
...

and my response if the rule Rule::in fails is this
{
"message": "The given data was invalid.",
"errors": {
    "live": [
        "The selected live is invalid."
    ]
}
}

now my question is how can I return the possible values of Rule:in within that response? in this case: "yes" and "no"


text:
Q: Unable to have an ImageBuffer in a struct — two arguments needed and only provided one I am new to Rust and still learning. I am a bit confused as to why when I compile this code it fails. I am building it with Cargo on my Linux development machine
extern crate image;
extern crate rand;

use image::{ImageBuffer, Rgb};
use rand::Rng;

struct ImageCanvas {
    image: image::ImageBuffer,
    WIDTH: i32,
    HEIGHT: i32,
    xPosition: i32,
    yPosition: i32
}

impl ImageCanvas {

    pub fn new(width: i32, height: i32) -> ImageCanvas {

        // create a new instance of an ImagePen.
        ImageCanvas{
            image: ImageBuffer::<Rgb<u8>>::new(width, height),
            WIDTH: width,
            HEIGHT: height,
            xPosition: 0,
            yPosition: 0
        }

    }

    pub fn paint(&self, x: i32, y: i32, rgb: i32){

        self.xPosition = x;
        self.yPosition = y;

        //RGB should be an array.
        self.image.get_pixel_mut(self.xPosition, self.yPosition).data = rgb;

    }

}

fn main() {

    let canvas = ImageCanvas::new(50, 50);

    canvas.paint(1, 1, [rand::thread_rng().gen_range(1, 255),
                        rand::thread_rng().gen_range(1, 255),
                        rand::thread_rng().gen_range(1, 255)]);

    canvas.image.save("yay.png").unwrap();

}

The error:
src/main.rs:9:9: 9:27 error: wrong number of type arguments: expected 2,                  found 0 [E0243]
src/main.rs:9   image: image::ImageBuffer,
                   ^~~~~~~~~~~~~~~~~~
src/main.rs:9:9: 9:27 help: run `rustc --explain E0243` to see a detailed   explanation
error: aborting due to previous error

I am not sure why it is giving me this error. I have searched, but I haven't  seen any other post about a noob like me not understanding the OOD of Rust.

A: image::ImageBuffer is a parametrized struct:
pub struct ImageBuffer<P: Pixel, Container> {
    // some fields omitted
}

So you have to provide these parameters in your struct ImageCanvas.
something like
struct ImageCanvas<P: Pixel, Container> {
    image: image::ImageBuffer<P, Container>,
    WIDTH: i32,
    HEIGHT: i32,
    xPosition: i32,
    yPosition: i32
}

or
struct ImageCanvas {
    image: image::ImageBuffer<RGB<u8>, Vec<RGB<u8>>>,
    WIDTH: i32,
    HEIGHT: i32,
    xPosition: i32,
    yPosition: i32
}

A: You are actually using an RGB Image so why not used the specialized version
extern crate image;
extern crate rand;

use image::{RgbImage, Rgb};
use rand::Rng;

// Had to change all of the `i32` to `u32`. I agree, `i32` makes more sense.
struct ImageCanvas {
    image: image::RgbImage, // image::ImageBuffer<Rgb<u8>>,
    WIDTH: u32,
    HEIGHT: u32,
    xPosition: u32,
    yPosition: u32
}

impl ImageCanvas {

    pub fn new(width: u32, height: u32) -> ImageCanvas {

        // create a new instance of an ImagePen.
        ImageCanvas{
            image: RgbImage::new(width, height), //ImageBuffer::<Rgb<u8>>::new(width, height),
            WIDTH: width,
            HEIGHT: height,
            xPosition: 0,
            yPosition: 0
        }

    }

    // RGB _IS_ an array
    // note the need for `mut`
    pub fn paint(&mut self, x: u32, y: u32, rgb: [u8;3]){

        self.xPosition = x;
        self.yPosition = y;

        self.image.get_pixel_mut(self.xPosition, self.yPosition).data = rgb;

    }

}

fn main() {

    // `mut` here too
    let mut canvas = ImageCanvas::new(50, 50);

    canvas.paint(1, 1, [rand::thread_rng().gen_range(1, 255),
                        rand::thread_rng().gen_range(1, 255),
                        rand::thread_rng().gen_range(1, 255)]);

    canvas.image.save("yay.png").unwrap();

}


text:
Q: @BeforeClass and inheritance - order of execution I have an abstract base class, which I use as a base for my unit tests (TestNG 5.10). In this class, I initialize the whole environment for my tests, setting up database mappings, etc. This abstract class has a method with a @BeforeClass annotation which does the initialization.
Next, I extend that class with specific classes in which I have @Test methods and also @BeforeClass methods. These methods do class-specific initialization of the environment (e.g. put some records into the database).
How I can enforce a specific order of the @BeforeClass annotated methods? I need the ones from the abstract base class to be executed before the ones of the extending class.
Example:
abstract class A {
    @BeforeClass
    doInitialization() {...}
}

class B extends A {
    @BeforeClass
    doSpecificInitialization() {...}

    @Test
    doTests() {...}
}

Expected order:
A.doInitialization
B.doSpecificInitialization
B.doTests

Actual order:
B.doSpecificInitialization // <- crashes, as the base init is missing
(A.doInitialization        // <---not executed
 B.doTests)                // <-/

A: I added public to the abstract class and TestNG (6.0.1) executed the doInitialization() before doTests. TestNG does not execute doInitialization() if I remove public from class A.
public abstract class A {
 @BeforeClass
 doInitialization() {...}
}

class B extends A {
 @Test
 doTests() {...}
}

A: I just tried your example with 5.11 and I get the @BeforeClass of the base class invoked first.
Can you post your testng.xml file? Maybe you are specifying both A and B there, while only B is necessary.
Feel free to follow up on the testng-users mailing-list and we can take a closer look at your problem.
--
Cedric

A: Don't put the @BeforeClass on the abstract class. Call it from each subclass.
abstract class A {
    void doInitialization() {}
}

class B extends A {
    @BeforeClass
    void doSpecificInitialization() {
        super.doInitialization();
    }

    @Test
    void doTests() {}
}

Seems like TestNG has @BeforeClass(dependsOnMethods={"doInitialization"}) - give it a try.

A: I've just gone through this and found one more way to achieve this. Just use alwaysRun on @BeforeClass or @BeforeMethod in the abstract class, works as you would expect.
public class AbstractTestClass {
    @BeforeClass(alwaysRun = true)
    public void generalBeforeClass() {
        // do stuff
        specificBeforeClass();
    }
}

A: For JUnit:
As @fortega has mentioned:
According to the JUnit api: "The @BeforeClass methods of superclasses will be run before those the current class."
But be careful not to name both methods with the same name. Since in this case the parent method will be hidden by child parent. Source.

A: When I run from: JUnitCore.runClasses(TestClass.class);
It will execute the parent properly, before the child (You do not need super.SetUpBeforeClass();)
If you run it from Eclipse:
For some reason it fails to run the base class.
The work around:
Call the base class explicitely: (BaseTest.setUpBeforeClass();)
 You may want to have a flag in the base class in case you run it from an application, to determine if it is already setup or not. So it only runs once if you run it via both possible methods (such as from eclipse for personal testing, and through ANT for a build release).
This appears to be a bug with Eclipse, or at least unexpected results..

A: edit: Answer below is for JUnit, but I will leave it here anyway, because it could be helpful.
According to the JUnit api: "The @BeforeClass methods of superclasses will be run before those the current class."
I tested this, and it seems to work for me.
However, as @Odys mentions below, for JUnit you need to have the two methods named differently though as doing otherwise will result in only the subclass method being run because the parent will be shadowed.

A: How about having your @BeforeClass method call an empty specificBeforeClass() method that may or may not be overwritten by sub classes like so:
public class AbstractTestClass {
  @BeforeClass
  public void generalBeforeClass() {
    // do stuff
    specificBeforeClass();
  }

  protected void specificBeforeClass() {}
}

public class SpecificTest {
  @Override
  protected void specificBeforeClass() {
    // Do specific stuff
  }

  // Tests
}

A: dependsOnMethod can be used.
e.g. in case of Spring (AbstractTestNGSpringContextTests)
@BeforeClass(alwaysRun = true, dependsOnMethods = "springTestContextPrepareTestInstance")

A: Check your import statement.
It should be
import org.testng.annotations.BeforeClass;
not
import org.junit.BeforeClass;

A: This works for me --
abstract class A {
    @BeforeClass
    doInitialization() {...}
}

class B extends A {
    @Override
    @BeforeClass
    doInitialization() {

       //do class specific init

    }

    @Test
    doTests() {...}
}

A: Why don't you try to create an abstract method doSpecialInit() in your super class, called from your BeforeClass annotated method in superclass.
So developpers inheriting your class is forced to implement this method.

A: There is another easy solution here.
My particular situation is that I need to inject mock services from "BeforeClass" in the subclass before "BeforeClass" in the superclass is executed.
To do this - simply use a @ClassRule in the subclass.
For example:
@ClassRule
public static ExternalResource mocksInjector = new ExternalResource() {
    @Override
    protected void before() {
        // inject my mock services here
        // Note: this is executed before the parent class @BeforeClass
    }
};

I hope this helps. This can effectively execute static setup in "reverse" order.

A: I've faced a similar issue today, the only difference was a Base class was not abstract
Here's my case
public class A {
    @BeforeClass
    private void doInitialization() {...}
}

public class B extends A {
    @BeforeClass
    private void doSpecificInitialization() {...}

    @Test
    public void doTests() {...}
}

It occurred that a @BeforeClass method from class A was never executed.

*

*A.doInitialization() -> THIS WAS NEVER EXECUTED silently

*B.doSpecificInitialization()

*B.doTests()

Playing with privacy modifiers I found that TestNG will not execute a @BeforeClass annotated method from inherited class if a method is not visible from a class-inheritor
So this will work:
public class A {
    @BeforeClass
    private void doInitialization() {...}
}

public class B extends A {
    @BeforeClass
    //Here a privacy modifier matters -> please make sure your method is public or protected so it will be visible for ancestors
    protected void doSpecificInitialization() {...}

    @Test
    public void doTests() {...}
}

As a result following happens:

*

*A.doInitialization()

*B.doSpecificInitialization()

*B.doTests()

A: A better and cleaner way to achieve this using inheritance may be as following -
abstract class A {

    @BeforeClass
    void doInitialization() {}
}

class B extends A {

    @Override
    @BeforeClass
    void doInitialization() {
        super.doInitialization();
    }

    @Test
    void doTests() {}
}

A: In my case (JUnit) I have the same methods called setup() in the base class and the derived class.  In this case only the derived class's method is called, and I have it call the base class method.


text:
Q: Passing variable between jobs in Azure Pipeline As it is not possible to pass a variable between stages in AzurePipeline, I'm trying to pass a variable between two jobs instead as it is explained in Azure documentation (https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch), however it wasn't successful and it returns an empty variable.
here is what I'm trying:
stages:
- stage: Deploy
  jobs:
  - deployment: A
    displayName: TerraformDeploy
    pool:
      vmImage: 'ubuntu-latest'
    environment: 'test'
    strategy:
      runOnce:
       deploy:
        steps:
        - checkout: self
        - task: Bash@3
          displayName: 'Deploying Terraform'
          inputs:
            targetType: 'inline'
            script: |
              cd environments/test
              terraform init
              terraform apply -var 'client_id=$(client-id)' -var 'client_secret=$(client-secret)' -var 'key_data=$(LinuxSSHPubKey)' -var 'tenant_id=$(tenant-id)' -auto-approve
              ip=$(terraform output public_ip_address)
              echo $ip   ###1.2.3.4
              echo "##vso[task.setvariable variable=myPubIP;isOutput=true]$ip"
            name: setvarStep

  - job: B
    dependsOn: A
    pool:
      vmImage: 'ubuntu-latest'
    variables:
      myIP: $[ dependencies.A.outputs['A.setvarStep.myPubIP'] ]
    steps:
    - task: AzureCLI@2
      inputs:
        azureSubscription: $(azureSubscription)
        scriptType: 'bash'
        scriptLocation: 'inlineScript'
        inlineScript: |
          echo "ip:"$(myIP)   ### Empty variable!!

I've tried so many different things for this case but it hasn't been fixed so far, can anyone help with this?
Updated:
It seems someone else is also reported this issue and they are planning to fix it:
https://developercommunity.visualstudio.com/content/problem/769690/sharing-variables-between-jobs-not-working-for-dep.html
Even if I use both jobs as normal job, it still doesn't work for my case..

A: Not very sure it is a paste format issue in the above YAML pipeline definition, and I saw the ip value has generated very successfully, it seems cause by the syntax of name in your YAML definition is not correct, so it is not correctly compiled as reference name.
Just go and confirm whether there has a yellow line under the name, like this:

If yes, remove 2 space before name, so that let it at the same level with inputs:

If I use the same definition with you, I also faced the issue of empty output variable. But if I did the change on space before name, then output variable can successfully get in job B.
So, you can have try with this on your side.


text:
Q: Multiple handles in firebase I'm building a chat app with rooms feature in iOS, and had built a Firebase data design like this:
"members" : {
  "userId1" : {
    "roomId1" : true
  },
  "userId2" : {
    "roomId1" : true
  }
}
"rooms" : {
  "roomId1" : {
    "lastMessage" : "Last message",
    "timeStamp" : 1494483604,
    //users in this room
    "users" : {
      "userId1" : true,
      "usreId2" : true
    }
  }
}

So to show list of conversations of a user, firstly I observe single event of type value of path members/userId to get list of rooms that user take part in.
Then for each roomId, I observe rooms/roomId to get data to show on the UI.
The question is if a user takes part in a great deal of rooms, is observing changes for all of them best practice ?
For example, if I have 30 conversations from roomId1 to roomId30, I want to update the latest messages on the UI whenever changes happened, is observing 30 references makes sense ?
Thank you.

A: It's not best practice but it's a practice that works. However, based on your structure it would be simpler to generate a query on the rooms node for any users/userIdx: true.
That will add and observer to one node and notify the app of any changes to rooms the user is part of.
For example
Given a structure
rooms
  room_0
    room_name: "My Room"
    users:
      uid_0: true
      uid_1: true
      uid_2: true
  room_1
    room_name: "Romper Room"
    users:
      uid_0: true
      uid_2: true

and some code to add an observer to watch for uid_1
let roomsRef = self.ref.child("rooms")

roomsRef.queryOrdered(byChild: "users/uid_1").queryEqual(toValue: true)
        .observe(.childAdded, with: { (snapshot) in
     let roomDict = snapshot.value as! [String: AnyObject]
     let roomName = roomDict["room_name"] as! String
     print(roomName)
})

When this code is first run, it will print out
My Room

because the user is part of My Room (room_0) and not part of room_1.
If you then add uid_1: true to room_1 it will print
Romper Room

A: You should use observe to update db changes, so you can update UI based on the observation.
Take a look at this document:
https://firebase.google.com/docs/database/ios/read-and-write


text:
Q: Offline Update Rhel 7.4 without changing the version of OS I have to Update my Rhel Server and keep the version of OS.
The current running version of OS is Rhel 7.4.
My server is not connected to internet. So i have to do an offline Update.
Is it possible to do an update using an ISO file of RHEL7.7 or RHEL 7.8, Attach the file to the server , then modify the Yum repo, and execute this command :
yum -x 'kernel*' -x 'redhat-release*' update

What are the risks?
what are others Packages that I should Exclude?
Is it the same architecture of files and folders for RHEL 7.4 and 7.6 ?

A: Since you are updating to a minor version, you will not encounter issues during the update, excluding all kernel related  packages using "kernel*' is enough, also yum will automatically pickup the packages related to your current architecture.


text:
Q: neo4j large scale data mmodelling I am new to neo4j. I would need to build a money flow graph
My initial modelling is as follow but I am unsure if this would scale good.
(:Account)-[:TRANSFER]->(:Account)

A: You can take a look at the Max DeMarzi blog post about scaling airports: https://maxdemarzi.com/2015/08/26/modeling-airline-flights-in-neo4j/
What you can do is to introduce month/day nodes between accounts and transactions:
(:Customer)-[:OWNS]->(:Account)-[:HAS_TRADING_DAY]->(:TradingDay)-[:TRANSFER]->(:TradingDay)<-[:HAS_TRADING_DAY]-(:Customer)

This way you could avoid supernodes. What you could also do is to encode the date into relationship
(:Account)-[:TRANSFER_2022_01_01]->(:Account)

This way you can avoid traversing all relationships between two nodes and filtering them by dates. This should optimize your queries as well, however the queries are a bit more complex.


text:
Q: I am running a code in pyaudio which works normaly but when i run it on sudo(I am on linux) OSError: [Errno -9997]Invalid sample rate It does not work When I run this code normally it works and when I run on Sudo(i need to run on Sudo) it shows this. Please help me.
I need to use keyboard import so i need to run this on sudo.
EDit(someone told me to paste full error this it it. I Need to write some more words or i cant post as it is saying my post mostly codes so pls ignore the edit i am just an idiot.Sorry to bother u if u are reading this Have a nice day if you read so far )
Expression 'PaAlsaStreamComponent_InitialConfigure( &self->playback, outParams, self->primeBuffers, hwParamsPlayback, &realSr )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 2721
Expression 'PaAlsaStream_Configure( stream, inputParameters, outputParameters, sampleRate, framesPerBuffer, &inputLatency, &outputLatency, &hostBufferSizeMode )' failed in 'src/hostapi/alsa/pa_linux_alsa.c', line: 2842
Traceback (most recent call last):
  File "/home/bear/Documents/code/audiotest/audio.py", line 51, in <module>
    a = Recorder()
  File "/home/bear/Documents/code/audiotest/audio.py", line 32, in __init__
    self.stream = self.p.open(format=FORMAT,
  File "/usr/local/lib/python3.8/dist-packages/pyaudio.py", line 750, in open
    stream = Stream(self, *args, **kwargs)
  File "/usr/local/lib/python3.8/dist-packages/pyaudio.py", line 441, in __init__
    self._stream = pa.open(**arguments)
OSError: [Errno -9997] Invalid sample rate

OSError: [Errno -9997] Invalid sample rate)

import pyaudio
import math
import struct
Threshold = 100
SHORT_NORMALIZE = (1.0/32768.0)
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 16000
swidth = 2

f_name_directory = r'C/home/bear/Documents/code/audiotest/'

class Recorder:

    @staticmethod
    def rms(frame):
        count = len(frame) / swidth
        format = "%dh" % (count)
        shorts = struct.unpack(format, frame)

        sum_squares = 0.0
        for sample in shorts:
            n = sample * SHORT_NORMALIZE
            sum_squares += n * n
        rms = math.pow(sum_squares / count, 0.5)

        return rms * 1000

    def __init__(self):
        self.p = pyaudio.PyAudio()
        self.stream = self.p.open(format=FORMAT,
                                  channels=CHANNELS,
                                  rate=RATE,
                                  input=True,
                                  output=True,
                                  frames_per_buffer=chunk)

    def listen(self):
        print('Listening beginning')
        while True:
            input = self.stream.read(chunk)
            rms_val = self.rms(input)
            print(rms_val)
            if rms_val > Threshold:
                break

a = Recorder()

a.listen()


text:
Q: Push array if array doesn't exist in array of arrays I am currently working on a small home project, and I am trying to push an array into an array of arrays, if said array does not already exist in the array of arrays.
var arrayArr = [[1,4]];

function pushArr() {

    var tempArr = [1, 3];
    var tempArr2 = [1, 4];

    for(i = 0; i < arrayArr.length, i++)
        if(!arrayArr.indexOf(tempArr[i])) {
            arrayArr.push(tempArr[i]);
        } else {
            //other logic
        }

  }

Now, I know this example does not really make sense in the real world, it's just to illustrate my concern. How do I search through an array of arrays to make sure, that I don't create duplicates.
If you have any questions, please ask.
Thanks !

A: In my solution, in isArrayInArray(), I'm looping through each element in the main array arrayArr. I'm then comparing if the first and second element of each given array match. If so, the array has been added already so it'll return true.

var arrayArr = [[1, 4]];

pushArray([1, 4]); // does not get added
pushArray([1, 3]); // gets added

console.log(arrayArr);

function isArrayInArray(arrayToSearch, arrayToFind) {
    for (let i = 0; i < arrayToSearch.length; i++) {
        if (arrayToSearch[i][0] === arrayToFind[0] && arrayToSearch[i][1] === arrayToFind[1]) {
            return true;
        }
    }

    return false;
}

function pushArray(array) {
    if (!isArrayInArray(arrayArr, array)) {
        arrayArr.push(array);
    }
}

A: You know [1,2] === [1,2] is false.
Please refer to How to Compare two Arrays are Equal using Javascript?

A: Even if you have the following:
let a = [1,2];
let b = [1,2];

Both a and b hold two different references to to arrays that have the same numbers. They are not equal !

let a = [1,2];
let b = [1,2];
console.log(a === b);

If we by pass this and we assume that for our problem that two arrays with the same length and the same data are the same, we can try to call the function arrayCanBePushed, before we want to append an array to our array of arrays and if it returns true, then we can proceed with the push.

var arrayOfArrays = [[1,2],[2,3],[3,4,5],[7]];

function arrayCanBePushed(arr){
    return !arrayOfArrays.filter(a => a.length === arr.length)
                         .some(a => a.every(ele=>arr.includes(ele)));
}

console.log(arrayCanBePushed([1,2]));
console.log(arrayCanBePushed([1,2,3]));

A: Tried to keep the answer as simple as possible. Basically we are iterating over arrayArr and checking if all of the elements of the input array match all of the elements of any of the element arrays. So it should be simply an every nested in a some. However if we are comparing just two-element arrays (array to string conversion should be pretty fast) as you have now clarified in your answer then I would use string comparison as illustrated in pushArr1. This is the general direction you were heading in your first attempt so I added it to my answer.

var arrayArr = [[1, 3, 5]];
var tempArr = [1, 3, 5];
var tempArr2 = [1, 4];
pushArr1(tempArr);

function pushArr(temp)
{
    if(!arrayArr.some(function(e){
        return e.every(function(e1, i)
        {
          return e1 === temp[i];
        })
      })) arrayArr.push(temp);

      console.log(arrayArr);
}

function pushArr1(temp)
{
    if(!arrayArr.some(function(e){return e.join(",") === temp.join(",")})) arrayArr.push(temp);

      console.log(arrayArr);
}


text:
Q: App to allow battery charge only to a certain extent I'd like to charge my rMBP battery only up to 85% or 90%, in order to preserve it.
Is there any app that stops charging at user selected percentages?
If not, is there any other method? (Apart from manually detaching power cable, obviously).


text:
Q: How to call a method of a child class of a father class type list? C++ Ok so I have the situation set up:
ClassA()
{
     method();
}
ClassB: public ClassA()
{
     overrides method();
}

The I have this situtation going on another class:
list<ClassA> members;
addMethod(ClassA newMember)
{
     members.push_back(newMember);
}

update()
{
   for(std::list<ClassA>::iterator list_iter = members.begin(); list_iter != members.end(); list_iter++)
   {
       ClassA tklb = *list_iter;
       tklb.method();
   }

    return 0;
 }

The thing is that when I'm doing tklb.method() I want to call the on from the child class but he always calls from the parent class since it's a list . I need this since I have other classes that are child of classA and will do 'method' differently.

A: You need to use pointers to the item for it to behave polymorphically.  You are at the moment in danger of object slicing as an object could be placed in the list via a copy constructor.
In addition for a method to behave as you describe (polymorphism) you are required to declare the method as virtual. (I assume the lack of return type is a typo?).
Change to a std::list<ClassA*> (or better yet an appropriate smart pointer).


text:
Q: How do I resolve an Angular/rxjs/observable error? ref: Angular, Observable, rxjx 6.4.0
My code reads:
import { Observable } from 'rxjs';
import 'rxjs/add/observable/of';
...
return Observable.of(this.products);
...

The error reads:
Property 'of' does not exist on type 'typeof Observable'.

I can also remove the /add from the import since of.js exists on both folders.  But this returns the same error.

A: Your code should look like:
 import { Observable, of } from 'rxjs'

 return of(this.products);

A: As others have pointed out, with that version of RxJs the static methods and operators are imported differently.
Here is an example from their docs:
import { of } from 'rxjs';

of(10, 20, 30)
.subscribe(
  next => console.log('next:', next),
  err => console.log('error:', err),
  () => console.log('the end'),
);
// result:
// 'next: 10'
// 'next: 20'
// 'next: 30'

So your code would look like:
import { of } from 'rxjs';

...
return of(this.products);
...


text:
Q: Python magic mock not setting the mocked value I am writing python tests for the first time. I am trying to test a basic mock. I want to return some value that I want when I call the function, rather than a mock object.
Here is the code:
 In views:
def myfunction():
    return "Actual data"

In test:
class TestBasic(unittest.TestCase):
    @patch('trailblazer.views.myfunction')
    def testMyFunction(self, val):
        print(val)
        val.return_value = "Test value"
        print(val)
        op = myfunction()
        print(op)

output:
<MagicMock name='myfunction' id='4520521120'>
<MagicMock name='myfunction' id='4520521120'>
Actual data
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

PS: I don't have my methods in a class and I don't want to change that.

A: You have a direct reference to myfunction() in your test module, and that reference is never patched. You only patched the reference in the trailblazer.views module.
Your test would work if you used that reference instead of myfunction:
from trailblazer import views

class TestBasic(unittest.TestCase):
    @patch('trailblazer.views.myfunction')
    def testMyFunction(self, val):
        print(val)
        val.return_value = "Test value"
        print(val)
        op = views.myfunction()
        print(op)

However, a more meaningful test is to test the code that uses myfunction(). You use mocking to be able to focus on the behaviour of a specific unit of code, where mocking lets you precisely control interactions with other units.
In other words, if you have code like:
def some_function_to_test():
    # other things
    result = myfunction()
    # more things working on result
    return final_result

then when testing some_function_to_test() it makes sense to patch myfunction().
I recommend you read up on how Python names work; I highly recommend Facts and myths about Python names and values, together with Where to patch in the unittest.mock documentation.


text:
Q: Why does wget'ing an image give me a file, not an image? I do
wget http://services.runescape.com/m=itemdb_rs/3809_obj_sprite.gif?id=2

and it downloads the following file:
3809_obj_sprite.gif?id=2

How can I make it save as the following?
2.png

A: There is the command line option --content-disposition which - if the website supplies a correct header - should cause your file to be saved with the right name.
My debian squeeze box it says the option is "experimental" though...

A: Why does wget choose this name?
Unfortunately, wget will make no assumptions about what you want to download unless you tell it to. It doesn't care if your file is an image, a document, a zipped file, et cetera.
The file is saved as whatever the URL ended with – so anything from the last slash to the end of the URL. In your case, that's .gif?id=2. The part after the actual file extension (.gif) is contained in the URL, but it's a HTTP query parameter. For wget, however, it will determine the output filename.
How can I set a different filename?
If you want to specify an output filename for wget, add the -O (uppercase O) option:
wget example.com/something.gif?id=2 -O 2.gif

This will override the default behavior and set the filename to 2.gif. Note that the -o (downcase) option specifies the output filename for any log messages wget might otherwise print to the shell.
Finally, there's the --content-disposition option which might result in the proper filename being set. But this entirely depends on the server you're downloading from sending the correct header information:

This option is useful for some file-downloading CGI programs that use Content-Disposition headers to describe what the name of a downloaded file should be.

The option is currently still marked as experimental and thus not enabled by default.

I strongly encourage you to read the manpage of the tools you're using to understand their behavior. Just enter man wget and read through it, especially the options it provides.
Also, to address what @Indrek wrote in the comment on your question: I assume you have a typo there  and don't mean to download a GIF file into a file called .png — just changing the extension will not automatically make it a PNG. GIF and PNG use different encodings and you will have to use any kind of image conversion tool to convert between these formats. This conversion, however, will be lossless, so there's no harm done in downloading the files in the "wrong" format and converting later.

A: This is simply because look at the path, it ends in ?id=2, therefore it will save as this, you can move the file or use the -O parameter to define a file name.

A: If the file you direct wget to download for you is indeed an image, then what it downloads is an image. wget doesn't bother to guess the correct file name and extension, it uses what it finds in the URL e.g http://foobar.com/photo.php?n=cat.png you might get something like photo.php?n=cat.png but it is still an image. To fix your problem, simply rename that file to the correct name cat.png. Note that on most operating systems programs need the correct file extension to know that they can open a given file.

A: curl also has an option to guess the file name from Content-Disposition header:
curl -OLJ http://services.runescape.com/m=itemdb_rs/3809_obj_sprite.gif?id=2

Here
-O tells curl to save to a file rather than flushing to stdout
-L makes it follow the redirects
-J enables guessing by Content-Disposition instead of dissecting the URL

A: Also, with curl, say you don't know what the filename is going to be, due to redirects, or whathaveyou.. just follow the redirects via -L and pipe it to a file, with the correct extension..
curl -L http://links.mrgray.com/ocrtest > /files/file.png
wget may have similar functionality, dunno.


text:
Q: Paste predefined text into an editable textbox by clicking the contextmenu using a browser extension I'm trying to create a extension for Firefox that inserts a predefined text into the textbox by clicking on an option in the contextmenu.
I wrote the following code but it does not work:
function insert(text) {
document.getElementById('textbox').innerHTML = "THE TEXT I WANT";
}

chrome.contextMenus.create({
title: "TITLE", onclick: insert});

The manifest is also as follows:
"manifest_version": 2,
"name": "NAME",
"description": "DESCRIPTION",
"version": "1",
"author": "ME",
"homepage_url": "https://github.com",

"icons": {
  "48": "icons/48.png",
  "96": "icons/96.png"
},

"permissions": [
  "activeTab",
  "contextMenus",
  "webNavigation"
],

"browser_action": {
  "default_icon": {
  "48": "icons/48.png",
  "96": "icons/96.png"
},
  "default_title": "TITLE"
},

"background": {
  "scripts": [
    "extension.js"
  ]
}

Thanks for your help.


text:
Q: Dynamically build lambda expression from a collection of objects? I have a list of sorts stored in this format:
public class ReportSort
{
    public ListSortDirection SortDirection { get; set; }
    public string Member { get; set; }
}

And I need to turn it into a lambda expression of type Action<DataSourceSortDescriptorFactory<TModel>>
So assuming I have the following collection of Report Sorts as:
new ReportSort(ListSortDirection.Ascending, "LastName"),
new ReportSort(ListSortDirection.Ascending, "FirstName"),

I would need to transform it into such a statement to be used like so:
.Sort(sort => {
        sort.Add("LastName").Ascending();
        sort.Add("FirstName").Ascending();
      })

And the sort method signature is:
public virtual TDataSourceBuilder Sort(Action<DataSourceSortDescriptorFactory<TModel>> configurator)

So I have some method right now:
public static Action<DataSourceSortDescriptorFactory<TModel>> ToGridSortsFromReportSorts<TModel>(List<ReportSort> sorts) where TModel : class
    {
        Action<DataSourceSortDescriptorFactory<TModel>> expression;
        //stuff I don't know how to do
        return expression;
    }

...and I have no idea what to do here.
EDIT: Answer is:
var expression = new Action<DataSourceSortDescriptorFactory<TModel>>(x =>
        {
            foreach (var sort in sorts)
            {
                if (sort.SortDirection == System.ComponentModel.ListSortDirection.Ascending)
                {
                    x.Add(sort.Member).Ascending();
                }
                else
                {
                    x.Add(sort.Member).Descending();
                }
            }
        });

I was thinking at first I had to dynamically build a lambda expression from scratch using the Expression class. Luckily that wasn't the case.

A:
...and I have no idea what to do here.

Well, reason it out.
What have you got in hand? A List<ReportSort> called sorts.
What do you need? An Action<Whatever>.
You've already taken the first step: you've make a method that takes the thing you have and returns the thing you need. Great first step.
    Action<DataSourceSortDescriptorFactory<TModel>> expression;
    //stuff I don't know how to do
    return expression;

And you've called out what you don't know how to do -- yet.  This is a good technique.
Start by filling in something that compiles but doesn't work properly.
Action<DataSourceSortDescriptorFactory<TModel>> expression =
  sort => {
    sort.Add("LastName").Ascending();
    sort.Add("FirstName").Ascending();
  };
return expression;

Excellent.  Now you have a compiling program which means you can run your tests and verify that if this case is expected, the test passes, and if anything else is expected, the test fails.
Now think, what have I got in hand?  I've got a list of stuff, and I'm doing an Action.  That means that a side effect is happening, probably involving every item on the list.  So there's probably a foreach in there somewhere:
Action<DataSourceSortDescriptorFactory<TModel>> expression =
  sort => {
    sort.Add("LastName").Ascending();
    sort.Add("FirstName").Ascending();
    foreach(var sort in sorts) {
      // Do something
    }
  };
return expression;

Compile it.  It fails.  Ah, we have confused the sort we are adding to with the new sort we are adding.  Fix the problem.
Action<DataSourceSortDescriptorFactory<TModel>> expression =
  existingSort => {
    existingSort.Add("LastName").Ascending();
    existingSort.Add("FirstName").Ascending();
    foreach(var newSort in sorts) {
      // Do something
    }
  };
return expression;

Great, now again we are in a position to compile and run tests.
The pattern here should be clear.  Keep it compiling, keep running tests, gradually make your program more and more correct, reason about the operations you can perform on the values that you have in hand.
Can you finish it off?

A: You could use the following lambda expression that you could assign to the Action<T> delegate. In that lambda expression, capture the List<T> variable and loop over it:
public static Action<DataSourceSortDescriptorFactory<TModel>> ToGridSortsFromReportSorts<TModel>(List<ReportSort> sorts) where TModel : class
{
    Action<DataSourceSortDescriptorFactory<TModel>> expression =
       result  =>
       {
           foreach (var sort in sorts)
           {
                if (sort.SortDirection == ListSortDirection.Ascending)
                    result.Add(sort.Member).Ascending();
                else // or whatever other methods you want to handle here
                    result.Add(sort.Member).Descending();
           }
       };
    return expression;
}


text:
Q: C# - Need Suggestions on Improving a Section of Code I have a function that receives three different "people" objects and generates a new "compatibility" object based on the combined values in the "people" objects.
However, about 1/3 of the time the three "people" objects that it receives as input are the same as one before, though possibly in a different order. In these cases I do NOT want to make a new "score" object, but simply return a value contained within the existing object.
Originally, the program just loops through the list<> of "compatibility" objects searching for the one that belongs to these three "people" (since each "compatibility" object contains an array of people objects). This method is really slow considering that there's over thousands of "compatibility" objects and over a million "people" objects.
I had the idea of using a dictionary where the key is a number I generated by combining the three people objects' id values into a single UInt64 using XOR, and storing the score objects in as dictionary values rather than in a list. This cuts down the time by about half, and is acceptable in terms of time performance, but there's way too many collisions, and it returns a wrong score too often.
Any suggestions or pointers would be much appreciated.
Edit: To add to the original question, each "people" object has a bunch of other fields that I could use, but the problem is making a key that is UNIQUE and COMMUTATIVE.

A: I think you're looking at things in a much too complex manner. Take the 3 PersonID values and sort them,so that they're always in the same order, no matter which order they were passed in. Then set a value in a hashtable using the three PersonIDs as the key, separated with a hyphen or some other character that won't occur in a PersonID value. Then later, check if there's a value in the hashtable with that key.
So if the three PersonIDs are 10, 5 and 22, the hash key could be something like "5-10-22".

A: Create the key by concatinating objectids after sorting the trio in a pre-determined order.

A: Your best option would be a custom IEqualityComparer class. Declare your Dictionary like this
Dictionary<List<People>, Compatability> people =
    new Dictionary<List<People>, Compatability>(new PersonListComparer());

You'll need to create a PersonListComparer class that implements IEqualityComparer<List<People>>. There are two methods you'll need to implement, one that gets a hash code and one that compares equality. The Dictionary will use GetHashCode to determine if two lists are POSSIBLY equal, and the Equals method to determine if they actually are (in other words, the hash code is fast but could give a false positive but never a false negative). Use your existing hashing algorithm (the XOR) for GetHashCode, then just comare the two lists explicitly in the Equals method.
This should do the trick!

A: Why not use the names of the people as the dictionary key? (Sort the names first, so that order of passing doesn't matter.)
IE, John, Alice, and Bob become something like my_dictionary["Alice_Bob_John"] <- if that key exists, you've already computed the score, otherwise, you need to compute it. As an alternative to my string hacking above, you could actually use a structure:
NameTriple n = new NameTriple("John", "Alice", "Bob");
// NameTriple internally sorts the names.
my_dictionary[n] ...

A: If you want to keep everything in memory and not use a database, I'd recommend something akin to a tree structure. Assuming your object IDs are sortable and order doesn't matter, you can accomplish this with nested dictionaries.
Namely, a Dictionary<Key, Dictionary<Key, Dictionary<Key, Compatibility>>> should do the trick. Sort the IDs, and use the lowest value in the outer dictionary, the next value in the next, and the final value to find the compatibility object. This way, there will be no collisions, and lookup should be quite fast.
Or, now that I think again, this doesn't have to be that complicated. Just use a string as a key and concatenate the IDs together in sorted order with a "!" or something else in between that doesn't occur naturally in the IDs.

A: assuming all "Person" objects are unique, store a UUID in the object.
in your function staticly store the quad (P1,P2,P3,V) where P1,P2,P3 are UUID's of a Person object, sorted (to avoid the ordering problem) and V is the result from the previous calculation.
then your function checks to is if there is an entry for this triplet of Persons, if not it does the work and stores it.
you can store the (P1,P2,P3,V) values in a dictionary, just key off some hash of the three P values


text:
Q: EXCEL VBA with VBS SAP session.findById variable not working I need to loop this section and overwrite the x marked positions with my variable x value but if i use it as it is shown on the pic nothings happen. If i enter any value like 1 or 2 instead of x it works. How can i use a variable instead of a value in these places?
Here is also the code:
For j = 1 To SumPositionen
If Sheets("Datenverarbeitung").Cells(Z, 4) = tempCommodityForm Then
session.findById("wnd[0]/usr/tabsTAB_DETAILS/tabpTAB_MF/ssubTABMF:/HERA/TRDMF10:2023/tbl/HERA/TRDMF10TC_2023/ctxt/HERA/TRDINOUT_S-MATNR[1,x]").Text = Sheets("Datenverarbeitung").Cells(a, 5) 'Eingabe Materialnummer in 1. Position
session.findById("wnd[0]/usr/tabsTAB_DETAILS/tabpTAB_MF/ssubTABMF:/HERA/TRDMF10:2023/tbl/HERA/TRDMF10TC_2023/txt/HERA/TRDINOUT_S-MFQUAN[2,x]").Text = Sheets("Datenverarbeitung").Cells(a, 6) 'Eingabe Menge in 1. Position
session.findById("wnd[0]/usr/tabsTAB_DETAILS/tabpTAB_MF/ssubTABMF:/HERA/TRDMF10:2023/tbl/HERA/TRDMF10TC_2023/ctxt/HERA/TRDINOUT_S-MFU[3,x]").Text = Sheets("Datenverarbeitung").Cells(a, 7) 'Eingabe UoM
x = x + 1
End If
a = a + 1
Next j

A: session.findById("wnd[0]/usr/tabsTAB_DETAILS/tabpTAB_MF/ssubTABMF:/HERA/" & _
  "TRDMF10:2023/tbl/HERA/TRDMF10TC_2023/ctxt/HERA/TRDINOUT_S-MATNR[1,x]").Text

Here your string includes the literal value "x".   What you really want is likely something more like:
session.findById("wnd[0]/usr/tabsTAB_DETAILS/tabpTAB_MF/ssubTABMF:/HERA/" & _
  "TRDMF10:2023/tbl/HERA/TRDMF10TC_2023/ctxt/HERA/TRDINOUT_S-MATNR[1," & x & "]").Text

So something like:
Dim s As String, sht As Worksheet
'....
'....

Set sht = Sheets("Datenverarbeitung")

s = "wnd[0]/usr/tabsTAB_DETAILS/tabpTAB_MF/ssubTABMF:/HERA/" & _
    "TRDMF10:2023/tbl/HERA/TRDMF10TC_2023/ctxt/HERA/"

For j = 1 To SumPositionen
    If sht.Cells(Z, 4) = tempCommodityForm Then
        session.findById(s & "TRDINOUT_S-MATNR[1," & x & "]").Text = sht.Cells(a, 5)  'Eingabe Materialnummer in 1. Position
        session.findById(s & "TRDINOUT_S-MFQUAN[2," & x & "]").Text = sht.Cells(a, 6) 'Eingabe Menge in 1. Position
        session.findById(s & "TRDINOUT_S-MFU[3," & x & "]").Text = sht.Cells(a, 7)    'Eingabe UoM
        x = x + 1
    End If
    a = a + 1
Next j

A: define data type to variable link string and integer


text:
Q: Token Authentication with web api My scenario is that we're using MongoDB as a storage backend, and on the client side we use DustJS/bootstrap and jquery plugins for the rest. No complex client side frameworks. It's a single page app and when the user has entered a user/pass in the login form, we create a token based on the user and password, store some info about the user in it (firstname, lastname and so on), expiry date, and the sign the token. This is like max 5-10 lines of code.
When the user logs out, we invalidate the token.
Then we auth the user from the token after this, this is all done in an actionfilter.
This takes me(you) 5 minutes to create.
I've been reading through dozens of tutorials and posts about asp.net identity, jwt bearer tokens, cookie middleware and so on. I've also looked through the sample project when you start a new project with Windows Authentcation in asp.net mvc api.
It really baffles me on how much complexity and code is needed to get this working.
So if anyone can enlighten me, why can't I just use my simple approach and still be as safe as the complex approach? If you have a reason, please specify exactly why, don't just say XSS and CSRF, those are easily avoided.


text:
Q: postback __EVENTTARGET ID in Page.Request.Form has $ not _ in ASP.NET I am using the ToolkitScriptManager from the Ajax tool kit and I am having a problem finding my button's ID.
My ID's on my controls come back with $ symbols instead of _ symbols, like the following:

Grid$ctl06$insertButton

This obviously causes problems when attempting to find the control from the Page.Request.Form keys.  I cannot seem to find the determining factor that would cause this.
Now, I know this is the name and in my source I see that the ID is with the _, so why is the Page.Request.Form showing up with the $ symbol instead?  Anybody encounter this before?
UPDATE: Is it possible that since this button is nested within the Grid that is in the UpdatePanel, it is not found in the PreInit event?  I see many other controls have already been initialized by this point, but this one has not.

A: In ASP.NET, the control IDs have '_' and the control names have '$'.  The form collection is based on name, not on ID which is why you are seeing this behavior.  As a side note, it looks like you are using controls within a databound grid, have you tried to use the grid's event handlers to handle these actions?  Then you wouldn't need to know which row or grid that it came from.  An example of a grid view event handler


text:
Q: Data.Data -- producing dataCast1 for an arity 2 type constructor (partially specialized) So Data.Map has dataCast2 defined, which makes sense, as it has an arity 2 type constructor. dataCast1 defaults to const Nothing. dataCast2 is easily defined as gcast2.
For reference:
class Typeable a => Data a where
    dataCast1 :: Typeable1 t => (forall d. Data d => c (t d)) -> Maybe (c a)
    dataCast2 :: Typeable2 t => (forall d e. (Data d, Data e) => c (t d e)) -> Maybe (c a)
    ...

gcast1 :: (Typeable1 t, Typeable1 t') => c (t a) -> Maybe (c (t' a))
gcast2 :: (Typeable2 t, Typeable2 t') => c (t a b) -> Maybe (c (t' a b))

The question at hand is this: given everything in Data.Data, Data.Typeable, etc., and given an arity 2 type constructor for which dataCast2 is defined (say, Map, or (,) ), is it possible to write a version of dataCast1 that does the right thing for a partial specialization of this type constructor, either for one specific constructor at a time, or in general?
Intuitively, I think there should be a good solution, but my first few tries crashed and burned.

A: I'm not sure if this is what you want, but it might steer you in the right direction if it's not. It is written in a very similar style to the gcast, gcast1, and gcast2 functions in the Data.Typeable library. For more details, "read the source, Luke".
myDataCast1 :: forall c t d e a.(Typeable d, Typeable e) => c (t d a) -> Maybe (c (t e a))
myDataCast1 x = r
   where
     r = case typeOf (getArg x) == typeOf (getArg (fromJust r)) of
           True  -> Just $ unsafeCoerce x
           False -> Nothing
     getArg :: c (t x a) -> x
     getArg = undefined

Using this function you can, for instance write foo
foo :: Typeable d => c (d, a) -> Maybe (c (Int, a))
foo = myDataCast1

A: According to this paper the way to implement dataCast1 is either as
dataCast1 f = gcast1 f -- for unuary type constructors

or
dataCast1 f = Nothing -- for non-unary type constructors

They haven't said that this is the only way to implement it, but it might be the case. Perhaps it's worth asking the authors? I think the core problem is that we can't partially apply type constructors. e.g. the following is not possible
data T a b = ...

instance Typeable a => Data (T Int) where
   dataCast1 f = ...

GHC will complain that T has not been applied to enough type arguments.
I can think of a work-around though. We define a newtype
newtype PairInt a = PairInt (Int, a) deriving Typeable

instance (Typeable a, Data a) => Data (PairInt a) where
  dataCast1 f = gcast1 f

It's pretty annoying but it does the job. But perhaps it doesn't fit with what you're trying to achieve.


text:
Q: Is it possible to Create sample movie ( mini movie) with ffmpeg? Is it possible to create a mini movie ( if i have a movie which is 1 hour - i want 3 seconds of it) with ffmpeg ?
How do i do it ?

A: This command will copy the first 3 seconds of input.avi to output.avi.
ffmpeg -ss 0 -t 3 -i input.avi -codec copy output.avi

This will stream copy (re-mux), so no encoding is occurring.
If you want to re-encode then remove -codec copy:
ffmpeg -ss 0 -t 3 -i input.avi output.flv


text:
Q: Openshift .kubeconfig file and certificate authentication I have been messing around with openshift and reading as much documentation as i can. Yet, the authentication performed by default(using admin .kubeconfig) puzzles me.
1)Are client-certificate-data and client-key-data the same as the admin certificate and key? I ask this because the contents of the certificate/key files are not the same as in .kubeconfig.
2).kubeconfig (AFAIK) is used to authenticate agains a kubernetes master. Yet, in OpenShift we are authentication against OpenShift master (right?). Why using .kubeconfig?
Kinds regards and thank you for your patience.

A: OpenShift builds on top of Kubernetes - it exposes both the OpenShift APIs (builds, deployments, images, projects) and the Kubernetes APIs (pods, replication controllers, services).  A client connecting to OpenShift will use both sets of APIs.  OpenShift can run on top of an existing Kubernetes cluster, in which case it will proxy API calls to the Kubernetes master and then apply security policy on top (via the OpenShift policy engine which may eventually become part of Kube).
So, the client is really an extension of Kubectl that offers some additional functionality, and it can use .kubeconfig to be consistent with a Kubectl setup.  You can talk to an OpenShift cluster via kubectl, so vice versa seems fair.
The client-certificate-data and key-data are base64 encoded versions of the files on disk.  They should be the same once you decode them.  We do that so the .kubeconfig can be shipped around as one unit, but you can also set it up to reference files on disk.


text:
Q: Insufficient privileges error on snowpipe with account admin role I have created a snowpipe to access s3 data in snowflake. I used the below query to pause the pipe which ran successfully.
use role accountadmin;
alter pipe PIPE1 set pipe_execution_paused = true;

But when I am trying to set pipe execution failed with the same above role it shows insuffiecient prileges error. I am trying following query.
use role accountadmin;
alter pipe PIPE1 set pipe_execution_paused = false;

Any idea whats going wrong here?? Thanks

A: No probs, glad I could help.
Has the ownership of the pipe changed? Try using SYSTEM$PIPE_FORCE_RESUME: Force Snowpipe


text:
Q: How to check if a variable is empty in python? I am wondering if python has any function such as php empty function (http://php.net/manual/en/function.empty.php) which check if the variable is empty with following criteria
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)

A: Just use not:
if not your_variable:
    print("your_variable is empty")

and for your 0 as string use:
if your_variable == "0":
    print("your_variable is 0 (string)")

combine them:
if not your_variable or your_variable == "0":
    print("your_variable is empty")

Python is about simplicity, so is this answer :)

A: See section 5.1:
http://docs.python.org/library/stdtypes.html
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:
None
False
zero of any numeric type, for example, 0, 0L, 0.0, 0j.
any empty sequence, for example, '', (), [].
any empty mapping, for example, {}.
instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]
All other values are considered true — so objects of many types are always true.
Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)

A: See also this previous answer which recommends the not keyword
How to check if a list is empty in Python?
It generalizes to more than just lists:
>>> a = ""
>>> not a
True

>>> a = []
>>> not a
True

>>> a = 0
>>> not a
True

>>> a = 0.0
>>> not a
True

>>> a = numpy.array([])
>>> not a
True

Notably, it will not work for "0" as a string because the string does in fact contain something - a character containing "0". For that you have to convert it to an int:
>>> a = "0"
>>> not a
False

>>> a = '0'
>>> not int(a)
True

A: Yes, bool. It's not exactly the same -- '0' is True, but None, False, [], 0, 0.0, and "" are all False.
bool is used implicitly when you evaluate an object in a condition like an if or while statement, conditional expression, or with a boolean operator.
If you wanted to handle strings containing numbers as PHP does, you could do something like:
def empty(value):
    try:
        value = float(value)
    except ValueError:
        pass
    return bool(value)

A: You can use the not keyword.
if not a
    print("a is empty")


text:
Q: Remove xmlns information from generated file? I am using Elementtree to parse an xml file, edit the contents and write to a new xml file. I have this all working apart form one issue. When I generate the file there are a lot of extra lines containing namespace information. Here are some snippets of code:
import xml.etree.ElementTree as ET
ET.register_namespace("", "http://clish.sourceforge.net/XMLSchema")
tree = ET.parse('ethernet.xml')
root = tree.getroot()

commands = root.findall('{http://clish.sourceforge.net/XMLSchema}'
                        'VIEW/{http://clish.sourceforge.net/XMLSchema}COMMAND')

for command in commands:
    all1.append(list(command.iter()))

And a sample of the output file, with the erroneous line xmlns="http://clish.sourceforge.net/XMLSchema:
<COMMAND xmlns="http://clish.sourceforge.net/XMLSchema" help="Interface specific description" name="description">
            <PARAM help="Description (must be in double-quotes)" name="description" ptype="LINE" />
            <CONFIG />
</COMMAND>

How can I remove this with elementtree, can I? Or will i have to use some regex (I am writing a string to the file)?


text:
Q: How to remove the rectagular white colored frame from my ax.pcolormesh() density plot? from mplsoccer.pitch import Pitch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import kde

np.random.seed(19680801)
plt.style.use('dark_background')
fields = ['id', 'minute', 'result', 'X1', 'Y','xG','h_a','situation','season',
          'shotType','X']
df=pd.read_csv('shots.csv', skipinitialspace=True, usecols=fields)

df1 = pd.DataFrame({'A':df.Y,'B':df.X} )
a=(df1.to_numpy())
x, y = a.T
k = kde.gaussian_kde(a.T)

nbins=50

xi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j]
zi = k(np.vstack([xi.flatten(), yi.flatten()]))

pitch = Pitch(orientation='vertical',pitch_type='metricasports', view='half',
              linewidth=2, line_zorder=1,
              line_color= '#94A7AE',pitch_length=105, pitch_width=68,pad_bottom=0)

fig, ax = pitch.draw()
ax.pcolormesh(xi, yi, zi.reshape(xi.shape), shading='gouraud', cmap='Reds',facecolor='black'
              )

ax.set_xlim(ax.get_xlim()[::-1])
ax.yaxis.tick_right()
plt.axis('off')
plt.show()

Output Plot here
I want the only red-colored density plot, not the white rectangular background frame. How to make the frame the same as my background?

A: Here is an approach using a colormap with an "under" color of 'none'. By setting vmin to a cut-off value, the cells with a lower value will get the "under" color ('none' stands for fully transparent). To get an idea of the values, temporarily a colorbar can be added. The values depend strongly on the extension of the x and y values (the integral of the kde is 1, so over a small domain the values need to be high enough).
from mplsoccer.pitch import Pitch
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import kde
from copy import copy

np.random.seed(19680801)
plt.style.use('dark_background')
# first create some random toy data roughly mimicking the given plot
x = np.random.randn(100, 20).cumsum(axis=0).flatten()
y = np.random.randn(100, 20).cumsum(axis=0).flatten()
x = x * 0.04 + 0.5
y = y * 0.01 + 0.9
k = kde.gaussian_kde([x, y])

nbins = 50
xi, yi = np.mgrid[x.min():x.max():nbins * 1j, y.min():y.max():nbins * 1j]
zi = k(np.vstack([xi.flatten(), yi.flatten()]))

pitch = Pitch(orientation='vertical', pitch_type='metricasports', view='half',
              linewidth=2, line_zorder=1,
              line_color='#94A7AE', pitch_length=105, pitch_width=68, pad_bottom=0)

fig, ax = pitch.draw()
cmap = copy(plt.get_cmap('Reds'))
cmap.set_under('none')
pmesh = ax.pcolormesh(xi, yi, zi.reshape(xi.shape), shading='gouraud', cmap=cmap, vmin=5, facecolor='black')
# fig.colorbar(pmesh, ax=ax) # to temporarily get an idea of the values
ax.invert_xaxis()
ax.yaxis.tick_right()
plt.axis('off')
plt.show()


text:
Q: Implementing ASP.NET Identity into existing web application Having read lots of articles and making lots of false starts I need some advise on adding Microsoft ASP.NET Identity to my existing ASP.NET Web Forms application.  There are so many subtle differences between my existing application and typical samples out there that I don't know how to get off the ground.  Here are some points about my existing application:

*

*It is a ASP.NET Web Forms application (.NET Framework 4.6) that has evolved over about 4-5 years

*It uses SQL Server database though Entity Framework (not Code First but Database First).  The database pre-dates the web application and is based on 10 year old designs.  It does however have good table relationships etc.

*My database's schema for Users and Roles are not structured as per "ASP.NET Identity / EntityFramework".  It has a [User] table with ID int PK, no username (as such), Password, First Name, Surname, Email and some other properties. It also has a Roles table (4-5 entries) and a UserRoles table that provides many-many relationships.  There is no "claims" as such other than properties on the User table.

*Existing login is based on entering a user id (primary key) and password which is then checked against the user table and on successful login (stored proc), details are then stored in Session - something that in itself isn't quite right!

*Although using Entity Framework, the Connection String is formed at runtime based on a template connection string in web.config (basically, the database name and server instance name is populated dynamically)

So, here are some the barriers, issues, questions I've come up with.  Any advise on any of the questions below would be most appreciated:

*

*Should I use as "User.Username" when my web application doesn't have one?  Should I use Email Address or UserID?  Email address unfortunately isn't unique across the existing [User] data set.  Should I use a string version of my (int) UserID?

*Should I allow ASP.NET Identity to set up its own code first tables into my own database and then add a mapping to my legacy [User] table?

*How can I inject a "resolver" to provide a (dynamically generated) connection string to the existing ASP.NET Identity Data Stored/Data Access Layer?

*How much of the Store classes am I likely needing to replace?

*I've read that NOT using an ORM/EntityFramework can provide very inefficient data access.  Does this mean that if implementing my own Storage classes, I can't simply use some of my existing Stored Procedures?

*My Web Forms application isn't making use of any async code.  Is this going to cause me problems with the ASP.NET Identity framework?  I've heard that async works best if implemented right through the call stack.

*Do I need to somehow disable the existing Forms Based Authentication?  Are they two going to clash over writing to HttpContext.User for example?

My Schema
CREATE TABLE [dbo].[User](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [OrganisationID] [int] NOT NULL,
    [SaltHashPassword] [nvarchar](128) NOT NULL,
    [FirstName] [nvarchar](64) NOT NULL,
    [Surname] [nvarchar](64) NOT NULL,
    [Email] [nvarchar](128) NULL,
    --...
 CONSTRAINT [PK_User] PRIMARY KEY NONCLUSTERED ([ID] ASC)
) ON [PRIMARY]

CREATE TABLE [dbo].[Roles](
    [Role] [varchar](8) NOT NULL,
    [Name] [varchar](32) NOT NULL,
    [Description] [varchar](1000) NOT NULL,
    [OrderNo] [tinyint] NOT NULL,
 CONSTRAINT [PK_Roles] PRIMARY KEY CLUSTERED ([Role] ASC)--...
 CONSTRAINT [IX_Roles] UNIQUE NONCLUSTERED ([Role] ASC)--...
) ON [PRIMARY]

CREATE TABLE [dbo].[UserRole](
    [UserID] [int] NOT NULL,
    [Role] [varchar](8) NOT NULL,
 CONSTRAINT [PK_UserRole] PRIMARY KEY CLUSTERED ([UserID] ASC,[Role] ASC)
) ON [PRIMARY]

A: That's a lot of questions here. I think a good starting point is this migration article: Migrating an Existing Website from SQL Membership to ASP.NET Identity
It will probably help you answer most of your questions here, especially 1, 3 and 4.
Answer to Question 2: As ASP.NET Membership and ASP.NET Identity are two different things, I would suggest a full migration, meaning that once you created the new tables for Identity, you map your foreign keys to the new tables and get rid of ASP.NET Membership tables.
Answer to Question 5: I think it depends how you want to set up ASP.NET Identity. In the project I am currently working on, we decided not to use Entity Framework at all, but this makes everything more complex as you have to get very deep knowledge of what happens, when, how, why... So if you are looking for easy implementation, use EF it makes life much more easy and you will find plenty of code samples on Internet.
Answer to Question 6: If you don't use async, it won't cause issues. The only downside is that you won't benefit from it...
Answer to Question 7: Microsoft does not recommend having multiple authentication systems activated. In the project I am currently working on, we managed to have both Identity and Azure AD authentication working together, but we had to develop our own middlewares and it was not that easy. In our web.config, we have:
<system.web>
    ...
    <authentication mode="None" />
    ...
</system.web>


text:
Q: When does a probability measure take all values in the unit interval? Let $\mathbb{P}$ be a probability measure on some probability space $(\Omega,\mathcal{A})$. Are there conditions on the $\sigma$-algebra $\mathcal{A}$ such that for every real number $c\in [0,1]$ we find a set $A\in\mathcal{A}$ with $\mathbb{P}(A)=c$.
It is like the intermediate value theorem for continuous functions.

A: This is a property of $\mu$, not that of $\mathcal A$, and it is called being atomless. It is equivalent to not having sets $A \in \mathcal A$ of positive measure such that for all $B \in \mathcal A$, $B \subseteq A$ the measure $\mu(B)$ is either 0 or $\mu(A)$.
edit: Wikipedia article, complete with the proof of the property you describe from atomlessness.
edit: yup, the comments are right and I'm wrong. The precise condition for finite measures composed entirely of atoms to have full range is $a_n \leq \sum_{j>n} a_j$ - it is clearly necessary as $a_n-\varepsilon$ has to be produced somehow, and the greedy algorithm shows sufficiency.

A: Here's a concrete example of an atomless measure.  Let $f \in L^1$ be an integrable function with total mass 1 (i.e. $\int_0^1 f = 1$).  Define $$\mathbb P(A) = \int_A f(x) ~dx$$ for any Borel set $A$.  It is a nice exercise to show that $\mathbb P$ is an atomless measure.
Note:  $f$ is called the Radon-Nikodym derivative of $\mathbb P$ with respect to Lebesgue measure, and often written $f = \tfrac{d\mathbb P}{dx}$.  If a random variable $X$ has distribution $\mathbb P$, then $f$ is called its density function.

A: A necessary and sufficient condition is that every atom is no larger than the sum of all smaller atoms, plus the non-atomic part.

A: A measure space $(\mathbb{P},\Omega,\mathcal{A})$ is atomless if for all $A\in\mathcal{A}$ with $\mathbb{P}(A)>0$ there exists $B\subset A, B\in\mathcal{A}$ such that $0<\mathbb{P}(B)<\mathbb{P}(A)$. Now according to a theorem of Sierpinski, the values of an atomless measure space form an interval. In particular, for probability spaces, every value in $[0,1]$ is taken. The original source of the article can be found here (in french). For a proof in english, you can look at on 215D on page 46 in Fremlin's book Measure Theory 2.


text:
Q: Publishing message having same messageId to Anypoint MQ I am creating custom messageId for each message published to MQ, but for few messages same messageId is generated.
How Anypoint MQ process message having same messageId in FIFO and standard queue?
I don't want to create duplicate records. Also, Want to keep the last copy of the message and discard the older one.
Any idea, how can I achieve this?

A: The default behaviour sounds like exactly what you want - The ID of an Anypoint MQ message must be unique. Make sure to choose a unique custom ID to avoid unwanted side effects of duplicated IDs. In FIFO queues, messages with duplicate IDs are overwritten.
But if your message has already been read, then The ID is free to use again.


text:
Q: Is there a parser/script to get data from github We recently started using GitHub+ZenHub as a project management tool. I'm looking for a way to get data from github for my manager to easily put in update emails she has to send weekly. I was able to connect to our github instance with curl command but it's pulling a lot of data I don't need.
curl -u user:token -i https://github.ibm.com/api/v3/issues

All I need is to get stuff like all updates added to certain issue, or list all updates posted by certain person. So far I wasn't able to write a proper curl command to get info on only one issue for example. Also am I correct that curl used with user:token gets only information about issues created by the user and not all from whole repository?
I read through the GitHub APIv3 documentation but no luck. I don't know how to narrow my command to give me only what I want.
Do you know if there is any tool that would help me to get the raw data? I know GitHub 2.10 has new API, but we're still using 2.9.5 and there's no telling when we will update.

A:
All I need is to get stuff like all updates added to certain issue, or list all updates posted by certain person. So far I wasn't able to write a proper curl command to get info on only one issue for example.

Have you seen this page?
https://developer.github.com/v3/issues/#get-a-single-issue
For example if your repository is at https://github.com/user/repo,
then you can use these queries to get info about issue #5:
curl -sL api.github.com/repos/user/repo/issues/5/
curl -sL api.github.com/repos/user/repo/issues/5/comments
curl -sL api.github.com/repos/user/repo/issues/5/events

In case of public repositories, the above works even without authentication.
As a tip, I recommend piping these commands to jq . | less for nice readable formatting.
You can get public events by a specific user with another API endpoint:
https://developer.github.com/v3/activity/events/#list-events-performed-by-a-user


text:
Q: Apply output format only to specific commands using [format] config section I modified gitconfig to obtain a colorful and easier to read git log:
[format]
    pretty = %C(yellow)%h %C(green)(%cd) %C(reset)%s%C(bold yellow)%d %C(bold cyan)<%an>%C(reset)

The issue is that this formatting also applies to git show, so I don't have any easy way to read multiple-lines commit messages anymore.
So far, I came up with two annoying solutions:

*

*leaving gitconfig with this format section and use --pretty=medium when I want to see multi-lines commit messages.

*removing the format section from gitconfig and create aliases for oneline logs:
l = log --decorate --pretty=format:'the whole formatting chain'
ll = log --decorate -p --pretty=format:'the whole formatting chain again'
Is there any shorter or more elegant way to apply this kind of formatting to the log command only ?

A: This is distinctly non-pretty and non-elegant, but at least you can tweak the format in one place:
[alias]
    l = !git log "--pretty=format:\"$(git config --get myformats.log)\"" --decorate

(add ll etc., as desired).  The quoting above was found by experiment....
[myformats]
    log = %C(yellow)%h %C(green)(%cd) %C(reset)%s%C(bold yellow)%d %C(bold cyan)<%an>%C(reset)


text:
Q: Twilio Video with Typescript I created a component with Angular 2 and Typescript that allow create a video calls using a library Twilio Video. I trying to create a custom typing for typescript of library twilio-video, the way used in other posts like:
declare var Twilio:any;

work for my only when I used a twilio client library, but not with twilio video.
interface Twilio {
  //Other declarations here
  Video: any;
}
declare namespace Twilio {
  //Others interface here like Connection and Device from client library
  interface Video {
    connect(token: string, options?:Object): Promise;
    createLocalTracks(options?:Object): Promise;
    //Other declarations of methods
  }
}

and finally can declare:
declare var Twilio:Twilio;

With these custom type work a video call, I can create a room and create a local tracks, but cannot use a disable or enable methods from LocalTrack, I review a code of library twilio-video and read about create custom types and I think that the library is necesary used a template like that show here, something like that:
export as namespace Twilio;
export = Video;

declare class Video {
  connect(token:string, options: Object): Promise;
  createLocalTracks(options?: Object): Promise;
  //Other declarations of functions of Video
}

declare namespace Video {
   export interface LocalVideoTrack {
       new(mediaStream:any, mediaStreamTrack:any, options:Object);
       disable():void;
       enable():void;
   }
}

That way can used as namespace Twilio, but cannot declare nothing using Twilio.Video as library used, I cannot use instanceof to cast a var, and don't have relationship with the code of library.
The primary problem for me is that I cannot declare correctly a custom typescript typing that used all functions declared in twilio video library. I am new using typescript only a few weeks ago.


text:
Q: Issue inserting ampersands into MySQL I've been trying to fix this issue for a while, I've spent endless amounts of time on the web searching for a solution for it. So I thought I'd come to you guys since I am at wits end with this problem. Basically I have a CMS system that I designed a while back, I recently updated it to modern standards using PDO and such like, now I seem to have an issue inserting ampersands (&) into the MySQL database, everything is set to 'UTF-8', the PDO connection, the MySQL collation, everything, yet for some reason when there is an ampersand in the form from the textarea's, the data is sent, but is cut off when it reaches the ampersand, as if it's parsing it and cutting it off because it thinks that the ampersand is a vulnerability.
Here is my code for the insert in PHP:
            $fbl = $_POST['fblValue'];
        $fbr = $_POST['fbrValue'];
        $sbl = $_POST['sblValue'];
        $sbr = $_POST['sbrValue'];
        $tbl = $_POST['tblValue'];
        $tbr = $_POST['tbrValue'];
        $fblDisabled = $_POST['fblDisabled'];
        $fbrDisabled = $_POST['fbrDisabled'];
        $sblDisabled = $_POST['sblDisabled'];
        $sbrDisabled = $_POST['sbrDisabled'];
        $tblDisabled = $_POST['tblDisabled'];
        $tbrDisabled = $_POST['tbrDisabled'];
        $footer = $_POST['footerValue'];
        $copyright = $_POST['copyrightValue'];

        $statement = $conn->prepare("UPDATE pages SET FBL = :fbl,
                                                    FBLDisabled = :fblDisabled,
                                                    FBR = :fbr,
                                                    FBRDisabled = :fbrDisabled,
                                                    SBL = :sbl, SBLDisabled = :sblDisabled,
                                                    SBR = :sbr, SBRDisabled = :sbrDisabled,
                                                    TBL = :tbr, TBLDisabled = :tblDisabled,
                                                    TBR = :tbr, TBRDisabled = :tbrDisabled,
                                                    Footer = :footer,
                                                    Copyright = :copyright
                                                    WHERE ID = :pageToEdit");
        $statement->bindParam(":fbl", $fbl);
        $statement->bindParam(":fblDisabled", $fblDisabled);
        $statement->bindParam(":fbr", $fbr);
        $statement->bindParam(":fbrDisabled", $fbrDisabled);
        $statement->bindParam(":sbl", $sbl);
        $statement->bindParam(":sblDisabled", $sblDisabled);
        $statement->bindParam(":sbr", $sbr);
        $statement->bindParam(":sbrDisabled", $sbrDisabled);
        $statement->bindParam(":tbl", $tbl);
        $statement->bindParam(":tblDisabled", $tbDisabled);
        $statement->bindParam(":tbr", $tbr);
        $statement->bindParam(":tbrDisabled", $tbrDisabled);
        $statement->bindParam(":footer", $footer);
        $statement->bindParam(":copyright", $copyright);
        $statement->bindParam(":pageToEdit", $pageToEdit);
        $statement->execute();
    }

Also may I add, that I use ajax to send the data, is there a possibility that it's something to do with that?
Here is the AJAX code:
<script type="text/javascript">

        function savePage(str1, str2, str3, str4, str5, str6, str7, str8, str9, str10, str11, str12, str13, str14)
        {
            var xmlhttp;

            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }

            xmlhttp.open("post", "putEditedPage.php", true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send("fblValue=" + str1 + "&fbrValue=" + str2 + "&sblValue=" + str3 + "&sbrValue=" + str4 + "&tblValue=" + str5 + "&tbrValue=" + str6 + "&fblDisabled=" + str7 + "&fbrDisabled=" + str8 + "&sblDisabled=" + str9 + "&sbrDisabled=" + str10 + "&tblDisabled=" + str11 + "&tbrDisabled=" + str12 + "&footerValue=" + str13 + "&copyrightValue=" + str14);
            document.getElementById('blackout').style.display="block";
            document.getElementById('Alert').style.display="block";
            document.getElementById('Alert').style.marginTop=((window.innerHeight/2)+((window.innerHeight/100) * 35))+"px";
            setTimeout(function(){
                document.getElementById('blackout').style.display='none';
                document.getElementById('Alert').style.display='none';
            }, 1250);
        }
        function insertTab(o, e)
        {
            var kC = e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which;
            if (kC == 9 && !e.shiftKey && !e.ctrlKey && !e.altKey)
            {
                var oS = o.scrollTop;
                if (o.setSelectionRange)
                {
                    var sS = o.selectionStart;
                    var sE = o.selectionEnd;
                    o.value = o.value.substring(0, sS) + "\t" + o.value.substr(sE);
                    o.setSelectionRange(sS + 1, sS + 1);
                    o.focus();
                }
                else if (o.createTextRange)
                {
                    document.selection.createRange().text = "\t";
                    e.returnValue = false;
                }
                o.scrollTop = oS;
                if (e.preventDefault)
                {
                    e.preventDefault();
                }
                return false;
            }
            return true;
        }

    </script>

Thanks in advance guys, cheers.

A: Right here:
xmlhttp.send("fblValue=" + str1 + "&fbrValue=" + str2 + "&sblValue=" + str3 + ...
                                   ^                     ^

See those ampersands? They are special characters in URL encoding. To submit a value which contains ampersands itself, you need to escape that ampersand using URL encoding. Therefore, encodeURIComponent your values before concatenating them into a URL-encoded string.
Maybe I can interest you in: The Great Escapism (Or: What You Need To Know To Work With Text Within Text)

A: Special characters are supported in PDO, Ajax, XML.
You must have little hole here: "everything is set to 'UTF-8'".
Check these things:

*

*HTML page charset (here: <head></head>)

*Encoding of JS file?
<script src="file.js" type="text/javascript" charset="utf-8">

*XML (i have no idea where)

*Database connection (set names, collation)

*Collation set on specyfic column

*Charset of source files

*If you are using some editor in JavaScript - maybe it has charset in config file?
You may try "step by step" debug. You may try to insert ampersand without AJAX.

A: Don't forget your ability to use http://php.net/manual/en/function.urlencode.php and http://php.net/manual/en/function.urldecode.php


text:
Q: Construct 2 time series random variables with fixed correlation Is there an easy way to generate two time-series with a fixed correlation? For instance 0.5.
Does anyone know a solution in R or Python?
Thanks!

A: This question is quite general, I think. It is not limited to just time-series. What you are asking is to generate 2d random variable, with known covariance. r==0.5, std1=1 and std2=2 would translate to a covariance matrix of [[1,1],[1,4]]. Therefore, if we assume the data is multidimensional normal distributed, we can generate such a random variable:
In [42]:
import numpy as np
val=np.random.multivariate_normal((0,0),[[1,1],[1,4]],1000)
In [43]:

np.corrcoef(val.T)
Out[43]:
array([[ 1.      ,  0.488883],
       [ 0.488883,  1.      ]])
In [44]:

np.cov(val.T)
Out[44]:
array([[ 1.03693888,  0.96490767],
       [ 0.96490767,  3.75671707]])
In [45]:

val=np.random.multivariate_normal((0,0),[[1,1],[1,4]],10)
In [46]:

np.corrcoef(val.T)
Out[46]:
array([[ 1.        ,  0.56807297],
       [ 0.56807297,  1.        ]])
In [48]:

val[:,0]
Out[48]:
array([-0.77425116,  0.35758601, -1.21668939, -0.95127533, -0.5714381 ,
        0.87530824,  0.9594394 ,  1.30123373,  1.92511929,  0.98070711])
In [49]:

val[:,1]
Out[49]:
array([-1.75698285,  2.24011423, -3.5129411 , -1.33889305,  2.32720257,
        0.53750133,  3.23935645,  2.96819425, -0.72551024,  3.0743096 ])

As shown in this example, if your sample size is small, the resulting random variable may deviate from r=0.5, considerably.


text:
Q: How to exclude ClientAbortException from SimpleMappingExceptionResolver I am using a SimpleMappingExceptionResolver that sends all exceptions to an view where it is nicely rendered. That works except one case:
If the user requests a page, and then send and "Abort" (I don't know exactly how that works, but I noticed that if I click an HTTP post form submit button very fast and often the Firefox 7 somehow notify the server that it is not longer interested in the result.) Then the Tomcat 6 rises an ClientAbortException when one try to render the page, or write the the http response in any kind.
Now starts the trouble: the SimpleMappingExceptionResolver "catches" the exception and trys to render it nicely to an html page. This then causes in a Stream already closed exception which pollute the log file. (java.lang.IllegalStateException: getOutputStream() has already been called for this response)
What I have done so fare, is to register the an empty jsp page for the "ClientAbortException". But I feel that this is a Hack. On the other Hand I guess this is not a so uncommen problem, because I will expect it in nearly every spring application that renders all exception. So does anybody have experience with that problem, or has an idea of an not so hacky solution?
<bean
  class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"
  p:defaultErrorView="uncaughtException">
    <property name="exceptionMappings">
        <props>
           <prop key=".MissingServletRequestParameterException">
               resourceNotFound
           </prop>
           <prop key=".ClientAbortException">nothing</prop>
        </props>
     </property>
</bean>

A: For newer versions of Spring, you can also use the @ExceptionHandler annotation, possibly with @ControllerAdvice (for global handling).
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(ClientAbortException.class)
    public void clientAbortExceptionHandler(HttpServletRequest request, ClientAbortException e) {
        // This usually means the browser closed or disconnected or
        // something. We can't do anything. To avoid excessive stack traces
        // in log, just print a simple message and return null
        String username = "<NONE>";
        Principal principal = request.getUserPrincipal();
        if (principal != null) {
            username = principal.getName();
        }
        logger.warn("ClientAbortException: username={},remoteAddr={},userAgent={},requestedURL={}", username,
                request.getRemoteAddr(), request.getHeader("User-Agent"), request.getRequestURL());
    }

}

A: Extend SimpleMappingExceptionResolver, override doResolveException() method, and in case the exception name is ClientAbortException and response.isCommitted() return null instead of returning super.doResolveException().

A: IMHO, registering the nothing view for the Exception you don't want to handle is elegant way; as opposed to feeling of hack; as you can have even more than one exception you don't / won't want to render as compared to other exceptions.
I won't recommend coming up with a custom implementation for HandlerExceptionResolver; as it may increase maintainability costs.


text:
Q: How to insert in php fo array of string value? I have an array
   Array(
         [0] => Column 1, Column 2 ,Column 3,Column 4,Column 5,Column 6
         [1] => 19506,7254,321878,8,1,60
         [2] => 187486,685,377,3,0,0
         [3] => 187498,682285,3354,45,1,400
         [4] => 18498,681285,38959,2,0,0
      )

store into a mysql table using a loop or any other solutions
how to insert in database
I have exact same columns in a table

A: Use below snippet to convert it into array to save into database,
// replace spaces with "" and explode with comma
$keys = explode(",", str_replace(" ","",$arr[0]));
array_shift($arr); // remove first index
$arr = array_map(function($a) use($keys){
    // first value as keys and rest array values exploding and combining as key value pair
    return array_combine($keys, explode(",",$a));
}, $arr);

Demo
Code to create an insert query
$sql = "INSERT INTO table_name (".implode(",",$keys).") VALUES ";
foreach($arr as $data){
    $sql .= "(".implode(",",$data)."),";
}
$sql = rtrim($sql,",");
echo $sql;

Output
INSERT INTO table_name (Column1,Column2,Column3,Column4,Column5,Column6)
VALUES (19506,7254,321878,8,1,60),(187486,685,377,3,0,0),
(187498,682285,3354,45,1,400),(18498,681285,38959,2,0,0)


text:
Q: Search in files excluding #if debug sections Is there a way to find in files (or solution) but ignoring results that are between #if debug / #endif sections?
Or is there a nice plugin that does such a thing, or a neat workaround?


text:
Q: No picture on HDMI Output from a Pioneer 921 AV Receiver to a Projector I am trying hard to tackle a what seemed to be simple problem if wiring my setup together. The setup:

*

*Mac Mini (2011) with HDMI Output

*Pioneer 921 K AV Receiver

*Acer HD Projector (HDMI)

When I hook up my Mac Mini directly to the Projector with a 30 foot (10 meter) HDMI Cable everything is just fine. The picture is sharp and the colors brilliant.
However, when I send HDMI to the receiver (into the BD HDMI Input) then I get absolutely no HDMI output to the projector, it keeps saying "no signal".
Is there perhaps some magic combination of setup buttons that may help me resolve this problem?

A: Have you seen this forum article? It may be relevant to what you're experiencing.
Specifically this line:

Receivers won't transcode digital HDMI video to analog component output. You'll need to either run an HDMI cable from the receiver to your display or switch to analog out from the computer (with a VGA or DVI to Component adapter).


text:
Q: How to get data on a reference first before executing other code? I need to get all data from a specific location on my Firebase and put that data inside an ArrayList before processing it. I have something like this:
final ArrayList<String> data = new ArrayList<String>();
Firebase ref = rootRef.child("data");
ref.addListenerForSingleValueEvent(new ValueEventListener() {}
    @Override
    public void onDataChange(DataSnapshot snap) {
        for (Object obj : snap.getChildren) {
            data.add(obj.getValue().toString());
        }
    }
);
processData(data);

I'm fairly a newbie with this kind of stuff, but I think this is not good especially if there's tons of data to be read and if the user's connectivity is slow.
Any idea on how to solve this problem?

A: I am not familiar with Firebase but I would be shocked if they did not have some sort of equivalent as the Android loader callback "onLoadFinished(){...}". You should find what is similar in Firebase, and call your "processData(data)" from within it.