text:
Q: Is it possible to set the DataContext through a trigger in xaml? I'm trying to set the Data Context of a parent StackPanel depending on a boolean value.
I have a boolean value named IsProductMode.
private bool isProductMode;
public bool IsProductMode
{
    get { return isProductMode; }
    set { isProductMode = value; RaisePropertyChange("IsProductMode"); }
}

I wanted said boolean to toggle the DataContext of a StackPanel and either bind them to my EditFormSelectedProduct or EditFormSelectedService that both has the property Name being bound to the Stack Panel's child TextBox's text.
<StackPanel>
   <Label Content="Name" />
   <TextBox Text="{Binding Name}" />
   <StackPanel.Style>
       <Style TargetType="{x:Type StackPanel}">
           <Setter Property="DataContext" Value="{Binding EditFormSelectedProduct}"/>
           <Style.Triggers>
               <DataTrigger Binding="{Binding IsProductMode}" Value="False">
                   <Setter Property="DataContext" Value="{Binding EditFormSelectedService}"/>
               </DataTrigger>
           </Style.Triggers>
       </Style>
   </StackPanel.Style>
</StackPanel>

What I've Tried:
I've tried removing the trigger and tried setting the Data Context first to EditFormSelectedProduct and then EditFormSelectedService. The results were that the TextBox displayed the correct Name values depending on its Data Context. So at the very least, I proved that the sources were indeed populated and that their bindings work.
For now I've temporarily settled on having two Stack Panels, each with their own appropriate Data Context and set their visibilities depending on IsProductMode.
What I expected:
I expected it to set the appropriate Data Context depending on the boolean value but it keeps on being set to EditFormSelectedProduct regardless of the boolean's value.


text:
Q: absolute value in cplex c++ I have to use absolute value in the cost function of some linear problem.
Part that bother me like this
for (t=0;t<T;t++)
   for (i=0;i<I; i++){
     for (j=1;j<J; j++)
       Sum += |x[i][j][t]-x[i][j][t-1]|*L/2;
     Sum += |x[i][0][t]-x[i][0][t-1]|*V/2;
   }

I am writing my code in c++ and I don't know how to implement absolute value. x is integer value.
I have tried with cplex.getValue(x[i][j][t])-cplex.getValue(x[i][j][t-1]) >0 but it couldn't work.

A: Since the absolute value function is nonlinear ( the reason is explained in this math question ) you need to linearize the objective function first.
Basically, you need to express each absolute-valued-term of that summation with a new variable and optimize the sum of these new variables (subject to some additional constraints). The method is explained in detail in Section 7.2 of Linear Programming textbook of Thomas S. Ferguson.

redpajama_set_name: RedPajamaStackExchange


text:
Q: gradle javadoc fail on UTF-8 chars, only on windows So i have a gradle based java project, with tons of hungarian docs string, witch mean a lot of non ASCII character.
It's perfectly fine since javac consume utf-8 characters in source code,and javadoc also should according to my knowledge.
In the build gradle has a task which create the java doc jar
task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}

artifacts {
    archives sourcesJar
    archives javadocJar
}

When i run gradle build, it's fail with the following error:

:compileJava
  C:\Home\Projects\InventoryCore\src\main\java\hu\rfit\inventory\models\entities\ItemState.java:11:
  error: unmappable character for encoding Cp1252  * ├?ru / term├⌐k
  állapot.
      ^ :processResources UP-TO-DATE :classes :jar :javadoc C:\Home\Projects\InventoryCore\src\main\java\hu\rfit\inventory\models\entities\ItemState.java:11:
  error: unmappable character for encoding Cp1252  * ├?ru / term├⌐k
  állapot.
      ^ 1 error :javadoc FAILED
FAILURE: Build failed with an exception.
  What went wrong:
  Execution failed for task ':javadoc'.
  Javadoc generation failed. Generated Javadoc options file (useful for troubleshooting): 'C:\Home\Projects\InventoryCore\build\tmp\javadoc\javadoc.options'

The best part is it's running perfectly in build pipeline, and on my other os (ubuntu 16.04 lts) it's fail only on windows.
I have already tried a fresh clone of the git repo, updated the the java jdk to the newest(oracle jdk 1.8.0_131 before was a _73 and _111 tried both).
All the files in the project are utf-8 encoded, and also tried put javadoc setting into my build.gradle file,
javadoc {
    options.charSet = 'UTF-8'
}

A: I suspect you want
options.encoding = 'UTF-8'

That would fit with the javadoc help text of:
-encoding <name>                 Source file encoding name

