text:
Q: Spring Boot OAuth 2 SSO how to extract token to pass back to thick client application I have a thick client application (C# but that should not matter).
All the users already exist in an authentication/authorization (3rd party) system that provides OAuth 2 API (authorize/access_token plus a user_info service).
I have a Spring Boot web service tier that will have RESTful web services that will be called by the thick client application that must only be called by authenticated users for protected web services.
To authenticate the thick client will launch a Web Browser (OS installed default) and will open https to restful.web.server:8443 /login of the Spring Boot web service tier. This will do the OAuth 2 (authorization_code) interaction. Once redirected back with a valid token I want to redirect to a custom URI passing the token and for the browser to close (if possible) so an OS registered application can extract the token and pass it via an IPC mechanism to the thick client application.
The thick client application can then pass the token to the Web Services in the header (Authorize: TOKEN_TYPE TOKEN_VALUE).
The Web Services must then validate the authenticity of the token.
The Web Services if called with an invalid token must just return an HTTP error and JSON error content (e.g. code+message) and not try and redirect to the login screen. This will be orchestrated by the thick client application.
I have no concern with any of the custom URI handling, IPC development, or thick client web service calls. It is all the Spring/SSO magic in getting the token to be sent to my thick client and returning the relevant error from protected web services without returning a redirect to the SSO login.
I appear to be authenticating and being sent a token but then I get an exception.
I have made some progress and it appears that by manually launching a browser and hitting my web service tier https to restful.web.server:8443 /login it redirects to the SSO site https to 3rdparty.sso.server /oauth/authorization (passing in client_id, redirect_uri, response_type=code, state). I can log in, and Spring is calling the https to 3rdparty.sso.server /oauth/access_token endpoint (I had to create a custom RequestEnhancer to add in Authorization: Basic ENCODED_CLIENT_ID_AND_CLIENT_SECRET to satisfy the access_token SSO API requirement).
This returns 200 OK but then I get exceptions and do not know how to extract the token. The access_token returned may not be using the standard property names but unsure when to go and check if this is the case.  I done the authentication this way to keep the client id and client secret out of the thick client application and my web services must do the authorisation anyway. If there is a better way or pointers to someone else doing this already it would be greatly appreciated. I find so many examples that are either not quite relevant or more towards web applications.
server:
  port: 8443
  ssl:
    key-store: classpath:keystore.p12
    key-store-password: **********
    keyStoreType: PKCS12
    keyAlias: tomcat
  servlet:
    context-path: /
  session:
    cookie:
      name: UISESSION
security:
  basic:
    enabled: false
  oauth2:
    client:
      clientId: *******
      clientSecret: *****************
      accessTokenUri: https://3rdparty.sso.server/oauth2/access_token
      userAuthorizationUri: https://3rdparty.sso.server/oauth2/authorize
      authorizedGrantTypes: authorization_code,refresh_token
      scope:
      tokenName: accessToken
      redirectUri: https://restful.web.server:8443/login
      authenticationScheme: query
      clientAuthenticationScheme: header
    resource:
      userInfoUri: https://3rdparty.sso.server/oauth2/userinfo
logging:
  level:
    org:
      springframework: DEBUG
spring:
  http:
    logRequestDetails: true
    logResponseDetails: true

@Configuration
@EnableOAuth2Sso
@Order(value=0)
public class ServiceConectWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter
{
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                // From the root '/' down...
                .antMatcher("/**")
                // requests are authorised...
                .authorizeRequests()
                // ...to these url's...
                .antMatchers("/", "/login**", "/debug/**", "/webjars/**", "/error**")
                // ...without security being applied...
                .permitAll()
                // ...any other requests...
                .anyRequest()
                // ...the user must be authenticated.
                .authenticated()
                .and()
                .formLogin().disable()
                .logout()
                .logoutSuccessUrl("/login")
                .permitAll()
                .and()
                .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())

        ;
    }

I expect that the secured web services would be accessible once authenticated via the browser whilst testing without the client and would not expect exceptions to be thrown. I need to be able to extract the returned token and pass it back to my thick client.
Redirects to 'https://3rdparty.sso.server/oauth2/authorize?client_id=***HIDDEN_CLIENT_ID***&redirect_uri=https://localhost:8443/login&response_type=code&state=***HIDDEN_STATE_1***'

Then FilterChainProxy        : /login?code=***HIDDEN_CODE_1***&state=***HIDDEN_STATE_1*** at position 6 of 12 in additional filter chain;

Request is to process authentication
RestTemplate              : HTTP POST https://3rdparty.sso.server/oauth2/access_token
RestTemplate              : Response 200 OK

