问:
Assembly Reference in ASP.NET
When I build my Web App I get the following error.

```<code>The type or namespace name 'LoginViewModel' could not be found (are you missing a using directive or an assembly reference?)
public class _Page_Views_Account_Login_cshtml : System.Web.Mvc.WebViewPage<LoginViewModel>
</code>```

I open the file where the using is defined in AppData. I have that.

```<code>using Repository.Models;
</code>```

This is the previous location of view model LoginViewModel.
Now this is another project named just ViewModel.
Each time when I build my application this old using is appear. Where can I set it?

答:
You Created another project to Store the LoginViewModel?
If So, You need to add reference to the new project.

Right Click on reference and Choose "Add Reference"
Select Project and Click on the project which contains the LoginViewModel.

Sorry i can't send Snapshot right now. Hope it helps.

Title: Assembly Reference in ASP.NET

Body:
When I build my Web App I get the following error.

The type or namespace name 'LoginViewModel' could not be found (are you missing a using directive or an assembly reference?)
public class _Page_Views_Account_Login_cshtml : System.Web.Mvc.WebViewPage<LoginViewModel>

I open the file where the using is defined in AppData. I have that.

using Repository.Models;

This is the previous location of view model LoginViewModel.
Now this is another project named just ViewModel.
Each time when I build my application this old using is appear. Where can I set it?


来源: stackexchange

问:
Add product to cart outside of magento (external script)
I have to add a product through an external page into the cart under the same URL.

The difference between these pages is that e.g. test.de is running TYPO3 and test.de/Shop is running Magento and test.de/productpage is running an external script through TYPO3.

From the product page, I have to add a product to the Magento cart to proceed the checkout.

The key problem is to start the session outside of Magento.
If I call test.de/Shop/checkout/cart before I go totest.de/productpage and add a product to the cart, it works flawlessly.
But if I go the normal way (site -> productpage -> cart) I cant get Magento to listen to the session on the product page.

I have something like this to call

```<code>function addToBasket()
    {

        require_once('../app/Mage.php');
        ob_start();
        session_start();
        umask(0);
        session_write_close();
        Mage::app()->setCurrentStore(33);

        $session = Mage::getSingleton('core/session', array('name'=>'frontend'));

        $productId = !isset($_GET['activeProdId']) ? '' : $_GET['activeProdId'];
        $qty = !isset($_GET['qty']) ? '1' : $_GET['qty'];

        if(empty($productId)) {
            return "no product-id found";
        }

        $request = Mage::app()->getRequest();

        $product = Mage::getModel('catalog/product')->load($productId);

        $cart = Mage::helper('checkout/cart')->getCart();

        $cart->addProduct($product, array('qty' => $qty));

        $session->setLastAddedProductId($product->getId());
        $session->setCartWasUpdated(true);

        $cart->save();

        return true;

   }
</code>```

The addToBasket is called through ajax.

So the question is: How do I start the session outside of the Magento-scope and put products into the cart?