... whereas charSet appears to affect the output. (I'd hope it would default to UTF-8 already..)


text:
Q: Is there a way to log found values in Detox? I'm trying to debug some Detox tests, I've got some assertions like the following:
await expect(eventScreenMatcher.component).toExist();
await expect(eventScreenMatcher.toggleButton).toExist();
await expect(eventScreenMatcher.toggleButton).toHaveText('Add to schedule');

The button that I believe is the toggleButton is on screen and has the correct text Add to schedule. But Detox is failing on that last assertion.
How does Detox determine what the text is (does it just check that element) and is there a way to log what it thinks is there?
This is the output I currently get:

Expected: (with text: is "Add to schedule" and view has effective visibility=VISIBLE)
Got: "ReactViewGroup{id=4605, visibility=VISIBLE, width=1300, height=139, has-focus=false, has-focusable=true, has-window-focus=true, is-clickable=true, is-enabled=true, is-focused=false, is-focusable=true, is-layout-requested=false, is-selected=false, layout-params=android.view.ViewGroup$LayoutParams@34f98eb, tag=ToggleScheduleButton, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}

A: Have you tried using the 'getAttributes()' method? It can be a little tricky sometimes but I think it would help solve your problem.
https://wix.github.io/Detox/docs/api/actions-on-element/#getattributes
Then you could try something like
const buttonAttributes = await eventScreenMatcher.toggleButton.getAttributes();

await jestExpect(buttonAttributes.text).toBe('Add to Schedule');


text:
Q: Gatsby - Cannot read property 'childImageSharp' of null I'm getting this error even my query giving me a proper results in GraphQL Explorer.
I'm trying to load cover images for articles, but I can't see where is error.
There is a lot blog posts and same questions, but I didn't found right answer which would fix this error.
Error: TypeError: Cannot read property 'childImageSharp' of null
This is what I've tried so far:
Mdx

    ---
    title: Hello World - from mdx!
    date: 2019-06-01
    published: true
    tags: ['react', 'javascript']
    ---

Gatsby Component
const Blog = ({ data }) => {
  const tags = data.allMdx.group
  const posts = data.allMdx.nodes

  return (
    <Layout>

Blog

              Thoughts about programming, design and random stuff

              {tags.map(tag => (
                <Link
                  to={`/tags/${kebabCase(tag.fieldValue)}/`}
                  className="tag is light"
                >
                  {tag.fieldValue}
                </Link>
              ))}

            {posts.map(({ id, excerpt, frontmatter, fields }) => (
              <Link to={fields.slug}>

                      <time className="home-red">{frontmatter.date}</time>

{frontmatter.title}

{excerpt}

                        {fields.readingTime.text}

              </Link>
            ))}

    </Layout>
  )
}

Query
export const query = graphql`
  query SITE_INDEX_QUERY {
    allMdx(
      sort: { fields: [frontmatter___date], order: DESC }
      filter: { frontmatter: { published: { eq: true } } }
    ) {
      group(field: frontmatter___tags) {
        fieldValue
      }
      nodes {
        id
        excerpt(pruneLength: 100)
        frontmatter {
          tags
          title
          date(formatString: "MM/DD/YYYY")
          cover {
            publicURL
            childImageSharp {
              fluid(maxWidth: 2000, traceSVG: { color: "#639" }) {
                tracedSVG
              }
            }
          }
        }
        fields {
          slug
          readingTime {
            text
          }
        }
      }
    }
  }
`

gatsby-config.js
module.exports = {
  siteMetadata: {
    title: `Lorem Ipsum Blog`,
    description: `Lorem ipsum.`,
  },
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/images`,
        name: `images`,
      },
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/posts`,
        name: `posts`,
      },
    },
    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        extensions: [`.mdx`, `.md`],
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-images`,
            options: {
              maxWidth: 630,
            },
          },
        ],
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    `gatsby-plugin-sass`,
    `gatsby-plugin-dark-mode`,
    `gatsby-plugin-feed`,
    `gatsby-remark-reading-time`,
  ],
}

Thanks in advance

A: According to your MDX:
---
title: Hello World - from mdx!
date: 2019-06-01
published: true
tags: ['react', 'javascript']
---

You don't have cover image in all posts, so at the moment you are requesting for frontmatter.cover.childImageSharp.fluid your code is breaking. Add a simple condition at:
  const tags = data.allMdx.group
  const posts = data.allMdx.nodes

  return (
    <Layout>

Blog

              Thoughts about programming, design and random stuff

              {tags.map(tag => (
                <Link
                  to={`/tags/${kebabCase(tag.fieldValue)}/`}
                  className="tag is light"
                >
                  {tag.fieldValue}
                </Link>
              ))}

            {posts.map(({ id, excerpt, frontmatter, fields }) => (
              <Link to={fields.slug}>

                  {frontmatter.cover &&  }

                      <time className="home-red">{frontmatter.date}</time>

{frontmatter.title}

{excerpt}

                        {fields.readingTime.text}

              </Link>
            ))}

    </Layout>
  )
}

Basically, if the looped post doesn't come with frontmatter.cover, don't print the image.
  {frontmatter.cover &&  }

If you've added the Babel plugin for optional chaining from new ECMAScript you can simplify it by:

Keep in mind cleaning cache with gatsby clean in the meantime.

A: Strange answer but with gatsby clean I've managed to solve this issue.


text:
Q: apt install package that depends on other package, but alternate is installed I am trying to install subuser, but it depends on docker.io.
subuser : Depends: docker.io but it is not going to be installed

However I have docker-ce installed.
I created a deb package using equiv-control
Section: local
Priority: optional
Package: my-docker-dependencies
Version: 1.0
Maintainer: ctrl-alt-delor
Depends:  docker-ce
Provides: docker.io
Description: docker

But I get a conflict
Breaks existing package 'docker-ce' that conflict: 'docker.io'. But the 'my-docker-dependencies_1.0_all.deb' provides it via: 'docker.io' (docker-ce is already installed).
This conflict makes sense, but I don't know how to fix things so that I can install subuser.
How can I install subuser with docker-ce, but not docker.io?

A: docker-ce itself conflicts with docker.io, so I don't think there's a way to make this work by adding another package which provides docker.io.
I suspect the only way to install subuser with docker-ce is to rebuild subuser with an alternative dependency:
Depends: ${misc:Depends}, ${sphinxdoc:Depends}, ${python3:Depends}, python3-pkg-resources, git, docker.io | docker-ce

The full recipe would be
apt source subuser
cd subuser-*
sed -i 's/Depends:.*/& | docker-ce/' debian/control
dch -n "Allow docker-ce instead of docker.io."
dch -r ignored
dpkg-buildpackage -us -uc


text:
Q: Accessing Mutidimension knockout array where dimension is known at runtime using javascript I have a situation where i need to access to multidimension knockout
array with coordinates not known until runtime.
Possible knockout arrays (it can be any one of those not known until runtime)
self.customers[0]
self.customers[0][0]
self.customers[0][0][0]
self.customers[0][0][0][0]
self.customers[0][0][0][0][0]

I have a code which give me array combination in a string literal like below
level = "[0]"
level = "[0][0]"
level = "[0][0][0]"
level = "[0][0][0][0]"
level = "[0][0][0][0][0]"

evaluating the value in array in the below fashion
  arr = arr.concat(eval('self.customers()' + level));

I know this works and it's a bad way. JSlint says "eval is evil"
> Is there a better way to access array self.customers()[i][j[k]... where i,j,k... can be built at runtime

A: You could create a helper function which returns the correct level based on the input. Something like this
var getLevel = function (arr, levels) {
    var retArr = arr();
    while(levels) {
        try {
            var currLvl = parseInt(levels.substring(1,2)); //get first level
            if (retArr) {
                retArr = retArr[currLvl]; //navigate to given level
            } else {
                //what happens if the array doesn't have enough levels?
            }
            levels = levels.substring(3); // go to next level
        } catch (ex) {
            console.log(ex);
            //what should happen if the levels string has a wrong format?
        }
    }

    return retArr;
}

Of course, you should also define what needs to happen when the input isn't valid or it's undefined.
You would then call this method as such : getLevel(self.customers, level);, thus avoiding eval :)

A: This is not really a Knockout-related question. In any case, there are several ways to solve this without using eval, some more clever than others. Here's a straightforward (though not necessarily the most elegant) way to do it.
Suppose:
var self = {
    customers: [[[1],[[2,3,4],5]],[6],[7,[8,9]]]
};

var level = "[0][1][0][2]";

Expected output would be "4". Now first find the levels, e.g. using a regex:
var myLevels = level.match(/\d+/g);

And use a recursive function to traverse the into the multi-dimensional array:
function multiDimensionFind(data, levels) {
    var result = data[levels[0]];
    if (result instanceof Array) {
        levels.splice(0, 1);
        return multiDimensionFind(result, levels);
    }
    return result;
}

var x = multiDimensionFind(self.customers, myLevels);

See this fiddle to see it in action.
PS. I'd rethink your design ;-)


text:
Q: React Native: How to display: 'none' a specific button in flatlist I'm making a flatlist that has a delete button inside each data. I want to show a data's name outside the flatlist and do the display: 'none' the button only for that line of the list to disable the delete button. Any way I can do this?
My renderItem code:
//----------------Render flatlist------------------
function renderItem({ item }) {

    return (
        <View style={styles.renderBox}>
            <Text numberOfLines={1} style={{ width: 230, fontSize: 17, fontWeight: 'bold' }} > {'=> '} {item.certificateName}</Text>
            <View style={{ flexDirection: 'row' }}>
                <TouchableOpacity onPress={() => changeCertification(item.id)} >
                    <Icon name='check-circle' size={40} />
                </TouchableOpacity>
                <Text>  </Text>
                <TouchableOpacity onPress={() => DeleteCertificate(item.id)} >
                    <Icon name='times-circle' size={40} />
                </TouchableOpacity>
            </View>
        </View>
    )
}

the display of my flatlist: image

A: Assume that an item can have a prop called isHidden (or something like that). In renderItem add a conditional to check isHidden isnt true:
function renderItem({ item }) {
    if(item.isHidden)
    // return empty view
    return <View />
    return (
        <View style={styles.renderBox}>
            <Text numberOfLines={1} style={{ width: 230, fontSize: 17, fontWeight: 'bold' }} > {'=> '} {item.certificateName}</Text>
            <View style={{ flexDirection: 'row' }}>
                <TouchableOpacity onPress={() => changeCertification(item.id)} >
                    <Icon name='check-circle' size={40} />
                </TouchableOpacity>
                <Text>  </Text>
                <TouchableOpacity onPress={() => DeleteCertificate(item.id)} >
                    <Icon name='times-circle' size={40} />
                </TouchableOpacity>
            </View>
        </View>
    )
}

in DeleteCertificate you would update your list to an item having isHidden
function DeleteCerticate(id){
   //...
  //im assuming your list is name DATA
  const ixToHide = DATA.findIndex(item=>item.id == id)
  if(ixToHide >= 0)
    DATA[ixToHide].isHidden = true
}


text:
Q: Cadastro infinito de cliente Estou estudando Python e resolvi criar um pequeno programa de cadastro via terminal, mas não consigo fazer um loop que passe por todas as opções, o programa fica interminavelmente no cadastro de cliente.
Segue código:
#cadastro de cliente em programacao procedural

clientes = []
n_clientes = 1

def menu() :
    option = int(input('''
[1] - Cadastrar cliente
[2] - Consultar Clientes
[3] - Editar Cliente
[4] - Sair do programa
'''))

    return option

def cadastra_cliente() :
    cliente_nome = input('Digite o nome do cliente: ')
    cliente_cep = input('Digite o cep do cliente: ')
    cliente_telefone = input('Digite o telefone do cliente: ')
    clientes_dados = (cliente_nome,cliente_cep,cliente_telefone)
    clientes.append(clientes_dados)
    print(clientes)
    print('Cliente adicionado')

def mostrar_cliente() :
    print(f'''
    Nome: {clientes[0]}
    Cep: {clientes[1]}
    Telefone: {Clientes[2]}''')

def programa() :

    option = menu()
    while True:
        if option == 1 :
            cadastra_cliente()
        if option == 2 :
            mostrar_cliente()
programa()

Poderiam me ajudar? Eu consegui fazer isso em Java uma vez com do {} while, mas não consigo fazer no Python.

Mais uma dúvida somente!
NO java quando fiz um programa similar, para alterar o cadastro eu tinha a seguinte estrutura.
public static void editarCadastro() {
    System.out.print("Informe o codigo que gostaria de atualizar: \n");
    int posicaoPessoa = Entrada.leiaInt();
    String pessoa[] = listaDePessoas.get(posicaoPessoa);

    if (pessoa != null) {
        System.out.println("Nome: '" + pessoa[0] + "'");
        pessoa[0] = Entrada.leiaString();
        System.out.println("CEP: '" + pessoa[1] + "'");
        pessoa[1] = Entrada.leiaString();
        System.out.println("Endereço : '" + pessoa[2] + "'");
        pessoa[2] = Entrada.leiaString();
        System.out.println("E-mail: '" + pessoa[3] + "'");
        pessoa[3] = Entrada.leiaString();
        System.out.println("Telefone: '" + pessoa[4] + "'");
        pessoa[4] = Entrada.leiaString();

        System.out.println("Pessoa atualizada");
    } else {
        System.out.println("Pessoa não encontrada");
    }
}

Eu ando com bastante dificuldade pra trabalhar com arrays no python, teria algumas dicas de como eu poderia fazer algo do tipo só que em python?

A: Isso ocorre, pois depois da primeira vez que o usuário escolhe a opção do menu, a variável option não tem mais o seu valor alterado, e você está dentro de um while True.
Uma correção simples, seria colocar o trecho que solicita a opção de menu ao usuário dentro do while True:
while True:
    option = menu()

Com isso, o programa passaria a questionar o usuário novamente, permitindo assim escolher uma outra opção.
Então para sair do programa, você deverá implementar uma condição para a opção 4, permitindo assim sair do loop, algo mais ou menos assim:
while True:
    option = menu()

    if option == 1 :
        cadastra_cliente()
    if option == 2 :
        mostrar_cliente()
    if option == 4 :
      break

Veja que agora, além de sempre perguntar ao usuário qual opção ele deseja, existe uma condição que faz o break para sair do loop e assim finalizar o programa.

O código completo ficaria mais ou menos da seguinte forma:
#cadastro de cliente em programacao procedural

clientes = []
n_clientes = 1

def menu() :
    option = int(input('''
[1] - Cadastrar cliente
[2] - Consultar Clientes
[3] - Editar Cliente
[4] - Sair do programa
'''))

    return option

def cadastra_cliente() :
    cliente_nome = input('Digite o nome do cliente: ')
    cliente_cep = input('Digite o cep do cliente: ')
    cliente_telefone = input('Digite o telefone do cliente: ')
    clientes_dados = (cliente_nome,cliente_cep,cliente_telefone)
    clientes.append(clientes_dados)
    print(clientes)
    print('Cliente adicionado')

def mostrar_cliente() :
    for cliente in clientes:
      print(f'''
      Nome: {cliente[0]}
      Cep: {cliente[1]}
      Telefone: {cliente[2]}''')

def programa() :

    while True:
        option = menu()

        if option == 1 :
            cadastra_cliente()
        if option == 2 :
            mostrar_cliente()
        if option == 4 :
          break

programa()

Obs.: Eu fiz uma pequena alteração na função mostrar_cliente, ela estava gerando exceção, criei um loop simples, para iterar na variável clientes e assim exibir todos os clientes no console.

Veja online: https://repl.it/repls/PlainGoldenrodProgram


text:
Q: jQuery Multiple Selector with split I have this row with two 's with classes messageROW and titleROW following a checkbox with the ID of 'activecd'. I'm trying to change the bg color of both messageROW and titleROW (the whole row) when the checkbox is toggled but instead titleROW only changes colors.
Any suggestions?
$('[id^=activecd]').change(function(){
    $('.messageROW,.titleROW'+$(this).prop('id').split('activecd')[1]).closest('td').toggleClass('colorcode', this);
});

HTML:

     <input id="activecd">

A: I'd suggest the following, albeit untested:
$('[id^=activecd]').change(function(){
    $(this).closest('tr').toggleClass('colorcode', this.checked);
});

This listens for the change event on the specified element(s), finds the closest tr element and adds the colorcode class if the checkbox is checked, and removes the class if not.

A: Try jQuery $().add(selector), $().toggleClass("bgOn") with css

Not clear question, I think.
<button onclick="someFunction(this)">Toggle color</button>

function someFunction(this){
  var $this=$(this);
  $this.parent().find(".messageROW,.titleROW").toggleClass("bgOn");
  // or
  $this.parent().parent().find("tr>td:first-child, tr>td:nth-child(2)").toggleClass("bgOn");
}

might help you.


text:
Q: Can ApacheDS LDAP change root user name? ApacheDS 1.5 has the following account by default.
Bind dn or user: uid=admin,ou=system
Bind password: secret
i would like to change it to the following to avoid making changes in my code
Bind dn or user: cn=root,dc=ldap,dc=local
Bind password: secret
I figured out how to switch dc=example,dc=com to dc=ldap,dc=local and i imported my LDIF backup successfully. I just can't use my old connection string. I was using openldap before.
There isn't any config in the example instance that specify uid=admin,ou=system as the administrator, so i am stucked.
Please help, Thanks in advance.


text:
Q: R How to select an observation from a data frame which is False and has the min value I have a data frame with three columns and i would like to select the observation that has the value FALSE in the column TEST and also has the minimum value at the Power column. I tried  which(kolibri[ ,"TEST"] == FALSE) && which(kolibri[ , "Power"] == min(kolibri[ , "Power"]))but no luck it returns TRUE but i want the index of the observation. My data frame is like this:
Variable_Name Power TEST
  A             2    true
  B             45   false
  C             33   false
  D             25   false
  E             15   true

in this case i want to have the index of the variable D

A: If your data.frame is df:
with(df, by(Power,TEST, FUN=min)['false'])
#false
#   25

If you want the full line:
with(df, df[Power==by(Power,TEST, FUN=min)['false'],])
#  Variable_Name Power  TEST
#4             D    25 false

If you want the index:
which.max(with(df, Power==by(Power,TEST, FUN=min)['false']))
#[1] 4

If you have FALSE and TRUE in your data.frame TEST column:
which.max(with(df, Power==min(Power[!TEST])))
#[1] 4

A: If TEST is not a boolean: transform it
kolibri$TEST <- as.logical(kolibri$TEST)

Then put everything in a call to which (used 25 as your other data are unavailable here)
   > which(kolibri$TEST == FALSE & kolibri$Power== 25)
[1] 4

Using OP's own example (which I cannot run on my machine), code would be:
which(kolibri$TEST == FALSE & kolibri$Power== min(fevgeis1$Power))


text:
Q: Can I select an element that finish with "string_ID"? On server side, I generate some div with these IDS, for example :

Hello

my name is

Marco

so, on client side, Id like to select these IDS checking the last part of the ID (that is fixed, can't change, _localita_UNIQUEID). Such as :
var myID = "80";
$('# HERE THE SELECTOR I NEED _localita_'+myID).hide();

is there a fast way?

A: Use ends with selector: http://api.jquery.com/attribute-ends-with-selector/
Try this:
var myID = "80";
$('div[id$="localita_'+myID + '"]').hide();

Update:
@raina77ow 's comment made me dig more and here's an alternatives to make it better.
(Refer to the excellent post on this: http://encosia.com/11-keystrokes-that-made-my-jquery-selector-run-10x-faster/)
Give a class name to the divs (e.g: "endswith") you need to query by ends with and then use this version to make it perform better:
var myID = "80";
$('div.endswith[id$="localita_'+myID + '"]').hide();

A: Yes, you can, try this:
$('div [id*=\"_Example_localita_\"+ myid]).hide();


text:
Q: " AttributeError: 'list' object has no attribute 'replace " Error. Fix: Use a basic for loop to replace all letters Its a hangman game and I know it isn't done, but I'm stuck on this error
I'm getting the error AttributeError: 'list' object has no attribute 'replace'
the code:
import random
word_list_easy = ["word", "apple", "banana", "cheese"]
difficulty = str(input("Please enter difficulty: Easy, Medium or Hard. "))
difficulty = difficulty.upper()
empty = ("")
if difficulty == ("EASY"):
    maximum = len(word_list_easy)
    maximum = maximum - 1
    #makes a random variable that cant excede the length of the list
    random = random.randint(0,maximum)
    random_word = word_list_easy[random]
    #chooses a random word in the list
    word_length = len(random_word)
    guessed_letters = ['_'] * word_length
    print('  ' + ' '.join (guessed_letters))
    print("There are ", word_length ,"letters in the word")
    #sets how many tries you get. (later will make graphical)
    tries = 5
    while tries >= 1:
        #will repeat untill out of tries
        guessed_letter = input("Enter your guess of the letter ")
        while len(guessed_letter) > 1:
                  guessed_letter = input("Enter one letter that you think is in the word ")
        while (guessed_letter) == (""):
            guessed_letter = input("Please enter a letter ")
                  #if the letter is in the word
        new_random_word = random_word.replace(guessed_letter, empty)
        if (guessed_letter) in (random_word):
            print("You guessed correctly")
            #find the length of the new word to repeat the "_" lines for length of new word
            for index in range (word_length):
                if guessed_letter == random_word [index]:
                    guessed_letters[index] = guessed_letter
            print (" " + " ".join (guessed_letters))
        else:
            print("Sorry but your guess was wrong ")
            tries = tries - 1
            print("You have",tries," tries left")
            print (guessed_letters)
        check_word = guessed_letters.replace(" ", "")
        if check_word == random_word:
            print("Congratulations, you managed to complete the word. Maybe try a higher difficulty next time ")

what does this mean and what am I doing wrong and how to fix it. The replace() method is From the end the third line.

A: There's nothing built-in method for replacement in lists, but it's just a loop to do the replacement, check it, maybe worked for you:
check_word = [x.strip() for x in guessed_letters]
check_word = "".join(check_word)


text:
Q: Add combobox to horizontal header in QTableWidget I want to create a table in PyQt5 that has a combobox in each column header. When I try to do it, the following error is returned:
TypeError: setHorizontalHeaderItem(self, int, QTableWidgetItem): argument 2 has unexpected type 'QComboBox'
Apparently the function setHorizontalHeaderItem() doesn't accept widgets as items. So is there a way to achieve this? If not, I would settle with putting the comboboxes above the headers, but they should be aligned with the size of each column, even if the user changes the width with the mouse. I don't know if this is possible either.
My code:
from PyQt5 import QtWidgets
import numpy as np

class App(QtWidgets.QWidget):
    def __init__(self):
        super(App,self).__init__()
        self.data = np.random.rand(5,5)
        self.createTable()
        self.layout = QtWidgets.QVBoxLayout()
        self.layout.addWidget(self.table)
        self.setLayout(self.layout)
        self.showMaximized()

    def createTable(self):
        self.header = []
        self.table = QtWidgets.QTableWidget(len(self.data), len(self.data[0]))
        for i in range(len(self.data[0])):
            self.header.append(QtWidgets.QComboBox())
            self.header[-1].addItem('Variable')
            self.header[-1].addItem('Timestamp')
            self.table.setHorizontalHeaderItem(i,self.header[-1])
        for i in range(len(self.data)):
            for j in range(len(self.data[0])):
                self.table.setItem(i,j,QtWidgets.QTableWidgetItem(str(self.data[i][j])))

if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    ex = App()
    app.exec_()

A: QHeaderView does not support widgets as items so you must create a custom header as I show below:
from PyQt5 import QtCore, QtWidgets
import numpy as np

class HorizontalHeader(QtWidgets.QHeaderView):
    def __init__(self, values, parent=None):
        super(HorizontalHeader, self).__init__(QtCore.Qt.Horizontal, parent)
        self.setSectionsMovable(True)
        self.comboboxes = []
        self.sectionResized.connect(self.handleSectionResized)
        self.sectionMoved.connect(self.handleSectionMoved)

    def showEvent(self, event):
        for i in range(self.count()):
            if i < len(self.comboboxes):
                combo = self.comboboxes[i]
                combo.clear()
                combo.addItems(["Variable", "Timestamp"])
            else:
                combo = QtWidgets.QComboBox(self)
                combo.addItems(["Variable", "Timestamp"])
                self.comboboxes.append(combo)

            combo.setGeometry(self.sectionViewportPosition(i), 0, self.sectionSize(i)-4, self.height())
            combo.show()

        if len(self.comboboxes) > self.count():
            for i in range(self.count(), len(self.comboboxes)):
                self.comboboxes[i].deleteLater()

        super(HorizontalHeader, self).showEvent(event)

    def handleSectionResized(self, i):
        for i in range(self.count()):
            j = self.visualIndex(i)
            logical = self.logicalIndex(j)
            self.comboboxes[i].setGeometry(self.sectionViewportPosition(logical), 0, self.sectionSize(logical)-4, self.height())

    def handleSectionMoved(self, i, oldVisualIndex, newVisualIndex):
        for i in range(min(oldVisualIndex, newVisualIndex), self.count()):
            logical = self.logicalIndex(i)
            self.comboboxes[i].setGeometry(self.ectionViewportPosition(logical), 0, self.sectionSize(logical) - 5, height())

    def fixComboPositions(self):
        for i in range(self.count()):
            self.comboboxes[i].setGeometry(self.sectionViewportPosition(i), 0, self.sectionSize(i) - 5, self.height())

class TableWidget(QtWidgets.QTableWidget):
    def __init__(self, *args, **kwargs):
        super(TableWidget, self).__init__(*args, **kwargs)
        header = HorizontalHeader(self)
        self.setHorizontalHeader(header)

    def scrollContentsBy(self, dx, dy):
        super(TableWidget, self).scrollContentsBy(dx, dy)
        if dx != 0:
            self.horizontalHeader().fixComboPositions()

class App(QtWidgets.QWidget):
    def __init__(self):
        super(App,self).__init__()
        self.data = np.random.rand(10, 10)
        self.createTable()
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.table)
        self.showMaximized()

    def createTable(self):
        self.header = []
        self.table = TableWidget(*self.data.shape)
        for i, row_values in enumerate(self.data):
            for j, value in enumerate(row_values):
                self.table.setItem(i, j, QtWidgets.QTableWidgetItem(str(value)))

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())


text:
Q: Express will Properly set CORS on localhost, but not on live server I've tried a couple of things, and they both work on my localhost (headers are present and correct), but not on the live server , which is amazon hosted, built from a bitnami NodeJS image behind an apache reverse proxy.
Configurations I've tried:
1) Set response header manually for each route necessary (so this code was in a routing file):
router.options('/:var1/:var2', function(req, res) {
    res.setHeader("Access-control-allow-origin", "*");
    var db = req.db;
    var data = db.get('data');
    actions.find({"criteria":req.params.var1}, function(err, docs)
    {
            res.send(docs);
    });
});

2) Use middleware from NPM (this code is in app.js):
//Includes/Requirements
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongodb = require('mongodb');
var monk = require('monk');
var cors = require('cors');
var db = monk('localhost:27017/app');

...

app.use(cors());

So using both of these techniques requests to localhost:3000 result in the expected headers (Access-allow-control-origin:*). However, when I push the code to my live server, those headers are not present in the responses.
Any ideas?

A: I have solved it using cors module .
var cors = require('cors');
app.use(cors()); // add this line at appropriate place in your code

then add app.options('*', cors()); before all the route is defined or included in server.js/app.js file


text:
Q: How to prevent extension installation problems with compilation mode enabling I have the extension which is listening to core_layout_block_create_after event.
It could be any event which is firing in magento admin.
Also I have magento instance with compiler mode enabled.
I installed the extension through magentoconnect. Installation was successful and cache was cleaned.
Now, after returning back to admin I will get the error:
Mage registry key "_singleton/extension/observer" already exists
 /var/www/magento/trunk/app/Mage.php(222): Mage::throwException('Mage registry k...')
 /var/www/magento/trunk/app/Mage.php(476): Mage::register('_singleton/exte...', false)
 /var/www/magento/trunk/includes/src/__default.php(21023): Mage::getSingleton('extension...')
 /var/www/magento/trunk/app/Mage.php(447): Mage_Core_Model_App->dispatchEvent('core_layout_blo...', Ar
ray)
 /var/www/magento/trunk/includes/src/__default.php(27297): Mage::dispatchEvent('core_layout_blo...', A
rray)
 /var/www/magento/trunk/includes/src/__default.php(27310): Mage_Core_Model_Layout->createBlock('adminh
tml/page', 'root')
 /var/www/magento/trunk/includes/src/__default.php(27077): Mage_Core_Model_Layout->addBlock('adminhtml
/page', 'root')
 /var/www/magento/trunk/includes/src/__default.php(27043): Mage_Core_Model_Layout->_generateBlock(Obje
ct(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
 /var/www/magento-demo/trunk/includes/src/__default.php(13507): Mage_Core_Model_Layout->generateBlocks()
 /var/www/magento/trunk/includes/src/__default.php(13432): Mage_Core_Controller_Varien_Action->generat
eLayoutBlocks()
 /var/www/magento/trunk/includes/src/Mage_Adminhtml_Controller_Action.php(275): Mage_Core_Controller_Varien_Action->loadLayout(NULL, true, true)
 /var/www/magento/trunk/app/code/core/Mage/Compiler/controllers/Adminhtml/Compiler/ProcessController.
php(59): Mage_Adminhtml_Controller_Action->loadLayout()
 /var/www/magento/trunk/includes/src/__default.php(13582): Mage_Compiler_Adminhtml_Compiler_ProcessController->indexAction()
 /var/www/magento/trunk/includes/src/__default.php(17927): Mage_Core_Controller_Varien_Action->dispatch('index')
 /var/www/magento/trunk/includes/src/__default.php(17484): Mage_Core_Controller_Varien_Router_Standar
d->match(Object(Mage_Core_Controller_Request_Http))
 /var/www/magento/trunk/includes/src/__default.php(20061): Mage_Core_Controller_Varien_Front->dispatch()
 /var/www/magento/trunk/app/Mage.php(683): Mage_Core_Model_App->run(Array)
 /var/www/magento/trunk/index.php(87): Mage::run('', 'store')

A: The only way that I think is possible to consistently avoid this is to turn off compilation mode before installing / making any code changes. You will also need to rerun the compilation process after the installation. Simply re-enabling it will have the same issue.
The underlying problem is that with compilation mode enabled Magento parses the new config.xml files but will only look for classes under the includes/ path. When you install a new extension the new files are placed in the standard Magento paths and are not found by Magento.
If the extension were to include the files in the compiled state as well as uncompiled state this could be an option to prevent this. The sql installation routines are also not part of the compiled state and could be used to change the php include paths (this seems rather hackish).
I consider this behaviour an oversight in the Magento compilation mode implementation - options that would have made sense are 1.) a change in config invalidates the compilaton mode 2.) config is also compiled to have a consistent site

A: You'll need to re-run the compiler via System > Tools > Compilation.

A: I am sorry about answering so late but I want to describe how I fixed that bug.
The problem was that my observer was attached in global area to core_layout_block_create_after event, which is firing in both areas (frontend, admin).
After installation during Compilation Mode enabled cache was cleaned. But code was not recompiling during installation. It means that after returning back I could not access admin, and rerun compilation. I could do that only from console.
As I needed watching for that event only for frontend area I just moved the observer initialization. And problem was fixed.
My advise do not initialize observers in global scope for events which runs in every page in admin.


text:
Q: How can I run a job when a title is one of the target titles in Github Actions? I want to run a job when a new issue title contains a certain string.
This can be achieved with:
jobs:
  my_job:
    name: My job
    if: contains(github.event.issue.title, 'Target Title')

But when there are multiple target titles, this becomes:
jobs:
  my_job:
    name: My job
    if: contains(github.event.issue.title, 'Target Title1') || contains(github.event.issue.title, 'Target Title2') || contains(github.event.issue.title, 'Target Title3')

, which is not good for readability.
What I need is to get the target title list from a file, and check whether an issue title contains any of the target titles.
# python
with open('target-titles.csv', 'r') as f:
  lines = f.readlines()
  target_titles = lines.split(',')

if any(target in issue-title for target in target-titles)
  run_job()

Is there a way to implement this in Github Actions?


text:
Q: "MobileNavigationHandler" does NOT exist anymore in PrimeFaces 7 The scenario is a mobile page developed with JSF and Primeface Mobile. I want to navigate in the same xhtml page between multiple pages (have a look at: JSF Primefaces Mobile navigation). After upgrading PrimeFaces from version 6.1 to 7.0 org.primefaces.mobile.application.MobileNavigationHandler does NOT exist anymore. What do i need to use instead? The migration guide "6.2 to 7.0" (https://github.com/primefaces/primefaces/wiki/Migration-Guide) doesnt help me: "[...] Mobile has been removed in favor of responsive features. [...]"

A: There is NO migration path for you other than rewriting your code.
PrimeFaces Mobile was completely removed in 7.0
See this blog post from Primefaces: https://www.primefaces.org/primefaces-6-2-roadmap/

PF Mobile is a renderkit for the existing components however we've
  just realized that we have to maintain two different sets at the same
  time so decided to deprecate PF Mobile and focus on the responsiveness
  of the standard renderkit. So in 6.2, mobile will be deprecated and
  removed in 7.0.

A: Have a look at my migrated fork: https://github.com/djmj/primefaces-mobile.
I extracted the mobile components from PrimeFaces 6.1 and adapted them to PrimeFaces 7.0 as a separate library. I did testing with mobile showcase and will test it in our own application and production the next days.


text:
Q: IE7 Bug: float:right width 100% rather than element sizes I am trying to something pretty simple.
I have two buttons inside a div.  One needs to be float right, one needs to be float left

Continue

Back

And the corresponding CSS
.calculator .btnwrapper { width:607px; }
.calculator .btnleft { float:left; border:1px solid green; }
.calculator .btnright { float:right; border:1px solid red; }
a.button { background:url(../images/bg-button-left.gif) no-repeat; float:right; height:29px; width:auto; padding:0 0 0 8px; display:block; color:#FFF; text-decoration:none; font-weight:bold; font-size:13px; cursor:pointer;}
a.button span { background:url(../images/bg-button-right.gif) top right; height:16px; padding:8px 8px 5px 0px; display:block; width:auto; cursor:pointer; }

Here is the results I'm getting in IE7.  All other modern browsers handle this correctly.

A: Remove float: right from a.button.
With it: http://jsfiddle.net/K8XQr/
Without it: http://jsfiddle.net/K8XQr/1/
They look identical, except that losing float: right fixes it in IE7.


text:
Q: .net Core : Angular SPA template update causing authentication issue We are using Angular 5.2 and recently updated the SPA template. Where in which :
1) New SPA template do not have index.cshtml file, now all request are getting redirected to index.html file. so my first question is :

Can we retain razor file behavior in new template ?

2) We are using OpenIDConnect authentication like :
  .AddOpenIdConnect(options =>
            {
                options.ClientId = azureAdConfig.ClientId;
                options.ClientSecret = azureAdConfig.ClientSecret;
                options.Authority = string.Format(azureAdConfig.AADInstance, azureAdConfig.Tenant);
                options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                options.Resource = azureAdConfig.ResourceURI_Graph;

                // PostLogoutRedirectUri = Configuration["AzureAd:PostLogoutRedirectUri"],
                options.Events = new AuthEvents(azureAdConfig, connectionStringsConfig);
            });

But after updating template, first UI is getting loaded and authentication is not getting called.
The reason being old startup.cs file has MapSpaFallbackRoute which is used to redirect to Home Index action which causing authentication to get called :
 routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });

In New template if we set this configuration, getting following error :
Not able to find file Views/Home/Index.cshtml
As new SPA template project structure do not have this file. If we remove this configuration then only UI gets loaded with no server calls.

so second question how to retain the old behavior of authentication being called first in this new template. which configuration i am missing here ?

A: Razor is a server side rendering technology. SPA means "all rendering is done client side". So no. Razor is the opposite to SPA.
You cannot marry the technologies since they are diametrically opposite.
If you endeavour to write SPA with razor. Then you must bring the mountain to Mohammad. You MUST run the razor on the client. There is a Microsoft beta tech called Blazor for that.


text:
Q: Unable to maintain data inside gridview across postback when used inside an user control I've a textbox that is present inside a GridView that itself is a part of user control and I'm dynamically loading this user control on page_Init.
The controls in my user control are a DropDown, a TextBox and a GridView.
Now DropDown and TextBox are able to retain values across postback but textboxes inside the GridView are not retaining the values.
Adding User Control on page init:
 if (postBackCntrl.Contains("AddUserControlButton"))
            {
                UserControl newGrid = (UserControl)LoadControl("~/UserControl.ascx");
                newGrid.ID = "test" + gridList.Count;
                gridList.Add(newGrid);
            }

GridView Code: TextBoxes inside GridView ItemTemplate not able to retain values across postback:
<asp:GridView runat="server" ID="grdUser" CssClass="GridTable" Width="90%" AutoGenerateColumns="false"
                ShowFooter="true" OnDataBound="MergeGridViewFooter">
                <Columns>
                    <asp:TemplateField HeaderText="ContactUs">
                        <ItemTemplate>
                            <asp:TextBox ID="txtContactUs" runat="server" CssClass="textbox" Height="60px" TextMode="MultiLine"></asp:TextBox>
                        </ItemTemplate>
                        <FooterTemplate>
                            <asp:Button ID="btnaddrow" runat="server" Text="Add Row" CssClass="ui-button jquery-ui" Style="font-size: 12px" OnClick="btnaddrow_Click" />
                            <asp:Button ID="btnDelRowAddress" runat="server" Text="Delete Row" CssClass="ui-button jquery-ui" Style="font-size: 12px" OnClick="btnDelRowAddress_Click" />
                        </FooterTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Definition">
                        <ItemTemplate>
                            <asp:TextBox ID="txtDefinition" runat="server" TextMode="MultiLine" Height="60px" CssClass="textbox"></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Address">
                        <ItemTemplate>
                            <asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine" Height="60px" CssClass="textbox"></asp:TextBox>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>


text:
Q: How to make new dataframe from raw dataframe This is raw DF.
sentence = pd.DataFrame({'sentence': ['<Donald Trump:PS> is <America:LC> President. He came to <Japan:OG> in <July 20:DT>', '<NC Soft:OG>is established in  <Match, 1993:DT>', '<NC Soft:OG>is one of the best game company.']})

THis is the result that I want to make.
       PS        LC       DT               OG
0 Donald Trump  America   20-Jul
1               Japan     Match, 1993   NC Soft

A: You can use extractall and pivot:
(df['sentence']
 .str.extractall(r'<([^<>:]+):(\w+)>')
 .droplevel('match')
 .pivot(columns=1, values=0)
 .rename_axis(columns=None)
 )

Output:
            DT       LC       OG            PS
0      July 20  America    Japan  Donald Trump
1  Match, 1993      NaN  NC Soft           NaN
2          NaN      NaN  NC Soft           NaN

Used input:
df = pd.DataFrame({'sentence': ['<Donald Trump:PS> is <America:LC> President. He came to <Japan:OG> in <July 20:DT>', '<NC Soft:OG>is established in  <Match, 1993:DT>']})


text:
Q: usage of scanf inside while test condition I want to store a series of integers till i press an enter in an array.How can i implement that
Input:
1(tab space)2(tab space)3(tab space)4(tab space)enter
i tried doing this
#include<stdio.h>
main()
{
int i,j,c,d;
int a[5];
for(i=0;i<2;i++){
        j=0;
    while((d=scanf("%d",&c))==1){
         a[j]=c;
         j=j+1;
    }
 }
}

I dont know how scanf works and using scanf return value.Please explain how i can store this input if its not impossible to do so with scanf and also
2)What else can be used inside scanf along with %d ?
I have a file with 200 rows with numbers like this
(NOTE: each row has varied number of values but all numbers are less than 200)
1\t2\t3\t4\t5\t
2\t3\t4\t5\t6\t7\t8\t
11\t12\t13\t
.
.
200

...                 so i have to store this as an adjacency list representation

A: For the first part of your question. scanf() returns number of elements successfully read but it is of no use here and you can just scan in a loop and scanf() will pick your integers in a line when you press enter.
   #include <stdio.h>

int main(void) {
    int a[5];
    int i, n;
    for(i=0;i<5;i++)
    {
       if(scanf("%d",&a[i]) != 1)
       {
          printf("Value not read correctly\n");
          break;
       }
    }
    n = i;
    for(i=0;i<n;i++)
        printf("%d\n",a[i]);
    return 0;
}

For the second question you have to do something line
1.Read a line from your file using fgets()
2.Break your line using strtok() with tab as delimiter.
3.Now convert each token to integer using atoi()
4.Now do whatever you want with the integer. i.e. create a node add your integer to the node

A: Let's make some reasonable assumptions about the width of each row.
These assumptions are useful for simple code, though not needed in general.
#define LINE_WIDTH_MAX 1000
#define INTS_PER_LINE_MAX 100
#define ROWS_PER_FILE (200 /* given by OP */)

Read each row with fgets(), then scan.  Could use strtol(), sscanf() or various approaches.
This method uses sscanf() and "%n" to determine when the next number might follow.
int row;
for (row = 0; row < ROWS_PER_FILE; row++) {
  char buf[LINE_WIDTH_MAX + 2];
  if (fgets(buf, sizeof buf, stdin) == NULL) {
    break;  // Handle EOF or IO error
  }
  int num[INTS_PER_LINE_MAX];
  char *p = buf;
  for (int i = 0; i<INTS_PER_LINE_MAX; i++) {
    int n = 0;
    if (1 != sscanf(p, "%d %n", &num[i], &n)) {
      break;
    }
    p += n;
  }
  if (*p) Handle_GarbageInLIne();

  // do something with the `i` numbers

}

Notes:
Advise never use scanf()/


text:
Q: Disadvantages of using TLB (and tlbimp.exe) with C# We're integrating a communications company's software into our own for doing things like answering calls, transfering calls, matching numbers with clients etc.
They have given us the API documentation, which includes a TLB file. We've used the tlbimp tool to create an assembly which we now want to use in our implementation.
Some of the classes created by tlbimp have been given internal constructors, rendering them uninstantiable. I think it should be ok in this instance as another class should return an instance of these classes.
This made me think though: are there any other pitfalls I should be aware of when using tlbimp.exe, and TLB's as a whole? Would it be better to create the DllImport/ComImport/PInvoke code by hand?

A: In general if you have a TLB I would at least start my work by consuming the assembly produced by tlbimp.
The tool itself is widely used and produces correct code based on the definitions provided in the TLB.  I have seen some circumstances where the resulting code was incorrect but it almost always came back to either a very complex marshalling situation with arrays or a place where the TLB author had simply added the wrong COM annotations.
If you do find any issues down the road then you should consider beginning to hand code the fixes.  But I certainly wouldn't start that way.

A: You cannot pinvoke the kind of COM interface methods that are declared in a type library.  The DLL that implements the COM server doesn't export the methods.  You can use late binding with reflection or the dynamic keyword but that's painful and error prone.  Use the import library, that's why it is there.


text:
Q: How to group total of same tax name in woocommerce I have 2 tax classes one is GST 18 and another is GST 10 when i am applying it to the products and generating the pdf invoice it shows both the tax rate separately. I want to combine the total tax value of same tax name together like CSGT and SGST should only show 1 time currently its showing as CGST 2.5 % & CGST 9 %  i want to combine it and call it just CGST. Please see the image for better understanding of my issue: https://ibb.co/72KTCZ5
For your information i am using pdf invoices and packing slips premium plugin.


text:
Q: Create thread via class constructor Is it possible to create a thread with a function pointer to a class constructor?
If this is possible, when how would the class destructor get called?
I have made this example of what i am looking for:
class ClassA
{
public:
    ClassA(void* argPtr)
    { ... }
};

int main(void)
{
    pthread_t thread;
    pthread_create(&thread, NULL, &ClassA(), NULL);
    return 0;
}

A: Constructors are classified as "special member functions", and it is not possible to get a pointer to constructor function because it does not have a name (note that you are using class name, not a constructor function name, to invoke it):

12.1 Constructors [class.ctor]
1
  Constructors do not have names.
...
2
  A constructor is used to initialize objects of its class type. Because constructors do not have names, they are never found during name lookup;

Also pthread_create takes a pointer to a regular function, not to a member function.


text:
Q: how to change colour of specific words in a powerpoint in python I am using python-pptx library of python to automate a powerpoint presentation that we are required to create on monthly basis as part of a report. Certain words in text of existing presentation are coloured red, green or yellow. I'd like to implement this using python-pptx library or any other method available but so far I don't see any way that I can use to achieve this. Please find below screenshot for reference and thanks in advance for help.

A: You would do this:
from pptx.dml.color import RGBColor
font.color.rgb = RGBColor(0x80, 0x18, 0x18)

Furthermore, if you are coloring multiple words/sentences:
from pptx.util import Pt

p = tf.add_paragraph()
run = p.add_run()
blue = p.add_run()
blue.text = 'this is blue'
blue.font.color.rgb = RGBColor(0, 0, 255)
run.text = 'this is red'
run.font.color.rgb = RGBColor(178,34,34)

Python-pptx docs: link
RGB colors: link


text:
Q: Get a JSON file from an AppScript backend, using an AppScript front end, without getting a CORS error? I'm trying to build a an API-driven front end in Google AppsScript that calls a REST API hosted on AppScript to make some database queries.
I am currently simply trying to retrieve a JSON file with a GET request.
Everything I try, I get "CORS Missing Allow Origin".
My understand of CORS is that I might experience this with POST request (but maybe there's some people who have phrased their requests to get work this?)
I have a sense that the situation has changed over time, and what has worked in previous SO threads, doesn't seem to work for me now.
Sigh. I feel like Google's Documentation Team would benefit from a dedicated article to explaining how this is supposed to work.
If anyone can shed light on how I can get this to work, I've be most grateful:
client side code:
useEffect(() => {
  fetch('https://script.google.com/macros/s/AKfycbz3_hgjZe0E35ZI2mw7aNs3ASkYCct77qIzL_WTOQMu_ZZeax9WpHpPIwm-MFPhZAW77g/exec/get/all', {
    redirect: "follow",
    headers: {
      "Content-Type": "text/plain",
    },
  })
    .then(result => result.json())
    .then(rowData => setRowData(rowData))
}, []);

Server side code:
export function doGet(e) {
  if (e.pathInfo.startsWith('get/all')) {
    return getAllRecords(e);
  }
  else if (e.pathInfo.startsWith('get')) {
    return getRecord(e);
  }
  else {
    return getAllRecords(e);

    //return HtmlService.createHtmlOutput('Error: invalid path-  ' + e.pathInfo + '\n\n' + e.parameter + e);
  }
}

function getAllRecords(e) {
  // Connect to the MySQL database using the JDBC connector
  const conn = Jdbc.getConnection(url, username, password);

  // Construct the SELECT statement
  const sql = `SELECT * FROM cars LIMIT 100`;

  // Execute the INSERT statement
  const stmt = conn.prepareStatement(sql);
  const results = stmt.executeQuery();

  // Return the inserted record with the generated id
  const records = [];
  while (results.next()) {
    const record = {
      id: results.getInt('id'),
      name: results.getString('name'),
      make: results.getString('make'),
      price: results.getInt('price')
    };
    records.push(record);
  }

  return ContentService.createTextOutput(JSON.stringify(records)).setMimeType(ContentService.MimeType.TEXT);
//   return ContentService.createTextOutput(JSON.stringify(records)).setMimeType(ContentService.MimeType.JAVASCRIPT);
}

I've tried various combination of MIME Type, and request headers and I'll try any combinations people suggest.

A: In order to use pathInfo, in this case, it is required to use the access token. I thought that this might be the reason for your current issue. But, when the access token is used, I'm worried that is might not be useful for your actual situation. So, in this answer, I would like to propose the following 2 patterns.
Pattern 1:
In this pattern, your script is modified using the access token. In this case, please modify your Javascript as follows.
From:
fetch('https://script.google.com/macros/s/AKfycbz3_hgjZe0E35ZI2mw7aNs3ASkYCct77qIzL_WTOQMu_ZZeax9WpHpPIwm-MFPhZAW77g/exec/get/all', {
  redirect: "follow",
  headers: {
    "Content-Type": "text/plain",
  },
})
  .then(result => result.json())
  .then(rowData => setRowData(rowData))

To:
const accessToken = "###"; // Please set your access token.
fetch('https://script.google.com/macros/s/AKfycbz3_hgjZe0E35ZI2mw7aNs3ASkYCct77qIzL_WTOQMu_ZZeax9WpHpPIwm-MFPhZAW77g/exec/get/all?access_token=' + accessToken)
  .then(result => result.json())
  .then(rowData => setRowData(rowData))

When you use the access token, please include the scopes of Drive API. Please be careful about this.
Pattern 2:
In this pattern, I would like to propose the modification without using the access token. When the access token cannot be used, unfortunately, pathInfo cannot be used. So, in this pattern, the query parameter is used instead of pathInfo.
Please modify your Javascript as follows.
From:
fetch('https://script.google.com/macros/s/AKfycbz3_hgjZe0E35ZI2mw7aNs3ASkYCct77qIzL_WTOQMu_ZZeax9WpHpPIwm-MFPhZAW77g/exec/get/all', {
  redirect: "follow",
  headers: {
    "Content-Type": "text/plain",
  },
})
  .then(result => result.json())
  .then(rowData => setRowData(rowData))

To:
fetch('https://script.google.com/macros/s/AKfycbz3_hgjZe0E35ZI2mw7aNs3ASkYCct77qIzL_WTOQMu_ZZeax9WpHpPIwm-MFPhZAW77g/exec?value=get%2Fall') // or ?value=get
  .then(result => result.json())
  .then(rowData => setRowData(rowData))

And also, please modify doGet of your Google Apps Script as follows.
Modified script:
function doGet(e) {
  if (e.parameter.value == "get/all") {
    return getAllRecords(e);
  } else if (e.parameter.value = "get") {
    return getRecord(e);
  } else {
    return getAllRecords(e);
  }
}

Note:

*

*In this modification, it supposes that your getAllRecords(e) works fine. Please be careful about this.

*And, in this modification, it supposes that your Web Apps is deployed as Execute as: Me and Who has access to the app: Anyone. Please be careful about this.

*When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.

*You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".

*Thit is a sample modification. So, please modify this for your actual situation.
Reference:

*

*Taking advantage of Web Apps with Google Apps Script (Author: me)


text:
Q: JAVASCRIPT Is this a good function for simulation of the sort() method? I wanted to make my own method for sorting an array high to low. Yes, I know that I can use sort(), and yes, I know I should use sort, but I'm a newbie programmer and wanted a little challenge.
So here's the live code for it: http://jsfiddle.net/qaaPu/3/
and here's the code:
//JavaScript sort() high to low simulation

//INPUT ARRAY:
var input = [1,2,3,4,5,6,7,8,9,10];

entireLoop: for (var i = 1; i < input.length; i++) {
    if (input[i] > input[i - 1]) {
        for (var o = i - 1; o >= 0; o--) {
            if (input[i] > input[0]) {
                input.splice(0, 0, input[i]);
                input.splice(i + 1, 1);
            }
            else {
                if (input[o] > input[i]) {
                    input.splice(o + 1, 0, input[i]);
                    input.splice(i + 1, 1);
                    continue entireLoop;
                }
            }
        }
    }
}
document.body.innerHTML = (input);

I'm just wondering if this is a good solution, or if there's a problem with how I did it (hogging RAM, or very hard on the processor, bandwidth, etc.)
So what do you pros think of this code?

A: for further inspiration watch that link:
http://phpjs.org/functions/sort:519


text:
Q: Unable to view .appspot.com on browser Trying to understand how Google Cloud App Engine works, I am trying the tutorial mentioned in:
https://medium.com/google-cloud/getting-started-with-google-app-engine-and-spring-boot-in-5-steps-2d0f8165c89
I can get the response "Hello Spring Boot!" on my local system using browser at "http://localhost:8080" but when I deploy the code to Google App Engine, I access .appspot.com then i fail to get the message "Hello Spring Boot!" but get 404 Error not found. I suspect this is an access/permissions issue but have not been able to solve it
Things I have checked:
1) My GCP has billing enabled for this project
2) I can see that there is one instance for in App Engine dashboard
3) My Google application credentials in bash ENV variable points to the API key created for this @appspot.gserivceaccount.com
4) I have used GCP to deploy an earlier project for maven spring boot, this is a new project to test APP engine.


text:
Q: URL with only slashes in pure php like codeigniter uri pattern I have an application which creates stores for users and they can create a single page store using my dashboard.The final URL generated after they create the store is as follows
baseurl/store/{username}/{random number}

Now how can I access the {username} and {random number}.
If I have a index file in directory 'store'
--store
----index.php will I be able to fetch the above username and random number from the url?If this was in codeingiter things would have been easy , and I could make a controller with name store and get the uri segments.But how can I do the same in pure PHP without any frame work.Please do help

A: You have to use a .htaccess in order to do that.
So create this file at the root of your project directory (where index.php is).
.htaccess content :
RewriteEngine On
RewriteRule ^store/([a-zA-Z0-9\_]+)/([0-9]+)$ index.php?username=$1&rand=$2

index.php content:
<?php
var_dump($_GET);
?>

Now try using an url like : mywebsite.com/store/jack_97/354 and you should end up with a dump of $_GET telling you that this array contains two keys : "username" and "rand"


text:
Q: Is the punctuation here correct? the following is the result of me translating and then subtitling I am not entirely sure if I should use a comma at the end of the 1st line or even in the second line. but I chose to put it as follows.

The reason why we eat oil and fats
and the reason we say that one is healthy, and the other is harmful
is that there are two types of Omega, aka fatty acids that the body
  needs.

the following is more confusing, as it's not clear to me whether I can use a semi colon in the first 2 sentences in place of ", and", then right after that use
semi colon because it's a list with comma used in one of the ingredients(the last one).

This subject specifically has shocked me.
I decided to flip the table while drinking a cup of Matcha tea,
    and tell you how to fry;
which oil to fry in;
which oils are beneficial and which are harmful;
what to know about your frying oil of choice;
everything about olive oil, butter, ghee, and other types of oil.

A: I don't think you should use the word "reason" twice in your first sentence. It sounds like there are two reasons, when in fact you are pointing to one reason for two things. If you abbreviate your sentence, the punctuation should be clearer:

The reason why we eat oil and fats, and why we say that one is healthy and the other is harmful, is that there are two types of Omega, aka fatty acids, that the body needs.

That is a lot of commas for one sentence, and so you may wish to change the commas acting as parenthesis for actual parenthesis:

The reason why we eat oil and fats, and why we say that one is healthy and the other is harmful, is that there are two types of Omega (aka fatty acids) that the body needs.

Regarding your second sentence and the use of semi-colons - the generally accepted rule is that you should use commas in lists unless the list items themselves contain commas. (eg: John, the baker; Simon, the policeman; and Toby, the architect)
Only the very last of your list items uses commas, and so for that reason I would stick with commas. Semi-colons are used far less frequently than commas - only use them if you have to. Also, you should begin the last of your list items with "and", even though it contains the word.
Before you begin a list though, your leading sentence should either transition into the first item, or you should use a colon. Your list is not of items that could append the leading sentence, so a colon is suitable:

This subject specifically has shocked me. I decided to flip the table while drinking a cup of Matcha tea and tell you how to fry: which oil to fry in, which oils are beneficial and which are harmful, what to know about your frying oil of choice, and everything about olive oil, butter, ghee, and other types of oil.


text:
Q: java - illegalStateException: Cannot find changelog location: class path resource (liquibase) I am getting this error when I try to run my spring boot application. I am new to java and spring development. Please let me know if you require more info. I'm not sure what it means by "cannot find changelog location ..."
2017-02-01 16:19:22.543 ERROR 17315 --- [  restartedMain] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml] (please add changelog or check your Liquibase configuration)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:137)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1575)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1128)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1022)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175)
    at com.ccc.Application.main(Application.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.IllegalStateException: Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml] (please add changelog or check your Liquibase configuration)
    at org.springframework.util.Assert.state(Assert.java:392)
    at org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration.checkChangelogExists(LiquibaseAutoConfiguration.java:92)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311)
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:134)
    ... 34 common frames omitted

A: Create or edit the file application.properties and add the address of the master changelog file:
liquibase.change-log=classpath:/db/changelog-profiles/changelog-master.xml

Additionally, you can create your master changelog file in the default address (as mentioned in @austin answer)
Note: Be aware that if you are using Spring Boot 2.0, the property is named spring.liquibase.change-log instead of liquibase.change-log.
Sources: Spring Boot 2 - Migration Guide, Spring Boot 2 - Release Notes

A: I solved this :
*Springboot 2.0 NOT USED
*Used GRADLE

*

*Entry in application.properties
  liquibase.change-log=classpath:db/changelog/db.changelog-master.yaml

*Path of db.changelog-master.yaml where this file is stored: src/main/resources/db/changelog/db.changelog-master.yaml

*Content of db.changelog-master.yaml:

databaseChangeLog:
  - includeAll:
      path: db/changelog/changes/


text:
Q: How to log bash commands executed non-interactively I want to log bash commands executed non-interactively.
Example:
on execution of ssh user@a.b.c.d ls -l command, it should be logged on syslog.
Found a   similar question but no help. Is there any way to achieve it by making code changes in bash package source code?
Thanks in Advance !!


text:
Q: My osclass links are working properly but returns 404 error when checked I have created used car website www.carsangrah.com using osclass.
Some links (http://www.carsangrah.com/buy-used-cars_maharashtra-r781510) are working perfect but returns broken link (404 error) when checked on http://validator.w3.org/checklink.
Google and Bing webmaster also showing as 404 error. I am not able to index these links in Google and Bing. Please suggest a solution.
Thanks

A: Here is the solution got to  oc-includes/osclass/controller then search.php then find this
                if( count($aItems) === 0 ) {
                header('HTTP/1.1 404 Not Found');
            }

replace if( count($aItems) === 0 ) with if( count($aItems) === -1 ).
that fixes

A: Osclass by default if a search have 0 results it returns 404 status code, you don't want to search engines index pages without any useful content.
If a link, results on a search results page with listings, 200 status code is returned.

A: Ah that explains the 404 issues I am seeing. I am going to log this as and error as no listings returned does not mean 404 it means no listings. 404 is page not found which is clearly wrong as the server is delivering a html page from the server.


text:
Q: How to pass only part of input value to variable and url? So on the site i am building i need to extract only part of value from input form field and pass that to variable but i am a bit confused how to do that.
Well i made a code where
mysite.com/?getid=620

Should return some data from json file with that id.
And this works.
But!
Now the problem is that i need to get that id from url address posted in input field.
The form with input field looks like this
        <form name="appids" method="get" action="?">

                Insert url from Steam

                <input class="form-control" type="text"  id="appids" name="appids" value="" placeholder="http://store.steampowered.com/app/620/" >

                    <button class="btn btn-default" type="submit">Calculate</button>

        </form>

As you can see it's bootstrap and there is already placeholder explaining user what he need to post in input field.
So the visitor just copy and paste url and i need to extract only number from that and pass it into variable or site url.
The user post this
http://store.steampowered.com/app/620/

And i need only this
620

What are the ways to do something like this ? Javascript or php code?
EDIT:
There sometime can be some type of code after the number in url, so sometime url can look like this
http://store.steampowered.com/app/241280/?snr=1_6_4__421

So i have to strip that part too ?snr=1_6_4__421
And i would try to avoid javascript because if user visit with certain mobile javascript might break sometime.

A: In JavaScript, you can extract app id with jQuery as user types in the field:
$('#appids').keyup(function(){
    var match = $.trim(this.value).match(/\/app\/(\d+)\/?$/);
    if (match) {
        console.log(match[1]);
    }
});

Or, preg_match can help you in PHP:
if (preg_match('@/app/(\d+)/?$@', $_GET['appids'], $match)) {
    echo 'App ID = '.$match[1];
}

A: In Javascript:
var num = "http://store.steampowered.com/app/620/".replace(/.+?(\d+)(\/)?$/,"$1");

In PHP:
I don't know PHP but you can use the regex /.+?(\d+)(\/)?$/ and replace it with $1

A:
Why are you not using session variable for storing a variable valus?
  try this`

    <?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>