IllegalStateException: Access token provider returned a null access token, which is illegal according to the contract.
    at OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:223) ```

Then end up at an error page

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

There was an unexpected error (type=Internal Server Error, status=500).
Access token provider returned a null access token, which is illegal according to the contract.

A: The access_token service was returning non-standard JSON names.
I created a MyOwnOAuth2AccessToken with the relevant non-standard JSON names the necessary de/serialisation classes.
I created a MyOauth2AccesTokenHttpMessageConverter class for returning my OAuth2AccessToken.
The MyOauth2AccesTokenHttpMessageConverter was plumbed in from an
    @Configuration
    public class ServiceConnectUserInfoRestTemplateFactory implements UserInfoRestTemplateFactory

within the
    @Bean
    @Override
    public OAuth2RestTemplate getUserInfoRestTemplate()

method with the following code:
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(new ItisOAuth2AccessTokenHttpMessageConverter());
    messageConverters.addAll((new RestTemplate()).getMessageConverters());
    accessTokenProvider.setMessageConverters(messageConverters);

There is probably a better way to do this but this worked for me.


text:
Q: Can't install mmh3 for Python3.7.1 on Win10x64 - visual C++ build tools aren't recognized I'm trying to install mmh3 (with some other libs) on Python  - other libs are installing OK, but mmh3 rises an error:
ERROR: Complete output from command 'c:\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\evgeniy\\AppData\\Local\\Temp\\pip-install-ppmbqvid\\mmh3\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\evgeniy\AppData\Local\Temp\pip-record-6no3ekq2\install-record.txt' --single-version-externally-managed --compile:
    ERROR: running install
    running build
    running build_ext
    building 'mmh3' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/
    ----------------------------------------
ERROR: Command "'c:\python37\python.exe' -u -c 'import setuptools, tokenize;__file__='"'"'C:\\Users\\evgeniy\\AppData\\Local\\Temp\\pip-install-ppmbqvid\\mmh3\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\evgeniy\AppData\Local\Temp\pip-record-6no3ekq2\install-record.txt' --single-version-externally-managed --compile" failed with error code 1 in C:\Users\evgeniy\AppData\Local\Temp\pip-install-ppmbqvid\mmh3\

After i got this error at first, i've installed Microsoft Visual C++ Build Tools 15 (v14 was installed too), checked, whether Python has its environment variables and restarted.
After restart and running pip install -r requirements.txt same error fires again. AND, really weird: the paths cited in the error text don't exist, both of them:

*

*not C:\Users\evgeniy\AppData\Local\Temp\pip-record-6no3ekq2\install-record.txt

*not C:\Users\evgeniy\AppData\Local\Temp\pip-install-ppmbqvid\mmh3\

In the folder named TEMP, which obviously exists, are no leftovers of mmh3 install or logs or anything related.
What should i do to get mmh3 installed?
PS:

*

*solution under https://www.scivision.dev/python-windows-visual-c-14-required/ doesn't help

*installing Python into default installation directory (AppData/Local/Programs/Python/Python37) doesn't help too

A: The trick is to install the lib (mmh3 or any other, which makes troubles) from within Visual Studio.
From within means from its own terminal / cmd window, like explained in the step 4 of Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to replace the text on  in a  - using javascript? I have a
 with a  where I would like to replace the text - using javascript.

        2014-08-16T11:00:00.000+02:00

I receive from the server a new_dates object of key/value pairs that I loop through:
Coffeescript version:
last_dates.map (last_date) ->
  for key of last_date
    console.log key + " has the date: " + last_date[key] # 53ffb262436872c499b90f00 has the date: 2014-08-16T11:00:55.000+02:00
    $("##{key}").text = "#{last_date[key]}"

Javascript version:
last_dates.map(function(last_date) {
  var key, _results;
  _results = [];
  for (key in last_date) {
    console.log(key + " has the date: " + last_date[key]); // 53ffb262436872c499b90f00 has the date: 2014-08-16T11:00:55.000+02:00
    _results.push($("#" + key).text = "" + last_date[key]);
  }
  return _results;
});

The above code is supposed to find all the id's from key's, and replace their text values with value's. My code, however, does not work. What am I doing wrong?

A: jQuery.text is a function. You're trying to use it as a property. Try this instead:
$("#" + key).text(last_date[key]);

You don't need to prepend an empty String - anything you insert as a text node will be converted into a String.


text:
Q: trace $0$ complex matrix is similar to a diagonal matrix having $0$'s in main diagonal Let $A$ be an $n\times n$ complex matrix with $trace(A)=0$. We need to Show that $A$ is similar to a matrix with all $0'$ s along the main diagonal.
What I thought: $A$ is not zero matrix, also $A\ne cI$ for any $c\in\mathbb{C}^*$
so $\exists v\in \mathbb{C}^n$ which is not an eigen vector of $A$, then I thought of taking a basis whose first two vectors are $v,Av$ and then with respect to this basis what will be the matrix $A$?
Thanks for helping.


text:
Q: SQL, Databases, Joining two tables, get average I have two tables one called Hotels and one called Ratings. I want to display the hotel names and then get the average rating for each hotel and display this. In the ratings table I might have 5 different ratings of a hotel so I want the average number and then display this. How would my query have to look like ?

A: You didn't provide details but I assume you have a primary key in Hotels which is a foreign key in Ratings (HotelId). You didn't specify your RDBMS but each one should have a function to average and the query will look like:
select h.HotelId, avg(r.Rating)
from Hotels h
inner join Ratings r on h.HotelId = r.HotelId
group by h.HotelId


text:
Q: "Break the doubt with certainty", is there such a phrase? If I wanted to confront someone, suppose a girl, whom I doubt of doing certain things, but still not sure if she is the one who actually did them.
So, I go to her and say:

I'm here to overcome my doubts about you by asking you directly if you did this and this...etc

My question:
Is there a common/known phrase or maybe idiom that summarizes that saying (doesn't necessarily have to be that one, but anything with the same case)?
I think there's a phrase that would be similar to break the doubt with certainty, but I searched it on the internet and found nothing similar to it.

*

*I have used "break" as in the idiom "Break the news" where it isn't used literally; however, I don't want it to mean "reveal".

A: Clear up
Clarify, explain, solve, as in:

Let's try to clear up this misunderstanding.

Straighten out
To resolve, clarify, or organize some confusion, disorder, or misunderstanding. A noun or pronoun can be used between "straighten" and "out."

I need to go straighten things out between me and Sandy. The project
  got so muddled that they had to bring in an outside advisor to
  straighten it all out. Please straighten out those files before you
  go.

Sort out To understand or resolve a problem or conflict. A noun can be used between "sort" and "out."

They brought in the head of human resources to sort the issue out.
  I've spent nearly an hour on this math problem, but I still can't sort
  it out.

Come clean To admit something to someone, often regarding a wrongdoing that one has tried to hide.

I need you to come clean with me and tell me what happened.

A: If you get rid of the doubts by ignoring them, you "quash" those doubts. ("Shut up!" he explained.)
If you get rid of the doubts by removing any sensible basis for them, you "dispel" them.

A: As for your example sentence- one thing I would do as an American English speaker is to replace the word doubts with the word suspicions- to overcome suspicions sounds better to me than to overcome doubts.
I think for this example sentence the phrases suggested by Kyle in his answer are all good, as well as "clear the air" as suggested by Canadian Yankee. "Smooth things over" is a phrase with a similar meaning also.
In terms of the phrase you mention that you translate as "break the doubt with certainty", sometimes expressions in other languages sound awkward when translated into English literally. Though I understand your frustration at not having an exact translation, I am not sure there is a particular idiom that exactly matches the original (either in overall meaning or in using the same words). The best I can think of is let the truth speak for itself.


text:
Q: In JavaScript ES6, for-in loop and for-of loop, the variable i stops to exist after each iteration of the block? Typically I'd use a let i in the following first two cases:
> for (const i in ["red", "green", "blue"]) { console.log(i) }
0
1
2

> for (const i of ["red", "green", "blue"]) { console.log(i) }
red
green
blue

> for (const i = 0; i < 10; i++) { console.log(i) }
0
TypeError: Assignment to constant variable.

But the Mozilla documentation stated a const can be used.  So the i ceased to exist after the end of the block { console.log(i) }?  Isn't that not true if it is the third case above?
Is it a subtle rule? The loop variable for for ( in ) and for ( of ) loop ceases to exist after the block, but for the for (;;) loop, it stays? It is somewhat subtle -- is it in any of the ES6 specs?

A: The variable in each case does cease to exist after the loop. You can see it work as you expect if you use let instead of const.

for (let i in ["red", "green", "blue"]) { console.log(i) }
for (let i of ["red", "green", "blue"]) { console.log(i) }
for (let i = 0; i < 10; i++) { console.log(i) }
console.log(i); // error, because `i` is local

However, you cannot use ++ on a constant, which accounts for your error. The constant or variable in for..of and for..in constructs is recreated in each loop; but you can't do that with for.
However, if you don't try to modify the constant, it again works as expected:

for (const i = [0]; i[0] < 10; i[0]++) { console.log(i[0]) }
console.log(i) // error, because `i` is local

A: If you need to limit the scope of the loop variable justo surround the loop with another block and use let.
{
    for (let i in ["red", "green", "blue"]) {console.log(i);}
}
console.log(i);

This way the last console.log will throw Reference error, because it's not defined in its scope


text:
Q: To add textbox to modalpop extender through javascript I  need to add dynamic textbox to a modalpopupextender through javascript,
for that i did the following
 function Add_Option_Panel() {
      var Var_NewRow = document.createElement("input");
      Var_NewRow.setAttribute("id","ctl00$ContentPlaceHolder2$Txt" + alpha);
      Var_New_Option.appendChild(Var_NewRow);
      $find('ctl00_ContentPlaceHolder2_Btn_PopUp_New_Question_ModalPopupExtender').show();
}

The textbox gets added but the page gets refreshed and the modalpopupextender gets disappeared. I don't want it through c#. How do I make the modalpopupextender visible?


text:
Q: shellcode works but driver program doesnt run shellcode it just hangs I have shellcode which run without any error in assembly,but when I put that opcode in driver program and try to invoke it, it doesnt execute that shellcode, it just hangs by running previous C instruction like printing size of shell code.
my system
physical(hardware) system is x86_64
Linux lenova 4.19.0-9-686 #1 SMP Debian 4.19.118-2+deb10u1 (2020-06-07) i686 GNU/Linux
gcc (Debian 8.3.0-6) 8.3.0
GNU ld (GNU Binutils for Debian) 2.31.1
NASM version 2.14
shellcode.asm
global _start

section .text

_start:
    jmp msg

proc:   mov al, 4
    mov bl, 1
    pop ecx
    mov dl, 12
    int 0x80

    mov al, 1
    mov bl, 1
    int 0x80

msg: call proc
     db "HellowOworld"
section .data

nasm -felf32 shellcode.asm &&
ld shellcode.o -o shellcode &&
./shellcode
HellowOworld (output)

driver.c
#include<stdio.h>
#include<string.h>

char shellcode[]="\xeb\x0f\xb0\x04\xb3\x01\x59\xb2\x0c\xcd\x80\xb0\x01\xb3\x01\xcd\x80\xe8\xec\xff\xff\xff\x48\x65\x6c\x6c\x6f\x77\x4f\x77\x6f\x72\x6c\x64";
int main(){
    printf("Shellcode of size %d \n", (int)strlen(shellcode));
    (*(void(*)())shellcode)();
}

gcc -s -fno-stack-protector -z execstack driver.c
./a.out
output=>
Shellcode of size 34
(blankline and hungs)


text:
Q: How to fetch content from rich text field Contentful I'm trying it out in a test project.
here is from the Index.js
const IndexPage = ({data: {posts}}) => {
  return (

Test Page

      {posts.edges.map(({node}) => (
        <Card key={node.id} node={node} />
      ))}

  )
}

export default IndexPage;

export const query = graphql`
query {
  posts: allContentfulPost {
    edges {
      node {
        id
        title
        slug
        content{
           content
         }
        body{
           raw
         }
      }
    }
  }
}
`

I've copied your suggested code into my template component card.js. Here's when I try to render out the rich text field.
import { BLOCKS, MARKS } from "@contentful/rich-text-types"
import { renderRichText } from "gatsby-source-contentful/rich-text"

    const Bold = ({ children }) => {children}
    const Text = ({ children }) =>
{children}

    let richTextField;

    const options = {
      renderMark: {
        [MARKS.BOLD]: text => <Bold>{text}</Bold>,
        },
      renderNode: {
        [BLOCKS.PARAGRAPH]: (node, children) => <Text>{children}</Text>,
        [BLOCKS.EMBEDDED_ASSET]: node => {
            return (
              <>

Embedded Asset

                  {JSON.stringify(node, null, 2)}

              </>
            )
          },
        },
    }

function Card({ node }) {
    const { body } = node.body

    return (

               {/*  */}
               {/* <a href={`/posts/${node.slug}`}>

{node.title}

               {node.content.content}

 */}

{body && renderRichText(richTextField, options)}

    )
  }

export default Card;

But it doesn't render out the richTextField. First it was complaining that richTextField was undefined, so I added let richTextField in the beginning of the file.

A: Use it like this:
import { BLOCKS, MARKS } from "@contentful/rich-text-types"
import { renderRichText } from "gatsby-source-contentful/rich-text"

const Bold = ({ children }) => {children}
const Text = ({ children }) =>
{children}

const options = {
  renderMark: {
    [MARKS.BOLD]: text => <bold>{text}</bold>,
  },
  renderNode: {
    [BLOCKS.PARAGRAPH]: (node, children) => <Text>{children}</Text>,
    [BLOCKS.EMBEDDED_ASSET]: node => {
      return (
        <>

Embedded Asset

            {JSON.stringify(node, null, 2)}

        </>
      )
    },
  },
}

function BlogPostTemplate({ data }) {
  const { bodyRichText } = data.contentfulBlogPost

  return
{bodyRichText && renderRichText(richTextField, options)}

}

The options object, in the end, is a bunch of functions that return custom markup based on your project logic (i.e: <bold>{text}</bold> when the rich text has bold styling, etc) so, you only need to render it using:
renderRichText(richTextField, options)

In your component where you want to render the content, ideally, in a template.
For further details check the plugin's docs.


text:
Q: Django NoReverMatch at / I read the book 'Django By Example' and run the examples in chaper7.
But the results call "NoReverMatch at /"
NoReverseMatch at /
Reverse for 'product_detail' with arguments '(5, u'ironman')' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<id>[\\d+])/(?P<slug>[-\\w+])/$']

This is the models.py
class Category(models.Model):
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True, unique=True)

    class Meta:
        ordering = ('name',)
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('shop:product_list_by_category', args=[self.slug])

class Product(models.Model):
    category = models.ForeignKey(Category, related_name='products')
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.PositiveIntegerField()
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-created',)
        index_together = (('id', 'slug'),)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('shop:product_detail', args=[self.id, self.slug])

This is the urls.py
urlpatterns = [
url(r'^$', views.product_list, name='product_list'),
url(r'^(?P<category_slug>[-\w]+)/$', views.product_list, name='product_list_by_category'),
url(r'^(?P<id>\d+)/(?P<slug>[-\w+])/$', views.product_detail, name='product_detail'),
]

This is the views.py
def product_list(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    products = Product.objects.filter(available=True)
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.filter(category=category)

    return render(request, 'shop/product/list.html', {'category': category,   'categories': categories, 'products': products})

def product_detail(request, id, slug):
    product = get_object_or_404(Product,
                            id=id,
                            slug=slug,
                            available=True)

    return render(request, 'shop/product/detail.html', {'product': product})

And this is the 'list.html' template where the error occurs.
{% extends "shop/base.html" %}
{% load static %}

{% block title %}
    {% if category %}{{ category.name }}{% else %}Products{% endif %}
{% endblock %}

{% block content %}

Categories

                All

            {% for c in categories %}

                    {{ c.name }}

            {% endfor %}

{% if category %}{{ category.name }}{% else %}Products{% endif %}

        {% for product in products %}

            {{ product.name }}

           ${{ product.price }}

        {% endfor %}

{% endblock %}

The error occurs at

-- line.
Why this error occurs??

A: It looks to me like you need to change your url pattern:
url(r'^(?P<id>\d+)/(?P<slug>[-\w+])/$', views.product_detail, name='product_detail')

perhaps to:
url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.product_detail, name='product_detail')

'+' does not function as a special character inside square brackets, so [-\w+] will only match a single character (alphanumeric or '-'), but you are passing multi-character strings like 'ironman'. [-\w]+ will match one or more characters.


text:
Q: Eleventy, gulp and modules I'm working on a project that uses eleventy (v1.0.2) and gulp (v4.0.2) with node (v16.17.0).
Some of the current versions of the node modules that I need to use in my gulpfile.js file have now been converted to Javascript modules, and need to be imported with import rather than require. However, this leads me into a whole world of pain.
gulp doesn't seem to be able to cope with ES6 syntax (with import) unless I change my package.json so that it includes "type": "module". However, that's fatal to eleventy, which breaks with:
require() of ES Module /Users/user/blahblah/eleventy.js from
/Users/user/blahblah/node_modules/@11ty/eleventy/src/TemplateConfig.js
not supported.
[11ty] .eleventy.js is treated as an ES module file as it is a .js file
whose nearest parent package.json contains "type": "module" which
declares all .js files in that package scope as ES modules.

The suggested solutions:
Instead rename .eleventy.js to end in .cjs, change the requiring code
to use dynamic import() which is available in all CommonJS modules,
or change "type": "module" to "type": "commonjs"

don't seem to be helpful. If I rename .eleventy.js to .eleventy.cjs, then it becomes invisible to eleventy, and changing the type in package.json back to commonjs would just put me back where I was with respect to gulp.
I tried renaming gulpfile.js to gulpfile.mjs, but that doesn't help: gulp can't see files with a .mjs extension.
One option is to drop the modules I need in my Gulpfile back to older versions that can be imported with require, but in some cases the previous versions of the modules are 3 years old. So that doesn't feel like a good solution.
It looks as if I might be able to work around the problem by installing the babel transpiler and writing my Gulpfile as gulpfile.babel.js. But it seems bizarre to me that in 2022 I still need to use transpilation just to get ES6 syntax; it feels like there should be a better way.
I'd like to future-proof this project as much as possible, so ideally I'd write my Gulpfile in ES6 (and, ideally, all my eleventy code as well). But it seems as if this isn't an option currently (unless I use transpilation).
Am I overlooking or misunderstanding something, or are gulp and eleventy still challenged with respect to modules?
ETA: Transpilation is not the answer, because babel just helpfully turns each import back into a require, and the modules that insist on being imported rather than required promptly break.

A: Answering my own question, it turns out that gulp is able to handle .mjs files without problems, but it is essential to have an up-to-date version of gulp-cli.
The solution was to upgrade gulp-cli to 2.3.0, then rename my Gulpfile to gulpfile.mjs and use ES6 syntax.
There is no need to change the type in package.json to make this solution work, so eleventy is unaffected. Both gulp and eleventy can then be launched by appropriate npm scripts. Thus, for example, I can define:
"scripts": {
  "build": "gulp; npx @11ty/eleventy",
  "serve": "gulp; npx @11ty/eleventy --serve"
}

in my package.json and launch a full build with:
npm run build


text:
Q: How to create objects from JSON in Rails I have a controller which is used to parse a site.  From that parsing, I get a JSON object.  In that JSON object I have mainly two things: prices and images.
So, a Page has many Price and Image.  First thing I do when creating the controller is:
@page = Page.create(:url => parsed_url)

Then from the @output, I want to be able to create several @images and @prices.  So, I do this:
@prices = @output["prices"]
@images = @output["images"]

So, @images look like [{:width => 12, :height => 13, :src => 'http...'}, {:width => 20,..}]
I want to create an Image associated with that @page for each object in the array. Before doing that though I might need to check those attributes (width, height) and manipulate them before inserting them to the DB. So my question is... Where and how should I do this?
I know how to create an Image by doing Image.create(:page_id => @page.id, :width => 12...), but how do I do that form that JSON response that needs to be treated first?

A: Instead of Image.create, use Image.new or @page.images.build:
@output["images"].each do |image_data|
  image = @page.images.build image_data
  //...  manipulate as needed
  image.save
end


text:
Q: Python: How to iterate over files changing their names in loop? I am a beginner with Python, and I come from MATLAB.
What I need to do is create a loop with years from 2000 to 2016. I have a directory with a lot of files, whose filenames contain these years, like "file_2006".
How can I create a loop to open the files for specific years? In MATLAB I would do it like:
for i=2000:2016
year=num2str(i);
filename=['file_' year];
X=cdfread(filename); % and then some operations with X that I read here
end

But is it possible to do it in Python? Thank you!

A: try something like
for year in range(2000,2017):
    file_name = "file_{year}".format(year=year)
    with open(file_name) as file:
        file_data = file.read()

see the documentation about how to work with files here https://docs.python.org/3/tutorial/inputoutput.html

A: Yes it's possible to do, just use format or %s like this:
for item in range(2000,2016):
    file_name = "%s" % item
    print (print file_name)
    # or do what you want


text:
Q: Why is the meta key is not working when using Emacs? Suddenly, I am not able to use any combination of meta keys. The Alt key is not working at all in my emacs. Can anyone help me on this issue?

A: I fixed this in my Ubuntu Terminal app by going in the menu:  Edit -> Keyboard Shortcuts and deselecting the 'Enable menu access keys (such as Alt+F to open the File menu)'.

A: My VNC server had to be restarted with an extra option -compatiblekbd like this example:
vncserver -geometry 2549x1476 :17 -compatiblekbd

Once I added that and restarted my server, the meta key started working as I expect it to.
Note that -compatiblekbd must come after the display number (e.g. :17) or it is interpreted as an argument to -compatiblekbd.

A: On Gnome 42.4+ you have a keyboard setting that might be enabled by default for using alternate characters on your keyboard.
Go to:

*

*Settings

*Keyboard

*Click on the "Alternate Character Key" option

*In the popup, select another alternate character key other than left alt

I choose "Right Menu" since I don't even have a menu key on my keyboard but you can choose anything else besides "Left Alt" which is the key that is used to some shortcuts in Emacs.
I was having trouble using the Meta key in Emacs because of that parameters and now it is working as intended since I changed the alternate character key.


text:
Q: How to focus a p:dataTable single selectable row using JavaScript PrimeFaces has excellent keyboard support. See for example, the showcase of a selectable p:dataTable. When you click a row in the "Single with Row Click" table, you are able to use the arrow keys to navigate rows and use the enter to select the focused row.
I would like to be able to set the focus on a row in a (single) selectable p:dataTable using JavaScript.
I checked the client side API documentation for DataTable and the code of the row click handler, and I assume it has something to do with the originRowIndex and cursorIndex properties. But setting them to 0 (in the JavaScript console) does not trigger a focus. Also, when I focus a row, and then focus the JavaScript console, the focus gets lost, making it hard to figure out what is going on.
Then I checked the code of the keydown handler. This made me try the following (again, on the console):
var widget = PF('widget');
row = $('tbody tr', widget.jq).eq(0);
widget.focusedRow = row;
widget.highlightFocusedRow();
row.focus();

This will highlight the first row, but the focus is not set. I think I'm close, but stuck with the focus issue.

A: The trick is to focus the focusable TBODY.
widget.getFocusableTbody().trigger('focus');

But you will still be facing the issue trying to set focus from the console. See Unable to set focus and cursor to input text using javascript in Chrome Console


text:
Q: Show Ordered Numerical Numbers of returned MySQL results I have a web page where I want to display the PHP/MySQL results in a list, but I want to add a number before each title, like:

01 ... Title of the first article
02 ... Title of the second article

And these will be based on the number of results I get from the database. Here is my code to get the list:
ERROR

How do I get it to show 01, 02, 03, etc in place of $post_number?

A: You'll want to declare a counter variable so we can keep track of each loop through and print it. $counter is the variable I'm going to use in this example, and I declare it BEFORE the loop.
Replace your $post_numbers variable with the $counter variable, and INSIDE your loop, but at the END of it, we'll want to increment the $counter variable by 1. $counter++ will increase after each loop through, so it will keep track of how many records there are.
    $posts_sql = "SELECT id, added, title FROM posts ORDER BY added DESC LIMIT $offset, $post_limit";
    $posts_res = mysqli_query($con, $posts_sql);
    $counter = 1;
    while($post = mysqli_fetch_assoc($posts_res)){

        $post_id = $post["id"];
        $post_added = $post["added"];
        $post_title = ucwords($post["title"]);

        $display_posts .= "

        $counter ... $post_title";

        $counter++;

    };

^For every loop through, it'll increment your counter variable by one AFTER it posts the current number. Since it will only loop while there are results, that will effectively count for you so you can number your list.
EDIT
As suggested by CatalinB:
sprintf("%02d",$counter) ... $post_title to show 01 02 03

This will allow you to have the preceding 0 in front of single-digit numbers.

A: Use mysqli_fetch_all function to fetch all the record at once and then using foreach loop display all results and use key of $results table to display the numbers of rows.
$posts_sql = "SELECT id, added, title FROM posts ORDER BY added DESC LIMIT $offset, $post_limit";
$posts_res = mysqli_query($con, $posts_sql);

$results = mysqli_fetch_all($posts_res,MYSQLI_ASSOC);

foreach($results as $key=>$post){

    $post_id = $post["id"];
    $post_added = $post["added"];
    $post_title = ucwords($post["title"]);

    $display_posts .= "

    ".sprintf("%02d",$key)." ... $post_title
};


text:
Q: How to get params from select form in rails I have this code in my view:
<% select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {include_blank: true }) %>

I want to get value of post[:person_id] from params.
When I am trying
@person_Select = params[:post[person_id]]

I am getting error.

A: You should use below way to get your params in controller:
@selected_person = params[:post][:person_id]

A: You are accessing it the wrong way.
It should be:
@person_Select = params[:post][:person_id]

Instead of:
@person_Select = params[:post[person_id]]

A: here this should be syntax error
instead of this
@person_Select = params[:post[person_id]]

you have to write
@person_Select = params[:post][person_id]

A: should use params[:post][:person_id]


text:
Q: Supermarket dataset for Apriori algorithm 'I have to develop a software which is meant for Business Analyst of "Future Stores" Supermarket, the software performs the Association Rule Mining on given transitional data of supermarket sales transactions and prepares Discounting policy by preparing Combo.
The software makes use of the data mining algorithms namely Apriori Algorithm. The Association Rules will be displayed in User friendly manner for generation of discounting
policy based on positive association rules.'
From where can I get the supermarket dataset to check the Apriori algorithm which i have coded?

A: To get a market dataset, you can go here : fimi.ua.ac.be/data/  and download the retail dataset.
It is an anonymized datasets of transactions from a belgian store.
It is perfect for testing Apriori or other frequent itemset mining and association rule mining algorithms.

A: Instead of looking for a real-world dataset, you should design a small, specific dataset for each unit test. The dataset should provide the minimal necessary precondition to verify a single feature of the system. This will make it easier to detect bugs, maintain tests over time, and demonstrate the capabilities and usage patterns of the system to other developers.
An example from a different domain would be tests for a User Subsystem that creates and validates logins to a website.

*

*addsNewUser - empty dataset

*throwsExceptionForDuplicateUsername - single-user dataset

*correctPasswordPasses - same dataset

*throwsExceptionForIncorrectUsername - same dataset

*throwsExceptionForIncorrectPassword - same dataset

*throwsExceptionWhenNewUsernameExists - two-user dataset

Update: If you need a very large dataset to perform integration or performance testing, you are probably left with writing a program to generate a random collection of purchases. I doubt any existing supermarkets are willing (or able) to part with their real datasets.
That being said, while working as a contractor for a health insurance provider many years ago (pre-HIPAA) I was given a sample dataset to work with. It contained real patient information including SSNs and confidential medical history. :(


text:
Q: Entering a black hole, jumping into another universe---with questions I'm quite familiar with SR, but I have very limited understanding in GR, singularities, and black holes. My friend, which is well-read and is interested in general physics, said that we can "jump" into another universe by entering a black hole.
Suppose that we and our equipments can withstand the tidal forces near black holes. We jumped from our spaceship into a black hole. As we had passed the event horizon, we couldn't send any information to the outside anymore.

*

*Can this situation be interpreted as that we were in another universe
separate from our previous universe?

*Is there corrections or anything else to
be added to above statement?

A: Let me attempt a more "popular science" answer (Ron please be gentle with me!).
In GR a geodesic is the path followed by a freely moving object. There's nothing especially complex about this; if you throw a stone (in a vacuum to avoid air resistance) it follows a geodesic. If the universe is simply connected you'd expect to be able to get anywhere and back by following geodesics.
However in a static black hole, described by the Schwartzchild geometry, something a bit odd happens to the geodesics. Firstly anything following a geodesic through the event horizon can't go back the way it came, and secondly all geodesics passing through the event horizon end at a single point i.e. the singularity at the centre of the black hole.
If you now rotate the black hole, or you add electric charge to it, or both, you can find geodesics that pass through the event horizons (there are now two of them!), miss the singularity and travel back out of the black hole again.
But, and this is where the separate universes idea comes in, you now can't find any geodesics that will take you back to your starting point. So you seem to be back in the normal universe but you're in a region that is disconnected from where you started. Does this mean it's a "separate universe". That's really a matter of terminology, but I would say not. After all you just got there by coasting - you didn't pass through any portals of the type so beloved by SciFi films. And there's no reason to think that physics is any different where you ended than where you started.
If you're interested in pursuing this further I strongly recommend The Cosmic Frontiers of General Relativity by William J. Kaufmann. It claims to be a layman's guide, but few laymen I know could understand it. However if you know SR you shouldn't have any problems with it.

A: This issue is largely settled today--- you cannot go to another disconnected universe, but you are either trapped in the black hole, or reemerge in this universe. The reason is the no-information loss property. If material could go between disconnected universes, information about the state of this material would be permanently lost to the other universe. Hawking in fact has recently admitted that this idea was the main motivation for his initial proposal that Hawking radiation is perfectly thermal, and does not encode information about infalling stuff. This would be a definitive sign that the black hole is linking to a disconnected universe
The reason people expected to be able to travel to another universe is because a generic rotating black hole has three regions. The easiest way to see the structure is to consider a charged black hole, which is qualitatively the same, but spherically symmetric. The metric has f(r) in the dt part, and 1/f(r) in the dr part, with $f(r) = 1 - a/r + b/r^2$, where b is the square of the electric charge, and a is half the mass.
The zeros of the time component of the metric tell you the position in r of the horizon. There is an outer horizon and an inner horizon (the third zero is at negative values of r, and is unphysical). The outer horizon is an event horizon--- once you cross, you are forced inward. The inner horizon is a Cauchy horizon, once you cross this horizon, you see the singularity at r=0.
Gravity becomes repelling in r inside the inner horizon. Then the particle falling in is shoved outward, to cross the Cauchy horizon going the other way, and then it crosses the event horizon going the other way, but considering the event horizon as a white hole horizon now. Classically, each of the regions is disconnected, there is no identification between them. So that you go from our universe to the interior, then to the inner part, then to the interior of the white hole, then out into another disconnected universe.
In the 1970s, the white hole and black hole horizons were considered distinct, so that a black hole would be one thing, and a white hole another. But Hawking himself noted that thermal equilibrium states are invariant under time reversal, so that by time reversing a black hole in equilibrium with radiation, you find that a black hole and a white hole are actually the same, once quantum mechanics, but in different perspective.
The full infalling process is not understood, because no-one has traced infalling matter going through a black hole in AdS/CFT (although it is just out of reach--- people are working on it). The result (I believe) is that the infalling matter does the classical circuit, and comes out of the event horizon at a time that is 1/hbar, so that the transit time diverges classically. But this is not supported by any detailed calculation, just by vague futzing around in AdS/CFT models. The only calculations in the literature make the claim (equally unsupported) that the black hole absorbs the stuff that falls in irreversibly, without spitting it out. I am pretty sure this is not true, it spits it out in this universe, if so, sometimes CPT reflected, so it comes out anti-matter.
I speculated that this could be the reason for the anomalous anti-electron signal observed recently by satellites near the galactic center. A rotating astrophysical black hole could be a copious antimatter source.


text:
Q: Tool to retrieve binary jpg data from SQL Server (Asking on behalf of a friend employed in a local bank)
Since he's no programming experience (neither do I with SQL Server), he's looking for a tool which can show all the jpg images stored in a windows SQL Server database. Google didn't give any satisfactory result.

A: SQL Image Viewer


text:
Q: Using shared array in multiprocessing I am trying to run a parallel process in python, wherein I have to extract certain polygons from a large array based on some conditions. The large array has 10k+ polygons that are indexed.
In a extract_polygon function I pass (array, index). Based on index the function has to either return the polygon corresponding to that index or not based on the conditions defined. The array is never changed and is only used for reading the polygon based on the index provided.
Since the array is very large, I am running into out of memory error during parallel processing. how can I avoid that? (In a way, how to effectively use shared array in multiprocessing?)
Below is my sample code:
def extract_polygon(array, index):

    try:
        islays = ndimage.find_objects(clone==index)
        poly = clone[islays[0][0],islays[0][1]]
        area = np.count_nonzero(ploy)

        minArea = 100
        maxArea = 10000

        if (area > minArea) and (area < maxArea):
            return poly
        else:
            return None

    except:
        return None

start = time.time()
pool = mp.Pool(10)
results = pool.starmap(get_objects,[(array, index) for index in indices])
pool.close()
pool.join()

#indices here is a list of all the indexes we have.

Can I use any other library like ray in this case?

A: You can absolutely use a library like Ray.
The structure would look something like this (simplified to remove your application logic).
import numpy as np
import ray

ray.init()

# Create the array and store it in shared memory once.
array = np.ones(10**6)
array_id = ray.put(array)

@ray.remote
def extract_polygon(array, index):
    # Change this to actual extract the polygon.
    return index

# Start 10 tasks that each take in the ID of the array in shared memory.
# These tasks execute in parallel (assuming there are enough CPU resources).
result_ids = [extract_polygon.remote(array_id, i) for i in range(10)]

# Fetch the results.
results = ray.get(result_ids)

You can read more about Ray in the documentation.
See some related answers below:

*

*Shared-memory objects in multiprocessing

*python3 multiprocess shared numpy array(read-only)


text:
Q: How do I create an ethereum wallet in Python? I am building an application that would create a wallet for a user. One option is the web3.personal API in web3.py, which has a newAccount('passphrase') method. The method only returns the address of created account.
What I'm looking for is a function similar to the eth.accounts API in web3.js, which has a create([entropy]) method. It returns an account object with 'address', 'privatekey' and other details.

A: Edit: I removed the deprecated pyethereum solution, replaced with the better eth-account one.
Setup
At shell: pip install eth_account
Generating Account
The eth-account library will help you create a private key with an attached address:
>>> from eth_account import Account

>>> acct = Account.create('KEYSMASH FJAFJKLDSKF7JKFDJ 1530')
>>> acct.privateKey
b"\xb2\}\xb3\x1f\xee\xd9\x12''\xbf\t9\xdcv\x9a\x96VK-\xe4\xc4rm\x03[6\xec\xf1\xe5\xb3d"
>>> acct.address
'0x5ce9454909639D2D17A3F753ce7d93fa0b9aB12E'

Adding some of your own randomness above helps address potential limitations of os.urandom, which depends on your version of Python, and your operating system. Obviously use a different string of randomness than the 'KEYSMASH...' one from above.
For more information about using the private key, see this doc with common examples, like signing a transaction.

As a side-note, you may find more support at ethereum.stackexchange.com

A: you can create private/public key pair with pure computations, bypassing the web3.py accounts api.
install requirements: pip install coincurve pysha3
from secrets import token_bytes
from coincurve import PublicKey
from sha3 import keccak_256

private_key = keccak_256(token_bytes(32)).digest()
public_key = PublicKey.from_valid_secret(private_key).format(compressed=False)[1:]
addr = keccak_256(public_key).digest()[-20:]
print('private_key:', private_key.hex())
print('eth addr: 0x' + addr.hex())

reference: https://www.arthurkoziel.com/generating-ethereum-addresses-in-python/


text:
Q: Picasso setIndicatorsEnabled(true) is not working I'm trying to add the option setIndicatorsEnabled(true) in my Picasso call but it doesn't work.
This is the call:
Picasso.with(context)
    .load(image)
    .placeholder(R.drawable.placeholder_img)
    .error(R.drawable.error_img)
    .into(imageView);

If I write .setIndicatorsEnabled(true) before .load(image), nothing works. If I write .setIndicatorsEnabled(true) after .into(imageView), .setIndicatorsEnabled(true) doesn't work.
The Picasso version is 2.5.2 (the last one).
Any suggestion?

A: To use set indicators enabled, you assume Picasso is a singleton instance when you use Picasso.with(context)....
Picasso mPicasso = Picasso.with(context);
mPicasso.setIndicatorsEnabled(true);
mPicasso....load().into(imageView);

Hope this helps..

A: Better yet, apply it to the single instance of picasso you get from .with(context).
Here you go:
    Picasso picasso = new Picasso.Builder(getApplicationContext())
            .indicatorsEnabled(true)
            .loggingEnabled(true) //add other settings as needed
            .build();
    Picasso.setSingletonInstance(picasso); //apply to default singleton instance

you can use above in your Application file in onCreate() (or the first activity that starts if you don't have one, but not really recommended since it's prone to error in case you change launching activity some day).


text:
Q: Vim - universal window for all tabs is it possible to have one universal window for all tabs in vim?
For example if I have a preview window open, that this window is the same for all the tabs, including its position and so on?

A: Short answer: not really.
Long answer: NERDTree fights against this and is far more complex for trying to do so.
From a comment:

The purpose of each tab is to allow for a different window layout.

In other words, I've seen people try to bolt this onto vim, and it's kludgy, only half works, and frankly goes so against the grain of what vim tries to be that it becomes a sacrifice of productivity.

If you absolutely must, see if you can figure out how NERDTree makes it work. I'll see about digging up the QA on vi.stackexchange.com.


text:
Q: WebClient.DownloadFile and HTTPS + SharePoint 2007 I am trying to download a file (.docx) from 1 SharePoint 2007 library with webclient.downloadfile(). SharePoint Webapp has SSL enabled. I get "401 Unauthorized" exception when trying to download the file.
Is it even possible to use webclient with SSL?
Resolution for this might be to use copy.asmx "ootb" webservice to download the file.

A: I found a solution for this problem.
http://couldbedone.blogspot.com/2007/08/webclient-handling-cookies.html
CookieAwareWebClient did the trick...


text:
Q: How can I allow only administrators to shutdown a program in windows I dont know if this has to do with how the program is programmed or how it is set up or how it is started.
But I created a program in WPF and I would like to make sure that none of he regular users on the computer shut it down.
The regular users need to be able to interact with it but they should not be able to close it.

A: The correct approach would be to run the application as a service with permissions set by the administrator to not let the user manipulate the service. Otherwise you will run into trouble with user-initiated shutdown and with preventing the application from being terminated.

A: If it is the case that the OP wants to prevent visibility of the OS, creating a terminal like experience. The best way to do this is to create a shell replacement.
Then the user wouldn't see the OS as windows directly.


text:
Q: Array is not changed after filter on javascript I'm trying yo filter the numeric values of an array with this code:
 function getNumerics(toFilter) {
        toFilter = toFilter.filter( element =>  !isNaN(element));
        console.log(toFilter);
      }

      var toFilter = [1, 'z', '4', 2, 6];
      getNumerics(toFilter);
      console.log(toFilter);

The console.log inside the function shows a correct result but but the last console.log show the array with all the values but if I pass the array to the function why is not change? in javascript  all parameters are passed are reference , aren't it?

A: Your function should return the filtered Array:

function getNumerics(toFilter) {
  return toFilter.filter( element =>  !isNaN(element));
}

var toFilter = [1, 'z', '4', 2, 6];
toFilter = getNumerics(toFilter);
console.log(toFilter);


text:
Q: Verifying method calls on lambda with Mockito I'm trying to verify and capture the arguments of some method calls within a lambda expression as so:
public Optional<UserDetails> findOne(String userName) {
    String selectStatement =
        "SELECT * FROM users WHERE userName = :userName;";

    return jdbi.withHandle(handle -> handle
            .createQuery(selectStatement)
            .bind("userName", userName)
            .map(new UserDetailsMapper())
            .findOne());
  }

jdbi.withHandle() takes an argument of HandleCallBack, which looks like this:
public interface HandleCallback<T, X extends Exception> {
  T withHandle(Handle handle) throws X;
}

For example, I want to verify that .bind() has been called with "userName" and the passed in userName argument string from my findOne method.
It does feel like I'm unit testing the Jdbi class rather than my own class, but I feel like the arguments to .createQuery() .bind() and .map() should be tested as these could be accidentally changed by a developer.
The approach I've currently taken is to create an in-memory database and test what is actually being returned, but this feels more like an integration test than a unit test. I also don't really care what is actually returned by the Jdbi .withHandle() method, as I would essentially be testing a library at that point.
My understanding is that I should be unit testing the arguments passed to .withHandle() (in this case, a lambda expression), which is what I'm trying to do here.
The closest I got was by moving the logic into a method reference, but that won't work as userName is passed into my findOne() method and then used inside the lambda.
I've also played around with Mockito's doAnswer to no avail.
I can only think of creating a new class with helper methods to return userName, selectStatement, etc, and verify that they are called, but it feels unnecessary and will be added simply to provide testability.

A: The lambda expression is part of the implementation of the findOne method. So, you should test it as part of testing findOne. But it is not executed when doing the call to findOne. So, to be able to test it, executing findOne and doing verifications and assertions on that will not be enough.
I would mock jdbi and then do a verification on the call with an ArgumentCaptor that captures the lambda function. Then you can pass that lambda function as a parameter to a test method which tests the lambda function. That method can look the same as any other test method except that it can never be ran as a separate test case.
In this case, I think one such test method will be enough. But sometimes when testing lambda function, you might need to create and call several test methods to test the captured lambda function with different input values.

A: The code you have shown is dominated by interactions with the various classes of jdbi.  Such code should rather be tested with integration testing than with unit-testing because there are many potential bugs in the interactions: Are you calling the right functions in the proper order, with the arguments in the right order and of the right format, and are the results of each call as you expect them to be (including possible exceptions)?
For identifying those potential bugs integration testing is the proper approach: A mocked environment will not help you find these bugs.  You would implement the mocks according to your own understanding (that is, also according to your own potential misunderstanding).
As an example, consider your stated goal that you would like to test that bind was called with "userName" and the userName argument: If you mock bind, then your mocked bind would test that "userName" comes as first argument, and the content of userName as second.  But, that does not tell you much, because your assumed order could be wrong, or because "userName" might still differ from the variable name in the SELECT statement, such that the real bind would fail etc.
That said, I agree with Stefan Mondelaers' point that the lambda expression belongs to the findOne method and should be tested together with it - it's just that I would test it directly with integration testing and not put any effort in unit-testing in this particular case.


text:
Q: Using Objective C/Cocoa to unescape unicode characters, ie \u1234 Some sites that I am fetching data from are returning  UTF-8 strings, with the UTF-8 characters escaped, ie: \u5404\u500b\u90fd
Is there a built in cocoa function that might assist with this or will I have to write my own decoding algorithm.

A: It's correct that Cocoa does not offer a solution, yet Core Foundation does: CFStringTransform.
CFStringTransform lives in a dusty, remote corner of Mac OS (and iOS) and so it's a little know gem. It is the front end to Apple's ICU compatible string transformation engine. It can perform real magic like transliterations between greek and latin (or about any known scripts), but it can also be used to do mundane tasks like unescaping strings from a crappy server:
NSString *input = @"\\u5404\\u500b\\u90fd";
NSString *convertedString = [input mutableCopy];

CFStringRef transform = CFSTR("Any-Hex/Java");
CFStringTransform((__bridge CFMutableStringRef)convertedString, NULL, transform, YES);

NSLog(@"convertedString: %@", convertedString);

// prints: 各個都, tada!

As I said, CFStringTransform is really powerful. It supports a number of predefined transforms, like case mappings, normalizations or unicode character name conversion. You can even design your own transformations.
I have no idea why Apple does not make it available from Cocoa.
Edit 2015:
OS X 10.11 and iOS 9 add the following method to Foundation:
- (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse;

So the example from above becomes...
NSString *input = @"\\u5404\\u500b\\u90fd";
NSString *convertedString = [input stringByApplyingTransform:@"Any-Hex/Java"
                                                     reverse:YES];

NSLog(@"convertedString: %@", convertedString);

Thanks @nschmidt for the heads up.

A: simple code:
const char *cString = [unicodeStr cStringUsingEncoding:NSUTF8StringEncoding];
NSString *resultStr = [NSString stringWithCString:cString encoding:NSNonLossyASCIIStringEncoding];

from: https://stackoverflow.com/a/7861345

A: There is no built-in function to do C unescaping.
You can cheat a little with NSPropertyListSerialization since an "old text style" plist supports C escaping via \Uxxxx:
NSString* input = @"ab\"cA\"BC\\u2345\\u0123";

// will cause trouble if you have "abc\\\\uvw"
NSString* esc1 = [input stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
NSString* esc2 = [esc1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
NSString* quoted = [[@"\"" stringByAppendingString:esc2] stringByAppendingString:@"\""];
NSData* data = [quoted dataUsingEncoding:NSUTF8StringEncoding];
NSString* unesc = [NSPropertyListSerialization propertyListFromData:data
                   mutabilityOption:NSPropertyListImmutable format:NULL
                   errorDescription:NULL];
assert([unesc isKindOfClass:[NSString class]]);
NSLog(@"Output = %@", unesc);

but mind that this isn't very efficient. It's far better if you write up your own parser. (BTW are you decoding JSON strings? If yes you could use the existing JSON parsers.)

A: Here's what I ended up writing.  Hopefully this will help some people along.
+ (NSString*) unescapeUnicodeString:(NSString*)string
{
// unescape quotes and backwards slash
NSString* unescapedString = [string stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];
unescapedString = [unescapedString stringByReplacingOccurrencesOfString:@"\\\\" withString:@"\\"];

// tokenize based on unicode escape char
NSMutableString* tokenizedString = [NSMutableString string];
NSScanner* scanner = [NSScanner scannerWithString:unescapedString];
while ([scanner isAtEnd] == NO)
{
    // read up to the first unicode marker
    // if a string has been scanned, it's a token
    // and should be appended to the tokenized string
    NSString* token = @"";
    [scanner scanUpToString:@"\\u" intoString:&token];
    if (token != nil && token.length > 0)
    {
        [tokenizedString appendString:token];
        continue;
    }

    // skip two characters to get past the marker
    // check if the range of unicode characters is
    // beyond the end of the string (could be malformed)
    // and if it is, move the scanner to the end
    // and skip this token
    NSUInteger location = [scanner scanLocation];
    NSInteger extra = scanner.string.length - location - 4 - 2;
    if (extra < 0)
    {
        NSRange range = {location, -extra};
        [tokenizedString appendString:[scanner.string substringWithRange:range]];
        [scanner setScanLocation:location - extra];
        continue;
    }

    // move the location pas the unicode marker
    // then read in the next 4 characters
    location += 2;
    NSRange range = {location, 4};
    token = [scanner.string substringWithRange:range];
    unichar codeValue = (unichar) strtol([token UTF8String], NULL, 16);
    [tokenizedString appendString:[NSString stringWithFormat:@"%C", codeValue]];

    // move the scanner past the 4 characters
    // then keep scanning
    location += 4;
    [scanner setScanLocation:location];
}

// done
return tokenizedString;
}

+ (NSString*) escapeUnicodeString:(NSString*)string
{
// lastly escaped quotes and back slash
// note that the backslash has to be escaped before the quote
// otherwise it will end up with an extra backslash
NSString* escapedString = [string stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
escapedString = [escapedString stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];

// convert to encoded unicode
// do this by getting the data for the string
// in UTF16 little endian (for network byte order)
NSData* data = [escapedString dataUsingEncoding:NSUTF16LittleEndianStringEncoding allowLossyConversion:YES];
size_t bytesRead = 0;
const char* bytes = data.bytes;
NSMutableString* encodedString = [NSMutableString string];

// loop through the byte array
// read two bytes at a time, if the bytes
// are above a certain value they are unicode
// otherwise the bytes are ASCII characters
// the %C format will write the character value of bytes
while (bytesRead < data.length)
{
    uint16_t code = *((uint16_t*) &bytes[bytesRead]);
    if (code > 0x007E)
    {
        [encodedString appendFormat:@"\\u%04X", code];
    }
    else
    {
        [encodedString appendFormat:@"%C", code];
    }
    bytesRead += sizeof(uint16_t);
}

// done
return encodedString;
}


text:
Q: Add a vector based on previous vectors Here is the data that I have:
round<-rep(1:5,4)
players<-rep(1:2, c(10,10))
decs<-sample(1:3,20,replace=TRUE)
game<-rep(rep(1:2,c(5,5)),2)
gamematrix<-cbind(players,game,round,decs)
gamematrix

Here is the output:
     players game round decs
 [1,]       1    1     1    2
 [2,]       1    1     2    2
 [3,]       1    1     3    1
 [4,]       1    1     4    2
 [5,]       1    1     5    1
 [6,]       1    2     1    1
 [7,]       1    2     2    1
 [8,]       1    2     3    2
 [9,]       1    2     4    1
[10,]       1    2     5    3
[11,]       2    1     1    2
[12,]       2    1     2    1
[13,]       2    1     3    3
[14,]       2    1     4    3
[15,]       2    1     5    3
[16,]       2    2     1    3
[17,]       2    2     2    2
[18,]       2    2     3    1
[19,]       2    2     4    1
[20,]       2    2     5    2

Now, I would like to add another column: "Same Choice" which I want to be "1" if the same player in the same game makes the same decision in next round as in previous round. For example, for player 1, the output should be: c(0,1,0,0,0,0,1,0,0,0).  Any ideas how can I do it?
Thanks!

A: Here is a data.table answer:
# set seed
set.seed(1234)

# load data
round<-rep(1:5,4)
players<-rep(1:2, c(10,10))
decs<-sample(1:3,20,replace=TRUE)
game<-rep(rep(1:2,c(5,5)),2)
gamematrix<-cbind(players,game,round,decs)

library(data.table)
dt <- data.table(gamematrix)
dt[, .(decs=decs, lag=c(0,head(decs,-1)),
                  sameDec=as.integer(decs==c(NA,head(decs,-1)))),
   by=c("players","game")]

I included the lag term so that you can verify.
@Frank s suggestion to use shift is much cleaner (and probably faster):
dt[, .(decs=decs, lag=shift(decs, 1),
                  sameDec=as.integer(decs==shift(decs, 1))),
by=c("players","game")]

compared to my hand-coded lag.

A: Following code will work
library(dplyr)
gamematrix %>% as.data.frame %>% group_by(players, game) %>% mutate(new_col = ifelse(decs == lag(decs), 1, 0) )
gamematrix$new_col[is.na(gamematrix$new_col)]<- 0


text:
Q: awk compare 2 files, print match and nonmatch lines In this example, need to compare two files f1.txt and f2.txt and obtain matches, and non-matches, for this case I am looking to match 2nd field of second file and 1st field of first file. And print first the second field of f2.txt, then print the entire line of f1.txt. And for no match found on f2.txt to state "Not Found" and then print f1.txt entire line.
F1.txt
1;2;3;4;5;6;7;8
1a;2;3;4;5;6;7;8
1b;2;3;4;5;6;7;8
2b;2;3;4;5;6;7;8

F2.txt
First;1
Firsta;1a
Firstb;1b

Desired Output:
First;1;1;2;3;4;5;6;7;8
Firsta;1a;1a;2;3;4;5;6;7;8
Firstb;1b;1b;2;3;4;5;6;7;8
Not Found;Not Found;2b;2;3;4;5;6;7;8

Tried but not working:
awk -F";" 'NR==FNR{a[$1]=$0;b[$1]=$0;next}{ if (a[$2]=b[$1]) print a[$1],$0;else print "NotAvailable","NotAvailable", $0;}' OFS=";" f2.txt f1.txt

A: You were close. Here is the correct script:
$ awk -F ";" 'NR==FNR{a[$2]=$0;next}{print (a[$1]?a[$1]:"Not Found;Not Found") ";" $0}' F2.txt F1.txt
First;1;1;2;3;4;5;6;7;8
Firsta;1a;1a;2;3;4;5;6;7;8
Firstb;1b;1b;2;3;4;5;6;7;8
Not Found;Not Found;2b;2;3;4;5;6;7;8

Take care to remove any trailing spaces from the input file.


text:
Q: I'm removing characters from a range of cells. How do I stop it looping? I'm trying to automate a few processes I regularly complete as a way of learning VBA. I'm writing a code that selects all cells in the worksheet and removes a certain character anywhere is occurs. In my case, I'm removing double spaces from strings.
The code I'm using does the job and removes the double spaces but it continues to loop for what seems like an indefinite amount of time.
Dim celref As String

    Range("A1").Select
    Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select

    For Each c In Range(Selection, ActiveCell)
    celref = c.Value
           Do While InStr(1, celref, "  ")
           Selection.Replace What:="  ", Replacement:=" ", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
        Loop
    Next c

End Sub

A: Assuming you are not trying to preserve leading/trailing spaces, you could do something like:
c.Value = application.trim(c.Value)

A: Get rid of the .Select statements, they're triggering unneeded processes.
For Each c In Range("A1", SpecialCells(xlLastCell)).Cells
    With c
        While InStr(.Value, "  "): .Value = Replace(.Value, "  ", " "): Wend
    End With
Next

Edit: Just noticed Rory's answer, much more efficient and quicker. I'll leave this here as an example.

A: This is great, works perfectly.
Sub Removestuff()

    Range("A1").Select
    Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select

       For Each c In Range(Selection, ActiveCell)
    c.Value = Application.Trim(c.Value)
    Next c

End Sub


text:
Q: Writing data in NetCDF file from multiple processors I have a simulation on meteorological field, my total domain (nx * ny * nz) is divided into number of processors (in my case 100). I have to send the job file created by local machine to the cluster for execution.
I want to write the Fortran routine for writing the output data from each processor into a NetCDF file.
Following is my code snippet, in user_init.f90
stat = NF90_CREATE('/home/sachin/e_output.nc', NF90_NETCDF4, ncid_user, comm = comm2d,info = MPI_INFO_NULL)

stat = NF90_DEF_DIM( ncid_user, i, NF90_UNLIMITED, i_id )
stat = NF90_DEF_DIM( ncid_user, j, NF90_UNLIMITED, j_id )
stat = NF90_DEF_DIM( ncid_user, k, NF90_UNLIMITED, k_id )

e_id=i_id(/i_id,j_id,k_id/)

stat = NF90_DEF_VAR( ncid_user, ene, NF90_INT, e_id, ev_id )

From other file I am writing the output data into the NetCDF file
stat1 = nf90_put_var(ncid_user, ev_id, pt, start = (/ 1 + myid*INT(procs1), 1 + myid*INT(procs1), 1 /),count = (/ 152,120,120 /))


text:
Q: Color title mapbox Does anyone know how to change the title color of a marker on a mapbox,
I would like home to be in blue, I tried to add paint : color-size:"blue", but it doesn't work,
thank you for your help!!

    map.on('load', function () {
  map.loadImage(
  'https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png',
  function (error, image) {
  if (error) throw error;
  map.addImage('custom-marker', image);

    map.addSource('points', {
    'type': 'geojson',
    'data': {
      'type': 'FeatureCollection',
      'features': [
      {
      // feature for Mapbox
      'type': 'Feature',
      'geometry': {
        'type': 'Point',
        'coordinates': [6.157902659395512,49.3612254277963],

        },
        'properties': {
        'title': 'Lieu de repas',
        'scale': 2,
    },
      }
      ]
      }
      });

    map.addLayer({
        'id': 'points',
        'type': 'symbol',
        'source': 'points',
        'layout': {
        'icon-image': 'custom-marker',
        'text-field': ['get', 'title'],
        "text-size": 28,
        'text-font': [
        'Open Sans Regular',
        ],
        'text-offset': [0, 1.25],
        'text-anchor': 'top',
        }
        });
}
);
});

A: You could possibly create an HTML marker for that in a way similar to this:
var el = document.createElement('div');
el.innerHTML = 'Lieu de repas';
el.style.color = 'blue';

new mapboxgl.Marker(el)
.setLngLat([6.157902659395512,49.3612254277963])
.addTo(map);


text:
Q: Having a Gradient go Across Two Side by Side Divs React As for setting up two divs to be side by side, I think I understand that part. I'm just trying to have a CSS gradient go across the two divs uninterrupted along the middle split.  I'm hoping there is a solution that doesn't involve like complex coloring.
What I tried doing is setting the background color in a parent div, and not have a color set for the two side by side child divs.
function Footer() {
    return (

                <Logo />

Hello

    )
}

.box {
  margin: 0;
  padding: 0;
  border: 0;
  background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(0,0,139,1) 100%);

}

.leftbox {
  float:left;
  width:50%;
  height:100%;
  clear: none;
}

.rightbox{
  float:right;
  width:50%;
  height:100%;
  clear: none;
}

What happens with this is that only the left div is colored.  Which makes me think I'm not doing this whole parent/child div thing correctly hahaha.  So that's the problem, I'm trying to have that background under "box" span across both divs without being interrupted in the middle.

A:
What happens with this is that only the left div is colored. Which makes me think I'm not doing this whole parent/child div thing correctly

The bug has to be elsewhere - my guess <Logo /> which breaks absolutely valid css.
As you are a beginner, a word of advice - don't use float and don't even touch flex, firstly - you don't need them, secondly they have more side effects than they're worth.
Snippet - without float, without redundancy, without troubles. Use borders in production - to see what you've done :)

body{
color: #fff;
text-align: center;
}
.blue, .green{
margin: 2vh 0;
padding: 0;
}
.blue{
background: linear-gradient(to right, rgb(2,0,36), rgba(0,0,139));
border: 1px solid red;
}
.green{
background: linear-gradient(to left, #cf8, #193);
border: 1px solid black;
}
.blue div, .green div{
height: 100%;
width: 49%;     /* kind of insurance - some space for weird devices and browsers */
margin: 0 auto;
display: inline-block;
vertical-align: middle;
box-sizing: border-box;
border: 1px dotted #fff;
}

two

three

four

Almost forgot - use Validator w3c, like the masters do.


text:
Q: How to run Database services in Docker container? Trying to build an docker image to install Node and databases in image.
Databases are installed but services are not running while trying to go for container logs ..
FROM ubuntu:lastest
RUN apt-get update && apt-get install -y curl wget gnupg && \
    apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv D68FA50FEA312927 && \
    echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list && \
    curl -sL https://deb.nodesource.com/setup_8.x | bash - && \
    apt-get update && \
    apt-get install -y nodejs mongodb-org redis-server && \
    node -v && \
    npm -v

Please do help regarding this issue, i am new to Docker.

A: Best run the database containers separate, e.g. one container for mongodb and one for redis. Then connect your application container to those containers (either by links (deprecated) or by creating and sharing a network as discussed in this question. You also do not to have to start from ubuntu:latest, but can start with a node image like nodejs. Some 'orchestration', like docker-compose, can make a task of plugging these services together much easier, see this tutorial (the postgres database in the article can easily be exchanged by mongodb and redis). Also consider reading the best practices for Dockerfile writing.

A: You need to actually start mongod, e.g. like
apt-get install -y nodejs mongodb-org redis-server && \
mongod --fork && \
node -v && \
npm -v

But bear in mind that mongo should be configured first and it requires some time to spin up.
As a side note it is considered a better practice to compose individual single-purpose docker images rather than pack both database and application in a single image.
Please read https://docs.docker.com/compose/overview/


text:
Q: Compile time error on Layers, but runtime okay Code below works fine at runtime, but receives an error at compile time which prevents me from building production code unless I ignore errors, which I don't want to do.
I'm unable to cast to a marker object as marker appears to be a method.
HTML

TypeScript
   markers: Layer[] = [];

       var markerObj: MarkerModel = {};

        markerObj.guid = this.utils.uuidv4();
        markerObj.iconUrl = pItem;
        markerObj.latitude = this.lat;
        markerObj.longitude = this.lng;
        const newMarker = marker(
            [markerObj.latitude, markerObj.longitude],
            {
                icon: icon( {
                    iconSize: [38, 38],
                    iconAnchor: [13, 13],
                    iconUrl: pItem
                } ),
                title: markerObj.guid
            }
        ).on( 'click', () => {
            this.zone.run(() => {
                this.onMarkerClick( markerObj );
            } );
        } );

        this.markers.push( newMarker );

            for ( var i = this.markers.length - 1; i >= 0; i-- ) {
                console.log( i, this.markers[i].title ); //compile time error
                if ( this.markers[i].title == pGuid ) { //compile time error
                    this.markers.splice( i, 1 );
                    //todo update server
                    break;
                }
            }

ERROR in src/app/map/map.component.ts:265:49 - error TS2339: Property 'title' does not exist on type 'Layer'.

A: So, Layer does not have a property title, but MarkerOptions does. The way the typings were set up for Leaflet, it looks like they'd want you to access it via marker.options.title. But, I'm not sure if that'll work the way you expect.
The typings definition (see the link below) is what determines what is and is not valid at compile type when it'd doing type checking.
https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/leaflet/index.d.ts
You have a couple options. First, you can try to find a way to access the title property in a way that is valid from a type checking perspective. Second, you could just cast to any to get it to compile without error/warning. The former is better, but the latter is fine if you just want to get it to work.
Here's an example of casting to any:
if ( (this.markers[i] as any).title == pGuid ) { //compile time error
      this.markers.splice( i, 1 );
      //todo update server
      break;
}


text:
Q: vbscript SelectionNamespaces selectSingleNode error runtime error: Object required: I have the following xml in a file called response2.xml
    <?xml version="1.0"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body><ns2:commonServiceResponse xmlns:ns2="http://webservice.mas.gepics.ab.com">
<return>
<responseData><?xml version="1.0" encoding="utf-8"?>
<tnsa:GetABQData xmlns:tns="http://www.ab.com/ns/ABQ/ABQSchemaExtensions"
        xmlns:tnsa="http://www.ab.com/ns/ABQ/ABQMessageStandard" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.ab.com/ns/ABQ/ABQMessageStandard ABQSchemaHeaders.xsd"
        releaseID="string" versionID="string">
        <tnsa:ApplicationArea>
                <tnsa:CreationDateTime>2012-04-03T08:53:20</tnsa:CreationDateTime>
                <tnsa:ABQHeader>
                        <tnsa:VehicleAssemblyPlant>CHW</tnsa:VehicleAssemblyPlant>
                        <tnsa:Source>GEPICS</tnsa:Source>
                        <tnsa:Destination>SEP</tnsa:Destination>
                        <tnsa:TransactionCode>
                                <tnsa:Transaction>TACK</tnsa:Transaction>
                        </tnsa:TransactionCode>
                        <tnsa:TriggerID>0</tnsa:TriggerID>
                        <tnsa:InputDevice>MAS01</tnsa:InputDevice>
                        <tnsa:OutputDevice>MASOUT01</tnsa:OutputDevice>
                </tnsa:ABQHeader>
        </tnsa:ApplicationArea>
        <tnsa:DataArea>
                <tnsa:Get>
                        <tnsa:Expression>string</tnsa:Expression>
                </tnsa:Get>
                <tnsa:ABQData releaseID="string">
                        <tnsa:ABQSpecific>
                                <tnsa:Vehicle>
                                        <tns:GEPICSTrgPrimaryKey>101718664</tns:GEPICSTrgPrimaryKey>
                                        <tns:GEPICSTrgSecondaryKey>   </tns:GEPICSTrgSecondaryKey>
                                </tnsa:Vehicle>
                                <tns:BroadCastData>
                                        <tns:DataTagID>231</tns:DataTagID>
                                        <tns:DataLength>34</tns:DataLength>
                                        <tns:DataString>ADDORDER1017186643G1SE51X3AS118601</tns:DataString>
                                </tns:BroadCastData>
                        </tnsa:ABQSpecific>
                </tnsa:ABQData>
        </tnsa:DataArea>
</tnsa:GetABQData>

</responseData>
<success>true</success>
</return>
</ns2:commonServiceResponse>
</S:Body>
</S:Envelope>

I have the following vbscript called 5.vbs to read a node from the file
Set oXMLDoc = CreateObject("MSXML2.DOMDocument.4.0")
oXMLDoc.async = False
oXMLDoc.load ("response2.xml")
oXMLDoc.setProperty "SelectionLanguage", "XPath"
oXMLDoc.setProperty "SelectionNamespaces", "xmlns:S='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ns2='http://webservice.mas.gepics.ab.com' xmlns:tnsa='http://www.ab.com/ns/ABQ/ABQMessageStandard'"
WScript.Echo oXMLDoc.selectSingleNode("//S:Envelope//S:Body//ns2:commonServiceResponse//return//responseData").text

I execute  the command cscript 5.vbs and I get the following error
runtime error: Object required: 'oXMLDoc.selectSingleNode(...)'
no matter what I do I cannot select any nodes in the tnsa:GetABQData tree.
Any suggestions
Thanks in advance

A: Maybe this is not obvious, but you don't have XML there. That is HTML encoded XML. You need to decode it if you expect to parse it with the XML parser. You can use this function to decode it first:
http://psacake.com/web/func/htmldecode_function.htm
Private Function HTMLDecode(byVal encodedstring)
    Dim tmp, i
    tmp = encodedstring
    tmp = Replace( tmp, """, chr(34) )
    tmp = Replace( tmp, "<"  , chr(60) )
    tmp = Replace( tmp, ">"  , chr(62) )
    tmp = Replace( tmp, "&" , chr(38) )
    tmp = Replace( tmp, " ", chr(32) )
    For i = 1 to 255
        tmp = Replace( tmp, "&#" & i & ";", chr( i ) )
     Next
    HTMLDecode = tmp
End Function


text:
Q: How can multiple calculations be launched in parallel, while stopping them all when the first one returns? [Python] How can multiple calculations be launched in parallel, while stopping them all when the first one returns?
The application I have in mind is the following: there are multiple ways of calculating a certain value; each method takes a different amount of time depending on the function parameters; by launching calculations in parallel, the fastest calculation would automatically be "selected" each time, and the other calculations would be stopped.
Now, there are some "details" that make this question more difficult:

*

*The parameters of the function to be calculated include functions (that are calculated from data points; they are not top-level module functions).  In fact, the calculation is the convolution of two functions.  I'm not sure how such function parameters could be passed to a subprocess (they are not pickeable).

*I do not have access to all calculation codes: some calculations are done internally by Scipy (probably via Fortran or C code).  I'm not sure whether threads offer something similar to the termination signals that can be sent to processes.

Is this something that Python can do relatively easily?

A: I would look at the multiprocessing module if you haven't already.  It offers a way of offloading tasks to separate processes whilst providing you with a simple, threading like interface.
It provides the same kinds of primatives as you get in the threading module, for example, worker pools and queues for passing messages between your tasks, but it allows you to sidestep the issue of the GIL since your tasks actually run in separate processes.
The actual semantics of what you want are quite specific so I don't think there is a routine that fits the bill out-of-the-box, but you can surely knock one up.
Note: if you want to pass functions around, they cannot be bound functions since these are not pickleable, which is a requirement for sharing data between your tasks.

A: Because of the global interpreter lock you would be hard pressed to get any speedup this way.  In reality even multithreaded programs in Python only run on one core.  Thus, you would just be doing N processes at 1/N times the speed.  Even if one finished in half the time of the others you would still lose time in the big picture.

A: Processes can be started and killed trivially.
You can do this.
import subprocess
watch = []
for s in ( "process1.py", "process2.py", "process3.py" ):
    sp = subprocess.Popen( s )
    watch.append( sp )

Now you're simply waiting for one of those to finish.  When one finishes, kill the others.
import time
winner= None
while winner is None:
    time.sleep(10)
    for w in watch:
        if w.poll() is not None:
            winner= w
            break
for w in watch:
    if w.poll() is None: w.kill()

These are processes -- not threads.  No GIL considerations.  Make the operating system schedule them; that's what it does best.
Further, each process is simply a script that simply solves the problem using one of your alternative algorithms.  They're completely independent and stand-alone.  Simple to design, build and test.


text:
Q: Split text string in a data.table columns I have a script that reads in data from a CSV file into a data.table and then splits the text in one column into several new columns. I am currently using the lapply and strsplit functions to do this. Here's an example:
library("data.table")
df = data.table(PREFIX = c("A_B","A_C","A_D","B_A","B_C","B_D"),
                VALUE  = 1:6)
dt = as.data.table(df)

# split PREFIX into new columns
dt$PX = as.character(lapply(strsplit(as.character(dt$PREFIX), split="_"), "[", 1))
dt$PY = as.character(lapply(strsplit(as.character(dt$PREFIX), split="_"), "[", 2))

dt
#    PREFIX VALUE PX PY
# 1:    A_B     1  A  B
# 2:    A_C     2  A  C
# 3:    A_D     3  A  D
# 4:    B_A     4  B  A
# 5:    B_C     5  B  C
# 6:    B_D     6  B  D

In the example above the column PREFIX is split into two new columns PX and PY on the "_" character.
Even though this works just fine, I was wondering if there is a better (more efficient) way to do this using data.table. My real datasets have  >=10M+ rows, so time/memory efficiency becomes really important.

UPDATE:
Following @Frank's suggestion I created a larger test case and used the suggested commands, but the stringr::str_split_fixed takes a lot longer than the original method.
library("data.table")
library("stringr")
system.time ({
    df = data.table(PREFIX = rep(c("A_B","A_C","A_D","B_A","B_C","B_D"), 1000000),
                    VALUE  = rep(1:6, 1000000))
    dt = data.table(df)
})
#   user  system elapsed
#  0.682   0.075   0.758

system.time({ dt[, c("PX","PY") := data.table(str_split_fixed(PREFIX,"_",2))] })
#    user  system elapsed
# 738.283   3.103 741.674

rm(dt)
system.time ( {
    df = data.table(PREFIX = rep(c("A_B","A_C","A_D","B_A","B_C","B_D"), 1000000),
                     VALUE = rep(1:6, 1000000) )
    dt = as.data.table(df)
})
#    user  system elapsed
#   0.123   0.000   0.123

# split PREFIX into new columns
system.time ({
    dt$PX = as.character(lapply(strsplit(as.character(dt$PREFIX), split="_"), "[", 1))
    dt$PY = as.character(lapply(strsplit(as.character(dt$PREFIX), split="_"), "[", 2))
})
#    user  system elapsed
#  33.185   0.000  33.191

So the str_split_fixed method takes about 20X times longer.

A: Using splitstackshape package:
library(splitstackshape)
cSplit(df, splitCols = "PREFIX", sep = "_", direction = "wide", drop = FALSE)
#    PREFIX VALUE PREFIX_1 PREFIX_2
# 1:    A_B     1        A        B
# 2:    A_C     2        A        C
# 3:    A_D     3        A        D
# 4:    B_A     4        B        A
# 5:    B_C     5        B        C
# 6:    B_D     6        B        D

A: We could try:
library(data.table)
cbind(dt, fread(text = dt$PREFIX, sep = "_", header = FALSE))
    #    PREFIX VALUE V1 V2
    # 1:    A_B     1  A  B
    # 2:    A_C     2  A  C
    # 3:    A_D     3  A  D
    # 4:    B_A     4  B  A
    # 5:    B_C     5  B  C
    # 6:    B_D     6  B  D

A: With tidyr the solution is:
separate(df,col = "PREFIX",into = c("PX", "PY"), sep = "_")

A: I add answer for someone who do not use data.table v1.9.5 and also want an one line solution.
dt[, c('PX','PY') := do.call(Map, c(f = c, strsplit(PREFIX, '-'))) ]

A: Update: From version 1.9.6 (on CRAN as of Sep'15), we can use the function tstrsplit() to get the results directly (and in a much more efficient manner):
require(data.table) ## v1.9.6+
dt[, c("PX", "PY") := tstrsplit(PREFIX, "_", fixed=TRUE)]
#    PREFIX VALUE PX PY
# 1:    A_B     1  A  B
# 2:    A_C     2  A  C
# 3:    A_D     3  A  D
# 4:    B_A     4  B  A
# 5:    B_C     5  B  C
# 6:    B_D     6  B  D

tstrsplit() basically is a wrapper for transpose(strsplit()), where transpose() function, also recently implemented, transposes a list. Please see ?tstrsplit() and ?transpose() for examples.
See history for old answers.


text:
Q: How to get Transformation object from a job in pentaho through java api? I have a job with one transformation. I want to get the TransMeta or Trans object from the job and modify the same before executing the job. I am executing the job(.kjb) file through java.
I have used the following code:
JobMeta jobMeta1 = new JobMeta(filename, repo);
Job job = new Job(repo, jobMeta1);
job.setInteractive(true);
Map<JobEntryCopy,JobEntryTrans> transFromJob =  job.getActiveJobEntryTransformations();
job.start();

But the transFromJob is empty. How can I achieve that?


text:
Q: run BLDC motor WD-1465FD of LG washing machine with frequency inverter Sunfar E300-2S0022L I have a BLDC motor WD-1465FD of washing machine LG . My question is can I drive the  bldc motor (directly) with inverter Sunfar E300-2S0022L.
I tried all VFD parameters but no good results.
 It only starts on 200v but after 30 sec. starts burning.

A: No, you cannot.
The Sunfar E300-2S0022L seems to be a typical variable frequency drive for 3-phase induction motors as found in machine tools.  It varies the frequency and likely voltage of the drive to accomplish speed control, but it relies on the ability of the induced magnets in an induction motor's rotor to "slip" or migrate through the iron, in order to achieve (near) synchronization of the loaded rotor with the drive frequency.
In contrast, the motor from a WD-1465FD actually is a 3-phase permanent magnet motor as you claim.  The use of these in appliances is a newer idea, but with drive electronics becomes possible.
Notably, PMDC motors cannot "slip" because rather than being induced poles which can migrate, their permanent magnets are attached at specific points on the rotor.  Instead, the driver must detect the position of the magnets on the rotor to calculate the proper waveform phase.  At high speeds, this can be done by detecting back EMF from the coils as the magnet poles pass, and a driver for something like an airplane propeller that prevents very little torque load at low speed can even get a motor started with an open loop algorithm to the point of moving enough for the back EMF detection to "find" the rotor.
But a motor that runs at low speed, and that needs to startup with torque to move a big drum full of wet clothes needs a more reliable way to measure rotor position at low speeds.  Your motor does this with what look to be an array of 3 sensors which detect the permanent magnets in the rotor - so in addition to the 3-lead power connection to the driver, it has another multi-lead connection for the sensors.

(WD-1465FD motor's stator, image from parts supplier http://www.europart.nl/a/lg-motor-4417ea1002g-wd1485-wd1465fd-06346020)
You cannot drive this PMDC motor with a driver meant for Induction Motors - the control algorithm is wrong, and there's no input for the sensors to inform a control algorithms estimate of rotor position.  You may have gotten it to run a little - unloaded and spun up somehow it might loaf along open loop.  But it won't have useful torque and can easily lose synchronization and merely vibrate, and/or enter faults where it pulls excessive current as no meaningful back EMF is being generated to oppose the voltages applied in expectation of a overcoming the high back EMF of the expected high rotation rate.
You might be able to drive the motor "crudely" with a "sensored" BLDC driver meant for electric bicycle hub motors or something like that, but really the best driver is the one in the washing machine, as that has been engineered and tuned to the specific motor.

A: EDIT    Short Answer: maybe
Hopefully you know more about motors, than this guy who was eventually successful.
After reviewing some Youtube Videos on the Sunfar E300-2S0022L with Mach3 CNC software, It has the acceleration software variables that allow you to optimize the torque to your expected load to accelerate to full speed.  Being a 3 phase VFD , you can power it with 220Vac(and others) split single-phase or 3 Phase input and it converts to DC then 3 Phase AC for the motor while increasing V with RPM of the motor according to the constants applied in Mach 3 software for number of poles, Max V, max RPM and Acceleration Time (seconds).  Then you can control the RPM directly with screen software settings and much more.

 Note the limitations of open loop  vs closed Loop with encoder or Hall sensors for V/F control to prevent saturation of core yet maximize torque.
(not necessarily to scale)
Looks like a very good budget solution.
end edit

Info:
Smart VFD Inverter rated 2.2kW 220V 3ph motor delta induction motor using carrier 1.5~12kHz and commutation rate of 0.1Hz to 1kHz with 20% boost option and variable ramp and V/F ratios.
LG draws 2.1kW 1ph 220V, with integrated driver.
Choosing proper driver requires scoping motor power and Hall pole sensor signals.
I was assuming he was powering the entire unit. But if not, and  attempting to convert  a BLDC to a VFD drive motor, you may need to include commutation feedback.

Note 5 pin power and 3 pin index sensor.
The motor runs from 0 to 50 RPM then in spin mode 600 RPM to 1400 RPM
There are 36 poles or 18 pole pairs or 6pairs per phase thus 50 RPM = 50RPM/60s*6p= 5Hz and 1400RPM= 1400rpm/60s*6p= 140Hz.
Did you try V/F settings for 0~2V/Hz assuming 280Vac@140Hz is what you can measure to verify?
I  now expect  5 pin sensor for 3 phase Hall sense and DC using 1 pole sense for all 6 poles.
Did you assume  motor was BLDC but is actually Induction Motor and not Variable Reluctance Motor.  Sensorless control requires more work with Vector current sense.
Expand your question to cover all unknowns.
I have never used either of these parts, but I would scope the LG power and sensor signals and add to question before trying to drive externally then you can compare with Sunfar E300 output.


text:
Q: Suggested practice for storing a lot of user uploaded files? I 'm looking a scalable way to store a lot of files from users. My strategy is to save them with a random name and save the name and file relationships in the database.
My question is what 's a suggested practice for storing the files on disk? One limitation I 've faced is that if I save them all in one directory, the OS performance degrade which is a no,no.
Obviously I can create directories at specified intevals and split the load but that 's just a hack and I 'm sure there must be tried and true procedures to deal with storage. I just can't seem to find them :)
I'm looking to host the files privately and not on an external storage like S3.

A: As you already give each file a random name, chop it into subdirectories.
Let's say there is a random name:
$randomName = 'Akj823daosd03hdx';

Save it to:
/Ak/j8/23/daosd03hdx

This will limit the number of nodes in each directory. If you have a good random distribution, this should be equally distributed.
Depending on how many files you have you can also distribute those differently, but with random names its normally straight forward in such a manner. You can vary with the length and number of subdirectory and final file names depending on your needs.


text:
Q: Universal link no redirection on iOS13 I am working on universal link of my app, which works fine before iOS13,
but after my phone into iOS13, the link don't work anymore and redirect me into the exact url in safari (e.g. https://testDomain.com/?yyy=zzz) and no 'Open in xxx' option provided.
I checked the sysdiagnose file and i found the below result for my app:
Service:              applinks
App ID:               397ETSW7L9.com.xxxxxxx
App Version:          0.2
Domain:               testDomain.com
User Approval:        unspecified
Site/Fmwk Approval:   unspecified
Flags:                updating
Last Checked:         2019-10-13 07:29:47 +0000
Next Check:           2019-10-13 11:11:19 +0000
Error:                Error Domain=SWCErrorDomain Code=100 "Disallowed trust result type." UserInfo={Line=174, Function=-[SWCSecurityGuard verifyTrust:error:], NSDebugDescription=Disallowed trust result type., TrustResultType=5}
Retries:              1

It keeps in "updating" 'Flags', and "unspecified" for 'Site/Fmwk Approval', and no 'Pattern' field which is abnormal i assumed?
Anyone has the same issue on iOS13? (especially 13.1.2)

A: I have same problem and I think it's ios13.1.2 bug or spec.
Sometimes works well and other devices work as well.
Each device and OS version shows a very different status.
In failure case, Ios  didn't call AASA url  after reinstalling the app.
I guess that the rules of calling the AASA url have changed on ios13.1.2.