text:
Q: Is it possible to check for source code equality of two functions by ignoring comments, formatting and name of the functions? I've been using my_function.__code__.co_code to check whether two functions have the same source code or not (as suggested e.g. here). However, it turns out that this doesn't do exactly what I was expecting. Let's take this example.
def f(a, b):
    return a
    return a

def g(a, b):
    return a

if __name__ == '__main__':
    print(f.__code__.co_code)
    print(g.__code__.co_code)
    print("f.__code__.co_code == g.__code__.co_code?",
          f.__code__.co_code == g.__code__.co_code)

The functions are logically equivalent, but they have different code, so I was expecting f.__code__.co_code == g.__code__.co_code to return False, but it returns True. This is probably because Python understands that f can be simplified to g.
However, would there be a way to stop Python from doing that, i.e. if the functions really contain different code (although they may be logically equivalent), f.__code__.co_code == g.__code__.co_code returns False? Or would there be any solution to my problem?
Essentially, I am looking for a function/property that would return a (preferably hashable) representation of a function, which, if compared to the representation of another function, would be different, unless the functions contain exactly the same code. It's fine that the functions have different names, i.e. if they have different names, but the same code, it should return True (the functions are equal).
f is g is not what I am looking for. It would return False for these functions
def f(a, b):
    return a

def g(a, b):
    return a

However, they contain the same code!
I would also like to note that I want spaces and comments to be ignored. So, the following two functions would be equal
def   f(  a , b):
    """Good job... hm, it was a good day..."""
    return a
    # NICE

def g(a,    b  ):
    #    HELLLOOOOOOO
    return         a

A: Code isn't generated directly from source code. The source code is first parsed to produce an abstract syntax tree (AST). The AST is used to generate the byte code.
>>> print(ast.dump(ast.parse("""def f(a,b):
...   return a
...   return a"""), indent=2)
... )
Module(
  body=[
    FunctionDef(
      name='f',
      args=arguments(
        posonlyargs=[],
        args=[
          arg(arg='a'),
          arg(arg='b')],
        kwonlyargs=[],
        kw_defaults=[],
        defaults=[]),
      body=[
        Return(
          value=Name(id='a', ctx=Load())),
        Return(
          value=Name(id='a', ctx=Load()))],
      decorator_list=[])],
  type_ignores=[])

You'll have to write your own code to do any node-by-node comparisons of two ASTs. The ast module provides a NodeVisitor class to assist in traversing a tree.

Taking a step back: you aren't interested in whether two pieces of code are identical, only if they are isomorphic under some structure-preserving transformation. Parsing is fine, as the transformation from source code to AST preserves the structure you want preserved. Code generation, however, does not preserve the structure when transferring the AST into a linear sequence of byte codes. (It only preserves the semantics.) For instance, it will do dead code elimination, constant folding, etc.
So what you want is a very specific transformation of one AST to another, normalized AST. Once you have normalized your two ASTs, you can compare them.
One transformation you expressed interest in was normalization of variable names (for example, def f(): pass and def g(): pass should be considered isomorphic). Something you may be interested in is applying de Bruijn numbering to the variables, which assigns a unique integer to each unique variable, regardless of the variables names.
There may be other similar transformations you are interested in. Unfortunately, you are going to have to write (or research) these yourself.


text:
Q: Insert a character at a specific location using sed How to insert a dash into a string after 4 characters using sed (e.g., 201107 to 2011-07)?

A: For uncertain sed version (at least my GNU sed 4.2.2), you could just do:
echo "201107" | sed 's/./&-/4'
/4 -> replace for the 4th occurrence (of search pattern .)
&  -> back reference to the whole match
I learned this from another post: https://unix.stackexchange.com/questions/259718/sed-insert-character-at-specific-positions

A: echo "201107" | sed 's/201107/2011-07/'

Should work. But just kidding, here's the more general solution:
echo "201107" | sed -r 's/(.{4})/\1-/'

This will insert a - after every four characters.

A: The following will match perform the replacement only on strings of four digits, followed by strings of two digits.
$ echo '201107' | sed 's/\([0-9]\{4\}\)\([0-9]\{2\}\)/\1-\2/'
2011-07

Sed regex is a little awkward, because of the lack of \d, and the need to escape parenthesis and braces (but not brakets). My solution ought to be 's/(\d{4})(\d{2})/\1-\2/' if not for these peculiarities.

A: I know this is diggin up a massive dinosaur, but if you wanted to eliminate the 6 tailing zeros
echo '20110715000000' | sed 's/\([0-9]\{4\}\)\([0-9]\{2\}\)\([0-9]\{2\}\)\([0-9]\{6\}\)/\1-\2-\3/'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a book / paper / theory where the Cartan-Eilenberg homology of Lie algebras consider representations on Lie algebras again? I know the standard theorems and concepts of Cartan-Eilenberg complexes for Lie algebras. They use operations $\mathfrak{g}\longrightarrow \mathfrak{gl}(V)$, if not even the adjoint representation $\mathfrak{g}\longrightarrow \mathfrak{gl(g)}.$ And on top, they seem to prefer semisimple $\mathfrak{g}.$
I am especially interested in solvable $\mathfrak{g}$ and representations $\mathfrak{g}\longrightarrow \mathfrak{gl(I(g))}$ where $\mathfrak{I(g)}$ are again Lie algebras, invariants of the original Lie algebra $\mathfrak{g}.$
My examples are
\begin{align*}
\mathfrak{I(g)}=\mathfrak{A(g)}&= \left\{ \alpha \in \mathfrak{gl(g)} \,|\,[\alpha(X),Y]+[X,\alpha(Y)]=0 \right\} \\
\mathfrak{I(g)}=\Phi(\mathfrak{g)}&=\left\{\varphi \in \mathfrak{A(g)}\,|\,[\mathfrak{g},\mathfrak{g}]\subseteq \operatorname{ker}(\varphi)\right\}
\end{align*}
They are $\mathfrak{g}$-modules and Lie algebras in their own right: $X.\alpha =[\operatorname{ad}(X),\alpha ]$. What makes them interesting is that the more complicated the multiplication in $\mathfrak{g}$ is, the easier the multiplication in those invariant Lie algebras is, and vice versa. E.g. $\mathfrak{A(g)}\cong \mathbb{C}$ if $\mathfrak{g}$ is the Borel subalgebra of a simple Lie algebra. And, of course, $\mathfrak{A}(\left\{a\right\})=\mathfrak{gl(a)}$ for abelian $\mathfrak{a}.$ However, all the interesting stuff happens in between.
Since those invariants are $\mathfrak{g}$-modules, I wonder if there is a homological theory in cases where the representation space isn't only a vector space but a Lie algebra again. E.g. $\mathfrak{A(g)}$ allows a tower and semidirect products via their module property.
And ...
... have those invariants been considered before?


text:
Q: Deploy options column greyed out, and no platform choices to deploy - Visual Studio 2022, Hololens 1, Unity 2021 I'm having an issue with VS where I can't select a platform to deploy to, or set any deploy options.
I'm trying to deploy a Unity (2021.1.16f) build to Hololens 1 via Visual Studio 2022.
Here are my Unity build settings:

But when I open the project in VS, I can't select a deploy platform (start is the only option).

And, the deploy checkbox is disabled in the config manager menu.

I've triple checked that the project that shares a name w/ my Unity scene is set as the startup project, and that hasn't helped.
Anyone ever run into this?

A: First of all, for HoloLens 1 development, the Unity 2019.4 LTS is recommended.

But when I open the project in VS, I can't select a deploy platform (start is the only option)

Please make sure the best matched VS version and components listed in this doc is installed.

Note about HoloLens (1st gen) and desktop Windows Mixed Reality
headsets: If you are only developing applications for desktop Windows
Mixed Reality headsets or HoloLens (1st gen), you can use Visual
Studio 2017 and use the Windows SDK installed by it.

In terms of the HoloLens 1 app deployment setting in Visual Studio, normally we will use the following ways:

*

*Remote connection and deployment.
Ensure dev PC and HoloLens device in the same local network, follow this doc to deply your app:
Remote connection

*Deploy app via USB cable. Please check out the doc

*Deploying an app to the HoloLens (1st gen) Emulator


text:
Q: Laravel 4.2 filter access to uploaded files I want to route to filter access to files in upploads folder.
Route::get('uploads/{class}/{id}/{filename}', array('before' => 'auth', function()
{
    return "route works";
}));

the code above works for link uploads/Deviation/1/Laravel%20Cheatsheet, but if the link is to an actual file uploads/Deviation/1/Laravel%20Cheatsheet.pdf, it seems like laravel is bypassing router. I get why does it do it, but is there a way to bend the rules for uploads folder?

A: By default characters like slashes and dots are not allowed in parameter values. In order to override that, you'll need to define the route as follows:
Route::get('uploads/{class}/{id}/{filename}', array('before' => 'auth', function()
{
  return "route works";
}))->where('filename', '[a-zA-Z0-9\.]+');

Just make sure that you don't store the files in publicly accessible location - I suggest to store it somewhere in storage/.

A: The recommended Laravel Apache configuration is:
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

The recommended nginx configuration is:
location / {
    try_files $uri $uri/ /index.php?$query_string;
}

Both of these prioritize any files with that exact filename first, falling back to Laravel's index.php only if a file is not found. This is fairly important - you don't want the largeish PHP framework involved in serving static files like CSS/JS/images, it'd be a heavy load on the server.
If you want to sit Laravel in front of your uploads, just use a different URL to reference them, and have Laravel serve the file after you've done whatever it is you need to do.
Route::get('not-the-real-uploads/{class}/{id}/{filename}', array('before' => 'auth', function()
{
    // something like this
    return Response::download('uploads/...', ...);
}));


text:
Q: What is the minimum interface that has the Count property in .Net I need to change a method that has one parameter that takes a serie of objects. I need to find the lowest Interface (in inheritance tree) that has the Count property. Until now I was using the IEnumerable but as this has not Count I need to change it to the wider interface possible so the method can work with the biggest number of types of series (collections, lists, arrays, etc).
Thanks in advance.

A: ICollection adds the Count property.
As @Joren rightly points point, IEnumerable<T> has the extension method Count<T>() if you're happy making your collection generic. However, as @Joel Coehoorn has pointed out, it is inadvisable to use this as it forces an iteration of the sequence.

A: ICollection adds the Count property.