A: Complete lack of validation and trailing slash notwithstanding:
Javascript variant:
var url = "http://store.steampowered.com/app/620/".split("/"),
    num = url[url.length - 2];

PHP variant:
$url = split("/", "http://store.steampowered.com/app/620/");
$num = $url[count($url) - 2];

A: A normal submission would do just fine: Demo
<?php
// try in your form
// http://store.steampowered.com/app/620/
// http://store.steampowered.com/app/241280/?snr=1_6_4__421

if(isset($_GET['submit'])) {
    $url = $_GET['appids'];
    $url = strtok($url, '?');
    $path = parse_url($url, PHP_URL_PATH);
    $pieces = array_filter(explode('/', $path));
    $id = end($pieces);
    echo $id;
}

?>

<form method="GET" name="appids">

        Insert url from Steam

        <input class="form-control" type="text" id="appids" name="appids" value="" placeholder="http://store.steampowered.com/app/620/" >

            <button class="btn btn-default" type="submit" name="submit">Calculate</button>

</form>


text:
Q: Creating static Mac OS X C build How can i create a static build of a .c file on Mac OS X ? When i try:
gcc -o test Main.c -static

I get:
ld: library not found for -lcrt0.o
collect2: ld returned 1 exit status

A: Imagine that you want to convert some functions into a library.
File: example.c
#include <stdio.h>