答:
Add first (like @samsonovits suggested) I had to add the store code in mage app and the store id (didn't test if the store-id is necessary after adding the store code).

```<code>Mage::app("default")->setCurrentStore(33);
</code>```

Afterwards I called the frontend on Mage::app

```<code>Mage::app()->loadArea('frontend');
</code>```

I switched the Mage::helper('checkout/cart') to the singleton Mage::getSingleton('checkout/cart').

Since Magento 1.8 we have to add a form_key to add products through an external script.

This was accomplished by the following code:

```<code>$param = array('product' => $productId,
                   'qty' => $qty,
                   'form_key' => Mage::getSingleton('core/session')->getFormKey());

$request = new Varien_Object();
$request->setData($param);
</code>```

Now we could proceed with a $cart->addProduct($product, $request) and $cart->save() to save the cart.

There is one more important part to change (since the external script is not in the same scope like magento) - the cookie url and path.

System -> Configuration -> Web -> Cookies

There we have to customize two fields:

Cookie-Path: /Shop (where /Shop is the destination of magento)

Cookie-Domain: .test.de (where .test.de is the URL of the project)

After this the /Shop/checkout/cart was able to inherit the frontend-Cookie of the external script (productpage)

NOTE: Without changing the Cookie-Path & Cookie-Domain Magento will create two frontend cookies with different content.

Full code:

```<code>function addToBasket()
{

    require_once('path/to/Mage.php');
    umask(0);
    Mage::app("default")->setCurrentStore(33);
    umask(0);
    Mage::app()->loadArea('frontend');
    $productId = !isset($_GET['activeProdId']) ? '' : $_GET['activeProdId'];
    $qty = !isset($_GET['qty']) ? '1' : $_GET['qty'];
    Mage::getSingleton("core/session", array("name" => "frontend"));
    $session = Mage::getSingleton("customer/session");
    $cart = Mage::getSingleton('checkout/cart')->setStoreId(33);

    $cart->init();

    $paramater = array('product' => $productId,
                        'qty' => $qty,
                        'form_key' => Mage::getSingleton('core/session')->getFormKey()
                );

    $request = new Varien_Object();
    $request->setData($paramater);

    if(empty($productId)) {
        return "no product-id found";
    }

    $product = Mage::getModel('catalog/product')->load($productId);

    $cart->addProduct($product, $request);

    $session->setLastAddedProductId($product->getId());
    $session->setCartWasUpdated(true);

    $cart->save();
    return 1;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have to add a product through an external page into the cart under the same URL.

The difference between these pages is that e.g. test.de is running TYPO3 and test.de/Shop is running Magento and test.de/productpage is running an external script through TYPO3.

From the product page, I have to add a product to the Magento cart to proceed the checkout.

The key problem is to start the session outside of Magento.
If I call test.de/Shop/checkout/cart before I go totest.de/productpage and add a product to the cart, it works flawlessly.
But if I go the normal way (site -> productpage -> cart) I cant get Magento to listen to the session on the product page.

I have something like this to call

function addToBasket()
    {

        require_once('../app/Mage.php');
        ob_start();
        session_start();
        umask(0);
        session_write_close();
        Mage::app()->setCurrentStore(33);

        $session = Mage::getSingleton('core/session', array('name'=>'frontend'));

        $productId = !isset($_GET['activeProdId']) ? '' : $_GET['activeProdId'];
        $qty = !isset($_GET['qty']) ? '1' : $_GET['qty'];

        if(empty($productId)) {
            return "no product-id found";
        }

        $request = Mage::app()->getRequest();

        $product = Mage::getModel('catalog/product')->load($productId);

        $cart = Mage::helper('checkout/cart')->getCart();

        $cart->addProduct($product, array('qty' => $qty));

        $session->setLastAddedProductId($product->getId());
        $session->setCartWasUpdated(true);

        $cart->save();

        return true;

   }

The addToBasket is called through ajax.

So the question is: How do I start the session outside of the Magento-scope and put products into the cart?

Body:
Add first (like @samsonovits suggested) I had to add the store code in mage app and the store id (didn't test if the store-id is necessary after adding the store code).

Mage::app("default")->setCurrentStore(33);

Afterwards I called the frontend on Mage::app

Mage::app()->loadArea('frontend');

I switched the Mage::helper('checkout/cart') to the singleton Mage::getSingleton('checkout/cart').

Since Magento 1.8 we have to add a form_key to add products through an external script.

This was accomplished by the following code:

$param = array('product' => $productId,
                   'qty' => $qty,
                   'form_key' => Mage::getSingleton('core/session')->getFormKey());

$request = new Varien_Object();
$request->setData($param);

Now we could proceed with a $cart->addProduct($product, $request) and $cart->save() to save the cart.

There is one more important part to change (since the external script is not in the same scope like magento) - the cookie url and path.

System -> Configuration -> Web -> Cookies

There we have to customize two fields:

Cookie-Path: /Shop (where /Shop is the destination of magento)

Cookie-Domain: .test.de (where .test.de is the URL of the project)

After this the /Shop/checkout/cart was able to inherit the frontend-Cookie of the external script (productpage)

NOTE: Without changing the Cookie-Path & Cookie-Domain Magento will create two frontend cookies with different content.

Full code:

function addToBasket()
{

    require_once('path/to/Mage.php');
    umask(0);
    Mage::app("default")->setCurrentStore(33);
    umask(0);
    Mage::app()->loadArea('frontend');
    $productId = !isset($_GET['activeProdId']) ? '' : $_GET['activeProdId'];
    $qty = !isset($_GET['qty']) ? '1' : $_GET['qty'];
    Mage::getSingleton("core/session", array("name" => "frontend"));
    $session = Mage::getSingleton("customer/session");
    $cart = Mage::getSingleton('checkout/cart')->setStoreId(33);

    $cart->init();

    $paramater = array('product' => $productId,
                        'qty' => $qty,
                        'form_key' => Mage::getSingleton('core/session')->getFormKey()
                );

    $request = new Varien_Object();
    $request->setData($paramater);

    if(empty($productId)) {
        return "no product-id found";
    }

    $product = Mage::getModel('catalog/product')->load($productId);

    $cart->addProduct($product, $request);

    $session->setLastAddedProductId($product->getId());
    $session->setCartWasUpdated(true);

    $cart->save();
    return 1;
}


问:
How to check an element is invisible via its text
I want to be able to wait for an element to be visible where the text = 'Vouchers by post'. However when I try the below, I am recieving a

cannot assign void as an implicit variable and cannot convert from OpenQA.Seleinium.By to OpenQA.Seleinium.ISearchContent.

What do i need to do to fix the below:

```<code>       public bool CheckBasketHolidayVoucherTextIsNotPresent(string basketLocation)
    {
        var topBasketItems = _driver.FindElements(CommonPageElements.TopBasketItems);
        var bottomBasketItems = _driver.FindElements(CommonPageElements.BottomBasketItems);

        var basketItems = basketLocation.ToLower() == "top" ? topBasketItems : bottomBasketItems;

        By selector = basketLocation.ToLower() == "top" ?
           CommonPageElements.TopBasketItems :
           CommonPageElements.BottomBasketItems;

        var test = _driver.WaitToBeInvisible(selector.FindElements(CommonPageElements.TopBasketItems).Text.Contains("Vouchers by post"), 5);
        return test.All(b => b.Text != "Vouchers by post");
    }
</code>```

答:
After knowing the position of your item (By), create a method that will try to wait for your element to appear for 0 seconds (Instant check if there is any element on the page), like so:

```<code>public bool isElementVisible(By locator)
{
    try
    {
        new WebDriverWait(driver, TimeSpan.FromSeconds(0)).Until(ExpectedConditions.ElementExists(locator));
        try
        {
            new WebDriverWait(driver, TimeSpan.FromSeconds(0)).Until(ExpectedConditions.ElementIsVisible(locator));
        }
        catch (WebDriverTimeoutException)
        {
            //Element exists but is not visible, return false or do other stuff
            return false
        }
    }
    catch (WebDriverTimeoutException)
    {
        //Element does not exist, return false or do other stuff
        return false;
    }
    //If code reaches this point, element both exists and is visible
    return true;
}
</code>```

You can adjust the TimeSpan seconds or minutes to wait for the element to appear for as long as you like. You can probably make an overload that will take the timeout as a parameter and the "default" function that has no timeout, will call itself with timeout 0.

After all that, you can add some lines of code to the bottom of the function that checks the text of the element and will return if its the one that you want. Returning the appropriate values.

Body:
I want to be able to wait for an element to be visible where the text = 'Vouchers by post'. However when I try the below, I am recieving a

cannot assign void as an implicit variable and cannot convert from OpenQA.Seleinium.By to OpenQA.Seleinium.ISearchContent.

What do i need to do to fix the below:

       public bool CheckBasketHolidayVoucherTextIsNotPresent(string basketLocation)
    {
        var topBasketItems = _driver.FindElements(CommonPageElements.TopBasketItems);
        var bottomBasketItems = _driver.FindElements(CommonPageElements.BottomBasketItems);

        var basketItems = basketLocation.ToLower() == "top" ? topBasketItems : bottomBasketItems;

        By selector = basketLocation.ToLower() == "top" ?
           CommonPageElements.TopBasketItems :
           CommonPageElements.BottomBasketItems;

        var test = _driver.WaitToBeInvisible(selector.FindElements(CommonPageElements.TopBasketItems).Text.Contains("Vouchers by post"), 5);
        return test.All(b => b.Text != "Vouchers by post");
    }

Body:
After knowing the position of your item (By), create a method that will try to wait for your element to appear for 0 seconds (Instant check if there is any element on the page), like so:

public bool isElementVisible(By locator)
{
    try
    {
        new WebDriverWait(driver, TimeSpan.FromSeconds(0)).Until(ExpectedConditions.ElementExists(locator));
        try
        {
            new WebDriverWait(driver, TimeSpan.FromSeconds(0)).Until(ExpectedConditions.ElementIsVisible(locator));
        }
        catch (WebDriverTimeoutException)
        {
            //Element exists but is not visible, return false or do other stuff
            return false
        }
    }
    catch (WebDriverTimeoutException)
    {
        //Element does not exist, return false or do other stuff
        return false;
    }
    //If code reaches this point, element both exists and is visible
    return true;
}

You can adjust the TimeSpan seconds or minutes to wait for the element to appear for as long as you like. You can probably make an overload that will take the timeout as a parameter and the "default" function that has no timeout, will call itself with timeout 0.

After all that, you can add some lines of code to the bottom of the function that checks the text of the element and will return if its the one that you want. Returning the appropriate values.


问:
Configure logging programmatically in Scala/Play
The Play framework requires (by default) that you configure logging through a logback.xml file. I'd like to build my log appenders through code so I can fetch parameters at runtime (e.g. the graylog destination for the logs is fetched from the deployment environment, rather than baking it in statically through an XML file). </p>

<p>This sort of thing is fairly easy to achieve in Java (by overriding logging factories and the like), I wondered if the same were possible in Play. </p>

答:
The solution I used in the end was to use a logback contextlistener to populate the context with the parameters pulled from the environment. The listener can be added as follows to the logback.xml:

```<code><contextListener class="LoggerStartup"/>
</code>```

The LoggerStartup can then populate the context, which I achieved through AWS SSM (see the simplified code below).

```<code>class LoggerStartup extends ContextAwareBase with LoggerContextListener with LifeCycle {
    override def start() = {
      val context = getContext()
      val graylogUrl = ... // Go get value from remote store
      context.putProperty("GRAYLOG_URL", graylogUrl)
    }
}
</code>```

And then referenced this context variable in the logback file:

```<code><appender name="GELF UDP APPENDER" class="me.moocar.logbackgelf.GelfUDPAppender">
  <remoteHost>${GRAYLOG_URL}</remoteHost>
  ...
</appender>
</code>```

Body:
The Play framework requires (by default) that you configure logging through a logback.xml file. I'd like to build my log appenders through code so I can fetch parameters at runtime (e.g. the graylog destination for the logs is fetched from the deployment environment, rather than baking it in statically through an XML file).

This sort of thing is fairly easy to achieve in Java (by overriding logging factories and the like), I wondered if the same were possible in Play.

Body:
The solution I used in the end was to use a logback contextlistener to populate the context with the parameters pulled from the environment. The listener can be added as follows to the logback.xml:

<contextListener class="LoggerStartup"/>

The LoggerStartup can then populate the context, which I achieved through AWS SSM (see the simplified code below).

class LoggerStartup extends ContextAwareBase with LoggerContextListener with LifeCycle {
    override def start() = {
      val context = getContext()
      val graylogUrl = ... // Go get value from remote store
      context.putProperty("GRAYLOG_URL", graylogUrl)
    }
}

And then referenced this context variable in the logback file:

<appender name="GELF UDP APPENDER" class="me.moocar.logbackgelf.GelfUDPAppender">
  <remoteHost>${GRAYLOG_URL}</remoteHost>
  ...
</appender>


问:
Prepared Statement doesn't exist
Currently running a simple sinatra app, using passenger, and using pgbouncer for connection pooling to a database on the same server as the app.  Currently I am intermittently getting a PG error that the prepared statement "a\d" doesn't exist.

```
A PG::Error occurred in #:
ERROR: prepared statement "a2" does not exist
```

the ruby code that is executed before the error

```
def self.get_ownership_record(id, key)
  self.where("user_id=? AND key=?", id, key ).first
end
```

pgbouncer config

```
; #########################################################
; ############# SECTION HEADER [DATABASES] ################
; #########################################################

[databases]

fakedatabase=fake

[pgbouncer]

; ----- Generic Settings --------------------------
; -------------------------------------------------
logfile=/opt/local/var/log/pgbouncer/pgbouncer.log
pidfile=/opt/local/var/run/pgbouncer/pgbouncer.pid
listen_addr=*
listen_port=5444

; unix_socket_dir=/tmp
user=_webuser
auth_file=/Users/Shared/data/global/pg_auth
auth_type=trust
pool_mode=transaction
; max_client_conn=100
; default_pool_size=20
; reserve_pool_size=0
; reserve_pool_timeout=5
; server_round_robin=0

; ----- Log Settings ------------------------------
; -------------------------------------------------
; syslog=0
; syslog_ident=pgbouncer
; syslog_facility=daemon
; log_connections=1
; log_disconnections=1
; log_pooler_errors=1

; ----- Console Access Control --------------------
; -------------------------------------------------
admin_users=admin,nagios
; -------------------------------------------------
; server_reset_query=DISCARD ALL;
 server_check_delay=0
 server_check_query=SELECT 1;
; server_lifetime=3600
; server_idle_timeout=600
; server_connect_timeout=600
; server_login_retry=15
```

Is my only solution, to turn off prepared statements?

database.yml

```
production:
  adapter: postgresql
  database: fakedatabase
  username: admin
  host: localhost
  port: 5444
  reconnect: true
  prepared_statements: false
```

EDIT

I have updated the pgbouncer.ini to use session pooling

pool_mode=session

and uncommented

server_reset_query=DISCARD ALL;

and I am still seemingly, randomly getting errors involving prepared statements, but this time

```
An ActiveRecord::StatementInvalid occurred in #:

PG::Error: ERROR: bind message supplies 2 parameters, but prepared statement "a1" requires 0
```

I have turned on statement level logging in my postgresql logs and will report back with more details if possible.

答:
In my case access to postgres directory and run "DEALLOCATE ALL" resolve the problem.

If you use heroku, like this

```<code>> heroku pg:psql -a app_name
app_name::DATABASE=> DEALLOCATE ALL
</code>```

Title: Prepared Statement doesn't exist

Body:
Currently running a simple sinatra app, using passenger, and using pgbouncer for connection pooling to a database on the same server as the app.  Currently I am intermittently getting a PG error that the prepared statement "a\d" doesn't exist.

A PG::Error occurred in #:
ERROR: prepared statement "a2" does not exist

the ruby code that is executed before the error

def self.get_ownership_record(id, key)
  self.where("user_id=? AND key=?", id, key ).first
end

pgbouncer config

; #########################################################
; ############# SECTION HEADER [DATABASES] ################
; #########################################################

[databases]

fakedatabase=fake

[pgbouncer]

; ----- Generic Settings --------------------------
; -------------------------------------------------
logfile=/opt/local/var/log/pgbouncer/pgbouncer.log
pidfile=/opt/local/var/run/pgbouncer/pgbouncer.pid
listen_addr=*
listen_port=5444

; unix_socket_dir=/tmp
user=_webuser
auth_file=/Users/Shared/data/global/pg_auth
auth_type=trust
pool_mode=transaction
; max_client_conn=100
; default_pool_size=20
; reserve_pool_size=0
; reserve_pool_timeout=5
; server_round_robin=0

; ----- Log Settings ------------------------------
; -------------------------------------------------
; syslog=0
; syslog_ident=pgbouncer
; syslog_facility=daemon
; log_connections=1
; log_disconnections=1
; log_pooler_errors=1

; ----- Console Access Control --------------------
; -------------------------------------------------
admin_users=admin,nagios
; -------------------------------------------------
; server_reset_query=DISCARD ALL;
 server_check_delay=0
 server_check_query=SELECT 1;
; server_lifetime=3600
; server_idle_timeout=600
; server_connect_timeout=600
; server_login_retry=15

Is my only solution, to turn off prepared statements?

database.yml

production:
  adapter: postgresql
  database: fakedatabase
  username: admin
  host: localhost
  port: 5444
  reconnect: true
  prepared_statements: false

EDIT

I have updated the pgbouncer.ini to use session pooling

pool_mode=session

and uncommented

server_reset_query=DISCARD ALL;

and I am still seemingly, randomly getting errors involving prepared statements, but this time

An ActiveRecord::StatementInvalid occurred in #:

PG::Error: ERROR: bind message supplies 2 parameters, but prepared statement "a1" requires 0

I have turned on statement level logging in my postgresql logs and will report back with more details if possible.

Body:
In my case access to postgres directory and run "DEALLOCATE ALL" resolve the problem.

If you use heroku, like this

> heroku pg:psql -a app_name
app_name::DATABASE=> DEALLOCATE ALL


问:
Web scraping and python data types
Web Scraping script using BeautifulSoup4 and Python 3.0
I want to remove the $ sign (in result) from price value, make it of type float and perform some numeric operation on it. But it is in text. </p>

```<code>import requests
from bs4 import BeautifulSoup

def bitcoin_scheduler():
    url = "https://coinmarketcap.com/currencies/bitcoin/"
    r = requests.get(url)
    offline_data = r.content
    soup = BeautifulSoup(offline_data, 'html.parser')

    name_box = soup.find('small', attrs={'class': 'bold hidden-xs'})
    name = name_box.text.strip()

    price_box = soup.find('span', attrs={'class': 'text-large'})
    price = price_box.text.strip()

    print(time.ctime(), name, price)
    threading.Timer(5.0, bitcoin_scheduler).start()

bitcoin_scheduler()
</code>```

<p>Result: </p>

```<code>Wed Nov 15 16:37:20 2017 (BTC) $6962.29
Wed Nov 15 16:37:25 2017 (BTC) $6962.29
Wed Nov 15 16:37:31 2017 (BTC) $6962.29
Wed Nov 15 16:37:36 2017 (BTC) $6962.29
</code>```

答:
Here's a simple example:

```<code>temp = "$6962.29"
temp = temp.strip("$")  # Removes $ from both sides
temp = float(temp)      # Converts to float
temp += 2               # Adding 2
print(temp)
</code>```

It should give 6264.29 as output, because we've added 2 to the number.

Title: Web scraping and python data types

Body:
Web Scraping script using BeautifulSoup4 and Python 3.0
I want to remove the $ sign (in result) from price value, make it of type float and perform some numeric operation on it. But it is in text.

import requests
from bs4 import BeautifulSoup

def bitcoin_scheduler():
    url = "https://coinmarketcap.com/currencies/bitcoin/"
    r = requests.get(url)
    offline_data = r.content
    soup = BeautifulSoup(offline_data, 'html.parser')

    name_box = soup.find('small', attrs={'class': 'bold hidden-xs'})
    name = name_box.text.strip()

    price_box = soup.find('span', attrs={'class': 'text-large'})
    price = price_box.text.strip()

    print(time.ctime(), name, price)
    threading.Timer(5.0, bitcoin_scheduler).start()

bitcoin_scheduler()

Result:

Wed Nov 15 16:37:20 2017 (BTC) $6962.29
Wed Nov 15 16:37:25 2017 (BTC) $6962.29
Wed Nov 15 16:37:31 2017 (BTC) $6962.29
Wed Nov 15 16:37:36 2017 (BTC) $6962.29

Body:
Here's a simple example:

temp = "$6962.29"
temp = temp.strip("$")  # Removes $ from both sides
temp = float(temp)      # Converts to float
temp += 2               # Adding 2
print(temp)

It should give 6264.29 as output, because we've added 2 to the number.


问:
C++ Enum equivalent in Kotlin
The problem I am trying to solve:

I have a list of elements. The list can be large and there can be many of them. I would like to access them by index. For those indexes I would like to use words instead of numbers. I would also like this words to be strongly typed, so I cannot mix numbers with them.

I believe Kotlin enum is not good for this, since every enumeration is an object instance itself. I can use Int constants, but then I lose the type safety.

In c++ this problem is solved by an Enum. Enumerations can be casted to their underlying type (in compile time) to be used as indexes. At the same type the Enum is a type and if a function takes it as a parameter, the compiler won't allow passing integers in. The enumerations themselves are not objects themselves, so you can have as many as you like without any performance hit.

C++ code example to show what I am looking for:

```<code>string someArray[] = {"element 0", "element 1"};

enum class Index
{
    first = 0,
    second = 1,
};

string getElement(Index i)
{
    return someArray[(int)i];
}

void foo()
{
    auto element0 = getElement(Index::first);
    auto element1 = getElement(1);  // compile time error - parameter type mismatch
}
</code>```

答:
How about defining an enum and also an extension to index lists of the desired type with the enum elements? This way, you can limit the indexing capabilities only to lists of Foo if you need it. Otherwise, make the extension generic.

```<code>enum class Index { FIRST, SECOND }
operator fun List<Foo>.get(index: Index) = get(index.ordinal)

// Usage:
val foo = listOfFoo[Index.FIRST]
</code>```

Use import com.example.Index.* to reference the elements it as just FIRST and SECOND.

Or define a non-operator function that does not get confused with the operator:

```<code>fun List<Foo>.getElement(index: Index) = get(index.ordinal)

// Usage:
val foo = listOfFoo.getElement(Index.FIRST)
</code>```

However, I don't think there's currently a solution that would allow you to both have pseudonyms for integers that are typed differently, and avoid having the instances for them at runtime (well, maybe a custom source transformation at compile time would). The concept that is closest to allowing this is value types, but it is currently supported by neither JVM nor Kotlin.

Title: C++ Enum equivalent in Kotlin

Body:
The problem I am trying to solve:

I have a list of elements. The list can be large and there can be many of them. I would like to access them by index. For those indexes I would like to use words instead of numbers. I would also like this words to be strongly typed, so I cannot mix numbers with them.

I believe Kotlin enum is not good for this, since every enumeration is an object instance itself. I can use Int constants, but then I lose the type safety.

In c++ this problem is solved by an Enum. Enumerations can be casted to their underlying type (in compile time) to be used as indexes. At the same type the Enum is a type and if a function takes it as a parameter, the compiler won't allow passing integers in. The enumerations themselves are not objects themselves, so you can have as many as you like without any performance hit.

C++ code example to show what I am looking for:

string someArray[] = {"element 0", "element 1"};

enum class Index
{
    first = 0,
    second = 1,
};

string getElement(Index i)
{
    return someArray[(int)i];
}

void foo()
{
    auto element0 = getElement(Index::first);
    auto element1 = getElement(1);  // compile time error - parameter type mismatch
}

Body:
How about defining an enum and also an extension to index lists of the desired type with the enum elements? This way, you can limit the indexing capabilities only to lists of Foo if you need it. Otherwise, make the extension generic.

enum class Index { FIRST, SECOND }
operator fun List<Foo>.get(index: Index) = get(index.ordinal)

// Usage:
val foo = listOfFoo[Index.FIRST]

Use import com.example.Index.* to reference the elements it as just FIRST and SECOND.

Or define a non-operator function that does not get confused with the operator:

fun List<Foo>.getElement(index: Index) = get(index.ordinal)

// Usage:
val foo = listOfFoo.getElement(Index.FIRST)

However, I don't think there's currently a solution that would allow you to both have pseudonyms for integers that are typed differently, and avoid having the instances for them at runtime (well, maybe a custom source transformation at compile time would). The concept that is closest to allowing this is value types, but it is currently supported by neither JVM nor Kotlin.


问:
IntelliJ custom language plugin - Language ID is already registered error
I am building a custom Javascript-Like custom language plugin. This custom language will be based on Ecmascript 6/Javascript. I want to add extra custom tags and keywords on top of Javascript. Most importantly, I want to make my code syntax highlighting look the same as Javascript together with auto-complete etc. I tested syntax highlighting with the Java Language and it worked.

Inside my MyScriptLanguage.java file I added this constructor and highlighting worked after debugging my plugin:

protected MyScriptLanguage() {
        super(JavaLanguage.INSTANCE, "MyScript", "text/ms", "application/ms");
}

Then I switched to the Javascript Language like this:

protected MyScriptLanguage() {
        super(JavascriptLanguage.INSTANCE, "MyScript", "text/ms", "application/ms");
    }

After switching on to Javascript debug stopped working with some language conflict errors (Language with ID 'JavaScript' is already registered: class com.intellij.lang.javascript.JavascriptLanguage) below:

```<code> 2017-11-14 08:57:56,531 [  12556]  ERROR - llij.ide.plugins.PluginManager - com.intellij.ide.plugins.PluginManager$StartupAbortedException: Fatal error initializing plugin com.ndoubismarck.mytest
java.lang.RuntimeException: com.intellij.ide.plugins.PluginManager$StartupAbortedException: Fatal error initializing plugin com.ndoubismarck.mytest
    at com.intellij.idea.IdeaApplication.run(IdeaApplication.java:210)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.idea.MainImpl$1$1.a(MainImpl.java:64)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:345)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: com.intellij.ide.plugins.PluginManager$StartupAbortedException: Fatal error initializing plugin com.ndoubismarck.mytest
    at com.intellij.ide.plugins.PluginManager.handleComponentError(PluginManager.java:272)
    at com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl.initStandardFileTypes(FileTypeManagerImpl.java:310)
    at com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl.<init>(FileTypeManagerImpl.java:267)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.picocontainer.defaults.InstantiatingComponentAdapter.newInstance(InstantiatingComponentAdapter.java:193)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.doGetComponentInstance(CachingConstructorInjectionComponentAdapter.java:103)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.instantiateGuarded(CachingConstructorInjectionComponentAdapter.java:80)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.getComponentInstance(CachingConstructorInjectionComponentAdapter.java:63)
    at com.intellij.openapi.components.impl.ComponentManagerImpl$ComponentConfigComponentAdapter.getComponentInstance(ComponentManagerImpl.java:469)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.createComponents(ComponentManagerImpl.java:118)
    at com.intellij.openapi.application.impl.ApplicationImpl.a(ApplicationImpl.java:462)
    at com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:170)
    at com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:548)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:493)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:94)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:157)
    at com.intellij.openapi.application.impl.ApplicationImpl.createComponents(ApplicationImpl.java:469)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:102)
    at com.intellij.openapi.application.impl.ApplicationImpl.load(ApplicationImpl.java:421)
    at com.intellij.openapi.application.impl.ApplicationImpl.load(ApplicationImpl.java:407)
    at com.intellij.idea.IdeaApplication.run(IdeaApplication.java:203)
    ... 20 more