A: System.Collections.ICollection, and also System.Collections.Generic.ICollection<T>. These two interfaces have no relation to eachother, but both inherit from IEnumerable, so they're at the same level.
IEnumerable obviously does not have a Count property (the count isn't necessarily predetermined).


text:
Q: Driver behavior executing parallel TestNG selenium tests with dataprovider I want to run selenium tests in TestNg in parallel that use the @dataprovider.  Ideally tests are parallel by method (one test = one method) and not simple suite parallelism by browser. I have read somewhere that about 5 instances of ChromeDriver can be controlled at a time so I thought this should be possible.  Later I plan to move to grid2. For developement I'm running things with IntelliJ Idea test runner by right-click + run on the XML config file.
I had problems running my tests in parallel (on grid2 and locally) so I created a sample of more or less what I want to do.
Here is my test class
package tests;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.*;
import java.util.concurrent.TimeUnit;
import static org.testng.Assert.assertNotNull;

public class ParallelTest {
    public static final String SEARCH_TERMS = "search-terms";
    private WebDriver driver;

    @BeforeMethod
    @Parameters({"browser"})
    public void beforeMethod(@Optional("chrome") String browser){
        driver = getBrowser(browser);
        driver.manage().deleteAllCookies();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    private WebDriver getBrowser(String browser) {
        if(browser.equals("chrome")){
            System.setProperty("webdriver.chrome.driver", "webdrivers\\chromedriver.exe");
            return new ChromeDriver();
        }
        return new FirefoxDriver();
    }

    @AfterMethod
    public void afterMethod(){
        driver.quit();
    }

    @Test(description = "Check parallel selenium works.",
          dataProvider = SEARCH_TERMS)
    public void parallelSeleniumTest(String searchTerm){
        driver.get("http://google.com");
        WebElement search = driver.findElement(By.id("gbqfq"));
        new Actions(driver)
                .sendKeys(search, searchTerm)
                .sendKeys(search, Keys.ENTER)
                .perform();
        String firstResult = driver.findElements(By.className("r")).get(0).getText();
        assertNotNull(firstResult);
        System.out.println(firstResult);
    }

    @DataProvider(name = SEARCH_TERMS, parallel = true)
    public Object[][] getSearchTerms(){
        return new Object[][]{
                {"google"},
                {"microsoft"},
                {"facebook"},
                {"amazon"},
                {"apple"},
                {"oracle"},
                {"yahoo"},
                {"jetbrains"},
                {"intellij idea"},
                {"selenium"},
                {"java"},
                {"testng"},
                {"code"}
        };
    }
}

I threw in some native events since I use them heavily in my test suite.
And here is the TestNg xml config file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="4" name="vfr6-ui-tests" parallel="methods">
    <test name="parallel-test-firefox">
        <parameter name="browser" value="firefox"/>
        <classes>
            <class name="tests.ParallelTest"/>
        </classes>
    </test>
    <test name="parallel-test-chrome">
        <parameter name="browser" value="chrome"/>
        <classes>
            <class name="tests.ParallelTest"/>
        </classes>
    </test>
</suite>

I read instantiating one driver per test tends to be the most maintainable.  The problem is that the firefox test runs in serial while the chrome test spits out all of the data points as test cases, attempts to open a trove of browser instances, then everything fails.  My tests will have either 10-25 or 300-500 data points (cycling between either clients or clients x products).
What is the best way to set up the driver, dataprovider, and test runner to achieve the best parallelism in running tests?

A: I had the same experience about dataProvider. In my case I used dataProvider's (parallel=true) attribute though. There are two solutions to your problem.

*

*Use dataProvider and in test class and use factory annotation for your constructor.
In the factory annotation's attribute, use dataProvider="Your dataProvider's name".
In the testng.xml, instead of parallel=methods, use parallel=instances.
The drawback of the above approach is that when you get the report; may be it is maven-
surefire, testng Eclipse report or reportNG report, you do not see parameters passed up
front. To overcome this, you can use the following approach.

*Create a factory class and instantiate your test class in the factory method using a
for loop. (Start for loop from 0.) In the test class define a constructor which
receives a parameter from factory class. Define a dataProvider in this test class which
can use the parameter (data-point) received in the constructor. Define a BeforeMethod
or BeforeClass which can use that parameter or data point and Your test methods should
have the "dataProvider" attribute pointing to the desired dataProvider. Again, in
testng.xml use parallel="instances".
Also, use try/catch block for instantiating driver object and closing the browser. This
will help you in avoiding skips due to failure of setUp of tearDown method.

A: You don't really need to use a Factory.  If I were you I would call this code within the dataprovider method:
driver = getBrowser(browser);

Then, return the driver instances as a 2nd column of args to the test method.  Doing it that way allows the dataprovider to generate browser instances.   To improve on that, you could instead use the builder design pattern, in the form of a DriverHelper class, that could replace the getBrowser method with a way to generate a much more specific driver configuration before passing the driver instance into the test method.
NOTE: Keep in mind that if you ever want to use Spring to load your drivers in the future, then this method won't work at all.  In fact, you wont be able to use a DataProvider at all.  But, if your not using Spring, then I would say this is the most elegant way of doing it.


text:
Q: JVM Memory for applet I have an applet and I need to increase his memory. If I pass this parameter:
    -Xmx=1024m

and execute this code:
    rt = Runtime.getRuntime()
    rt.maxMemory()/1024/1024

It returns 989M
If I instead pass:
    -Xmx=2048m

It returns 154M
Why is this, and how can I increase the maximum available memory for my Applet?

A: Xmx option you provide to limit JVM for max memory , now it is upto JVM how much memory it usages at Runtime. When you observed once it was 989M and the other time 154M, even it can go beyond also till it reaches Max Limit. You can not control how much memory applet will use other than giving max limit , JVM will control that.


text:
Q: Why hibernate is saving values without transaction? i'm using spring boot(2.1.4) with hibernate(5.3.9).
public class BaseDao{

@Autowired
private SessionFactory sessionFactory;

private Session session;
private Transaction transaction;

@Autowired
private EntityManagerFactory entityManagerFactory;

@PersistenceContext
private EntityManager entityManager;

public SessionFactory getSessionFactory() {
    return sessionFactory;
}

public EntityManagerFactory getEntityManagerFactory() {
    return entityManagerFactory;
}

public EntityManager getEntityManager() {
    return entityManager;
}

public Session getSession() throws Exception{
    if(session == null) {
        session = getSessionFactory().openSession();
    }

    if(transaction == null) {
        transaction = session.beginTransaction();
    }
    return session;
}

public void commit() throws Exception{
    if(transaction != null) {
        transaction.commit();
        transaction = null;
    }

    if(session != null) {
        session.close();
        session = null;
    }
}

public void rollback() throws Exception{
    if(transaction != null) {
        transaction.rollback();
        transaction = null;
    }

    if(session != null) {
        session.close();
        session = null;
    }
}

protected void save(Object object) throws Exception {
    getSessionFactory().openSession().save(object);    //saves data in db
    getSession().save(object);    //is not saving data
}

getSessionFactory().openSession().save(object); this code is saving data to db even without commit
getSession().save(object); this code required commit to be called as txn is created but not commited
hibernate log
i see below log for both the line of code

insert
into
TEST_ENTITY
(CREATED_BY, CREATED_DATE, ENABLED, LAST_MODIFIED_BY, LAST_MODIFIED_DATE, NAME)
values
(?, ?, ?, ?, ?, ?)

i have few questions on this behavior.

*

*I know write operation will not happen without commit, so any idea what is wrong here or what causing commit in first scenario ?

*Is it ok to use above code i.e. first scenario ?

*If first approach is not right then do i need to create and commit txn for each object, any better approach so that even if i have to commit txn, i don't want to replicate the txn.commit() in every new method i write in BaseDao.java i.e. say i have create(), update(),delete() methods can i move this txn.commit() out of methods ?

*Few places i'm using spring data jpa for fetching/saving record (given below), how txn is being handled in spring data jpa ? any references ?
@Repository
public interface TestEntitytRepo extends JpaRepository<TestEntity, Long> {
...
}
Please let me know if i missed any details to capture here.
Thanks in advance.

A: In hibernate, the Save() method stores an object into the database. It will Persist the given transient instance, first assigning a generated identifier. It returns the id of the entity created. When a session in hibernate is created using SessionFactory.openSession(), no transaction is created, so all the operations are executed outside of the transaction context !! In order to ensure the data gets saved into the database, a new transaction needs to be created.
I am a bit skeptical about the behaviors explained by you above. Seems like auto-commit option is enabled. If so, then this is not an issue as save() method is done, commit automatically happens backstage !!


text:
Q: Port 9200 Refused Connection? I'm trying to implement an elasticsearch client in NodeJS on a Cloud9 workspace and I'm just trying to get it running. My app runs on port 5678 and my MongoDB runs on 27017. I have tried searching for other answers, but I haven't really found anything particularly useful. This is the error message that I receive when trying to connect to localhost:9200.
    Elasticsearch ERROR: 2015-06-26T04:24:19Z
  Error: Request error, retrying -- connect ECONNREFUSED
      at Log.error (/home/ubuntu/workspace/node_modules/elasticsearch/src/lib/log.js:213:60)
      at checkRespForFailure (/home/ubuntu/workspace/node_modules/elasticsearch/src/lib/transport.js:192:18)
      at HttpConnector.<anonymous> (/home/ubuntu/workspace/node_modules/elasticsearch/src/lib/connectors/http.js:153:7)
      at ClientRequest.wrapper (/home/ubuntu/workspace/node_modules/elasticsearch/node_modules/lodash/index.js:3128:19)
      at ClientRequest.emit (events.js:95:17)
      at Socket.socketErrorListener (http.js:1552:9)
      at Socket.emit (events.js:95:17)
      at net.js:441:14
      at process._tickCallback (node.js:442:13)

Elasticsearch TRACE: 2015-06-26T04:24:19Z
  -> HEAD http://localhost:9200/

  <- 0

Elasticsearch WARNING: 2015-06-26T04:24:19Z
  Unable to revive connection: http://localhost:9200/

Elasticsearch WARNING: 2015-06-26T04:24:19Z
  No living connections

Trace: elasticsearch cluster is down!
    at Server (/home/ubuntu/workspace/app.js:32:13)
    at respond (/home/ubuntu/workspace/node_modules/elasticsearch/src/lib/transport.js:251:9)
    at sendReqWithConnection (/home/ubuntu/workspace/node_modules/elasticsearch/src/lib/transport.js:171:7)
    at next (/home/ubuntu/workspace/node_modules/elasticsearch/src/lib/connection_pool.js:213:7)
    at process._tickCallback (node.js:442:13)

.
My code for the elastic search client is very simple
    var client = new elasticsearch.Client({
  hosts: 'localhost:9200',
  log: 'trace'
});

client.ping({
  // ping usually has a 3000ms timeout
  requestTimeout: 30000,

  // undocumented params are appended to the query string
  hello: "elasticsearch!"
}, function (error) {
  if (error) {
    console.trace('elasticsearch cluster is down!');
  } else {
    console.log('All is well');
  }
});

If I try to connect to localhost:5678, I don't get an error refused, but the elastic cluster is still down? Any suggestions would be helpful, thanks :)

A: //Client.js
    const es = require('elasticsearch');
    const esClient = new es.Client({
        host: {
            protocol: 'http',
            host: 'localhost',
            port: 9200

        },
        log: 'trace'
    });

    module.exports = esClient;

//ping.js
const esClient = require('./client');

esClient.ping({
// ping usually has a 3000ms timeout
    requestTimeout: 3000
}, function (error) {
    if (error) {
        console.trace('elasticsearch cluster is down!');
    } else {
        console.log('All is well');
    }
});

A: Hey to anyone who wants to know what I did. I basically just downloaded elasticsearch onto cloud9 and ran it. Then I pinged the port accordingly and it worked. Looks like a noobie mistake on my part :P

A: In my case, stock elasticsearch with everything in default and using the JS client results in this error.
(short term) fix: http.cors.enabled and https.cors.allow-origin settings


text:
Q: Casting redundant or not Here is my original function
 private static Int32 getInt(byte[] Data, char Endianness)
        {
            if (Data.Length > 3)
            {
                switch (Endianness)
                {
                    case 'l':
                        return ((Int32)(Data[3]) << 24) + ((Int32)(Data[2]) << 16) + ((Int32)(Data[1]) << 8) + (Int32)(Data[0]);
                    case 'b':
                        return ((Int32)(Data[0]) << 24) + ((Int32)(Data[1]) << 16) + ((Int32)(Data[2]) << 8) + (Int32)(Data[3]);
                    default:
                        throw new ArgumentException("Wrong endianness type", "Endianness types are 'l' or 'b'");
                }
            }
            else
            {
                throw new ArgumentException("NVM data corruption", "Failed to parse NVM data");
            }
        }

I am using Resharper and it suggested I remove the casting to Int32 since it is redundant.
so we get this code as an output
 private static int getInt(byte[] Data, char Endianness)
    {
        if (Data.Length > 3)
        {
            switch (Endianness)
            {
                case 'l':
                    return (Data[3] << 24) + (Data[2] << 16) + (Data[1] << 8) + Data[0];
                case 'b':
                    return (Data[0] << 24) + (Data[1] << 16) + (Data[2] << 8) + Data[3];
                default:
                    throw new ArgumentException("Wrong endianness type", "Endianness types are 'l' or 'b'");
            }
        }
        throw new ArgumentException("NVM data corruption", "Failed to parse NVM data");
    }

in the code you have see I am shifting Data[2] << 16 that number can overflow from the original byte, if I removed the cast to Int32 am I risking here some  sort of trim to byte?
Can you please explain what C# preprocessor/ compiler is doing here?
Thanks

A: The cast is redundant because compiler automatically promotes Data[2] to integer when you use left-shift operator and the result of that operation will also be an integer. So no data will be lost.


text:
Q: How to run multiple instance of PowerShell script I wants to run a multiple instance of one powershell script for multiple service with different parameter. I have written below powershell script , but not sure what i am doing its not taking parameter.
    [string[]] $ScriptstrArray = '-command Invoke-Expression ".\Smoke-Test.ps1 -Environment QA -servicename rpms"' ,
   '-command Invoke-Expression ".\Smoke-Test.ps1 -Environment QA - servicename rsms"' ,
  '-command Invoke-Expression ".\Smoke-Test.ps1 -Environment pvs - servicename spsms"'

workflow RunSmokeTests {
########################################################################
param([string[]]$sList)
    ForEach -Parallel ($s in $sList) {
       start-process powershell.exe -argument $s
    }
}

 RunSmokeTests -sList $ScriptstrArray

Can someone please me to identify the issue. Thanks in advance.

A: I have used the external helper Invoke-Parallel for such scenarios in the past. It has a -InputObject parameter that allows you to pass in an array with e.g. the servers/services and their corresponding details. See here or here for source and examples.


text:
Q: Expand PERC 6/i RAID 10 SSD array, or add new VD for SQL Server? On a Dell R710 server running Window Server 2008 R2 there are currently 4 50GB SSDs in a RAID 10 array, and I'm adding 2 additional 50GB SSDs. This server runs SQL Server and not much else. If these were spindled HDs, from what I've read I would be better off to create a new VD dedicated to the DB logs and temp DB. Since the entire system is SSDs, though...I don't know if it really matters? It will certainly be easier to create a new VD. It seems that PERC 6/i RAID 10 arrays can't be expanded by adding new drives? That means I'd have to backup, create delete and create a new VD with all drives, and restore. I think. I'm primarily a programmer, and not a server admin.

A: The PERC 6/i is capable of online capacity extension. You should be able to use the OpenManage Storage Management GUI to "Reconfigure" your virtual disk, take a look at the docs specific to your version for the "how".
If you indeed would need to bother with an extension or rather create a new VD is an entirely different question. Even with SSDs you might want to isolate I/O so your database log ops are not starving out other I/O (or your other I/O not starving out the log I/O, depending on the constellation). On the other hand, you probably add the new drives because you need the capacity - it probably would be easier to use when it is part of the currently configured volume. Whatever reason outweighs the other one would be up to you to decide since it is quite specific to your situation.


text:
Q: Need help for a regex I'd like to build a regex, but I'm stuck.
This is the format I'm looking for:
x;y => 7 times, separated by -
where x is a number from 1 to 7
and y is a number from 1 to 4
Here's what I've done so far:
^([0-7;&-]*)$

example :
1;1-2;3-3;1-4;4-5;2-6;2-7;4
Could you help me?
Thank you

A: Your current pattern is a broad match as repeating your character class does not take any structure into account or different ranges for the digits.
You could match a digit 1-7, then : and a digit 1-4. Then repeat 6 times the same pattern preceded with a hyphen.
^[1-7];[1-4](?:-[1-7];[1-4]){6}$

Regex demo


text:
Q: Is there a t-test equivalent to Stouffer's z-test? I have $k$ pairs of samples from different distributions. For each pair of samples I want to check if the samples are taken from a normal distribution with the same mean and variance. I assume the normal distributions for each pair is different and independent of other pairs. I do not know the mean and variance of any of the distributions.
I am doing a two sample t-test for each of the pairs. I want to combine the $k$ resulting p-values.
I could use Fisher's method but I am wondering about the distribution of the average t-value. If these were z-values rather than t-values I would use Stouffer's z-test. I could also approximate the t-distribution with a z-distribution and than use Stouffer's z-test, but I am not sure if that is a good approximation.
Is there a test like Stouffer's z-test for t-values?
Is there a better way to combine the t-values?

A: According to Becker's chapter on combining $p$-values in Cooper and Hedges book you can use
$$
\frac{\sum {t_f}_i (p_i)}{{\sqrt{\sum\frac{f_i}{f_i-2}}}} > z(\alpha)
$$
where ${t_f}_i$ is Student's $t$ with $f_i$ the degrees of freedom $p_i$ the p-value and $\alpha$ is the desired significance value.
She does not give a reference for the method which she attributes to Winer. The resemblance to the formula for Stouffer's method is clear though.

Cooper, H and Hedges, L V
A handbook of research synthesis 1994 (Russell Sage, New York)


text:
Q: Laravel 4 Dynamic Query Being Output Wrong I have a query function in a model of mine, and I am trying to have it take input for specific offsets and limit of returned rows.  This is the query function:
public static function friend_activity_json($start = 0, $number_of_posts = 2) {
        $friend_activity = DB::table('fanartists')
                        ->join('fans', 'fanartists.fan_id', '=', 'fans.id')
                        ->join('artists', 'fanartists.artist_id', '=', 'artists.id')
                        ->orderBy('fanartists.created_at', 'DESC')
                        ->skip($start)
                        ->take($number_of_posts)
                        ->select('fans.fbid', 'fans.first_name', 'fans.last_name', 'fans.gender', 'fans.city', 'fanartists.artist_id', 'artists.stage_name', 'fanartists.created_at')
                        ->get();

        $posts = $json_encode($friend_activity);

        return $posts;

    }

When I have this query function called, I get the error:
    SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL
 syntax; check the manual that corresponds to your MySQL server version for the right syntax
 to use near 'offset 0' at line 1 (SQL: select `fans`.`fbid`, `fans`.`first_name`,
`fans`.`last_name`, `fans`.`gender`, `fans`.`city`, `fanartists`.`artist_id`,
`artists`.`stage_name`, `fanartists`.`created_at` from `fanartists` inner join `fans` on
`fanartists`.`fan_id` = `fans`.`id` inner join `artists` on `fanartists`.`artist_id` =
`artists`.`id` order by `fanartists`.`created_at` DESC offset 0) (Bindings: array ( ))

Do you see what the issue is?  Thank you for your help.

A: The LIMIT keyword and rowcount is missing in the query. That syntax is invalid.
The query should be something like:
... DESC LIMIT 2 OFFSET 0

The OFFSET keyword is part of the LIMIT clause, it can't appear just by itself. It's not at all clear why Eloquent is generating that, since it isn't valid SQL.

Followup:
Verify that $number_of_posts evaluates to a non-negative integer, so that a valid LIMIT clause can be generated. If $number_of_posts contains something other than a valid value for LIMIT, it's unlikely that it would generated invalid SQL.
(It looks like the error in the query builder is generating a statement that includes OFFSET without a corresponding LIMIT.

A: I just tried your code, and it does work here, provided that I supply a not null, positive value for $start and $number_of_posts. When I don't do that for $number_of_posts, I get exactly the same query you are getting, so my guess is you're probably failing somewhere, when passing $number_of_posts to the function.
When checking the source code, on the Illuminate\Database\Query\Builder's take method, we can see why:
/**
 * Set the "limit" value of the query.
 *
 * @param  int  $value
 * @return \Illuminate\Database\Query\Builder|static
 */
public function take($value)
{
    if ($value > 0) $this->limit = $value;

    return $this;
}

It only sets the limit value if the value is greater than 0.

A: Instead of:
$users = User::offset(5)->get();

Use:
$users = User::limit(10000000)->offset(5)->get();

You must use limit() and offset() at the same time
1000000 - random big number, because we don't want to limit nothing


text:
Q: Segmentation fault of pointer&char Im trying to make the program that extract filenames by inputing some folderpath.
The outcome is fine, but the problem is at the end of outcome, there's some segmentation fault that i cant figure out.
Here's what I wrote in.
#include <stdio.h>
#include <dirent.h>

int main() {

char folderpath;
printf("enter the path : \n");
scanf("%s",&folderpath);

DIR   *d;
struct dirent *dir;
d = opendir(&folderpath);
if (d)
{
    while((dir= readdir(d)) != NULL)
    {
        printf("%s\n", dir->d_name);
    }
    closedir(d);

};

return 0;
}

And, result is like
enter the path : /Users/gui/Desktop/extract/extract
.
..
main
main.c
Segmentation fault: 11

Sorry for asking really simple question like this, which I tried hard to figure out but I cant.
Thanks for reading this question.
Best Regard.

A: When you call scanf with the %s format specifier, it expects a pointer to an array of characters.  What you're passing is the address of a single character.  So it writes past the memory location of that variable into whatever happens to be next to it.  This invokes undefined behavior.
You need pass a character array to scanf:
char folderpath[256];
printf("enter the path : \n");
scanf("%s",folderpath);

...

d = opendir(folderpath);

A: you cannot do this
char folderpath;
printf("enter the path : \n");
scanf("%s",&folderpath);

You have reserved space for one character. YOu need
char folderpath[MAX_PATH];
printf("enter the path : \n");
scanf("%s",&folderpath);

A: When you declare char foldrpath only one byte of memory is allocated that is you can store only one character. When you try to store more than one byte it results in to segmentation fault (access of the memory location out side your process space in this case). So try to use an array like char folderpath[MAXFOLDERLENGTH]  else you can get the contiguous block of bytes by calling malloc like
char foldrpath = (char) malloc(MAXFOLDERLENGTH),  this malloc assigns the memory in Heap area where as the former declaration will give you memory allocated in stack area.  Hope this helps


text:
Q: no puedo desabilitar servicios ni cerrar puertos en ubuntu he escaneado mi red con nmap.
Host is up (0.000047s latency).
Not shown: 1995 closed ports
PORT     STATE         SERVICE
25/tcp   open          smtp
68/udp   open|filtered dhcpc
631/udp  open|filtered ipp
5353/udp open|filtered zeroconf
5355/udp open|filtered llmnr

con sudo /etc/init.d/zeroconf disable no consigo nada.
con el gufw he creado las reglas para cerrar los puertos 5353 y 5355 pero siguen abiertos.
¿que puedo hacer?

A: Yo te recomendaria usar el siguiente firewall.
UFW (Uncomplicated Firewall)
Es el que uso y me ha funcionado correctamente, y facil de usar.
Instalación:
root@linux:~# apt-get install ufw

Activar el registro de eventos
root@linux:~# ufw logging on

Activar acceso mediante SSH
root@linux:~# ufw allow ssh/tcp

Activar el Firewall
root@linux:~# ufw enable

Verificar el estatus del Firewall
root@linux:~# ufw status verbose

Bloquear los puertos 5353 y 5355
root@linux:~# ufw deny 5353
root@linux:~# ufw deny 5355

Te dejo un link para que puedas verificar un poco más sobre su uso.
Tutorial de UFW


text:
Q: unable to instantiate a PackageManager I am making a application which relies on a class which uses a BroadCastReceiver so that I can catch when a application is installed and uninstalled. The intent is received just fine, and the code in onReceive executes as it should. Hoever, the problem I am having is that I get a a error message when I try to instantiate a new PackageManger. The error is: "Cannot instantiate the type PackageManager".
I've pretty much tried all variations, but I just can't get it to work.
my code:
package com.my.package;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;

public class PackageReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Uri datauri         = intent.getData();
        String uri          = datauri.toString();
        PackageManager pm   = new PackageManager();
        //pm.getApplicationInfo(uri);   //broken
        test(datauri);                  //works fine
    }//end method

    public void test(Uri uri){
        Log.d("test", "data: "+uri);
    }//end method
}// end class

A: use
PackageManager pm= context.getPackageManager();
List<ApplicationInfo> applicationInfos = pm.getInstalledApplications(0);
....

instead of
PackageManager pm   = new PackageManager();


text:
Q: Newbie CSS positioning/mapping I'm currently running a word-press theme and I am trying to implement typed.js
I successfully installed and now stuck with the CSS part of it.
As you can see in this screenshot:

I am trying to position it properly. But every time I am doing changes on that section, the whole page changes too so i need a solution to make just changes for that part of the typed.js section on the header...
I am a noob in those things but if someone could explain how i can make another section to just edit the typed.js i would really appreciate that.

A: Try this:
.typed-div-3949 span.typed-preview-div {
   /* Your CSS here like this */
   display: block;
   test-align: center;
}

What do you exactly want to achieve? Centered text?

A: If you want to change only in one page just add the unique page ID like below
#uniqueid .typed-div-3949 span.typed-preview-div {
     /*Add your CSS here */
     text-align: center;
     display: block;
}

and yes what do you want to achieve?


text:
Q: Use bower.json location as a parameter to bower install Is it possible to use the bower.json location as a parameter to the bower install command?
Something like:
bower install -d /var/www/html/bower.json

I would like to run bower install in a single line command and I do not have the option to "cwd" first.

A: cd /var/www/html/your_directory && bower install


text:
Q: How to edit the source code from node modules dependencies? all! I currently met a difficulty with my project. I want to modify the code of a component from a UI library (like Semantic-UI, Material-UI). What I do now is just edited the code from the node_modules. But the reality is no matter how I change the code from node_modules, my project will not be affected. Why this will

A: Well that's because most modules have build process which you need to run before using them. Also editing a module directly is not a good idea because any change you do to them is guaranteed to be lost after next npm install.
As Vuetify is a MIT licensed, I suggest to fork its GitHub project and then publish it as your own npm package.


text:
Q: Screen Flicker on a black MacBook I have a MacBook Black.  For about the last six months I have had a strange screen flicker when I:

*

*start my machine and

*plug in the power cord of my machine

This morning when I woke up my computer the screen backlight did not turn on at all.  When I held the computer in direct sunlight I could see the screen and I could tell that everything was working normally (other than the backlight).
Pressing the screen brightness controls (F2) brought up the brightness panel.  The brightness panel informed me that the screen was at maximum brightness.
I did a bit of Searching and this is what I found:

*

*This post describes how to buy and replace a macbook screen.  Do you think that this would solve my problem?

Additional info:

*

*I am running 10.6.4

*I recently upgraded from 10.4.  I experienced similar issues in 10.4.  I am pretty sure that this is a hardware issue.

*The problem does not occur when the screen is at a specific angle.  It usually only happens at startup/wakeup or when the power is plugged/unplugged.

A: I've had this problem on my macbook. Tried all sorts to no avail. Then went to Energy Saver, System prefs, Preference panes and noticed there was an alert if 'put display to sleep' was less than 'put computer to sleep'.I set them both the same, (in my case 21 mins) and the problem has not recurred!

A: I once had a similar problem with my Compaq machine (Windows). It was solved by replacing the inverter. Good luck.

A: As @Xavierjazz suggests, the problem is most likely the inverter board.
iFixit sells display inverters for the MacBook.
The part is relatively inexpensive ( verify your exact model first ), but getting the inverter board back in without mangling the plastics on the MacBook is a challenge. The board itself is rather fragile as well.
iFixit does have excellent illustrated instructions to walk you through. Heed their warning of the level of difficulty as being "Very Difficult."


text:
Q: Edit CSV file with Python I have a CSV that looks like this
"String1","variablelengthstring1","No"
"String2","variablelengthstring2","No"

String1 and string2 does NOT contain the characters " or ,
variablelengthstring1 and variablelengthstring2 does NOT contain the characters " or ,
The output file should look like this
String1 variablelengthstring1
String2 variablelengthstring2

So I want to remove the last 6 chars on each line, i.e.
","No"
Then, I want to remove all " from the file
Then, I want to replace all , with a space
That should safely accomplish what I am trying to do

A: The easiest way is to just create a program that reads the file line by line, splitting each line up with .split(','), removing all "s from the string, then printing the first parts. Like this:
with open('test.csv') as csv:
    for row in csv.readlines():
        cols = [s.replace('"', '') for s in row.split(',')]
        print(cols[0], cols[1])

If you need to output it to a file, then you can use redirection in your command line. Just run the program like this:
python program.py > output.txt

Alternatively, you can use another nested with statement and .writelines(), like this:
lines = []
with open('test.csv') as csv:
    for row in csv.readlines():
        cols = [s.replace('"', '') for s in row.split(',')]
        lines.append(f'{cols[0]} {cols[1]}\n')

with open('out.txt', 'w') as out:
    out.writelines(lines)


text:
Q: EF Core: In a Db first project standardizing Id properties in order to implement a generic repository I have just scaffolded a new database, I want to create a generic repository for crud, but the problem is; DbModels have different Unique Id variable types and names. e.g. Customer.Id, User.UserId, Company.ActuallyRandomPropertyNameId etc.
So I want to rename all of them as 'UniqueId' in DbModels and keep their table column name counterpart as they were, In code first I know 2 different methods to do it. One is giving a [Column("Id")] attribute to the Primary Key property,
the other method is using Fluent API
modelBuilder.Entity<Contact>()
            .Property<int>("ContactId")
            .HasColumnName("Id");

but upon my research data annotations and fluent API are both viable only for code first approach. Is there really no reliable way to this other than manually converting them one by one?


text:
Q: GMAIL: Magento Order/Invoice Emails Bounce Back Basically, when someone places an order and they are using GMAIL account, such customers do not receive any order confirmation, invoice or tracking information.
72 hrs later I receive bounce back
Delay reason: SMTP error from remote mail server after end of data:
[MY SERVER IP ADDRESS] Our system has detected that this message is
suspicious due to the very low reputation of the sending IP address.
To protect our users from spam, mail sent from your IP address has
been temporarily rate limited.

Emails get bounce back only for GMAIL accounts.  Hotmail, Yahoo are all fine get delivered. Also, my server IP is not blacklisted anywhere.
However, I am able to send email to GMAILaddresses using webmail application such as roundcube and horder.
Any idea how to fix the issues with default Magento email not being received by GMAIL accounts?

A: I may have discovered something to this problem. Recently, my accounting department started getting bounce backs. When I looked at the list of bounce backs, there were some common themes to them. The terms "INVOICE", "CHECK", "REQUEST", "INV", and various other accounting terms were used in the subject line.
Recently, there have been loads of spam that say things like "your invoice is ready" with a link to bad places. I think that some anti-spam agents have simply said "these are the words that we will flag as spam to keep everyone happy."
The problem is obvious... when someone sends out a legit invoice, it will get caught in this net. SO, I told my accounting dept. to simply not use accounting language in their subject line. We will see how that goes.


text:
Q: Redirect IP to host name in NGINX I want to redirect each IP address of my web site to the host name of that web site using rewrite directive and than access the web site using proxy_pass directive in NGINX like this
 proxy_pass http://host/name ;

Using NGINX as a proxy works for but i couldn't change my script to rewrite addresses and proxy my request at the same time. I tried to use Rewrite directive but i can't find the right syntax for that.

A: Using rewrite directive to change host will cause a redirection. It means client needs to post another request with new host, and then, you can proxy_pass this request. In this case, the URL in client (for example, browser) will change, like 'http://*.*.*.*:port/uri?request_string' -> 'http://host/uri?request_string'.
Usually, we use rewrite directive to change the URI of the request which will be proxy_passed. If you want to change the host, using proxy_set_header. An example:
location ~* "^/maishenme/(knowse|knowdetail|iget|ilist|initem|i?compare)(.*)?$" {
        rewrite "^/maishenme/(.*)?$" /$1 break;
        proxy_pass http://***.xxx.com;
        proxy_set_header Host "internal.xxx.com";
        break;
}

And in this case, from the client side, the url do not change, but for the backend server, you can print the host field and see it changed to "internal.xxx.com"


text:
Q: Mule: DB Insert fails with timeout I am trying to insert data into the database table & I am getting the following error:
Exception stack is:
1. Timeout exceeded (java.util.concurrent.TimeoutException)
  com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProvider:426 (null)
2. Error sending HTTP request. Message payload is of type: String (org.mule.api.MessagingException)
  org.mule.module.http.internal.request.DefaultHttpRequester:287 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html)