void aFunction( int a )
{
    printf( "%d\n", a );
}

File: example.h
void aFunction( int a );

File: main.c
#include "example.h"

int main( )
{
    aFunction( 3 );

    return 0;
}

To create the library:
gcc -c example.c
ar -r libmylibrary.a  example.o

To link the library:
gcc main.c -lmylibrary -L. -I.

And then the file example.c is a static build of the entire program.

A: It is not supported in Mac OS X's gcc:
http://discussions.apple.com/message.jspa?messageID=11053384

Perhaps that "-static" flag flat out won't work on MacOS X. Not all features of gcc are implemented on MacOS X. Apple won't even be using gcc in future versions of the OS.
I don't know how to link using "-static". I can't think of any reason to do so on MacOSX. If I knew why you wanted to use "-static" I might be more interested in the problem. Right now, I just don't get it. By asking for help, you are essentially asking for collaborators on the project - even if it is only for 10 minutes. You need to get me interested.

And http://developer.apple.com/library/mac/#qa/qa2001/qa1118.html

Static linking of user binaries is not supported on Mac OS X. Tying user binaries to the internal implementation of Mac OS X libraries and interfaces would limit our ability to update and enhance Mac OS X. Instead, dynamic linking is supported (linking against crt1.o automatically instead of looking for crt0.o, for example).
We strongly recommend that you consider the limitations of statically linking very carefully, and consider your customer and their needs, plus the long-term support you will need to provide.