Caused by: com.intellij.diagnostic.PluginException:  [Plugin: com.ndoubismarck.mytest]
    ... 44 more
Caused by: java.lang.ExceptionInInitializerError
    at com.ndoubismarck.mytest.lang.myscript.MyScriptLanguage.<init>(MyScriptLanguage.java:12)
    at com.ndoubismarck.mytest.lang.myscript.MyScriptLanguage.<clinit>(MyScriptLanguage.java:7)
    at com.ndoubismarck.mytest.lang.myscript.MyScriptFileType.<init>(MyScriptFileType.java:12)
    at com.ndoubismarck.mytest.lang.myscript.MyScriptFileType.<clinit>(MyScriptFileType.java:9)
    at com.ndoubismarck.mytest.lang.myscript.MyScriptFileTypeFactory.createFileTypes(MyScriptFileTypeFactory.java:10)
    at com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl.initStandardFileTypes(FileTypeManagerImpl.java:307)
    ... 42 more
Caused by: com.intellij.diagnostic.ImplementationConflictException: Language with ID 'JavaScript' is already registered: class com.intellij.lang.javascript.JavascriptLanguage
    at com.intellij.lang.Language.<init>(Language.java:89)
    at com.intellij.lang.Language.<init>(Language.java:73)
    at com.intellij.lang.javascript.JavascriptLanguage.<init>(JavascriptLanguage.java:26)
    at com.intellij.lang.javascript.JavascriptLanguage.<clinit>(JavascriptLanguage.java:23)
    ... 48 more