Root Exception stack trace:
java.util.concurrent.TimeoutException: Timeout exceeded
    at com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProvider.timeout(GrizzlyAsyncHttpProvider.java:426)
    at com.ning.http.client.providers.grizzly.GrizzlyAsyncHttpProvider$3.onTimeout(GrizzlyAsyncHttpProvider.java:274)
    at org.glassfish.grizzly.utils.IdleTimeoutFilter$DefaultWorker.doWork(IdleTimeoutFilter.java:398)
    at org.glassfish.grizzly.utils.IdleTimeoutFilter$DefaultWorker.doWork(IdleTimeoutFilter.java:377)
    at org.glassfish.grizzly.utils.DelayedExecutor$DelayedRunnable.run(DelayedExecutor.java:158)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

My Insert code is as follows:
     <flow name="api-main">
   <http:listener config-ref="db-system-api-httpListenerConfig" path="/api/*" doc:name="HTTP"/>
    <apikit:router config-ref="db-system-api-config" doc:name="APIkit Router"/>
    <exception-strategy ref="db-system-api-apiKitGlobalExceptionMapping" doc:name="Reference Exception Strategy"/>
    </flow>

    <flow name="put:/contract/{id}:db-system-api-config" processingStrategy="synchronous" >
    <set-property propertyName="Content-Type" value="application/json" doc:name="Set Content Type"/>
    <logger message="#[payload]" level="INFO" doc:name="Initial Payload"/>

    <json:json-to-object-transformer returnClass="java.util.HashMap" mimeType="text/plain" doc:name="JSON to Object"/>

        <foreach collection="#[payload.entrySet()]" doc:name="For Each">
        <db:insert config-ref="Oracle_Configuration" doc:name="Database">
        <db:parameterized-query><![CDATA[INSERT INTO XX.XX_OE_HDR (ID,
                                                                               NUMBER,
                                                                                EFF_START_DATE,
                                                                                EFF_END_DATE,
                                                                                CUST_NUMBER)
                                                                                VALUES (xx.XX_HDR_SEQ.NEXTVAL,
                                                                                xx.XX_HDR_NUM_SEQ.NEXTVAL,
                                                                                TO_DATE('2017-05-23','YYYY-MM-DD HH24:MI:SS'),
                                                                                TO_DATE('2017-06-23','YYYY-MM-DD HH24:MI:SS'),
                                                                                #[payload.myField])]]></db:parameterized-query>
         </db:insert>
         </foreach>
        <logger message="Record successful" level="INFO" doc:name="Log Success"/>

A: according to  Timeout exceeded at com.ning.http.client  your issue is located in the http request.   As far as I know, Oracle Database ( as most of the common databases)  use TCP protocol for transport while your issue is located in an http timeout.
Can you provide the full flow and also how are you triggering the flow?
On the other hand, can you try to isolate the issue and replace the Database for a logger and check if there is no problem with your http request to the flow ? (assuming you are triggering this flow via http request)


text:
Q: Add Function to entity in LINQ Let say I have an entity customer using northwind database.
If I created a function GetCustomerByID under partial class customer. I can execute this function by using Linq query such as
Dim q = From t in db.Customers where t.GetCustomerByID(my_parameter) Select T

If I created the function under partial class dx_northwindDataContext. I can execute this function by using :
Dim result = db.GetCustomerByID(my_parameter)

Since I am creating Data Access Layer for my database, and for not exposing all my function to all my entity to the db variable. I was looking for a way of calling my functions like :
Dim result = db.Customers.GetCustomerByID(my_parameter)

Is there away to do that?

A: Yes, you can create an extension for db.Customers like:
Imports System.Runtime.CompilerServices

    Module IQueryableExtensions

        <Extension()>
        Public Function GetCustomerByID(ByVal source As IQueryable(Of Customer), ByVal id As Int32) As IQueryable(Of Customer)
            return source.Where(Function(f)f.Id == id)
        End Sub

    End Module


text:
Q: What are my options for filtering custom .net controls from the WinForms toolbox of Visual Studio 2008? Visual Studio 2008 does a much better job of detecting and adding controls from projects to the toolbox for use in the forms designer. If you have an assembly with a UserControl- or DataSet-derived type, then it will automatically detect and add that control to the toolbox for designing forms. This is slightly better than the old system in 2005 that made you manually add controls and would occasionally forget them, etc.
However, on the legacy, monolithic project I am working on (now upgraded to vs2008) this means many controls that I don't want and don't need (and a redesign would not be warranted against so much legacy code :( ). I imagine that if I made certain types internal or private, then they wouldn't show up. However, I need many of those to remain public, but not show up in the toolbox. Furthermore, with so many controls getting added to the toolbox, opening the winforms designer slows significantly.

*

*Is there an attribute or other mechanism that prevents toolbox appearance (that wouldn't otherwise affect functionality) ?

*Would filtering using such a mechanism improve performance while still autodetecting new types that SHOULD be in the toolbox? (I know you can disable the autodetect, but its nice to have in many cases)

*Have others encountered this irritation on large solutions (with many csproj/vbproj files)?

Edit: Thanks everyone! I knew it had to be simple (and was likely an attribute) but that fills the gap. Nice to know that I was in good company in not knowing about ToolBoxItem(false).

A: The following attribute should hide it from the toolbox:
[ToolboxItem(false)]

If you apply it to all the types you don't want to show, it will still show any new ones you create without this attribute. Note, you may have to manually remove the items to start with.
This blog post shows some other attributes you may want to use.

A: Go through the toolbox and for each custom control that you see that you want to hide, add the following attribute above the class:

[ToolboxItem(false)]

Of course, this is a compiled attribute and will affect everyone using the code, so I only recommend doing this for controls that don't make drag-drop sense. Otherwise, you will probably make someone that loves that control very very angry. :)


text:
Q: Convert frame pandas in python I receive the output from my pandas datareader as the following:
       Date        AAPL         ACN
0 2016-11-21  111.730003  119.680000
1 2016-11-22  111.800003  119.480003
2 2016-11-23  111.230003  119.820000
3 2016-11-25  111.790001  120.739998
4 2016-11-28  111.570000  120.760002

What I that the frame looks like:
       Date   Minor   Adj Close
0 2016-11-21  AAPL    111.730003
1 2016-11-22  AAPL    111.800003
2 2016-11-23  AAPL    111.230003
3 2016-11-25  AAPL    111.790001
4 2016-11-28  AAPL    111.570000
0 2016-11-21  ACN     119.680000
1 2016-11-22  ACN     119.480003
2 2016-11-23  ACN     119.820000
3 2016-11-25  ACN     120.739998
4 2016-11-28  ACN     120.760002

How can I converte my code that I receive the output mentioned above? The code looks like:
import pandas_datareader.data as pdr

DataLevels = pdr.DataReader(['ACN','AAPL'], 'yahoo', '2016-11-19', '2016-12-1')
DataLevels = DataLevels['Adj Close'].reset_index()
DataLevels.rename(columns={'minor': ['ACN','AAPL'], 'Adj Close': 'Adj Close'}, inplace=True)
print(DataLevels)

A: Use melt to reshape the DF from wide to long format:
pd.melt(df, id_vars=['Date'], value_name='Adj Close', var_name='Minor')


text:
Q: Convert wide-like data to a long one in Stata? I have a dataset like
year CNMubiBeijing CNMubiTianjing CNMubiShanghai  ··· ···  Wulumuqi
1998        .            .             .                      .
1999        .            .             .                      .
····
2013        .            .             .                      .

As you can see, the first row is a list of city names in China,like Beijing, Shanghai and so on, combined with a prefix "CNMubi" (which is redundant). The first column corresponds to the year,and the observations are of another variable(like local government's tax revenue).It's similar to a "wide" type data and I want to convert it to a long type panel data like
city      year tax_rev
Beijing   1998
···
Beijing   2013
Shanghai  1998
···
Shanghai  2013

Two immediate solutions come into my mind. One is to directly use the --reshape-- command, like reshape long CNMubi,i(year) j(city_eng) but it turn out give me a column of missing values (column of city_eng)
The second possible solution is use loop,like
foreach var of varlist _all {

    replace city_eng="`var'"
}

It also doesn't work (in fact,the new generated city_eng equals to the last variables in the varlist), I need to "expand" the data from a mn to a mnm matrix. So how can I achieve my goal, thank you.

A: This works:
clear
set more off

*----- example data -----

input ///
year CNMubiBeijing CNMubiTianjing
1998        .            .
1999        .            .
2000
2001
2002
2003
end

set seed 259376
replace CNMubiBeijing = runiform()
replace CNMubiTianjing = runiform()

*----- what you want -----

reshape long CNMubi, i(year) j(city) string

sort city year
list, sepby(city)

Notice the string option, since j() contains string values.
The result is:
. sort city year

. list, sepby(city)

     +----------------------------+
     | year       city     CNMubi |
     |----------------------------|
  1. | 1998    Beijing    .658855 |
  2. | 1999    Beijing    .494634 |
     |----------------------------|
  3. | 1998   Tianjing   .0204465 |
  4. | 1999   Tianjing   .0454614 |
     +----------------------------+


text:
Q: How to merge two UIImages? I am trying to merge two different images and create a new one. This is the way I would like to do:
I have this image (A):

It's a PNG image and I would like to merge this one with another image (B) which I took from the phone to create something like this:

I need a function who merge A with B creating C. The size must remain from the A image and the image B should auto adapt the size to fit into the polaroid (A). Is it possible to do that? Thank for your help!
UPDATE
Just one thing, the image (A) is a square and the image i took is a 16:9, how can i fix that?? If i use your function the image (B) that i took become stretched!

A: Objective C version of this solution with top image re-centered logic :
-(UIImage *)getImageInclosedWithinAnotherImage
{
    float innerImageSize = 20;
    UIImage *finalImage;

    UIImage *outerImage = [UIImage imageNamed:@"OuterImage.png"];
    UIImage *innerImage = [UIImage imageNamed:@"InnerImage.png"];

    CGSize outerImageSize = CGSizeMake(40, 40); // Provide custom size or size of your actual image
    UIGraphicsBeginImageContext(outerImageSize);

    //calculate areaSize for re-centered inner image
    CGRect areSize = CGRectMake(((outerImageSize.width/2) - (innerImageSize/2)), ((outerImageSize.width/2) - (innerImageSize/2)), innerImageSize, innerImageSize);
    [outerImage drawInRect:CGRectMake(0, 0, outerImageSize.width, outerImageSize.height)];
    [innerImage drawInRect:areSize blendMode:kCGBlendModeNormal alpha:1.0];

    finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return finalImage;
}

A: The upvoted answer stretches the background image changing its ratio. The solution below fixes that by rendering the image from a UIView that contains the two image views as subviews.
ANSWER YOU ARE LOOKING FOR (Swift 4):
func blendImages(_ img: UIImage,_ imgTwo: UIImage) -> Data? {
    let bottomImage = img
    let topImage = imgTwo

    let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: 306, height: 306))
    let imgView2 = UIImageView(frame: CGRect(x: 0, y: 0, width: 306, height: 306))

    // - Set Content mode to what you desire
    imgView.contentMode = .scaleAspectFill
    imgView2.contentMode = .scaleAspectFit

    // - Set Images
    imgView.image = bottomImage
    imgView2.image = topImage

    // - Create UIView
    let contentView = UIView(frame: CGRect(x: 0, y: 0, width: 306, height: 306))
    contentView.addSubview(imgView)
    contentView.addSubview(imgView2)

    // - Set Size
    let size = CGSize(width: 306, height: 306)

    // - Where the magic happens
    UIGraphicsBeginImageContextWithOptions(size, true, 0)

    contentView.drawHierarchy(in: contentView.bounds, afterScreenUpdates: true)

    guard let i = UIGraphicsGetImageFromCurrentImageContext(),
        let data = UIImageJPEGRepresentation(i, 1.0)
        else {return nil}

    UIGraphicsEndImageContext()

    return data
}

The returned image data doubles the size of the image, so set the size of the views at half the desired size.

*

*EXAMPLE: I wanted the width and height of the image to be 612, so I set the view frames width and height to 306)
// Enjoy :)

A: Swift 5: Extension for UIImage
extension UIImage {
  func mergeWith(topImage: UIImage) -> UIImage {
    let bottomImage = self

    UIGraphicsBeginImageContext(size)

    let areaSize = CGRect(x: 0, y: 0, width: bottomImage.size.width, height: bottomImage.size.height)
    bottomImage.draw(in: areaSize)

    topImage.draw(in: areaSize, blendMode: .normal, alpha: 1.0)

    let mergedImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()
    return mergedImage
  }
}

A: Slightly modified version of answer by budidino. This implementation also handles negative posX and posY correctly.
extension UIImage {
    func overlayWith(image: UIImage, posX: CGFloat, posY: CGFloat) -> UIImage {
        let newWidth = posX < 0 ? abs(posX) + max(self.size.width, image.size.width) :
            size.width < posX + image.size.width ? posX + image.size.width : size.width
        let newHeight = posY < 0 ? abs(posY) + max(size.height, image.size.height) :
            size.height < posY + image.size.height ? posY + image.size.height : size.height
        let newSize = CGSize(width: newWidth, height: newHeight)

        UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
        let originalPoint = CGPoint(x: posX < 0 ? abs(posX) : 0, y: posY < 0 ? abs(posY) : 0)
        self.draw(in: CGRect(origin: originalPoint, size: self.size))
        let overLayPoint = CGPoint(x: posX < 0 ? 0 : posX, y: posY < 0 ? 0 : posY)
        image.draw(in: CGRect(origin: overLayPoint, size: image.size))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return newImage
    }
}

A: Swift 4 UIImage extension that enables easy image merging / overlaying.
extension UIImage {

  func overlayWith(image: UIImage, posX: CGFloat, posY: CGFloat) -> UIImage {
    let newWidth = size.width < posX + image.size.width ? posX + image.size.width : size.width
    let newHeight = size.height < posY + image.size.height ? posY + image.size.height : size.height
    let newSize = CGSize(width: newWidth, height: newHeight)

    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
    draw(in: CGRect(origin: CGPoint.zero, size: size))
    image.draw(in: CGRect(origin: CGPoint(x: posX, y: posY), size: image.size))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()!
    UIGraphicsEndImageContext()

    return newImage
  }

}

A: This way the overlay picture will be much cleaner:
class func mergeImages(imageView: UIImageView) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(imageView.frame.size, false, 0.0)
    imageView.superview!.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
}

A: Hope this may help you,
var bottomImage = UIImage(named: "bottom.png")
var topImage = UIImage(named: "top.png")

var size = CGSize(width: 300, height: 300)
UIGraphicsBeginImageContext(size)

let areaSize = CGRect(x: 0, y: 0, width: size.width, height: size.height)
bottomImage!.draw(in: areaSize)

topImage!.draw(in: areaSize, blendMode: .normal, alpha: 0.8)

var newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()

All the Best :)


text:
Q: How can I render bevel polygon on iPhone? I checked out Tangram from App Store. How can I make this bevel effect on different shapes? What technology do I need create such a layout?
Do I need OpenGL ES or cocos2D maybe Quartz2D?

A: Actually I've documented the development process of tangram!, find it here: http://gotoandplay.freeblog.hu/categories/compactTangram/
At that time there was no option to render OpenGL polygons with anti-aliasing, so I made a demanding workaround to achieve the result (I wanted to add bump effect too, but later on I skipped). The point is in this post: http://gotoandplay.freeblog.hu/archives/2010/02/04/compactTangram_074_-_organizing_textures_performance_preservingincreasing_plan/
Funny.
Since than, you can easily render with anti-alias, and retina also a solution for that pain, so some polygon mesh, some shader for specular stuff, and there you go, or go with Cocos2D, as you mentioned, it has growing 3D support.


text:
Q: stop threaded STDIN listeners from interfering with each other Here is my main thread, which does nothing but launch other threads and then sleeps forever while the other threads do their work.
require 'io/console'
4.times { Thread.new { loop { App.process_char(STDIN.getch) } } }
loop { sleep }

This is running for the duration of my program and sends all individual keystrokes to App.process_char. However, some inputs will cause this method to run an additional gets.chomp. This is not working - it's not getting input because the other threads are eating it all.
I'm thinking there's a way to isolate my STDIN from existing thread listeners before calling gets.chomp. In searched I've seen a mention of redefining $stdin and $stdout but I'm not sure how to maintain the ability to capture user keystrokes.


text:
Q: OpenGL/Glut draw Pyramid - Skeleton Bones I would like to draw a human skeleton (pose estimation project) in OpenGL, using whichever toolkit might be helpful.
I already have something simple working, drawing the joints with
glvertex3d // and/or
glutWireSphere

and the bones with
glBbegin(GL_Lines)
glvertex3d // coordinates of starting point
glvertex3d // coordinates of ending point
glEnd()

This looks like very similar to the next picture, however this bone depiction doesn't give any intuition about bone rotation.

I would like to have something looking more similar to the following picture, with bones drawn as elongated pyramids.

Glut doesn't seem to help on this.
glutWireCone // better than simple line, but still no intuition about rotation
glutWireTetrahedron // not really useful / parametrizable

Is there any tool available or should this be a custom solution?

A: GLUT objects will be drawn using the current OpenGL modelview matrix.  This can be used to control the position, rotation, or even the scaling of the rendered object.  With a cone, you would first translate (using glTranslate()) to the position of one end point, and then rotate (using glRotate() or glMultMatrix()) so that your cone was pointed towards the other endpoint.  Finally you call your glutWireCone() method so that the height is equal to the distance from one endpoint to the other.
The tricky bit is finding the glRotate() parameters.  GLUT will draw the cone by default along the Z axis, so your rotation needs to be whatever rotation would be required to rotate the Z axis to the axis defined by your end point minus your start point.  The GLM math library can be really useful for this kind of thing.  It even has a function for it
quat rotation(vec3 const & orig, vec3 const & dest)

So you could do something like this:
// these are filled in with your start and end points
glm::vec3 start, end;
glm::vec3 direction = end - start;
glm::quat rotation = rotation(glm::vec3(0, 0, 1), direction);
glm::mat4 rotationMatrix = glm::mat4_cast(rotation);
glMultMatrixf(&rotationMatrix);

You can get the tetrahedron effect by specifying 3 for the number of slices in your glut cone.  In fact I wouldn't be very surprised if glutWireTetrahedron wasn't implemented in terms of glutWireCone

A: As mentioned in the comment above, Jherico's answer really helped me solve this problem.
This answer builts uppon his post, just to make things a bit more complete, for future reference.
Please find the GLM library here, it's a header only library, so you don't need to build this, just link to it and include the necessary header files. It has some great tools, as can be seen below.
#define GLM_FORCE_RADIANS // for compatibility between GLM and OpenGL API legacy functions
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>    // for glm::mat4_cast // casting quaternion->mat4
#include <glm/gtx/quaternion.hpp>  // for glm::rotation
#include <glm/gtx/string_cast.hpp> // for glm::to_string
...
...
...
// _startBoneVec3 used below is Eigen::Vector3d
// _endddBoneVec3 used below is Eigen::Vector3d
...
...
...
//
// for JOINTS
//
glPushMatrix();
    glTranslated( _startBoneVec3(0),_startBoneVec3(1),_startBoneVec3(2) );
    glutWireSphere(1.0,30,30);
glPopMatrix();
...
...
//
// for BONES
//
glPushMatrix();
    float boneLength = ( _endddBoneVec3  - _startBoneVec3 ).norm();
    glTranslated(        _startBoneVec3(0),_startBoneVec3(1),_startBoneVec3(2) );
    glm::vec3 _glmStart( _startBoneVec3(0),_startBoneVec3(1),_startBoneVec3(2) );
    glm::vec3 _glmEnddd( _endddBoneVec3(0),_endddBoneVec3(1),_endddBoneVec3(2) );
    glm::vec3 _glmDirrr   = glm::normalize( _glmEnddd - _glmStart ); // super important to normalize!!!
    glm::quat _glmRotQuat = glm::rotation( glm::vec3(0,0,1),_glmDirrr); // calculates rotation quaternion between 2 normalized vectors
  //glm::mat4 _glmRotMat = glm::mat4_cast(_glmRotQuat); // quaternion -> mat4
    glm::mat4 _glmRotMat = glm::toMat4   (_glmRotQuat); // quaternion -> mat4
  //std::cout <<  glm::to_string(_glmDirrr) << std::endl;
    glMultMatrixf(glm::value_ptr(_glmRotMat));
    glutWireCone(4.2,boneLength,4,20); // cone with 4 slices = pyramid-like
glPopMatrix();

Result:


text:
Q: Is the "when" keyword in a try catch block the same as an if statement? In C# 6.0 the "when" keyword was introduced, now you're able to filter an exception in a catch block. But isn't this the same as a if statement inside a catch block? if so, isn't it just syntactic sugar or i'm missing something?
For example a try catch block with the "when" keyword:
try { … }
catch (WebException ex) when ex.Status == WebExceptionStatus.Timeout {
   //do something
}
catch (WebException ex) when ex.Status== WebExceptionStatus.SendFailure {
   //do something
}
catch (Exception caught) {…}

Or
try { … }
catch (WebException ex) {
   if(ex.Status == WebExceptionStatus.Timeout) {
      //do something
   }
}
catch (WebException ex) {
   if(ex.Status == WebExceptionStatus.SendFailure) {
      //do something
   }
}
catch (Exception caught) {…}

A: In addition to the several fine answers you already have here: there is a very important difference between an exception filter and an "if" in a catch block: filters run before inner finally blocks.
Consider the following:
void M1()
{
  try { N(); } catch (MyException) { if (F()) C(); }
}
void M2()
{
  try { N(); } catch (MyException) when F() { C(); }
}
void N()
{
  try { MakeAMess(); DoSomethingDangerous(); }
  finally { CleanItUp(); }
}

The order of calls differs between M1 and M2.
Suppose M1 is called. It calls N(), which calls MakeAMess().  A mess is made.  Then DoSomethingDangerous() throws MyException. The runtime checks to see if there is any catch block that can handle that, and there is.  The finally block runs CleanItUp(). The mess is cleaned up. Control passes to the catch block.  And the catch block calls F() and then, maybe, C().
What about M2?  It calls N(), which calls MakeAMess().  A mess is made.  Then DoSomethingDangerous() throws MyException. The runtime checks to see if there is any catch block that can handle that, and there is -- maybe.  The runtime calls F() to see if the catch block can handle it, and it can.  The finally block runs CleanItUp(), control passes to the catch, and C() is called.
Did you notice the difference?  In the M1 case, F() is called after the mess is cleaned up, and in the M2 case, it is called before the mess is cleaned up.  If F() depends on there being no mess for its correctness then you are in big trouble if you refactor M1 to look like M2!
There are more than just correctness problems here; there are security implications as well.  Suppose the "mess" we are making is "impersonate the administrator", the dangerous operation requires admin access, and the cleanup un-impersonates administrator.  In M2, the call to F has administrator rights. In M1 it does not.  Suppose that the user has granted few privileges to the assembly containing M2 but N is in a full-trust assembly; potentially-hostile code in M2's assembly could gain administrator access through this luring attack.
As an exercise: how would you write N so that it defends against this attack?
(Of course the runtime is smart enough to know if there are stack annotations that grant or deny privileges between M2 and N, and it reverts those before calling F.  That's a mess that the runtime made and it knows how to deal with it correctly. But the runtime doesn't know about any other mess that you made.)
The key takeaway here is that any time you are handling an exception, by definition something went horribly wrong, and the world is not as you think it should be.  Exception filters must not depend for their correctness on invariants that have been violated by the exceptional condition.
UPDATE:
Ian Ringrose asks how we got into this mess.
This portion of the answer will be somewhat conjectural as some of the design decisions described here were undertaken after I left Microsoft in 2012. However I've chatted with the language designers about these issues many times and I think I can give a fair summary of the situation.
The design decision to make filters run before finally blocks was taken in the very early days of the CLR; the person to ask if you want the small details of that design decision would be Chris Brumme. (UPDATE: Sadly, Chris is no longer available for questions.)  He used to have a blog with a detailed exegesis of the exception handling model, but I don't know if it is still on the internet.
It's a reasonable decision. For debugging purposes we want to know before the finally blocks run whether this exception is going to be handled, or if we're in the "undefined behaviour" scenario of a completely unhandled exception destroying the process. Because if the program is running in a debugger, that undefined behaviour is going to include breaking at the point of the unhandled exception before the finally blocks run.
The fact that these semantics introduces security and correctness issues was very well understood by the CLR team; in fact I discussed it in my first book, which shipped a great many years ago now, and twelve years ago on my blog:
https://blogs.msdn.microsoft.com/ericlippert/2004/09/01/finally-does-not-mean-immediately/
And even if the CLR team wanted to, it would be a breaking change to "fix" the semantics now.
The feature has always existed in CIL and VB.NET, and the attacker controls the implementation language of the code with the filter, so introducing the feature to C# does not add any new attack surface.
And the fact that this feature that introduces a security issue has been "in the wild" for some decades now and to my knowledge has never been the cause of a serious security issue is evidence that it's not a very fruitful avenue for attackers.
Why then was the feature in the first version of VB.NET and took over a decade to make it into C#?  Well, "why not" questions like that are hard to answer, but in this case I can sum it up easily enough: (1) we had a great many other things on our mind, and (2) Anders finds the feature unattractive. (And I'm not thrilled with it either.) That moved it to the bottom of the priority list for many years.
How then did it make it high enough on the priority list to be implemented in C# 6?  Many people asked for this feature, which is always points in favour of doing it.  VB already had it, and C# and VB teams like to have parity when possible at a reasonable cost, so that's points too. But the big tipping point was: there was a scenario in the Roslyn project itself where exception filters would have been really useful. (I do not recall what it was; go diving in the source code if you want to find it and report back!)
As both a language designer and compiler writer, you want to be careful to not prioritize the features that make only compiler writer's lives easier; most C# users are not compiler writers, and they're the customers! But ultimately, having a collection of real-world scenarios where the feature is useful, including some that were irritating the compiler team itself, tipped the balance.

A:
But isn't this the same as a if statement inside a catch block?

No, because your second approach without when won't reach the second Catch if the ex.Status== WebExceptionStatus.SendFailure. With when the first Catch would have been skipped.
So the only way to handle the Status without when is to have the logic in one catch:
try { … }
catch (WebException ex) {
   if(ex.Status == WebExceptionStatus.Timeout) {
      //do something
   }
   else if(ex.Status == WebExceptionStatus.SendFailure) {
      //do something
   }
   else
      throw; // see Jeppe's comment
}
catch (Exception caught) {…}

The else throw will ensure that only WebExceptions with status=Timeout or SendFailure are handled here, similar to the when approach. All others will not be handled and the exception will be propagated. Note that it won't be caught by the last Catch, so there's still a difference to the when. This shows one of the advantages of when.

A:
isn't this the same as a if statement inside a catch block?

No.
It acts more as a "discriminator" for the benefit of the Exception-throwing system.
Remember how Exceptions are thrown twice?
The first "throw" (those "first-chance" Exceptions that 'Studio goes on about) tells the Run-Time to locate the nearest Exception Handler that can deal with this Type of Exception and to collect up any "finally" blocks between "here" and "there".
The second "throw" unwinds the call stack, executing each of those "finally" blocks in turn and then delivers the execution engine to the entry point of the located Exception handling code.
Previously, we could only discriminate between different Types of Exception.  This decorator gives us finer-grain control, only catching a particular Type of Exception that happens to be in a state that we can do something about.
For example (out of thin air) you might want to handle a "Database Exception" that indicates a broken connection and, when that happens, try to reconnect automatically.
Lots of database operations throw a "Database Exception", but you're only interested in a particular "Sub-Type" of them, based on the properties of the Exception object, all of which are available to the exception-throwing system.
An "if" statement inside the catch block will achieve the same end result, but it will "cost" more at run-time.  Because this block will catch any and all "Database Exceptions", it will be invoked for all of them, even if it can only do something useful for a [very] small fraction of them.  It also means that you then have to re-throw [all] the Exceptions that you can't do anything useful with, which is just repeating the whole, two-pass, handler-finding, finally-harvesting, Exception-throwing farago all over again.
Analogy: A [very strange] Toll bridge.
By default, you have to "catch" every car in order for them to pay the toll.
If, say, cars driven by city employees are exempt from the toll (I did say it was strange), then you only need to stop cars driven by anybody else.
You could stop every car and ask:
catch( Car car )
{
   if ( car.needsToPayToll() )
      takePayment( car );
}

Or, if you had some way of "interrogating" the car as it approached, then you could ignore those driven by city employees, as in:
catch( Car car ) when car.needsToPayToll()
{
   takePayment( car );
}

A: Extending the answer by Tim.
C# 6.0 introduces a new feature exception filter and a new keyword when.

Is the "when" keyword in a try catch block the same as a if statement?

The when keyword works like if. A when condition is a predicate expression, which can be appended to a catch block. If the predicate expression is evaluated to be true, the associated catch block is executed; otherwise, the catch block is ignored.
A wonderful explanation is given on C# 6.0 Exception Filter and when Keyword


text:
Q: Rsync files in local directories and chmod issues When I do rsync this is my command:
rsync -a source dest

I am using dest as my web root /var/www/
so some folder which are set to chmod 777 were no longer with 777 permission.
does rsync change folder permission as well?
What is best way to sync two local folders in same server.? Will rsync delete any changes done in destination and use the source files?

A: The manual page for rsync says this:
-a, --archive    archive mode; equals -rlptgoD (no -H,-A,-X)

Among those options is -p, about which it says:
-p, --perms      preserve permissions

So, yes, rsync is making the permissions on dest match those on source in this case. If that is not desired, then read the manual page and decide what options are more appropriate to your need than rsync -a, and use those instead. In the simplest case, add the --no-perms flag after -a to disable the permission preservation.


text:
Q: Shade area between 2 y coordinates in matplotlib I'm trying to create a shaded rectangle based on two vertical coordinates (the length of the rectangle should span the whole x axis).
I've tried to use fill_between with the following (p1 & p2 are the data coordinates):
f, ax1 = plt.subplots()
x = np.linspace(200,300,2000)
y = x**(2)
y1 = x
p1 = 4700
p2 = 7700

ax1.plot(x, y, lw=2)
ax1.set_xlabel('Temperature $[K]$', fontweight='bold')
ax1.set_ylabel('Pressure $[mb]$', fontweight='bold')
ax1.fill_between(x, y1.fill(p1), y1.fill(p2))

But i'm getting the following error:
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

What is wrong? Any better way to do this?
Thank you!!

A: Possibly you mean to use axhspan.
p1 = 4700
p2 = 7700
ax1.axhspan(p1, p2, color="limegreen", alpha=0.5)

A: IIUC, the issue is with the use of the .fill() function. You can avoid that, using fill_between with your x array and just the p1 and p2 values, as fill_between can accept scalar values for y1 and y2.
ax1.fill_between(x, p1, p2)

Note, you can change the color and transparancy easily by adding a color and alpha argument:
ax1.fill_between(x, p1, p2, color='limegreen', alpha=0.5)

A: The fill method of an array doesn't return an array, it returns None.

A: You've misunderstood fill_between. When  you use it is advisable to express y as a function:
def y(x):
    return x**2
section = np.arange(start,end,0.1)
plt.fill_between(section,y(section))

will do the job with suitable values for start and end.


text:
Q: Where am I leaking memory? (Valgrind) 24 bytes lost in one block Each node is 8 bytes and I allocate 3 in my program (8*3 = 24) so I assume thats the memory im losing.
This is the valgrind error
24 (8 direct, 16 indirect) bytes in 1 blocks are definitely lost in loss record 3 of 3
==2381==    at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2381==    by 0x8048598: mh_alloc (in /media/sf_Z_DRIVE/comp2401a4/a4)
==2381==    by 0x8048857: main (in /media/sf_Z_DRIVE/comp2401a4/a4)

this is the BlockType which is the data the nodes carry.
typedef struct {
  int  rsv;
  void *addr;
  int   size;
  char  tag[MAX_STR];
 } BlockType;

This is where valgrind says im losing the data.
void *mh_alloc(HeapType *heap, int n, char *label){ //this is the allocation function

BlockType *blk;
blk = (BlockType *)malloc(sizeof(BlockType));
blk->rsv = C_TRUE; //set block to reserved
blk->addr = blk;  //set the address to keep track of where the block is stored in memory
blk->size = n;   // set the size of the block
strcpy(blk->tag, label); //add the name of the block

    Node *temp2 = malloc(sizeof(struct Node));
    temp2->block = blk;
    temp2->next = NULL;
    if (heap->head == NULL) {
     heap->head = temp2;
    }
    else{
    struct Node *temp = heap->head;
    while (temp->next != NULL)
            {
            temp = temp->next;
            }
            temp->next = temp2;
            }
     return blk; //we return blk because we assign pointers to such blocks in the main function.
 }

This the function called at the end to free all blocks and nodes ->
   void mh_collect(HeapType *heap){ //function to unreserve all elements in the array, and free each            address

    struct Node *temp = heap->head;
    struct Node *prev = NULL;

            if (temp->next == NULL){
                    printf("Only the head left");
                    temp->block->rsv = C_FALSE;
                    return;
                    }
            while(temp != NULL){
                    temp->block->rsv = C_FALSE;
                    free(temp->block->addr);
                    temp = temp->next;
                    }

   }

A: Edit: (The original question was modified)
This code looks wrong:
while(temp != NULL){
    temp->block->rsv = C_FALSE;
    free(temp->block->addr);
    temp = temp->next;
}

In your loop, you don't free the node temp itself.  Note that this doesn't "leak" any memory, but it does leave the memory hanging around.  You may want to consider something like this:
while(temp != NULL){
    Node *next = temp->next;
    temp->block->rsv = C_FALSE;   // Seems useless because you are freeing it.
    free(temp->block);            // Note: temp->block->addr == temp->block
    free(temp);
    temp = next;
}

Also, if you ever assign to block->addr other than what you showed above, then that could be the cause of your leak.  I'm not sure what the use of block->addr is, but I would suggest removing it unless it serves some other purpose.


text:
Q: Select the parent node from child node I have an XML file and need to find the node with a specific description. The code does that and adds it to the xmlFINode. But now I need to select the parent element  of that node (xmlFiNode).
Example XML
<dmodule>
<content>
    <faultIsolation>
        <faultIsolationProcedure applicRefId="Software" id="tree1">
            <fault faultCode=" "/>
            <faultDescr>
                <descr>This nodes description</descr>
            </faultDescr>
        </faultIsolationProcedure>
    </faultIsolation>
</content>

Code
    xmlFINode = "dmodule/content/faultIsolation/faultIsolationProcedure/faultDescr[descr='" + selectedItem + "']"
    Dim parentNode = xmlFINode ?

A: You can use the below.
//faultIsolation/faultIsolationProcedure[.//descr='This nodes description']

Another option using ancestor.
//descr[.='This nodes description']/ancestor::faultIsolationProcedure

A: Use Xml Linq with a dictionary :
Imports System.Xml
Imports System.Xml.Linq
Module Module1
    Const FILENAME As String = "c:\temp\test.xml"
    Sub Main()
        Dim doc As XDocument = XDocument.Load(FILENAME)

        Dim dict As Dictionary(Of String, List(Of XElement)) = doc.Descendants("faultIsolationProcedure") _
                                                               .GroupBy(Function(x) CType(x.Descendants("descr").FirstOrDefault(), String), Function(y) y) _
                                                               .ToDictionary(Function(x) x.Key, Function(y) y.ToList)

    End Sub

End Module


text:
Q: Pacemaker and DRBD on Hyper-V I need to setup two-node Web cluster for Apache web site. I have Hyper-V infrastructure and only two nodes.
The points are load-balancing and high availability.
I installed and configured two VMs with CentOS 7, Pacemaker cluster, MariaDB 10. I configured Master/Slave ocf::percona:mysql resource in Pacemaker.
Next i need a shared storage for web site content.
I created DRBD disk in dual-primary mode and GFS2 in top of it. I tested it without adding to Pacemaker. All worked fine but, to make it automaticaly promoted, i need to manage these via Pacemaker.
The problem is that Pacemaker need fencing to create DRBD resource but there is no stonith agents for Hyper-V.
I read that in previous version for CentOS 6 it was possible to create SSH stonith agent. I tried to do this, but pcs not works with it.
Is it possible to use Pacemaker in top of Hyper-V for now? Or may be exist another way to use DRBD in dual primary?

A: I have tried many solutions but no one did not work well.
I have made two-way file replication using lsyncd instead.


text:
Q: JIRA API components name is not valid I am currently attempting to create an issue within JIRA via API and have been running across an issue that I have no clue to fix.
I used a curl command to find the components and I got the following:
"components":[{"self":"https://jira-server/rest/api/2/component/18458","id":"18458","name":"JIRA","description":"#"},{"self":"https://jira-server/rest/api/2/component/18463","id":"18463","name":"JIRA"}]

when I run my script by using python-JIRA API with the following command:
new_issue = jira.create_issue(project='IT', summary='New issue from jira-python', description='look here', issuetype={'name': 'Task'}, components = [{'name': "JIRA"}])

I get the following error message:
response text = {"errorMessages":[],"errors":{"components":"Component name 'JIRA' is not valid"}}

Can anyone tell me what exactly I am doing wrong? I am 100% "JIRA" is a component since I manually created a test issue and selected "JIRA" as a component.

A: You have to make sure the Component you're linking to belongs to the same Jira Project that your issue is being created under

A: I believe your issue might be that you have too many brackets, components = [{'name': "JIRA"}] should be components = {'name': "JIRA"}
This is what I think your error is trying to tell you too when it says "errorMessages":[]....., the api only expects one set of brackets and passing it a set with information enclosed in another pair sets it off.
However I have not tried this solution but I do know it works when using issuetype = {'name' : 'Bug'}

Alternatively you probably don't even need the components part, it should create the issue with the other items given, if it doesn't its probably another field that only task requires. If you try to create an epic you need customfield_10814 to be filled with a description and for bug you need to fill the found at location.

A: The syntax is correct. components should be a list.
Did you create 'JIRA' as a component in the same project?
Make sure the component name is available for that project. If you go to any ticket in the same project, the 'dropdown' in the component section should list all the available components.

A: Create a component for  'JIRA' . From error it seems you project doesn't have any value called 'JIRA' .
Creation of value 'JIRA' for component will solve the problem


text:
Q: How to register a dynamic backward hook on tensors in Pytorch? I'm trying to register a backward hook on each neuron's weights in a network. By dynamic I mean that it will take a value and multiply the associated gradients by that value.
From here it seem like it's possible to register a hook on a tensor with a fixed value (though note that I need it to take a value that will change). From here it also seems like it's possible to register a hook on all of the parameters -- they use it to do gradients clipping (though note that I'm trying to only do it on each neuron's weights).
If my network is as follows:
class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()

        self.fc1 = nn.Linear(3,5)
        self.fc2 = nn.Linear(5,10)
        self.fc3 = nn.Linear(10,1)

    def forward(self, x):
        x = torch.relu(self.fc1(x))
        x = torch.relu(self.fc2(x))
        x = torch.relu(self.fc3(x))
        return x

The first layer has 5 neurons with 3 associated weights for each. Hence, this layer should have 5 hooks that modifies (i.e change the current gradient by multiplying it) their 3 associated weights gradients during the backward step.
Training pseudo-code example:
net = Model()
for epoch in epochs:
    out = net(data)
    loss = criterion(out, target)
    optimizer.zero_grad()
    loss.backward()
    for hook in list_of_hooks: #not sure if there's a more "pytorch" way of doing this without a for loop
        hook(random_value)
    optimizer.step()

A: What about exploiting lambdas closure over names?
A short example:
import torch

net_params = torch.rand(5, 3, requires_grad=True)

msg = "Hello!"

t.register_hook(lambda g: print(msg))

out1 = net_params * 2.

loss = out1.sum()
loss.backward()  # Activates the hook and prints "Hello!"

msg = "How are you?"  # The lambda is affected by this change

out2 = t ** 4.
loss2 = out2.sum()

loss2.backward()  # Activates the hook again and prints "How are you?"

So a possible solution to your problem:
net = Model()
# Replace it with your computed values
rand_values = torch.rand(net.fc1.out_features, net.fc1.in_features)

net.fc1.weight.register_hook(lambda g: g * rand_values)

for epoch in epochs:
    out = net(data)
    loss = criterion(out, target)
    optimizer.zero_grad()
    loss.backward()  # fc1 gradients are multiplied by rand_values
    optimizer.step()

    # Update rand_values. The lambda computation will change accordingly
    rand_values = torch.rand(net.fc1.out_features, net.fc1.in_features)

Edit
To make things clearer, if you specifically want to multiply each set of weights i by a single value vi you can exploit broadcasting semantic and define values = torch.tensor([v0, v1, v2, v3, v4]).reshape(5, 1), then the lambda becomes lambda g: g * values