Update: The prohibited is a static binary. But you still can compile some static library and use it with you another program. Program will be linked statically with your library, but other libraries like libc will be dynamic, so program will be a dynamic executable.

A: A binary that has no dynamic loaded libraries can not be built under OSX. I tried both apple llvm-gcc and macports gcc. However what no answer mentioned so far is that this is not needed. You can link the c/c++ library statically (and live with some dynamic part).
File hello.cpp:
#include <iostream>
using namespace std;
int main()
{
    cout << "Hello World!";
}

Compile as usual:
g++ hello.cpp -o hello

Check linkage:
otool -L hello
hello:
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 52.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 159.1.0)

We can not get rid of the libSystem.B.dylib dependency but with macports gcc we can do this:
g++-mp-4.6 -static-libgcc -static-libstdc++ hello.cpp -o hello

otool -L hello
hello:
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 159.1.0)

Apparently just Apple does not support static linking:
llvm-g++ -static-libgcc -static-libstdc++ hello.cpp -o hello

otool -L hello
hello:
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 52.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 159.1.0)


text:
Q: Summary function in R does not give frequency table When I use summary() function in R, it gives me correct output for continuous numerical variables, but it does not give me the frequency tables for character variables.  My colleague uses the same code on the same data sets and gets the frequency tables. I have the most updated version of R. What can I do to get summary to work for me? (Note: it never works, no matter what data set I use, even data sets from tutorials on R.)
This is the output I get:
summary(chem)
#>   plantid            species             deerpr             forest
#> Length:104         Length:104         Length:104         Length:104
#> Class :character   Class :character   Class :character   Class :character
#> Mode  :character   Mode  :character   Mode  :character   Mode  :character