2017-11-14 08:57:56,538 [  12563]  ERROR - llij.ide.plugins.PluginManager - IntelliJ IDEA 2017.2.5  Build #IU-172.4343.14
2017-11-14 08:57:56,538 [  12563]  ERROR - llij.ide.plugins.PluginManager - JDK: 1.8.0_111
2017-11-14 08:57:56,538 [  12563]  ERROR - llij.ide.plugins.PluginManager - VM: Java HotSpot(TM) 64-Bit Server VM
2017-11-14 08:57:56,539 [  12564]  ERROR - llij.ide.plugins.PluginManager - Vendor: Oracle Corporation
2017-11-14 08:57:56,539 [  12564]  ERROR - llij.ide.plugins.PluginManager - OS: Mac OS X
</code>```

1. plugin.xml

```<code><idea-plugin>
    <id>com.ndoubismarck.mytest</id>
    <name>My Custom Language</name>
    <version>1.0</version>
    <vendor email="support@yourcompany.com" url="http://www.yourcompany.com">YourCompany</vendor>

    <description><![CDATA[
      My custom language which is extending Javascript, HTML and CSS.<br>
      <em>Javascript, HTML, CSS</em>
    ]]></description>

    <change-notes><![CDATA[
      <br>
      <em></em>
    ]]>
    </change-notes>

    <!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/build_number_ranges.html for description -->
    <idea-version since-build="145.0"/>

    <!-- please see http://www.jetbrains.org/intellij/sdk/docs/basics/getting_started/plugin_compatibility.html
         on how to target different products -->
    <!-- uncomment to enable plugin in all products
    <depends>com.intellij.modules.lang</depends>
    -->

    <extensions defaultExtensionNs="com.intellij">
        <!-- Add your extensions here -->
        <fileTypeFactory implementation="com.ndoubismarck.mytest.lang.myscript.MyScriptFileTypeFactory"/>
    </extensions>

    <actions>
        <!-- Add your actions here -->
    </actions>

</idea-plugin>
</code>```

2. MyScriptFileTypeFactory.java

```<code>package com.ndoubismarck.mytest.lang.myscript;

import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;
import org.jetbrains.annotations.NotNull;

public class MyScriptFileTypeFactory extends FileTypeFactory {
    @Override
    public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
        fileTypeConsumer.consume(MyScriptFileType.INSTANCE, "ms");
    }
}
</code>```

3. MyScriptFileType.java

```<code>package com.ndoubismarck.mytest.lang.myscript;

import com.intellij.lang.Language;
import com.intellij.lang.javascript.JavascriptLanguage;

public class MyScriptLanguage extends Language {
public static final MyScriptLanguage INSTANCE = new MyScriptLanguage();

protected MyScriptLanguage() {
    //super(JavaLanguage.INSTANCE, "MyScript", "text/ms", "application/ms");
    super(JavascriptLanguage.INSTANCE, "MyScript", "text/ms", "application/ms");
}

@Override
public String getDisplayName() {
    return "MyScript language";
}
}
</code>```

Can someone help me out. I just need to extend the Javascript highlighting and Autocomplete functions on top of my own custom ones.

答:
This may be happening due to missing dependency on JavaScript plugin in your plugin.xml.
Please try adding

<depends>JavaScript</depends>

after vendor tag

Body:
I am building a custom Javascript-Like custom language plugin. This custom language will be based on Ecmascript 6/Javascript. I want to add extra custom tags and keywords on top of Javascript. Most importantly, I want to make my code syntax highlighting look the same as Javascript together with auto-complete etc. I tested syntax highlighting with the Java Language and it worked.

Inside my MyScriptLanguage.java file I added this constructor and highlighting worked after debugging my plugin:

protected MyScriptLanguage() {
        super(JavaLanguage.INSTANCE, "MyScript", "text/ms", "application/ms");
}

Then I switched to the Javascript Language like this:

protected MyScriptLanguage() {
        super(JavascriptLanguage.INSTANCE, "MyScript", "text/ms", "application/ms");
    }

After switching on to Javascript debug stopped working with some language conflict errors (Language with ID 'JavaScript' is already registered: class com.intellij.lang.javascript.JavascriptLanguage) below:

 2017-11-14 08:57:56,531 [  12556]  ERROR - llij.ide.plugins.PluginManager - com.intellij.ide.plugins.PluginManager$StartupAbortedException: Fatal error initializing plugin com.ndoubismarck.mytest
java.lang.RuntimeException: com.intellij.ide.plugins.PluginManager$StartupAbortedException: Fatal error initializing plugin com.ndoubismarck.mytest
    at com.intellij.idea.IdeaApplication.run(IdeaApplication.java:210)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.idea.MainImpl$1$1.a(MainImpl.java:64)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.awt.EventQueue$3.run(EventQueue.java:703)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:345)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: com.intellij.ide.plugins.PluginManager$StartupAbortedException: Fatal error initializing plugin com.ndoubismarck.mytest
    at com.intellij.ide.plugins.PluginManager.handleComponentError(PluginManager.java:272)
    at com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl.initStandardFileTypes(FileTypeManagerImpl.java:310)
    at com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl.<init>(FileTypeManagerImpl.java:267)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.picocontainer.defaults.InstantiatingComponentAdapter.newInstance(InstantiatingComponentAdapter.java:193)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.doGetComponentInstance(CachingConstructorInjectionComponentAdapter.java:103)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.instantiateGuarded(CachingConstructorInjectionComponentAdapter.java:80)
    at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.getComponentInstance(CachingConstructorInjectionComponentAdapter.java:63)
    at com.intellij.openapi.components.impl.ComponentManagerImpl$ComponentConfigComponentAdapter.getComponentInstance(ComponentManagerImpl.java:469)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.createComponents(ComponentManagerImpl.java:118)
    at com.intellij.openapi.application.impl.ApplicationImpl.a(ApplicationImpl.java:462)
    at com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:170)
    at com.intellij.openapi.progress.impl.CoreProgressManager.a(CoreProgressManager.java:548)
    at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:493)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:94)
    at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:157)
    at com.intellij.openapi.application.impl.ApplicationImpl.createComponents(ApplicationImpl.java:469)
    at com.intellij.openapi.components.impl.ComponentManagerImpl.init(ComponentManagerImpl.java:102)
    at com.intellij.openapi.application.impl.ApplicationImpl.load(ApplicationImpl.java:421)
    at com.intellij.openapi.application.impl.ApplicationImpl.load(ApplicationImpl.java:407)
    at com.intellij.idea.IdeaApplication.run(IdeaApplication.java:203)
    ... 20 more
Caused by: com.intellij.diagnostic.PluginException:  [Plugin: com.ndoubismarck.mytest]
    ... 44 more
Caused by: java.lang.ExceptionInInitializerError
    at com.ndoubismarck.mytest.lang.myscript.MyScriptLanguage.<init>(MyScriptLanguage.java:12)
    at com.ndoubismarck.mytest.lang.myscript.MyScriptLanguage.<clinit>(MyScriptLanguage.java:7)
    at com.ndoubismarck.mytest.lang.myscript.MyScriptFileType.<init>(MyScriptFileType.java:12)
    at com.ndoubismarck.mytest.lang.myscript.MyScriptFileType.<clinit>(MyScriptFileType.java:9)
    at com.ndoubismarck.mytest.lang.myscript.MyScriptFileTypeFactory.createFileTypes(MyScriptFileTypeFactory.java:10)
    at com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl.initStandardFileTypes(FileTypeManagerImpl.java:307)
    ... 42 more
Caused by: com.intellij.diagnostic.ImplementationConflictException: Language with ID 'JavaScript' is already registered: class com.intellij.lang.javascript.JavascriptLanguage
    at com.intellij.lang.Language.<init>(Language.java:89)
    at com.intellij.lang.Language.<init>(Language.java:73)
    at com.intellij.lang.javascript.JavascriptLanguage.<init>(JavascriptLanguage.java:26)
    at com.intellij.lang.javascript.JavascriptLanguage.<clinit>(JavascriptLanguage.java:23)
    ... 48 more
2017-11-14 08:57:56,538 [  12563]  ERROR - llij.ide.plugins.PluginManager - IntelliJ IDEA 2017.2.5  Build #IU-172.4343.14
2017-11-14 08:57:56,538 [  12563]  ERROR - llij.ide.plugins.PluginManager - JDK: 1.8.0_111
2017-11-14 08:57:56,538 [  12563]  ERROR - llij.ide.plugins.PluginManager - VM: Java HotSpot(TM) 64-Bit Server VM
2017-11-14 08:57:56,539 [  12564]  ERROR - llij.ide.plugins.PluginManager - Vendor: Oracle Corporation
2017-11-14 08:57:56,539 [  12564]  ERROR - llij.ide.plugins.PluginManager - OS: Mac OS X

1. plugin.xml

<idea-plugin>
    <id>com.ndoubismarck.mytest</id>
    <name>My Custom Language</name>
    <version>1.0</version>
    <vendor email="support@yourcompany.com" url="http://www.yourcompany.com">YourCompany</vendor>

    <description><![CDATA[
      My custom language which is extending Javascript, HTML and CSS.

      Javascript, HTML, CSS
    ]]></description>

    <change-notes><![CDATA[

    ]]>
    </change-notes>

    <idea-version since-build="145.0"/>

    <extensions defaultExtensionNs="com.intellij">

        <fileTypeFactory implementation="com.ndoubismarck.mytest.lang.myscript.MyScriptFileTypeFactory"/>
    </extensions>

    <actions>

    </actions>

</idea-plugin>

2. MyScriptFileTypeFactory.java

package com.ndoubismarck.mytest.lang.myscript;

import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;
import org.jetbrains.annotations.NotNull;

public class MyScriptFileTypeFactory extends FileTypeFactory {
    @Override
    public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
        fileTypeConsumer.consume(MyScriptFileType.INSTANCE, "ms");
    }
}

3. MyScriptFileType.java

package com.ndoubismarck.mytest.lang.myscript;

import com.intellij.lang.Language;
import com.intellij.lang.javascript.JavascriptLanguage;

public class MyScriptLanguage extends Language {
public static final MyScriptLanguage INSTANCE = new MyScriptLanguage();

protected MyScriptLanguage() {
    //super(JavaLanguage.INSTANCE, "MyScript", "text/ms", "application/ms");
    super(JavascriptLanguage.INSTANCE, "MyScript", "text/ms", "application/ms");
}

@Override
public String getDisplayName() {
    return "MyScript language";
}
}

Can someone help me out. I just need to extend the Javascript highlighting and Autocomplete functions on top of my own custom ones.


问:
search and convert Uppercase to small case and inserting ''-'' in javascript
thanks in advance,
I have a string as "fileName = 'CampaignDetail'" .I want to make it 'campaign-detail'.That is converting all the upper case letters to small and insert hyphen wherever in between it is capital letter.how can I do it with for loop. </p>

答:
Check this approach using split and reduce

```<code>"CampaignDetail".split(/(?:([A-Z]))/).reduce( (a,b,i) => i == 1 || i % 2 == 0 ? a + b : a + "-" + b ).toLowerCase() //campaign-detail
</code>```

Demo

function toHypenCase( input )
{
  return input.split(/(?:([A-Z]))/).reduce( (a,b,i) => i == 1 || i % 2 == 0 ? a + b : a + "-" + b ).toLowerCase();
}

console.log( toHypenCase( "CampaignDetail" ) );```