This is the output she gets:
summary(chem)
#>    plantid   species       deerpr          forest
#> B1     : 1   fagr:102   higher:45   baldpate  :34
#> B10    : 1              lower :57   curlis    :10
#> B100   : 1                          eames     :13
#> B12    : 1                          herrontown:23
#> B13    : 1                          rosedale  :22
#> B15    : 1
#> (Other):96

A: I suspect the reason the two of you are getting different results is because starting in R version 4.0.0, the default for stringsAsFactors changed to FALSE. Therefore, when you read the data from a .csv or other text file, your data is loaded as character vectors. In contrast, she has a version less than 4.0.0 and the data is automatically converted to type factor.
You can change this while reading in the data with stringsAsFactors = TRUE. For example:
data <- read.csv("data.csv",stringsAsFactors = TRUE)

A: if you do this:
chem[] <- lapply(chem, as.factor)
summary(chem)

You will get the same result of your colleague.

As someone suggested in the comments (for some reason I don't see that comment anymore), it's likely that you have two different R versions, or anyway when you read your data you do it in two different ways.
Therefore, for your colleague all strings gets read as factors, while you keep them like strings.
Just convert all character variables to factor.
You can also do it this way, in case you have other columns that you don't want to transform to factor:
chem <- purrr::modify_if(chem, is.character, as.factor)


text:
Q: Can't trigger AVR ADC Interrupt I am using an Atmel's XPlained mini board with Atmega328PB. I am trying to use ADC interrupt, however I can't get it to fire. Here's the code that I have a problem with:
#define F_CPU 16000000UL
#include <avr/io.h>
#include <avr/interrupt.h>

ISR(ADC_vect){
    PORTC ^= (1<<PINC2);
}

int main(void)
{
DDRC |= (1<<PINC2); //pin 2 as output
DDRC &= ~(1<<PINC3); //adc pin as input
sei();
ADMUX |= (1<<REFS0); //reference voltage VCC
ADMUX |= (1<<MUX0);
ADMUX |= (1<<MUX1);// channel 3
ADCSRA |= (1<<ADPS2);//
ADCSRA |= (1<<ADPS1);//
ADCSRA |= (1<<ADPS0);//prescaler to 128
ADCSRA |= (1<<ADATE);//auto trigger enable
ADCSRA |= (1<<ADIE); //adc interrupt enable
ADCSRA |= (1<ADEN); //adc enable
ADCSRA |= (1<< ADSC); //start conversion

while (1)
    {
    }
}

As far as I understand the code should enable a constant conversion in a free running mode with the frequency of 16MHz/128, and each time the conversion is completed the ADC_vect should fire toggling PIN2 of Port C. The problem is it doesn't. I am guessing I am not initializing the ADC correctly, however I can not pin point were the problem is.
EDIT:
After pointing out that the adc was not being run in a free running mode I cleared the ADTS bits. However I still couldn't toggle the pin. I think something else is at fault here.

A: You've written
ADCSRA |= (1<ADEN); //adc enable

And I think it should be
ADCSRA |= (1<<ADEN); //adc enable

Which seems plausible since the error you've come across is that it never does anything.

A: See table 24-6 of the datasheet. You are setting bits ADTS1 and ADTS0 high (leaving ADTS2 as zero). It means that the trigger signal is "Timer/Counter0 Compare Match A". You are not doing anything to configure that timer (and the reset state of the timer is simply "stopped").
To use the free running mode you have to clear ADTS0, ADTS1, ADTS2 in ADCSRB (or just leave ADCSRB alone at its reset value).


text:
Q: Where is this Errno::ENOENT error from? Beginner here, teaching myself Ruby. I'm getting Errno::ENOENT and I think I figured out how, but I don't understand why I'm getting it. Here's the error:
Downloading 4 files:  .  .  . c11-photos.rb:29:in `rename': No such file or
directory - (c:/users/7/dropbox/3-coding/ruby/study/blizz-01.jpg, blitz-03.jpg)
(Errno::ENOENT)
    from c11-photos.rb:29:in `block in <main>'
    from c11-photos.rb:20:in `each'
    from c11-photos.rb:20:in `<main>'

First, the program works. All files are accurately moved and renamed. But this error pops up after it's done running. For this particular job, there were only 2 pictures to be moved to a new directory, but notice that the program says it downloaded 4 files. What seems to be happening is that my #each method is somehow repeating itself when executed. It's trying to continue moving files even when the target directory has no more picture files to move. I'm guessing this because the "blizz-01.jpg" file is one of the files to be moved, but the "blitz-03.jpg" isn't the name of any file (this is the would-be name if there was a third picture to move). Since "blizz-01.jpg" has already been moved, this would make it give me a "No such file ..." error. Of course, I don't really know if this is what's happening, but that seems to be what the error says.
Why am I getting this error and/or what's wrong with my code that it's producing this problem?
Here's my code:
require "yaml"

puts "Where to move the pictures?"
destination = gets.chomp

Dir.chdir "#{destination}"

puts "What shall we name this batch?"
batch = gets.chomp

puts "Where to get your new pictures?"
findpics = gets.chomp

pictures = Dir["#{findpics}/*.{jpg,JPG,JPEG,jpeg,png,PNG}"]

print "Downloading #{pictures.length} files: "

amount = 1

pictures.each do |pic|
print ' . '

newname = if amount < 10
    "#{batch}-0#{amount}.jpg"
else
    "#{batch}-#{amount}.jpg"
end

File.rename pic, newname
amount += 1
end

puts

puts "Operation complete!"

Thank you your help!

A: Case-insensitive filesystem?
blizz-01.jpg is matched twice, once by "#{findpics}/*.jpg" and once by "#{findpics}/*.JPG", which are two of the expansions of your filesystem glob argument to Dir[].  Same remark for the other file.  Obviously, the second time it's processed in your each loop, it's already been renamed.
If you want this to work both on case-sensitive and case-insensitive filesystems, and permit ".jpg" and ".JPG" and so on, you can quickly and simply unique-ify the matches:
pictures = Dir["#{findpics}/*.{jpg,JPG,JPEG,jpeg,png,PNG}"].uniq


text:
Q: how to assign values to state array in a class component of react How to assign values to state array in a class component of react?
class Dashboard4 extends React.Component {
  state = {
    TotalParts: 0
  };

  async componentDidMount() {
    const d = await actions.getTotalParts();

    this.setState({ TotalParts: d[0].Total });
    this.setState({ v_date: d[0].v_date });
  }
}

In the above snippet, only one value is getting assigned to TotalParts (d[0].Total), but I want to assign multiple values to the same from an receiving object called d having two fields Total.
When I declare TotalParts as an array in state. Can any one help me how to assign all Total values in d object to TotalParts?
class Dashboard4 extends React.Component {
  state = {
    TotalParts: []
  };

  async componentDidMount() {
    const d = await actions.getTotalParts();

    // How to assign multiple values of Total
    // available in d object to TotalParts:[]?
  }
}

Expecting all values of Total present in d object to be assigned to TotalParts

A: You can use the array method map on the d array and just extract the Total values.
this.setState({ TotalParts: d.map(element => element.Total) })

A: You can do it by maping through d array and then return a new object which contains Total and v_date
this.setState({
    TotalParts: d.map(element => {
        return {
            Total: element.Total,
            v_date: element.v_date
        }
    })
})


text:
Q: How can the number of rational points depend on the choice of height function? Let $V/\mathbb{Q}$ be a subvariety of $\mathbb{P}^n$. There are many plausible choices of height function, some differing only by constant factors: $\max |x_i|$ (for $(x_0,x_1,\dotsc,x_n)$, $\gcd(x_1,\dotsc,x_n)=1$, representing a given point $P$), or also $\sqrt{\sum_i |x_i|^2}$, etc.
Given a height function $H$, we can define $N_H(V;x)$ to be the number of points $P$ in $V(\mathbf{Q})$ with $H(P)\leq x$. For $H_1\ll H_2\ll H_1$, we clearly have $N_{H_1}(V;x)\ll O(1)^n N_{H_2}(V;x)$ and $N_{H_2}(V;x)\ll O(1)^n N_{H_1}(V;x)$. Could the behavior of $N_{H_1}(V;x)$ and $N_{H_2}(V;x)$ nevertheless be qualitatiely different? For example -- could it be that $N_{H_1}(V;x)$ has an asymptotic, whereas $N_{H_2}(V;x)$ does not (i.e. it oscillates)?

A: Surely this behaviour can never happen, but it will be near impossible to prove this. Conjectures of Manin and others predict that there is an asymptotic formula for these functions in many cases, and the shape of the asymptotic only depends on the choice of embedding and not the choice of norm. (Changing the norm just changes the leading constant in the asymptotic formula).
A nice trick however is that if you can prove an asymptotic for a "dense" set of norms, then you get an asymptotic for all norms via standard approximation arguments. In particular, e.g. it suffices to prove an asymptotic for all norms which are given by infinitely differentiable functions.


text:
Q: Applying Permission Scope on Relation in Rails Let's say that I'm using the rolify gem.  The rolify gem handles permissions that a user can have on resource instances or a resource class.  This is simple.  If one needed to find out if a user could perform a certain task, it would result in something similar to this:
if user.has_role? :admin
  @article.update(article_params)
else
  fail # just as an example
end

However, I want to be able to apply these permissions on a scope, e.g. Article.all - specifically, I want to be able to determine which articles that a user can read.  Assuming that only users with the role :admin can read articles, how would I go about doing this?
Edit: The problem I'm facing is this.  I don't know, at runtime, which articles that any given user would be able to read.  That information is stored in the database.  Therefore, using a solution like cancancan or pundit would not - and cannot - help in this instance (note: I actually do use pundit).  Essentially, I have to figure out how to implement the Pundit's Scope class.
Before I found the rolify gem, I posed the question to a friend as such:

So what I did in order to solve it was this: every user has a set of groups; permissions can be defined on either the user or the groups (both work). Permissions effect a generalized set of records (where I just store the record type, with no ID), a specific record (record type and ID), or on the record as a whole (the record type, no ID, with a global flag). Permissions can also be negated, effectively removing any permissions a user has on a subject. So my database looks somewhat like this:
Permissions
   id: Integer
   actor_id: Integer
   actor_type: String
   subject_id: Integer
   subject_type: String
   action: String
   negated: Boolean
   global: Boolean
   precedence: Integer

Users
   id: Integer

Groups
   id: Integer

Articles
   id: Integer

I included Articles to help demonstrate what I'm trying to do. So if I apply these permissions:
Permission.create(actor: Group.find(1), subject: Article.find(1), action: "show")
Permission.create(actor: Group.find(1), subject_type: "Article", action: "show")
Permission.create(actor: User.find(1), subject: Article.find(1), action: "show", negated: true, precedence: 1)

When I go permission_scope(Article, User.find(1)), I should get this:
[#
, #
, ...]

The problem is, I don't know what the contents of permission_scope would be, so I don't know how to make it.

A: These are the basic policy examples from the Pundit readme adapted for Rolify.
For a simple case where you only need to check for a role on the user:
class PostPolicy < ApplicationPolicy
  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      if user.has_role?(:admin)
        scope.all
      else
        scope.where(:published => true)
      end
    end
  end

  def update?
    user.has_role?(:admin) or not post.published?
  end
end

If you have resource scoped roles you can use the scopes provided by Rolify:
class PostPolicy < ApplicationPolicy
  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      Post.with_role(:author, user)
      # or
      Post.with_all_roles([:author, :editor], user)
    end
  end

  def update?
    user.has_role?(:author, post)
  end
end

Why it's complicated:
To do the same scoping with your permissions system you would need something like:
user = User.joins(:permissions, groups: [:permissions]).find(1)

article_ids = Permission.where(
  actor_id: [user.id] + groups.ids,
  subject_type: 'Article',
  action: :show
).pluck(:subject_id)

Article.where(id: article_ids)

A: Based on your update you certainly want this logic in a separate class and probably in different modules due to the perceived complexity.  If this is in any open source stuff let me know because seeing it in use will help more.  This is not an easy problem but hopefully this will get you closer.
module Scope
  class Permission < Struct.new(:relation, :entity, :action)
    def call
      relation.merge(::Query::Permission.new(:relation, :entity, :action)
    end
  end
end

module Query
  class Permission < Struct.new(:relation, :entity, :action)
    def call
      #Here is where you implement the logic to find records related to a relation/entity/action
    end
  end
end

So now you have something that takes care of scoping and something that will search through your permission stuff to find the correct records.