Body:
Check this approach using split and reduce

"CampaignDetail".split(/(?:([A-Z]))/).reduce( (a,b,i) => i == 1 || i % 2 == 0 ? a + b : a + "-" + b ).toLowerCase() //campaign-detail

Demo

function toHypenCase( input )
{
  return input.split(/(?:([A-Z]))/).reduce( (a,b,i) => i == 1 || i % 2 == 0 ? a + b : a + "-" + b ).toLowerCase();
}

console.log( toHypenCase( "CampaignDetail" ) );


问:
Using jQuery in CRM Dynamics 365 webresource in popup-window
In my CRM Dynamics 365 solution I have a form with an embedded webresource A. This webresource A opens another webresource B in a popup-window using window.open. The opening could of course also be done using  Xrm.Utility.openWebResource.

I would like to utilize jQuery in webresource B. I am aware that CRM itself loads jQuery in some version, which is easy to spot when monitoring network requests and filtering for jquery.

The problem is that the webresource B doesn't have "access" to the jQuery or $-variable. The question is what you would recommend to do in order to use jQuery. I've prioritized a list of some possible solutions:

Load a webresource with an independent version of jQuery

An option I haven't thought of

Load it from a CDN

Look for all loaded scripts with jQuery and pass the URL to webresource B so it can load it by itself (almost a hack)

Avoid jQuery, use vanilla JS

UPDATE:
The main reason for using jQuery was to easily resize an iframe (with random contents) embedded in popup-window which displayed webresource B according to the dimensions of the popup-window.

I decided to lose jQuery altogether and use CSS instead. My solution became this which work nicely in Google Chrome, Windows Edge and Internet Explorer 11:

```<code>#externalframe {
    width: 100%;
    height: 100%;
    display: block;
    float: left;
}
</code>```

答: If you can access jsquery in webresourceA then it means that the jquery already exists (as a webresource) in CRM. Find the url(path) of jquery and add it as a reference to the webresourceB and that's it.

Body:
In my CRM Dynamics 365 solution I have a form with an embedded webresource A. This webresource A opens another webresource B in a popup-window using window.open. The opening could of course also be done using  Xrm.Utility.openWebResource.

I would like to utilize jQuery in webresource B. I am aware that CRM itself loads jQuery in some version, which is easy to spot when monitoring network requests and filtering for jquery.

The problem is that the webresource B doesn't have "access" to the jQuery or $-variable. The question is what you would recommend to do in order to use jQuery. I've prioritized a list of some possible solutions:

Load a webresource with an independent version of jQuery

An option I haven't thought of

Load it from a CDN

Look for all loaded scripts with jQuery and pass the URL to webresource B so it can load it by itself (almost a hack)

Avoid jQuery, use vanilla JS

UPDATE:
The main reason for using jQuery was to easily resize an iframe (with random contents) embedded in popup-window which displayed webresource B according to the dimensions of the popup-window.

I decided to lose jQuery altogether and use CSS instead. My solution became this which work nicely in Google Chrome, Windows Edge and Internet Explorer 11:

#externalframe {
    width: 100%;
    height: 100%;
    display: block;
    float: left;
}


问:
I can not see the app as I would like it
I'm doing this exercise with the fragments .. how do i see from the code i have developed .. i have my two classes fragment1 and fragment2, in the java / layout folder. There are then the two .xml files of the interfaces .. what is difficult now is to understand why this does not work properly .. what I have to get is: the screen must show two parts one with the script "This is the fragment 1" and on the other side "This is the fragment 2" ... but this is not visible I even attach the screens .. if you have time and patience, look up your news .. thanks and good day :)
fragment1.java

```<code>    package layout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.test.testfragment.R;

/**
 * A simple {@link Fragment} subclass.

 */
public class fragment1 extends Fragment {
    public fragment1(){
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment1,container,false);
    }
}
</code>```

fragment2.java

```<code>    package layout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.test.testfragment.R;

/**
 * A simple {@link Fragment} subclass.

 */
public class fragment2 extends Fragment {
    public fragment2(){
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment2, container,false);
    }
}
</code>```

fragment1.xml

```<code>    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:ignore="HardcodedText">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Questo e' il fragment 1"
        android:textSize="25sp"/>

</LinearLayout>
</code>```

fragment2.xml

```<code>    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00FF00"
    tools:ignore="HardcodedText">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Questo e' il fragment 2"
        android:textSize="25sp"/>

</LinearLayout>
</code>```

activity_main.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:baselineAligned="false"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.example.test.testfragment.MainActivity">

    <fragment
        android:id="@+id/fragment1"
        android:layout_width="0px"
        android:name="layout.fragment1"
        android:layout_height="match_parent"
        android:layout_weight="1"
        tools:layout="@layout/fragment1" />

    <fragment
        android:name="layout.fragment2"
        android:id="@+id/fragment2"
        android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent" />

</LinearLayout>
</code>```

activity_main (Design)

Error

答:
try installing the apk with adb , if it fails you will get an error message ,then you can work on that.</p>

```<code>adb install my.apk
</code>```

Body:
I'm doing this exercise with the fragments .. how do i see from the code i have developed .. i have my two classes fragment1 and fragment2, in the java / layout folder. There are then the two .xml files of the interfaces .. what is difficult now is to understand why this does not work properly .. what I have to get is: the screen must show two parts one with the script "This is the fragment 1" and on the other side "This is the fragment 2" ... but this is not visible I even attach the screens .. if you have time and patience, look up your news .. thanks and good day :)
fragment1.java

    package layout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.test.testfragment.R;

/**
 * A simple {@link Fragment} subclass.

 */
public class fragment1 extends Fragment {
    public fragment1(){
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment1,container,false);
    }
}

fragment2.java

    package layout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.test.testfragment.R;

/**
 * A simple {@link Fragment} subclass.

 */
public class fragment2 extends Fragment {
    public fragment2(){
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState){
        return inflater.inflate(R.layout.fragment2, container,false);
    }
}

fragment1.xml

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:ignore="HardcodedText">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Questo e' il fragment 1"
        android:textSize="25sp"/>

</LinearLayout>

fragment2.xml

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#00FF00"
    tools:ignore="HardcodedText">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Questo e' il fragment 2"
        android:textSize="25sp"/>

</LinearLayout>

activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:baselineAligned="false"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context="com.example.test.testfragment.MainActivity">

    <fragment
        android:id="@+id/fragment1"
        android:layout_width="0px"
        android:name="layout.fragment1"
        android:layout_height="match_parent"
        android:layout_weight="1"
        tools:layout="@layout/fragment1" />

    <fragment
        android:name="layout.fragment2"
        android:id="@+id/fragment2"
        android:layout_weight="1"
        android:layout_width="0px"
        android:layout_height="match_parent" />

</LinearLayout>

activity_main (Design)

Error

Body:
try installing the apk with adb , if it fails you will get an error message ,then you can work on that.

adb install my.apk


答:
You can do it using regular expression. Try following

let regex = /[A-Z](\s\S)*[a-z]*/g;

let name = 'CampaignDetail';

let tempData = name.match(regex);

filename = tempData.reduce((a,b) => {
    return a.toLowerCase() + '-' + b.toLowerCase();
})

console.log(filename);```

Title: search and convert Uppercase to small case and inserting ''-'' in javascript

Body:
thanks in advance,
I have a string as "fileName = 'CampaignDetail'" .I want to make it 'campaign-detail'.That is converting all the upper case letters to small and insert hyphen wherever in between it is capital letter.how can I do it with for loop.


问:
Custom DialogPreference/ListPreference
In my preferences I have a ListPreference which opens DialogPreference. Now I would like to create a simple dialog without Cancel button and title Category. I want just the list of options, which I would like to make custom too. I already looked at the source code and I'm a bit confused because do I have to write my own dialog preference class just to remove title and cancel button? Or I can just extend DialogPreference to create all the customizations? There are also some widgetLayout/dialogLayout attributes, but I don't see an option how to remove a title/cancel button from there. Or should I extend ListPreference? Any suggestions would be greatly appreciated, because I'm running out of ideas.
dialog</p>

答:
I managed to solve my problem with title and cancel button. Here is the solution:

```<code>public class PreferenceDialog extends ListPreference {

public PreferenceDialog(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
    super.onPrepareDialogBuilder(builder);    //To change body of overridden methods use File | Settings | File Templates.
    builder.setNegativeButton(null,null);
    builder.setTitle(null);
}
</code>```

}

I just had to pass null values and it worked like a charm.

ContentLicense: CC BY-SA 2.5

Title: Custom DialogPreference/ListPreference

Body:
I managed to solve my problem with title and cancel button. Here is the solution:

public class PreferenceDialog extends ListPreference {

public PreferenceDialog(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
    super.onPrepareDialogBuilder(builder);    //To change body of overridden methods use File | Settings | File Templates.
    builder.setNegativeButton(null,null);
    builder.setTitle(null);
}

}

I just had to pass null values and it worked like a charm.


答:
If your price is in the format "$100.00", then to remove the dollar symbol you can simply do:

```<code>price = price[1:]
</code>```

This would make "$100.00" into "100.00" - It strips the first character off the string.

To convert to a float:

```<code>price = float(price)
</code>```

Altogether it would simply be:

```<code>price = float(price[1:])
</code>```

It may be worth performing some error checking on top of that.

Title: Web scraping and python data types

Body:
If your price is in the format "$100.00", then to remove the dollar symbol you can simply do:

price = price[1:]

This would make "$100.00" into "100.00" - It strips the first character off the string.

To convert to a float:

price = float(price)

Altogether it would simply be:

price = float(price[1:])

It may be worth performing some error checking on top of that.


问:
How to call an external function inside a view in laravel 5.2
I want to call an external function from my blade view.

I have tried in this way,

```<code>{{ controllername::function name()}}
</code>```

But i get a response like Class 'controllername' not found.

How i can solve this?Looking for a solution.

答:
In addition to above response. Just to correct your approach.

```<code>//include the controller class in to your blade file.
<?php use App\Http\Controllers\MyController;?>

//call the controller function in php way.
<?php echo MyController::myFunction(); ?>

// Or call the controller function in blade way.
{{MyController::myFunction()}}
</code>```

We first map the controller in our blade file and call controller function from view in. We just make a static function in our controller class and calling in the static function.

Body:
I want to call an external function from my blade view.

I have tried in this way,

{{ controllername::function name()}}

But i get a response like Class 'controllername' not found.

How i can solve this?Looking for a solution.

Body:
In addition to above response. Just to correct your approach.

//include the controller class in to your blade file.
<?php use App\Http\Controllers\MyController;?>

//call the controller function in php way.
<?php echo MyController::myFunction(); ?>

// Or call the controller function in blade way.
{{MyController::myFunction()}}

We first map the controller in our blade file and call controller function from view in. We just make a static function in our controller class and calling in the static function.


问:
how to iterate a List that contains Map and get the key and value of that map
I have a list that contains a map on class type. I want to iterate that list and get the key and values of the inner map.

Here is the List :

```<code>quotationList =  quotationService.searchByIdList(accountId, Account.class);
</code>```

It contains one index i.e at 0 index it contains a map. i need to get the key and values of that map.

My attempt:

```<code>for (int i = 0; i < quotationList.size(); i++) {
            Map myMap = (Map) quotationList.get(i);
            System.out.println("Data For Map" + i);
            for (Entry<String, Object> entrySet : ((Map<String, Object>) myMap).entrySet()) {
                System.out.println("Key = " + entrySet.getKey() + " , Value = " + entrySet.getValue());
            }
        }
</code>```

答:
Java 8: if your map is Map<String, String> then

```<code>quotationList.forEach(item -> item.entrySet().forEach(entry -> {
        String key = entry.getKey();
        String value = entry.getValue();
    }));
</code>```

Body:
I have a list that contains a map on class type. I want to iterate that list and get the key and values of the inner map.

Here is the List :

quotationList =  quotationService.searchByIdList(accountId, Account.class);

It contains one index i.e at 0 index it contains a map. i need to get the key and values of that map.

My attempt:

for (int i = 0; i < quotationList.size(); i++) {
            Map myMap = (Map) quotationList.get(i);
            System.out.println("Data For Map" + i);
            for (Entry<String, Object> entrySet : ((Map<String, Object>) myMap).entrySet()) {
                System.out.println("Key = " + entrySet.getKey() + " , Value = " + entrySet.getValue());
            }
        }

Body:
Java 8: if your map is Map<String, String> then

quotationList.forEach(item -> item.entrySet().forEach(entry -> {
        String key = entry.getKey();
        String value = entry.getValue();
    }));


问:
How do I override a magento 2 theme's phtml with my own custom theme?
I'm attempting to customise the ultimo theme (although presumably this would apply to any magento theme). I have created a new custom theme which (using theme.xml) uses Infortis/ultimo as it's parent.

Ultimo has the following path for it's header.phtml

```<code>ultimo/default/template/page/html/header.phtml
</code>```

I've tried a number of different options for my theme to override this - none of which appear to work e.g.

```<code>frontend/my_theme/default/template/html/header.phtml
frontend/my_theme/default/template/page/html/header.phtml
</code>```

Does anyone have any ideas?

答:
In Your theme.xml you set the parent the as  Infortis/ultimo

```<code>  <parent>Infortis/ultimo</parent>
</code>```

just like
/Infortis/ultimo/template/page/html/header.phtml

/Custom/Theme/template/page/html/header.phtml

please clear and flush cache

and deploy and give permission

sudo php bin/magento cache:clean

sudo php bin/magento cache:flush

sudo php bin/magento setup:static-content:deploy

sudo chmod 777 -R var/ pub/media pub/static

Note: dont' forget to set Store Them As your custom created theme..

registration.php Code

```<code>\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::THEME,
'frontend/Custom/Theme',
__DIR__
</code>```

);

theme.xml

```<code><theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
<title>New Custom</title>
<parent>Infortis/ultimo</parent>
<media>
    <preview_image>media/preview.png</preview_image>
</media>
</code>```

Body:
I'm attempting to customise the ultimo theme (although presumably this would apply to any magento theme). I have created a new custom theme which (using theme.xml) uses Infortis/ultimo as it's parent.

Ultimo has the following path for it's header.phtml

ultimo/default/template/page/html/header.phtml

I've tried a number of different options for my theme to override this - none of which appear to work e.g.

frontend/my_theme/default/template/html/header.phtml
frontend/my_theme/default/template/page/html/header.phtml

Does anyone have any ideas?

Body:
In Your theme.xml you set the parent the as  Infortis/ultimo

  <parent>Infortis/ultimo</parent>

just like
/Infortis/ultimo/template/page/html/header.phtml

/Custom/Theme/template/page/html/header.phtml

please clear and flush cache

and deploy and give permission

sudo php bin/magento cache:clean

sudo php bin/magento cache:flush

sudo php bin/magento setup:static-content:deploy

sudo chmod 777 -R var/ pub/media pub/static

Note: dont' forget to set Store Them As your custom created theme..

registration.php Code

\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::THEME,
'frontend/Custom/Theme',
__DIR__

);

theme.xml

<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
<title>New Custom</title>
<parent>Infortis/ultimo</parent>
<media>
    <preview_image>media/preview.png</preview_image>
</media>


问:
HashSet<Point>: How to sort all points according to x coordinates?
can you give me a hint how to sort the points according to x coordinates in  O(nLogn)?

```<code>    Set<Point> points = new HashSet<Point>();
    points.add(new Point(9, 0));
    points.add(new Point(1, 1));
    points.add(new Point(5, 6));
    points.add(new Point(3, 3));
    points.add(new Point(2, 7));
    points.add(new Point(1, 8));
    points.add(new Point(6, 1));
</code>```

I wish I could do something like Point[] points2 = points.toArray(); and afterwards sort it. But of course it isn´t working.

答:
Any Set that implements SortedSet interface can keep elements sorted within it. TreeSet is a known implementation of SortedSet.

You can pass a custom Comparator for your class in the TreeSet constructor in order to obtain a set sorted according to your conditions.

```<code>public static void main(String[] args) {
    SortedSet<Point> points = new TreeSet<>(new Comparator<Point>() {
        @Override
        public int compare(Point o1, Point o2) {
            return o1.getX()- o2.getX();
        }
    });
    points.add(new Point(9, 0));
    points.add(new Point(1, 1));
    points.add(new Point(5, 6));
    points.add(new Point(3, 3));
    points.add(new Point(2, 7));
    points.add(new Point(1, 8));
    points.add(new Point(6, 1));
}
</code>```

If the comparator code looks verbose to you, you can try the new Java 8 style comparator declaration.

```<code>SortedSet<Point> points = new TreeSet<>(Comparator.comparing(Point::getX));
</code>```

Regarding the last point, if you want to obtain an array from the Set, you can always do that by using following:

```<code>Point[] points2 = points.toArray(new Point[0]);
</code>```

But, if your sole purpose is sorting the data, this should be avoided.

Body:
can you give me a hint how to sort the points according to x coordinates in  O(nLogn)?

    Set<Point> points = new HashSet<Point>();
    points.add(new Point(9, 0));
    points.add(new Point(1, 1));
    points.add(new Point(5, 6));
    points.add(new Point(3, 3));
    points.add(new Point(2, 7));
    points.add(new Point(1, 8));
    points.add(new Point(6, 1));

I wish I could do something like Point[] points2 = points.toArray(); and afterwards sort it. But of course it isn´t working.

Body:
Any Set that implements SortedSet interface can keep elements sorted within it. TreeSet is a known implementation of SortedSet.

You can pass a custom Comparator for your class in the TreeSet constructor in order to obtain a set sorted according to your conditions.

public static void main(String[] args) {
    SortedSet<Point> points = new TreeSet<>(new Comparator<Point>() {
        @Override
        public int compare(Point o1, Point o2) {
            return o1.getX()- o2.getX();
        }
    });
    points.add(new Point(9, 0));
    points.add(new Point(1, 1));
    points.add(new Point(5, 6));
    points.add(new Point(3, 3));
    points.add(new Point(2, 7));
    points.add(new Point(1, 8));
    points.add(new Point(6, 1));
}

If the comparator code looks verbose to you, you can try the new Java 8 style comparator declaration.

SortedSet<Point> points = new TreeSet<>(Comparator.comparing(Point::getX));

Regarding the last point, if you want to obtain an array from the Set, you can always do that by using following:

Point[] points2 = points.toArray(new Point[0]);

But, if your sole purpose is sorting the data, this should be avoided.


问:
How can reference the last item in a list in a Django template? {{ list.-1.key }}
if I have a variable in the context of unknown length, for example;

list=[{'key':'A'},{'key':'B'},{'key':'C'}]

How can I get the last object? {{ list.0.key }} works for the first, but {{ list.-1.key }} gives;

Could not parse the remainder: '-1.key' from 'list.-1.key'

答:
Use this piece of code in your template:</p>

```<code>{{ list|slice:":-1".items.0.0 }}
</code>```

Body:
Use this piece of code in your template:

{{ list|slice:":-1".items.0.0 }}


问:
Cassandra : Required RAM Space
I have a two node Cassandra (3.10) cluster. I have migrated some data. Data size is 1.4 TB according to nodetool in each node.
I tried to check RAM size required by Cassandra instance-

```<code>ps -aux | grep cassandra
</code>```

I got :

```<code>root      2510  124 80.2 1515965216 26435808 pts/0 SLl 10:36 138:10 java -Xloggc:/opt/cassandra/logs/gc.log ...... /*/*.jar org.apache.cassandra.service.CassandraDaemon
</code>```

here we can see that Cassandra is taking nearly 26.5 GB space in RAM, and I observe that this size is continuously increasing.

I want to know is it a normal behavior of Cassandra?

答:
This site gives specifications for different packages and provides hardware requirements for all the types:

https://docs.datastax.com/en/dse-planning/doc/planning/planningHardware.html#planningHardware__memory

Take a look over it and find if its in range or not. You can even reduce and keep a limit on the size of RAM its occupying.

Title: Cassandra : Required RAM Space

Body:
I have a two node Cassandra (3.10) cluster. I have migrated some data. Data size is 1.4 TB according to nodetool in each node.
I tried to check RAM size required by Cassandra instance-

ps -aux | grep cassandra

I got :

root      2510  124 80.2 1515965216 26435808 pts/0 SLl 10:36 138:10 java -Xloggc:/opt/cassandra/logs/gc.log ...... /*/*.jar org.apache.cassandra.service.CassandraDaemon

here we can see that Cassandra is taking nearly 26.5 GB space in RAM, and I observe that this size is continuously increasing.

I want to know is it a normal behavior of Cassandra?


问:
Python app with tesseract does not work on Bluemix
I have a python application which uses tesseract for detecting checkboxes in scanned images, works perfectly fine on my local machine, but when I push my code to Bluemix along with the python-tesseract buildpack it fails generating the output file which means the tesseract is not getting detected on Bluemix.

This is my manifest.yml:

applications:

  - path: .

    memory: 512M

    instances: 1

    domain: mybluemix.net

    name: edge-noise-detector-bluemix

    host: edge-noise-detector-bluemix

    disk_quota: 1024M

    buildpack: https://github.com/LeoKotschenreuther/python-tesseract-buildpack.git

This is my requirements.txt:

Flask

  numpy

  Pillow==4.1.1

  pycparser

  pyOpenSSL

  pyparsing

  pytesseract

  python-dateutil

  python-swiftclient

  pytz

  PyWavelets

  scikit-image

  scipy

  requests

  matplotlib==1.4.3

  opencv-python

  cf_deployment_tracker

  tesseract

Here is the logs from Bluemix:

```<code>Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "server.py", line 217, in predict_square_checkboxes
    ImgOcr = image_hocr_class.ocr_hocr('temporary.png')
  File "/home/vcap/app/src/image_hocr_class.py", line 39, in __init__
    self.HTMLTree = xml.etree.ElementTree.parse(self.HOCRFileName).getroot()
  File "/app/.heroku/python/lib/python3.6/xml/etree/ElementTree.py", line 1196, in parse
    tree.parse(source, parser)
  File "/app/.heroku/python/lib/python3.6/xml/etree/ElementTree.py", line 586, in parse
    source = open(source, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'images/8e297b93a39f1e08a490f72c8db53bf0.hocr'
</code>```

This normally happens when pytesseract could not locate the path of tesseract. Not sure how to get this work on Bluemix.
Does anyone got python with tesseract working on Bluemix? Please help.

答:
IBM Cloud gives you a number of possibilities to run your applications.
Cloud Foundry Runtimes is one of them, but in your situation doesn't seem a good fit. Whenever you have a dependency that you need to install you need to create your custom buildpack which can be a rather complex task. (https://docs.cloudfoundry.org/buildpacks/custom.html)
Ever heard about Docker/Kubernetes? If you have a number of application dependency (like tesseract in your case) I would suggest you to create a Kubernetes environment to build your app!
have a look at these resources: https://hub.docker.com/r/tesseractshadow/tesseract4re/
https://console.bluemix.net/docs/containers/container_index.html#container_index</p>

Body:
I have a python application which uses tesseract for detecting checkboxes in scanned images, works perfectly fine on my local machine, but when I push my code to Bluemix along with the python-tesseract buildpack it fails generating the output file which means the tesseract is not getting detected on Bluemix.

This is my manifest.yml:

applications:

  - path: .

    memory: 512M

    instances: 1

    domain: mybluemix.net

    name: edge-noise-detector-bluemix

    host: edge-noise-detector-bluemix

    disk_quota: 1024M

    buildpack: https://github.com/LeoKotschenreuther/python-tesseract-buildpack.git

This is my requirements.txt:

Flask

  numpy

  Pillow==4.1.1

  pycparser

  pyOpenSSL

  pyparsing

  pytesseract

  python-dateutil

  python-swiftclient

  pytz

  PyWavelets

  scikit-image

  scipy

  requests

  matplotlib==1.4.3

  opencv-python

  cf_deployment_tracker

  tesseract

Here is the logs from Bluemix:

Traceback (most recent call last):
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "/app/.heroku/python/lib/python3.6/site-packages/flask/app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "server.py", line 217, in predict_square_checkboxes
    ImgOcr = image_hocr_class.ocr_hocr('temporary.png')
  File "/home/vcap/app/src/image_hocr_class.py", line 39, in __init__
    self.HTMLTree = xml.etree.ElementTree.parse(self.HOCRFileName).getroot()
  File "/app/.heroku/python/lib/python3.6/xml/etree/ElementTree.py", line 1196, in parse
    tree.parse(source, parser)
  File "/app/.heroku/python/lib/python3.6/xml/etree/ElementTree.py", line 586, in parse
    source = open(source, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'images/8e297b93a39f1e08a490f72c8db53bf0.hocr'

This normally happens when pytesseract could not locate the path of tesseract. Not sure how to get this work on Bluemix.
Does anyone got python with tesseract working on Bluemix? Please help.


问:
Shuffle array key and values php
I want to randomly shuffle the keys and values of a php array. I've already found solution to shuffle the order, but I want to shuffle the keys and values themselves.

The array array('yes' => 'oui', 'no' => 'non', 'hello' => 'bonjour') would for example become array('oui' => 'yes, 'no' => 'non', 'bonjour' => 'hello'). Note that the first and last value have randomly swapped key and value.

I know you can use array_flip to flip the keys and values in an array. But this flips all keys and values, while I want to randomly flip a few keys and values. How would I do this?

答:
```<code>$array = array('yes' => 'oui', 'no' => 'non', 'hello' => 'bonjour');

// Run it in a foreach loop
foreach ($array as $key => $val){
    // rand(0, 1) will return either 0 or 1
    // It's up to you which value you want to set as anchor.
    if (rand(0, 1) === 0){
        // Set the value as key,
        // then set the key as value.
        $array[$val] = $key;

        // Delete the original one.
        unset($array[$key]);
    }
}
</code>```

Title: Shuffle array key and values php


问:
Assert multiple fields with the same path
In my SoapUI response I have a XML structure that repeats itself. For examples:

```<code>  <b:quote-data>
    <b:quote-data>
      <b:premium>4.66</b:premium>
    </b:quote-data>
    <b:quote-data>
      <b:premium>5.6</b:premium>
    </b:quote-data>
    <b:quote-data>
      <b:premium>7.58</b:premium>
    </b:quote-data>
  </b:quote-data>
</code>```

I currently have the assertion which works to assert the value in the first premium field. I don't understand how to have multiple asserts to match all three fields.

```<code>// get the xml response
def response = messageExchange.getResponseContent()
// parse it
def xml = new XmlSlurper().parseText(response)
// find your node by name
def node = xml.'**'.find { it.name() == 'premium' }
// assert
assert node.toString().matches("4.66")
</code>```

Is there a Way to skip over the first field to asset the second?

答:
Use findAll to get all 'premium' nodes and iterate over the node list:

```<code>    def nodelist = xml.'**'.findAll{ it.name() == 'premium' }
    def assertions = [4.66, 5.6, 7.58]
    def i=0
    // assert
    for (node in nodelist) assert node.toString().matches(assertions[i++].toString())
</code>```

Body:
In my SoapUI response I have a XML structure that repeats itself. For examples:

      4.66

      5.6

      7.58

I currently have the assertion which works to assert the value in the first premium field. I don't understand how to have multiple asserts to match all three fields.

// get the xml response
def response = messageExchange.getResponseContent()
// parse it
def xml = new XmlSlurper().parseText(response)
// find your node by name
def node = xml.'**'.find { it.name() == 'premium' }
// assert
assert node.toString().matches("4.66")

Is there a Way to skip over the first field to asset the second?

Body:
Use findAll to get all 'premium' nodes and iterate over the node list:

    def nodelist = xml.'**'.findAll{ it.name() == 'premium' }
    def assertions = [4.66, 5.6, 7.58]
    def i=0
    // assert
    for (node in nodelist) assert node.toString().matches(assertions[i++].toString())


答:
Use the last template tag:

```<code>{{ value|last }}
</code>```

If value is the list ['a', 'b', 'c', 'd'], the output will be the string "d".

Title: How can reference the last item in a list in a Django template? {{ list.-1.key }}

Body:
if I have a variable in the context of unknown length, for example;

list=[{'key':'A'},{'key':'B'},{'key':'C'}]

How can I get the last object? {{ list.0.key }} works for the first, but {{ list.-1.key }} gives;

Could not parse the remainder: '-1.key' from 'list.-1.key'

Body:
Use the last template tag:

{{ value|last }}

If value is the list ['a', 'b', 'c', 'd'], the output will be the string "d".


问:
Split ng-model values(javascript+angularjs)
I am getting input text box values in my angular ng-model as 903290,902020. I want to insert this in mysql using nodejs with sequelize , so for bulk create i need array. How to convert this above 903290,902020 into  array [903290,902020]

答:
You can use the JavaScript split function for this.

var string = "903290,902020";
var split = string.split(",");

console.log(split)```


问:
The timeout period elapsed prior to obtaining a connection from the pool
Our site works fine for 90% of the day, then during our peak hours when traffic is about twice as heavy as normal, everything slows down to a crawl.  Page load times that are normally 1 second take 30 seconds.  Checking our error logs, it looks like it may be a connection pool issue.  We have 3 web servers connected to 1 sql server db.  The SQL server is flying under 25% utilization on all cores.

I look at the User Connections counter on our SQL server and see that during our peak we have 400+ User Connections, but off-hours it is around 120+.

I am pretty sure we are just using whatever default settings MS comes with to deal with our app pool.  What can I do to test to see if is an app pool issue?  What are the negatives of increasing the app pool size to 1000 (and how do I do this?).

Thanks!

答:
In my experience there are 3 primary types of timeouts you can receive from SQL Server:

1) InvalidOperationException - A failure for the client to obtain a pooled connection from its own pool before the timeout specified on the command string (default 15 seconds).  The client's pool is at its maximum size, and all pooled connections are in use and stay in use before the timeout elapses.

2) SQLException - Connection Timeout.  The client's connection pool is creating a new connection to the database, but the database does not respond before the timeout specified in the command string (default 15 seconds).

3) SQLException - Command Timeout.  A connection was obtained, but the time taken for the SQL statement to exercise the command exceeded the timeout specified on the command's CommandTimeout property (default 30 seconds)

Your circumstances of a server performing normally until load is added sounds like case #1.  I've found the timeouts come very fast - usually 2 seconds.

I've found the solution to this is to increase the maximum threads in SQL Server.  The default is zero - let SQL Server decide.  I've seen cases where a stout server sits with little resource use while it has restricted itself by allocating too few threads.

You can increase the max threads setting with this transact-sql:

```<code>sp_configure 'max worker threads', 8192
go
Reconfigure
</code>```

Then, restart your SQL Service.

BTW, you can see how many threads are currently allocated by SQL Server with this command:

```<code>select sum(current_workers_count) from sys.dm_os_schedulers
</code>```

This threading setting makes an enormous difference in how SQL Server performs under many connections.  SQL Server becomes very unresponsive once it runs out of threads.

Body:
In my experience there are 3 primary types of timeouts you can receive from SQL Server:

1) InvalidOperationException - A failure for the client to obtain a pooled connection from its own pool before the timeout specified on the command string (default 15 seconds).  The client's pool is at its maximum size, and all pooled connections are in use and stay in use before the timeout elapses.

2) SQLException - Connection Timeout.  The client's connection pool is creating a new connection to the database, but the database does not respond before the timeout specified in the command string (default 15 seconds).

3) SQLException - Command Timeout.  A connection was obtained, but the time taken for the SQL statement to exercise the command exceeded the timeout specified on the command's CommandTimeout property (default 30 seconds)

Your circumstances of a server performing normally until load is added sounds like case #1.  I've found the timeouts come very fast - usually 2 seconds.

I've found the solution to this is to increase the maximum threads in SQL Server.  The default is zero - let SQL Server decide.  I've seen cases where a stout server sits with little resource use while it has restricted itself by allocating too few threads.

You can increase the max threads setting with this transact-sql:

sp_configure 'max worker threads', 8192
go
Reconfigure

Then, restart your SQL Service.

BTW, you can see how many threads are currently allocated by SQL Server with this command:

select sum(current_workers_count) from sys.dm_os_schedulers

This threading setting makes an enormous difference in how SQL Server performs under many connections.  SQL Server becomes very unresponsive once it runs out of threads.


问:
trying to get single column data with switch case statement
I am trying to get  query the table based on role like this below but I am getting error  like this

Incorrect syntax near '='.

I am not sure why I am getting this error

below is my query

```<code>CREATE procedure [dbo].[getName]
    @AccountId int,
    @role varchar(50),
    @Activated_By nvarchar(100)
AS
BEGIN

    SELECT   Name
    FROM     pass_activationinfo
    WHERE
        CASE WHEN @role = 'Admin'
             THEN account_id = @AccountId
             ELSE Activated_By = @Activated_By
        END
END
</code>```

答:
Change the case and use OR instead</p>

```<code>CREATE procedure [dbo].[getName]
    @AccountId int,
    @role varchar(50),
    @Activated_By nvarchar(100)
AS
BEGIN

    SELECT
        Name
    FROM pass_activationinfo
    WHERE
        (
            @role = 'Admin'
            AND
            account_id = @AccountId
         )
         OR
         (
            @role <> 'Admin'
            AND
            Activated_By = @Activated_By
         )

END
</code>```

Body:
I am trying to get  query the table based on role like this below but I am getting error  like this

Incorrect syntax near '='.

I am not sure why I am getting this error

below is my query

CREATE procedure [dbo].[getName]
    @AccountId int,
    @role varchar(50),
    @Activated_By nvarchar(100)
AS
BEGIN

    SELECT   Name
    FROM     pass_activationinfo
    WHERE
        CASE WHEN @role = 'Admin'
             THEN account_id = @AccountId
             ELSE Activated_By = @Activated_By
        END
END

Body:
Change the case and use OR instead

CREATE procedure [dbo].[getName]
    @AccountId int,
    @role varchar(50),
    @Activated_By nvarchar(100)
AS
BEGIN

    SELECT
        Name
    FROM pass_activationinfo
    WHERE
        (
            @role = 'Admin'
            AND
            account_id = @AccountId
         )
         OR
         (
            @role <> 'Admin'
            AND
            Activated_By = @Activated_By
         )

END


问:
UPDATE prepared statement with Object
I have an Object that maps column names to values. The columns to be updated are not known beforehand and are decided at run-time.

e.g. map = {col1: "value1", col2: "value2"}.

I want to execute an UPDATE query, updating a table with those columns to the corresponding values. Can I do the following? If not, is there an elegant way of doing it without building the query manually?

```<code>db.none('UPDATE mytable SET $1 WHERE id = 99', map)
</code>```

答:
Something like this :</p>

```<code>map = {col1: "value1", col2: "value2",id:"existingId"}.

db.none("UPDATE mytable SET col1=${col1}, col2=${col2} where id=${id}", map)
</code>```

Title: UPDATE prepared statement with Object

Body:
I have an Object that maps column names to values. The columns to be updated are not known beforehand and are decided at run-time.

e.g. map = {col1: "value1", col2: "value2"}.

I want to execute an UPDATE query, updating a table with those columns to the corresponding values. Can I do the following? If not, is there an elegant way of doing it without building the query manually?

db.none('UPDATE mytable SET $1 WHERE id = 99', map)

Body:
Something like this :

map = {col1: "value1", col2: "value2",id:"existingId"}.

db.none("UPDATE mytable SET col1=${col1}, col2=${col2} where id=${id}", map)


问:
search and convert Uppercase to small case and inserting ''-'' in javascript
thanks in advance,
I have a string as "fileName = 'CampaignDetail'" .I want to make it 'campaign-detail'.That is converting all the upper case letters to small and insert hyphen wherever in between it is capital letter.how can I do it with for loop. </p>

答:
Try it. Hope it helps

var string = "CampaignDetail";

string = string.replace(/([a-z])([A-Z])/g, '$1-$2');
string = string.replace(/([A-Z])([A-Z][a-z])/g, '$1-$2')
alert(string.toLowerCase());```


答:
First variant

```<code>SELECT   Name
FROM     pass_activationinfo
WHERE
        (@role = 'Admin' AND account_id = @AccountId)
    OR (@role <> 'Admin' AND Activated_By = @Activated_By)
</code>```

Second variant

```<code>SELECT   Name
FROM     pass_activationinfo
WHERE
    CASE
      WHEN @role = 'Admin' AND account_id = @AccountId THEN 1
      WHEN @role <> 'Admin' AND Activated_By = @Activated_By THEN 1
      ELSE 0
    END = 1
</code>```

Title: trying to get single column data with switch case statement

Body:
First variant

SELECT   Name
FROM     pass_activationinfo
WHERE
        (@role = 'Admin' AND account_id = @AccountId)
    OR (@role <> 'Admin' AND Activated_By = @Activated_By)

Second variant

SELECT   Name
FROM     pass_activationinfo
WHERE
    CASE
      WHEN @role = 'Admin' AND account_id = @AccountId THEN 1
      WHEN @role <> 'Admin' AND Activated_By = @Activated_By THEN 1
      ELSE 0
    END = 1


答:
RegEx only solution:

```<code>"CampaignDetailKebabCase".replace(/(.)([A-Z]{1})/g, '$1-$2').toLowerCase();
</code>```

Here we globally search for uppercase letter ([A-Z]) placed after any symbol (.) and replace this with the same any symbol '$1' , dash symbol '-' and the same upper case later '$2'.

Body:
thanks in advance,
I have a string as "fileName = 'CampaignDetail'" .I want to make it 'campaign-detail'.That is converting all the upper case letters to small and insert hyphen wherever in between it is capital letter.how can I do it with for loop.

Body:
RegEx only solution:

"CampaignDetailKebabCase".replace(/(.)([A-Z]{1})/g, '$1-$2').toLowerCase();

Here we globally search for uppercase letter ([A-Z]) placed after any symbol (.) and replace this with the same any symbol '$1' , dash symbol '-' and the same upper case later '$2'.