text:
Q: How to map this JSON file in react gatsby I have this JSON file and I want to show in cards the information inside of gallery, how can I do that? Any ideas? Thank you very much
[
    {
        "slug": "camping",
        "img": "../assets/images/campingDetails.jpg",
        "name": "Camping",
        "description": "Acampada, campismo, campamento o el anglicismo camping hacen referencia a la actividad humana que consiste en colocar una vivienda temporal, ya sea portátil o improvisada, en un lugar con el fin de habitarla. También se denomina así al lugar físico donde se realiza esta actividad.",
        "gallery" : [

                {
                    "product" : [
                                  {"imageC": "../assets/images/campingDetails.jpg",
                                   "nombrePro": "Horometro",
                                   "descripcionPro": "Marca las horas de uso"
                                  },

                                  {"imageC": "../assets/images/campingDetails.jpg",
                                   "nombrePro": "Plasticos",
                                   "descripcionPro": "Para motos honda desde los años 2008-2011"
                                  }
                                ]
                }

    ]
    }
]

This is my query in graphql, the information that returs is everything OK, now I need to map
    detallesCategoriasJson(slug: {eq: camping}) {
      nombre
      descripcion
      img {
        childImageSharp {
          fluid {
            ...GatsbyImageSharpFluid
          }
        }
      }
      galeria {
        producto {
          imageC {
            id
            base
            childImageSharp {
              fluid {
                ...GatsbyImageSharpFluid
              }
            }
          }
          nombrePro
          descripcionPro
        }
      }
    }
`;

Now I want to display the information in cards this is my code , and I can't, this is my component
import React from 'react'
import styled from 'styled-components'
import Layout from '../components/layout'
import Button from '../components/Button'
import { graphql } from 'gatsby';
import Image from 'gatsby-image';
import { Container, Row, Col,Carousel, Card} from 'react-bootstrap'
import Logo from "../assets/images/logoimagen3.png"

import 'bootstrap/dist/css/bootstrap.min.css';

export const query = graphql`
  query ($slug : String! ) {
    detallesCategoriasJson(slug: {eq: $slug}) {
      nombre
      descripcion
      img {
        childImageSharp {
          fluid {
            ...GatsbyImageSharpFluid
          }
        }
      }
      galeria {
        producto {
          imageC {
            id
            base
            childImageSharp {
              fluid {
                ...GatsbyImageSharpFluid
              }
            }
          }
          nombrePro
          descripcionPro
        }
      }
    }
  }
`;

const templateDetalleCat = ({ data }) => {

  const tD = data.detallesCategoriasJson;
  return (
    <Layout>
        <Container>
        <ProductsHeading> Productos de {tD.nombre} </ProductsHeading>
        <Row>
          {tD.gallery.product.map(image => (
             <Col md={3}>
             <Card className="mb-3">
               <Image
                 fluid={image.gallery.product.imageC.childImageSharp.fluid}
                 alt={image.gallery.product.imageC.base.split('.')[0]}
                 className="card-img-top"
               />
             <Card.Body>
               <Card.Title> Hello </Card.Title>
               <Card.Text>
                 <p> Hello </p>
               </Card.Text>
               <Button  target="_blank" href="https://www.google.com.ec" >Comprar</Button>
             </Card.Body>
           </Card>
             </Col>
          ))}
          </Row>
        </Container>

    </Layout>
  )
}

export default templateDetalleCat

Hope you can help me
Regards.

A: Your nested structure is wrong. In your loop, image, stands for the iterable object (the array of products so, each product in each loop). In addition, if gallery (or galeria, the issue about the naming persists) is another array, you need to nest loops or get the desired position. I will assume that is your first position ([0]) but you may need to change it
import React from 'react'
import styled from 'styled-components'
import Layout from '../components/layout'
import Button from '../components/Button'
import { graphql } from 'gatsby';
import Image from 'gatsby-image';
import { Container, Row, Col,Carousel, Card} from 'react-bootstrap'
import Logo from "../assets/images/logoimagen3.png"

import 'bootstrap/dist/css/bootstrap.min.css';

export const query = graphql`
  query ($slug : String! ) {
    detallesCategoriasJson(slug: {eq: $slug}) {
      nombre
      descripcion
      img {
        childImageSharp {
          fluid {
            ...GatsbyImageSharpFluid
          }
        }
      }
      galeria {
        producto {
          imageC {
            id
            base
            childImageSharp {
              fluid {
                ...GatsbyImageSharpFluid
              }
            }
          }
          nombrePro
          descripcionPro
        }
      }
    }
  }
`;

const templateDetalleCat = ({ data }) => {

  const tD = data.detallesCategoriasJson;
  return (
    <Layout>
        <Container>
        <ProductsHeading> Productos de {tD.nombre} </ProductsHeading>
        <Row>
          {tD.galeria[0].product.map(item => (
             <Col md={3}>
             <Card className="mb-3">
               <Image
                 fluid={item.imageC.childImageSharp.fluid}
                 alt={item.imageC.base.split('.')[0]}
                 className="card-img-top"
               />
             <Card.Body>
               <Card.Title> {item.nombrePro} </Card.Title>
               <Card.Text>
                 <p> {item.descriptionPro} </p>
               </Card.Text>
               <Button  target="_blank" href="https://www.google.com.ec" >Comprar</Button>
             </Card.Body>
           </Card>
             </Col>
          ))}
          </Row>
        </Container>

    </Layout>
  )
}

export default templateDetalleCat


text:
Q: CodeDOM: Named Arguments I am trying to generate code for a constructor call. Something like
var obj = new Foo("bar", "baz", thirdParam: 5);

Part of my code:
var arg1 = new CodePrimitiveExpression("bar");
var arg2 = new CodePrimitiveExpression("baz");
var arg3 = new CodePrimitiveExpression(5);

var objectCreate = new CodeObjectCreateExpression(typeof(Foo), arg1, arg2, arg3);

var decl = new CodeVariableDeclarationStatement("var", "obj", objectCreate);

This is what is generated:
var obj = new Foo("bar", "baz", 5);

Is there any way (except from using CodeSnippetExpression) to create a named argument in CodeDOM?

A: No, this can't be done using CodeDOM (without using a Code Snippet as you suggest). Named arguments are syntactic sugar handled by the C# compiler.
Using CodeDOM you will need to provide a value for each parameter, even if it is null.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to type hint without import Is it possible to hint a non-native type without importing the class it comes from?
For example, I have a function that requires a 'pandas.DataFrame' object and uses its 'index' method. In this case, it is useless to import 'pandas', yet I cannot declare my input without importing the latter since 'DataFrame' is not a native python type:
def foo(x: DataFrame):
    print(x.index)

A: Pyi stub files
https://google.github.io/pytype/user_guide.html#pyi-stub-files

In some cases, it's not possible to add annotations to a module by
editing its source: C extension modules, external python source files,
etc . For those cases, PEP 484 allows you to declare a module's types
in a separate "stub" file with a .pyi extension. Pyi files follow a
subset of the python syntax and are analogous to header files in C
(examples).


text:
Q: Want to pull and convert items from a list to print as numbers less than a specific number I'm writing a program that takes 2 arguments, a list of numbers 1-10. and a variable of n = 6.
I made a function that takes in the two arguments and returns the values that are less than 6 into a new list. But I'm trying to print the numbers that are less than 6. It's printing the index numbers.
Is there a quick fix or simple way to convert the items in input_list into integers to print as a result?
it's printing [0,1,2,3,4]
but I want it to print [1,2,3,4,5]
Thanks for your help!
* Python3 code *
This program takes in two arguments, a number, and a list.
A function should return a list of all numbers less than the number
def main():

    #initialize a list of numbers
    input_list = [1,2,3,4,5,6,7,8,9,10]
    n = 6

    print("List of Numbers:")
    print(input_list)

    results_list = smaller_than_n_list(input_list,n)

    print("List of Numbers that are smaller than 6:")
    print(results_list)

def smaller_than_n_list(input_list,n):
    # create an empty list
    result = []

    for num in range(len(input_list)):
        if n > input_list[num]:
            result.append(num)
    return result

main()

A: you can just do:
def smaller_than_n_list(input_list, n):
    result = []
    for i in input_list: #i will be equal to 1, then, 2 ... to each value of your list
        if n > i:
            result.append(i) #it will append the value, not the index
    return result

A: the index in python starts from 0, when you iterate over range(len(input_list))  you are accessing and storing the indices so you get  [0, 1, 2, 3, 4], to fix you may use:
for item in input_lsit:
    if n > item:
        result.append(item)

in this way you are iterating over the elements from input_list and store in your list result the elements that are less than n
also, you may use a list comprehension:
def smaller_than_n_list(input_list,n):
    return [e for e in input_list if e < n]


text:
Q: SetEntryInHash vs. SetEntryInHashIfNotExists I've read in a couple places that Redis is idempotent, so a repeated call to SetEntryInHash() will have no effect, right?
Is there any good case for using SetEntryInHashIfNotExists()?  Can this give quicker results than just blindly calling SetEntryInHash()?

A: Idempotent means you can replay the same action multiple times and it will have the same side-effect. Only idempotent operations like SADD are idempotent, i.e. after calling that 1 or more than 1 times you will end up with the same result, i.e. a single item in the set.
Adding to a redis list, e.g. LINSERT is by contrast not idempotent as every new item adds a new item to the redis list.
If you want to know how operations in ServiceStack's Redis Client are implemented, just inspect the source code. SetEntryInHash and SetEntryInHashIfNotExists are here. They both call HSET and HSETNX respectively. Refer to the documentation in redis to learn about the behavior of each operation.

A: @mythz is right, with the source code at hand, quick to find the real answer, not to mention also including links to the redis documentation.  I was curious about the difference myself, and thought I would post the clarification here for others.
HSETNX : Sets field in the hash stored at key to value, only if field does not yet exist. If key does not exist, a new key holding a hash is created. If field already exists, this operation has no effect.
HSET : Sets field in the hash stored at key to value. If key does not exist, a new key holding a hash is created. If field already exists in the hash, it is overwritten.


text:
Q: Dynamic width of 'inline-block' while resizing window I put several tables (display: inline-block & fixed column width: 140px) side by side seperated by a 100px margin.
► CodePen / Original code
I want these margins to reduce when I resize the width of the window so that the line doesn't collapse too soon. I did find a way to do that, but it's hacky and I don't really like this solution.
► CodePen / Hacky solution
Exemple:

Env 3a	Env 3b

v1.2	v1.2

Env 4a	Env 4b

v1.2	v1.2

Env 5a	Env 5b

v1.1+	v1.1+

Is there a way to avoid max-width: 100px; width: calc(100vw - 840px - 135px);?
The values inserted in the 'calc' are an hit-and-miss.

A: You should give margin in percentage instead of px.
margin-right: 2%;


text:
Q: F# Excel Interop: Marshal.GetActiveObject("Excel.Application") does not work I am trying to use F# to automate some Excel tasks. I actually got two issues:
1. If I open a workbook using an Excel.Application instance, I would miss all the add-ins that would have been automatically loaded if I had just opened the workbook in Excel. So I try to open the workbook in Excel first, with all add-ins loaded, and then hand the instance to F#. Then I got the second issue:
2. The Marshal.GetActiveObject("Excel.Application") actually open a new instance, instead of getting the existing instance. The code is below:
#r "Microsoft.Office.Interop.Excel"
#r "office"

open Microsoft.Office.Interop
open System
open System.Runtime.InteropServices

let app = Marshal.GetActiveObject("Excel.Application")
let app1 = app :?> Excel.Application

let wb = app1.ActiveWorkbook

let visible = app1.Visible

let n = app1.Workbooks.Count

and the output is:

val app : obj
val app1 : Excel.Application
val wb : Excel.Workbook = null
val visible : bool = false
val n : int = 0

But I am very sure I have an Excel instance running and it is visible. Thanks!

A: I have double checked my code and this is the way to use Excel from F# script (use Excel-DNA for other cases). However, very often (especially when using add-ins) Excel does not close properly and some semi-dead Excel processes hang in the task manager until they are manually killed. Probably you are getting a wrong process, not the one where you open your workbook.


text:
Q: Second .wav file plays enhanced noise of first .wav file instead of reduced noise I am trying to achieve active noise reduction in python. My project is composed of two set of codes:

*

*sound recording code

*sound filtering code

What I aim for is that when you run the program, it will start recording through the microphone. After you've finished recording there will be a saved file called "file1.wav" When you play that file, it is the one that you recorded originally. After you're finished with that, you will now put "file1.wav" through a filter by calling "fltrd()". This will create a second wav file in the same folder and that second wav file is supposedly the one with less/reduced noise. Now my problem is that the second wav file is enhancing noise instead of reducing it. Can anyone please troubleshoot my code? :(
Here is my code below:
import pyaudio
import wave
import matplotlib.pyplot as plt
import numpy as np
import scipy.io.wavfile
import scipy.signal as sp

FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "file1.wav"

audio = pyaudio.PyAudio()

# start Recording
stream = audio.open(format=FORMAT, channels=CHANNELS,
                rate=RATE, input=True,
                frames_per_buffer=CHUNK)
print ("recording...")
frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)
print ("finished recording")

# stop Recording
stream.stop_stream()
stream.close()
audio.terminate()

waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()

x = scipy.io.wavfile.read('file1.wav')
n = x[1]
y = np.zeros(n.shape)
y = n.cumsum(axis=0)

def fltrd():
    n,x = scipy.io.wavfile.read('file1.wav')
    a2 = x.cumsum(axis=0)
    a3 = np.asarray(a2, dtype = np.int16)
    scipy.io.wavfile.write('file2.wav',n,a3)

A: Actual noise filtering is difficult and intense. However, an simple noise filter using high and low pass filter can be easily created using pydub library. See here for more details  (install, requirements etc)
Also see here for more details on low and high pass filter using pydub.
Basic idea is to take a audio file and then pass it through both low and high pass filter such that audio above and below certain threahold will be highly attenuated (in effect demonstrating filtering).
Although, this will not affect any noise falling in pass-band for which you will need to look at other noise cancellation techniques.
from pydub import AudioSegment
from pydub import low_passfilter
from pydub import high_pass_filter
from pydub.playback import play

song = AudioSegment.from_wav('file1.wav')

#Freq in Hz ,Adjust as per your needs
new = song.low_pass_filter(5000).high_pass_filter(200)
play(new)


text:
Q: Looking for records of the current month with a DataMapper query I'm trying to reproduce this SQL query I used with ActiveRecord:
Post.all(:conditions => ["EXTRACT(MONTH from created_at) = ? AND EXTRACT(YEAR from created_at) = ?", month, year])

But since I'm converting everything to DataMapper I was looking for a way to do this...
Can anyone help?

A: I presume since this is tagged with "ruby-on-rails" that you have ActiveSupport loaded. This will provide the Time#end_of_month helper method. With it you can rewrite your query as:
time = Date.new(year, month).to_time

Post.all(:created_at => time..time.end_of_month)

Not only is this simpler, it eliminates raw SQL from the query (so the query is more portable to things other than RDBMS), and most importantly it will probably perform much better than the other query. With EXTRACT the database will likely have to perform a full table scan to  extract the year and month from created_at in every row, and then compare them against your expected values. If you have a large dataset, this could be a significant load on your DB. However, provided your created_at column is indexed, the above approach should be extremely efficient in comparison.


text:
Q: Could not find bcrypt-3.1.7 in any of the sources I have installed bcrypt using the command
gem install bcrypt
I can confirm that it is installed in my gem folder both local and @global and it is the correct version '3.1.7'. And... I have added the following line to my project:
gem 'bcrypt', '~> 3.1.7'
When I run bundle install I get this...
Your bundle is complete!
However when I issue this command:
rails generate devise:install
I get the following...
Could not find bcrypt-3.1.7 in any of the sources
Run `bundle install` to install missing gems.
user-pc:blog user$

I have even run:
bundle list
And I get a list of installed bundles and bcrypt 3.1.7 shows up!!

A: Killing the spring server worked for me.
$ ps aux | grep spring
46124   0.1  0.2  2479932  17964   ??  Ss   11:19AM   0:00.31 spring app    | Boomtownrack | started 33 secs ago | development mode
58978   0.0  0.1  2514736  11696 s002  S     3:30PM   0:00.43 spring server | Boomtownrack | started 12 hours ago
46130   0.0  0.0  2432784    628 s002  S+   11:19AM   0:00.00 grep spring

$ kill 58978

A: I had this same problem, it seems all I had to do was delete the Gemfile.lock file, and then re-run bundle!
You may also need to run bundle exec rails generate devise:install but it worked fine for me without the bundle exec.

A: You should try bundle update or bundle install --path=vendor/bundle


text:
Q: Append Values in NSSet To An Array of Type [String] I am attempting to get the values from an NSSet in core data and append those values to an array of type String.
func addStepsToArray() {
    if let steps = entity.steps {
        for i in steps {
            recipeStep.append(String(i))
        }
    }
}

entity.steps is the list of steps tied to a core data entity. This is an NSSet. I am trying to copy those values to an array of type String.
@State var recipeStep: [String]

When trying to do this in my for in loop, I receive the following error: No exact matches in call to initializer
If I remove the conversion of "I" to String, I receive the following error:

Cannot convert value of type NSSet.Element (aka Any) to expected argument type String

Any idea on how to get this to work?

A: NSSet is defined in Objective C, which didn't have generics. It's an untyped collection, so you don't statically know anything about its elements.
As you've noticed, your i variable isn't a String, it's an Any.
You're confusing type coercion ("casting") with type conversion. If i were a Double, you could call String(i) to invoke an initializer which takes a double, and processes into a String.
You tried something similar by calling String(i), where you're making the Swift compiler find an initializer on String with the signitiure init(_: Any).
There is no such initializer. And besides, that's not what you want. You don't want to create a new String from a different kind of value. You already have a string, it's just "hidden" behind an Any reference.
What you're looking for is to do a down-cast, from Any to String:
func addStepsToArray() {
    if let steps = entity.steps {
        for i in steps {
            guard let step = i as? String else {
                fatalError("Decide what to do if the value isn't a String.")
            }
            recipeStep.append(i as String)
        }
    }
}

I'll warn you though, there are several issues/blemishes with this code:

*

*You're using a for loop to do what is ultimately just a mapping operation

*Your computation doesn't return its ouput, and instead indirectly achieves its goal through a side-effect on recipeStep

*Your computation doesn't take a its input as a parameter, and instead indirectly achieves its goal through a side-effect on entity

*i is conventionally expected to be an integer index of a for loop iterating over a sequence of numbers. Here it's an Any (a String at runtime)

Here's what I would suggest instead:
func getRecipeSteps(from entity: MyEntityType) -> [String] {
    guard let steps = entity.steps else { return [] }

    return steps.map { step in
        guard let stringStep = step as? String else {
            fatalError("Decide what to do if the value isn't a String.")
        }

        return step
    }
}

Then in the rest of your code (and your tests), you can write self.recipeSteps = getRecipeSteps(from: myEntity). Elegant!
If you're certain that these entity.steps values can only ever be strings, then you can boil this down to a single map with a force-cast:
func getRecipeSteps(from entity: MyEntityType) -> [String] {
    entity.steps?.map { $0 as! String } ?? []
}

A: Just convert directly:
let set = Set(["1", "2", "3"])
let array = Array(set)
DDLog(set)//Set<String>)
DDLog(array)//[String]


text:
Q: Обработка нажатия клавиш winforms Процесс делает некоторые действия в браузере и на рабочем столе. Соответственно фокус находится вне winforms приложения во время исполнения. Вопрос, как задать обработку клавиш, которая оказывала воздействия именно на приложение. Нашел несколько решений, но все они рассматривались при условии, что приложение находилось в фокусе.

A: Если ваше окно теряет фокус, но вы все равно хотите, что бы оно реагировало на нажатия клавиш клавиатуры, то решением тут будет глобальный хук на клавиатуру (можно и на мышь, кстати, тоже).
В целом, при запуске приложения вы регистрируете свой обработчик нажатий на клавиатуру, обрабатываете нажатия, потом передаете события дальше (могут быть помимо вашего и другие хуки в системе), а при завершении работы приложения корректно снимаете свой хук.
Тема работы с клавиатурными хуками поднималась тут, например, вот ответ на аналогичный вопрос, в котором есть ссылки на статьи и реализации хуков.
Или вот, пример ответа с кодом (не буду его копипастить сюда).
Есть еще вот такая статья с примером на английском.
И есть еще замечательная статья на русском в блоге Miccrosoft, с примером.
Статья со временем может переехать или исчезнуть, потому код оттуда позволю себе продублировать тут. В примере есть и назначение хука, и его снятие, и обработка сочетания клавиш, в частности, обрабатывается Alt + Tab.
Как говорит автор,

Пример этот будет работать как на 32х так и на 64 битной Windows. Программа выводит в отладочную консоль нажатия на клавиши в любом приложении, а также производит блокировку нажатия Alt+Tab. Как вы уже понимаете, перехват клавиатуры ведется на уровне всех приложений.

Итак:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace HookDemoApp
{
   internal class HookDemoHelper
   {
       private const int WH_KEYBOARD_LL = 13;

       private LowLevelKeyboardProcDelegate m_callback;
       private IntPtr m_hHook;

       [DllImport("user32.dll", SetLastError = true)]
       private static extern IntPtr SetWindowsHookEx(
        int idHook,
        LowLevelKeyboardProcDelegate lpfn,
        IntPtr hMod, int dwThreadId);

       [DllImport("user32.dll", SetLastError = true)]
       private static extern bool UnhookWindowsHookEx(IntPtr hhk);

       [DllImport("Kernel32.dll", SetLastError = true)]
       private static extern IntPtr GetModuleHandle(IntPtr lpModuleName);

       [DllImport("user32.dll", SetLastError = true)]
       private static extern IntPtr CallNextHookEx(
        IntPtr hhk,
        int nCode, IntPtr wParam, IntPtr lParam);

       private IntPtr LowLevelKeyboardHookProc(
        int nCode, IntPtr wParam, IntPtr lParam)
       {
           if (nCode < 0)
           {
               return CallNextHookEx(m_hHook, nCode, wParam, lParam);
           }
           else
           {
               var khs = (KeyboardHookStruct)
                         Marshal.PtrToStructure(lParam,
                         typeof (KeyboardHookStruct));

               Debug.Print("Hook: Code: {0}, WParam: {1},{2},{3},{4} ",
                         nCode, wParam, lParam,
                         khs.VirtualKeyCode,
                         khs.ScanCode, khs.Flags, khs.Time);

               Debug.Print(khs.VirtualKeyCode.ToString());

               if (khs.VirtualKeyCode == 9 &&
                  wParam.ToInt32() == 260 &&
                  khs.ScanCode == 15) //alt+tab
               {
                   System.Console.WriteLine("Alt+Tab pressed!");
                   IntPtr val=new IntPtr(1);
                   return val;
               }
               else
               {
                   return CallNextHookEx(m_hHook, nCode, wParam, lParam);
               }
           }
       }

       [StructLayout(LayoutKind.Sequential)]
       private struct KeyboardHookStruct
       {
           public readonly int VirtualKeyCode;
           public readonly int ScanCode;
           public readonly int Flags;
           public readonly int Time;
           public readonly IntPtr ExtraInfo;
       }

       private delegate IntPtr LowLevelKeyboardProcDelegate(
        int nCode, IntPtr wParam, IntPtr lParam);

       public void SetHook()
       {
           m_callback =LowLevelKeyboardHookProc;
           m_hHook =SetWindowsHookEx(WH_KEYBOARD_LL,
            m_callback,
            GetModuleHandle(IntPtr.Zero),0);
       }

       public void Unhook()
       {
           UnhookWindowsHookEx(m_hHook);
       }
}

}
Всё...


text:
Q: High scores table I am looking to add a (local, not online) high scores table to my Android app and I wanted to get some insight on the best way to approach the problem.
I have a list of users (right now being saved out to a file and read back in as an array of User objects), and the high scores need to reference this data to populate the table with the user's name and photo, etc.
For the display, I think a TableLayout would probably be my best option. I can make columns for picture, name, score, etc.
For the information itself, I'm thinking maybe a SQLite table would be the best way to organize my data? If so, then it may be worthwhile to move my user data to a SQLite table as well so I can ensure the data is cross-referenced properly.
Does anybody here have any helpful information or opinions on this? Thanks.
UPDATE: I went with the SQLite database (using two tables) and it works great! Wasn't too hard to learn and get working either. For the layout, it turns out a ListView with a custom adapter was the best way to accomplish what I wanted (more flexible than a TableLayout).

A: I haven't done a lot with Andriod but I believe you are on the right path.  Using the SQLite for data will not only help keep your data structured and organized it will allow your data set to grow exponentially and you can use a common standard way to go from SQL database to Objects using a DAO pattern.  I would recommend using SQLite with MyBatis.  MyBatis is an Object Relational Mapping utility for java.  It allows you to write sql and get back your results as java object.  MyBatis

A: I personally think it would be simpler to use a SQlite table for this. From what I can tell you only really need one table, so it might be a bit of overkill but to me it seems much simpler than dealing with file I/O.
Also with database you can more readily add extra information such as date it was recorded etc.

A: For something as dirt simple and non-critical as a high scores list, a database feels a little like overkill to me.  I'd be inclined to use a CSV file myself.
Of course, take that with a suitable grain of salt, as I don't develop on Android.  If the overhead for SQLite is trivial (or if it's already on Android waiting for you to use it!), may as well use it for your data storage needs, if only to keep your code consistent.

A: ScoreNinja, the open-source score library for Android, might save you some time, or give you some ideas.


text:
Q: c++ futures/promises like javascript? I've been writing some javascript and one of the few things I like about the environment is the way it uses promises/futures to make handlers for asynchronous events.
In C++ you have to call .get on a future and it blocks until the result of the future is available but in Javascript you can write .then(fn) and it will call the function when the result is ready. Critically it does this in the same thread as the caller at a later time so there are no thread synchronization issues to worry about, at least not the same ones as in c++.
I'm thinking in c++ something like -
auto fut = asyncImageLoader("cat.jpg");
fut.then([](Image img) { std::cout << "Image is now loaded\n" << image; });

Is there any way to achieve this in c++? Clearly it will need some kind of event queue and event loop to handle dispatching the callbacks. I could probably eventually write the code to do most of this but wanted to see if there was any way to achieve the goal easily using standard facilities.

A: I don't like c++'s future, so i wrote a promise libraries as javascript here
https://github.com/xhawk18/promise-cpp
/* Convert callback to a promise (Defer) */
Defer myDelay(boost::asio::io_service &io, uint64_t time_ms) {
    return newPromise([&io, time_ms](Defer &d) {
        setTimeout(io, [d](bool cancelled) {
            if (cancelled)
                d.reject();
            else
                d.resolve();
        }, time_ms);
    });
}

void testTimer(io_service &io) {

    myDelay(io, 3000).then([&] {
        printf("timer after 3000 ms!\n");
        return myDelay(io, 1000);
    }).then([&] {
        printf("timer after 1000 ms!\n");
        return myDelay(io, 2000);
    }).then([] {
        printf("timer after 2000 ms!\n");
    }).fail([] {
        printf("timer cancelled!\n");
    });
}

int main() {
    io_service io;
    testTimer(io);
    io.run();
    return 0;
}

compare with Javascript promise, just --

*

*Use newPromise instead of js's new Promise

*Use lambda instead of js function

*Use d.resolve instead of js's resolve

*Use d.reject instead of js's reject

You can resolve/reject with any type of paramters, and need not care about the troublesome of <> in c++ template.

A: While then is proposed, you can implement your own infix then via the named operator technique.
Create a struct then_t {}; and a static then_t then;.  Now override operator* on the left and right so that std::future<bool> *then* lambda creates a std::async that waits on the future, and passes the result to the lambda, then returns the return value of the lambda.
This requires lots of care and attention, as you have to carefully create copies to avoid dangling references, and mess around with r and l value syntax to make it fully efficient.
The end syntax you get is:
aut fut = asyncLoader("cat.jpg");
fut *then* [&](Image img) { std::cout << "Image loaded: " << img; };

which is pretty close to what you want.
If you are really smart, you could even have it also support:
aut fut = asyncLoader("cat.jpg");
fut *then* [=] { std::cout << "Image loaded: " << fut.get(); };

which gets rid of some of the boilerplate and would be useful sometimes.  This requires asyncLoader to return a std::shared_future instead of a future.

A: You could pass an object thats for example implementing a Runnable class to the "then" method of the Future class. Once the Future finished its work, call the "run" method of the passed object.

A: A .then function for std::future has been proposed for the upcoming C++17 standard.
Boost's implementation of future (which is compliant with the current standard, but provides additional features as extensions) already provides parts of that functionality in newer versions (1.53 or newer).
For a more well-established solution, take a look at the Boost.Asio library, which does allow easy implementation of asynchronous control flows as provided by future.then. Asio's concept is slightly more complicated, as it requires access to a central io_service object for dispatching asynchronous callbacks and requires manual management of worker threads. But in principle this is a very good match for what you asked for.

A: Take a look at https://github.com/Naios/continuable .  It supports Javascript style .then().  It also supports exceptions with .fail() (instead of .catch()).  There is a great talk about it here https://www.youtube.com/watch?v=l6-spMA_x6g

A: Use JavaScript-like Promises for C++20.  It relies on C++20 coroutines, supports ES6 await/async semantics, and very importantly, it supports 'move' so you can write wrappers for frameworks like asio (e.g. because asio::ip::tcp::socket cannot be copied).
Link: https://github.com/virgil382/JSLikePromise

A: The question is a bit old, but here is a Javascript-like promise library (consist of a single header that you simply need to include) that aims to do exactly what you ask for, of course together with some sort of async I/O library to implement the actual asyncImageLoader().
https://github.com/alxvasilev/cpp-promise


text:
Q: Services running on same host as OpenVPN do not receive traffic from VPN So we are setting up and testing new internal systems, using Docker to deploy OpenVPN, Jenkins, and bind all on the same host. We want to restrict access to only come from traffic that originates from our VPN.
For our other internal systems (on different hosts), this works as expected. We can configure ufw to restrict based on the IP of our VPN server, and it works as expected, meaning we can't access when off the VPN, and we can when on the VPN.
However, for the services running within Docker on the same host as our OpenVPN server, traffic never appears to come from the VPN. Connected or not, it always appears to be from the actual IP address of the remote (connecting) client.
OpenVPN is setup using the popular Docker OpenVPN image. We're using the defaults, which means all traffic is supposed to be routed over the VPN connection.
What am I missing/forgetting?

A: That sounds like you have a masquerade/snat rule in the nat/postrouting chain (edit: of the vpn server host) that transforms source IP addresses from the client address to the VPN server host address for traffic bound to other hosts on the vpn server side.
But the postrouting chain would not be hit for traffic that is destined for the host that runs the vpn server. The last chain would be filter/input. This is the case even if traffic from the client comes into the host running the vpn server on its tun/tap dev for a service that is listening on the eth0 dev.
If this is the case, the easiest way to deal with that would be on the client side by snat/masquerading all traffic routed over the vpn to the client's tun/tap address.


text:
Q: Hyperledger Farbic v2.0 problem with ChaincodeException payload The main problem is getting payload error from client perspective.
Basic setup:
Fabric chaincode -> implemented in Java with fabric-chaincode-shim: v2.3.0
Application client -> implemented in Typescript by using fabric-network: 2.2.5.
Every transaction which were implemented works properly but I would like to know how can I implement error_codes which should be readable by client.
When I was throwing ChaincodeException with payload as below, then I have got empty buffer property from client application perspective.
Example code from chaincode perspective:
public void createAsset(final Context ctx, String createAssetDto) {
    throw new ChaincodeException("Sample message", "SamplePayloadWithSpecifiedCode");
}

Example code from application client perspective:
    try {
        await contract.submitTransaction('createAsset', JSON.stringify(createAssetDto));
        success = true;
    } catch (err) {
        logException(err);
        success = false;
    }

I have noticed that in peer implementation there is a function which parse ChaincodeMessage as an Error

    case pb.ChaincodeMessage_ERROR:
        return nil, resp.ChaincodeEvent, errors.Errorf("transaction returned with failure: %s", resp.Payload)

From peer perspective log:
failed to invoke chaincode ecmr, error: transaction returned with failure: Sample Message
github.com/hyperledger/fabric/core/chaincode.processChaincodeExecutionResult
    /go/src/github.com/hyperledger/fabric/core/chaincode/chaincode_support.go:182

From this perspective it means that ChaincodeException message is the payload.
From client perspective error has got:
{
  status: 500,
  message: "error in simulation: transaction returned with failure: Sample Message",
  payload: {
  },
}

I think that I should get "SamplePayloadWithSpecifiedCode" in response.payload property.
I've already found possible the place in source code where message is set as payload from ChaincodeException in java chaincode implementation:

Any advice welcome. Thanks

A: SDKs should provide the payload in case of error in Fabric v2.x. however this is currently a known issue. You can check through Fabric Jira and Rocket Chat.
See the related links below.

*

*FABN-1667 - Payload no longer provided in Evaluation errors in SDK

*FABG-974 - Error codes >= 400 do not return a message or payload

*FABN-1041 - inconsistent response if promise is rejected

*Java SDK chat

*

*Returning contexts(with error logs) to the client(requester) can see the internal structure, it is considered bad security practice


text:
Q: How to generate PDF in Rails 5 Grape API endpoint and send in response? I am using rails 5 and grape gem for building my application. Now I have a requirement of generating a PDF and send back to the response using grape endpoint. I am using wicked_pdf gem and wkhtmltopdf-binary for generate PDF. But I am facing the issue of undefined method 'render_to_string'.
I have tried various way to resolve it. but couldn't find any solution.
Below is my code snippet
API Endpoint:
module Endpoints
  class GeneratePdf < Grape::API
    get do
      users = User.all # I want this users list in my PDF
      pdf = WickedPdf.new.pdf_from_string(render_to_string('users/index.html.erb')) # placed in app/views/users/pdf.html.erb
      # some code here for send pdf back to response
    end
  end
end

Gemfile:
gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'

Config > initializers > mime_types.rb
Mime::Type.register "application/pdf", :pdf

A: Grape::API, don't have a render_to_string method that you can call on it, unlike a typical Rails controller. You should be able to replace that with something similar to this:
require 'erb'
binding_copy = binding
binding_copy.local_variable_set(users: User.all)
template = File.open(Rails.root.join('app/views/users/index.html.erb))
string = ERB.new(template).result(binding_copy)
pdf = WickedPdf.new.pdf_from_string(string)


text:
Q: How to send extra **Kwargs to event click method of an ipyvuetify button I am using ipyvuetify to create a dashboard including several buttons.
here the code for one of them:
import ipyvuetify as vue
from ipywidgets import Output

out = Output()
mybtn = vue.Btn(color='primary', children=['Run'])

def btn_method(widget, event, data):
    with out:
        print('btn was clicked')

mybtn.on_event('click', btn_method)

display(mybtn,out)

My problem is that when clicking a button the actions carried out depend on some varaibles. The question is how can I send to the button extra data, i.e. a dictionary of data.
Pseudo code:
import ipyvuetify as vue
from ipywidgets import Output
out = Output()
mybtn = vue.Btn(color='primary', children=['Run'])
# t followoing does not work, nor it gives an error:
def btn_method(widget, event, data, **kwargs):
    with out:
        print('btn was clicked')
        print(len(kwargs))
    if myvar==4:
        #do this
        pass
    else:
        #do that
        pass

mybtn.on_event('click', btn_method, kwargs={'myvar':4})

display(mybtn,out)

Of course the error is: on_event() got an unexpected keyword argument 'kwargs', i.e. you are not supposed to send other vars into the on_event method.
Any idea how to proceed?
thanks

A: One possibility is to use functools.partial to make a new callback
function on-the-fly, that would have the extra args you want to pass already defined:
import functools

def btn_method(widget, event, data, **kwargs):
    with out:
        print('btn was clicked')
        print(len(kwargs))
    if kwargs.get("myvar")==4:
        #do this
        pass
    else:
        #do that
        pass

mybtn.on_event('click', functools.partial(btn_method, myvar=4))

(untested code)

A: you can simply set your dictionary as an additional attribute of the button object and read it inside the callback function.
mybtn = vue.Btn(color='primary', children=['Run'])

def btn_method(widget, event, data):
    with out:
        print('btn was clicked')
        print(widget.kwargs)
    if widget.kwargs['myvar']==4:
        #do this
        pass
    else:
        #do that
        pass

mybtn.on_event('click', btn_method)
mybtn.kwargs={'myvar':4}


text:
Q: How to send Emails via Spring In my JavaFx project I inject my controllers like so, which works fine:
@Configuration
public class AppFactory {

    @Bean
    public HomeController homeController() throws IOException {
        return (HomeController) loadController("/wakiliproject/Home.fxml");
    }

    FXMLLoader loader = null;

    protected Object loadController(String url) throws IOException {
        loader = new FXMLLoader(getClass().getResource(url));
        loader.load();
        return loader.getController();
    }
}

However, for non-controller classes, I get a null pointer exception, probably because the class never gets injected. Say, for example, I try to call a method in a non-controller class from another non-controller class like so:
Sending email via Spring, for example:
public class HomeController extends Application {

    @Autowired
    MailMail mailMail;

    // Send email here
    public void sendEmailMethod() {
        System.out.println("Here ----------------------------------------------------------------");
        mailMail.sendMail("olireylikesyou@gmail.com", "tryrevilo@yahoo.com", "Hello", "Subjecto");

    }

    // The other class methods

The other classes:
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
    <property name="host" value="smtp.gmail.com" />
    <property name="username" value="mygmailusername@gmail.com" />
    <property name="password" value="gmailpassword" />
    <property name="javaMailProperties">
        <props>
            <prop key="mail.smtp.auth">true</prop>
        </props>
    </property>
</bean>

<bean id="mailMail" class="wakiliproject.ServerSide.EMail.MailMail">
    <property name="mailSender" ref="mailSender" />
</bean>

--
public class MailMail {

    private MailSender mailSender;

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void sendMail(String from, String to, String subject, String msg) {
        //creating message
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(msg);
        //sending message
        mailSender.send(message);
    }
}

The stacktrace:
Exception in Application start method
java.lang.reflect.InvocationTargetException
    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:483)
    at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:367)
    at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:305)
    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:483)
    at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:894)
    at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:56)
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:158)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.mail.MailSendException: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. k10sm2188955lae.42 - gsmtp
; message exceptions (1) are:
Failed message 1: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. k10sm2188955lae.42 - gsmtp

    at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:448)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:308)
    at org.springframework.mail.javamail.JavaMailSenderImpl.send(JavaMailSenderImpl.java:297)
    at wakiliproject.ServerSide.EMail.MailMail.sendMail(MailMail.java:22)
    at wakiliproject.HomeController$HomeInit.homeInit(HomeController.java:618)
    at wakiliproject.HomeController$HomeInit.access$100(HomeController.java:613)
    at wakiliproject.HomeController.initHomeController(HomeController.java:319)
    at wakiliproject.WakiliProject.start(WakiliProject.java:34)
    at com.sun.javafx.application.LauncherImpl$8.run(LauncherImpl.java:837)
    at com.sun.javafx.application.PlatformImpl$7.run(PlatformImpl.java:335)
    at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:301)
    at com.sun.javafx.application.PlatformImpl$6$1.run(PlatformImpl.java:298)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl$6.run(PlatformImpl.java:298)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$300(WinApplication.java:39)
    at com.sun.glass.ui.win.WinApplication$4$1.run(WinApplication.java:112)
    ... 1 more
Exception running application wakiliproject.WakiliProject
Java Result: 1

A: had a similar problem... got me some attempts to configure it right in my application.properties (I'm injecting JavaMailSender using spring)
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth = true;
spring.mail.properties.mail.socketFactory.port=587
spring.mail.properties.mail.socketFactory.class=javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.socketFactory.fallback=false

later i was required to enable looser security to my account during the test:
"change your settings at https://www.google.com/settings/security/lesssecureapps so that your account is no longer protected by modern security standards"
or i got an authentication error.
I hope that helps

A: According to Mladen Uzelac You need to set some properties for your SMTP connection.
Link related:
http://forum.spring.io/forum/spring-projects/web/68425-javax-mail-messagingexception-530-5-7-0-must-issue-a-starttls-command-first-5sm505


text:
Q: Javascript array display buttons on each click HTML and JS....I need the array values to be displayed one by one on each click of the "create new button" button. Right now when I click it displays each button in the array???

    <button onClick="myPar()">Directions</button>
    <button onClick="make()">Create New Button</button>

A: You are iterating the whole array on every click. Instead of the for loop just hold a currentIndex variable outside of the function, then on each click get the sit[currentIndex], use it per your need and afterwards raise the currentIndex by 1.
var currentIndex = 0;
sit = new Array("kilroerock.com","ultimateguitar.com","premierguitar.com","jhspedals.com","sweetwater.com","guitarcenter.com","musiciansfriend.com","patriots.com","bostonceltics.com")

function make(){
    if ( currentIndex < sit.length )
    {
        var btn = document.createElement("input");
        btn.setAttribute("value",sit[currentIndex]);
        btn.setAttribute("type","button");
        btn.setAttribute("style","background:#1B0D0D;color:white");
        btn.setAttribute("onClick","document.location='http://www." + sit[currentIndex] + "'")
        document.body.appendChild(btn);

        currentIndex++;
    }
}

Here is a working example.

A: Simplest route based on your existing code is to implement a "counter".

// Initialize the counter outside of all functions, set to zero
var buttonIndex = 0;

function myPar() {
  var pgp = document.createElement("p");

  var txt = document.createTextNode('Click on the "Create New Button" to reveal up to 10 links!!!');

  pgp.appendChild(txt);

  document.body.appendChild(pgp);
}

function make() {
  sit = new Array("kilroerock.com", "ultimateguitar.com", "premierguitar.com", "jhspedals.com", "sweetwater.com", "guitarcenter.com", "musiciansfriend.com", "patriots.com", "bostonceltics.com")

  // Only add the button if within the array length
  if (buttonIndex < sit.length) {
    var btn = document.createElement("input");

    // Modify this line to use buttonIndex, not i
    btn.setAttribute("value", sit[buttonIndex]);

    btn.setAttribute("type", "button");

    btn.setAttribute("style", "background:#1B0D0D;color:white");

    // Modify this line to use buttonIndex, not i
    btn.setAttribute("onClick", "document.location='http://www." + sit[buttonIndex] + "'")

    document.body.appendChild(btn);

    // Increment the buttonIndex
    buttonIndex++;
  }
}

  <button onClick="myPar()">Directions</button>
  <button onClick="make()">Create New Button</button>

A: Are you expecting something like this
Here s working example
https://plnkr.co/edit/juTx9sEZ4PhAoDrb2uHM?p=preview
function buttonClick(){
  var length = sit.length;

        if(i<length){
        var btn = document.createElement("input");

        btn.setAttribute("value",sit[i]);

        btn.setAttribute("type","button");

        btn.setAttribute("style","background:#1B0D0D;color:white");

        btn.setAttribute("onClick","document.location='http://www." + sit[i] + "'")

        document.body.appendChild(btn);
        i++;}
}


text:
Q: Is the set of points for which $\lim f_n$ exists still measurable? Suppose $(X,\mathscr A)$ is a measurable space, $Y$ is Polish and $f_n:X\to Y$ is a sequence of measurable functions. Then  the set $L\subseteq X$ for which $\lim f_n$ exists is measurable. The proof relies on the fact that $L$ is just the set of $x\in X$ for which $(f_n(x))_n$ is Cauchy in $Y$. Of course, this only works because $Y$ is complete. Moreover, it is clear that separability is necessary, to ensure that $\mathscr B(Y\times Y)=\mathscr B(Y)\times \mathscr B(Y).$ Now I am wondering what happens if we remove the condition of completeness of $Y?$ Obviously the forementioned proof won't work. In fact, I think that completeness is necessary, and am looking for a counterexample. i.e.; a sequence of measurable $f_n$ such that $L=\left \{ x:\lim f_n(x)\  \text {exists} \right \}$ is not measurable.

A: Let $X$ be a measurable space, $S\subset X$ a non-measurable subset. Let $Y=X\times\mathbb{R}-S\times\{0\}$, and define $f_n(x)=(x,n^{-1})$. Then
$$
\{x:\lim_n\, f_n(x)\text{ exists}\}=X- S
$$
is not measurable.


text:
Q: How to make a TextBox non-interactive in C# I've got a TextBox on a form that I am using to just display data.  I have set it to ReadOnly which stops the user from changing the data displayed in the TextBox.  Although the user can still highlight the data in the TextBox, how do I disable this?
NOTE: I know using a label would be much easier, although for some reason the label wont let me display the data how I would like.  I want to display a number starting from the right of the display area, IE: "  25", although the label displays it like "25  ".  I have tried making the label right-justified this does not solve the issue.  Therefore I am using a TextBox.

A: TextBox1.Enabled = false;

Or you can use the label with the property RightToLeft set to True

A: You can display right aligned text in label by setting TextAlign property to e.g. MiddleRight. Remember also to set AutoSize property to false, otherwise it will resize the label and the position will change to left.

A: You can modify an event handler (say, on the Enter action) to move the Active property of the form to another control.

A: This is just a simple C# code and I just wrote it to disable some of my textboxes and button. But, you can change it as per your requirements:

TextBox[] tbArray = new TextBox[]
{
    custid,custname , field, email, phone, address
};
for (int i = 0; i < tbArray.Length; i++)
{
    if (status.SelectedIndex == 1)
    {
        tbArray[i].Enabled = false;
        savecust.Enabled = false;
        deletecust.Enabled = false;
    }
    else
    {
        tbArray[i].Enabled = true;
        savecust.Enabled = true;
        deletecust.Enabled = true;
    }
}


text:
Q: C# class to XML where a list of entries show up without "father property" node Having the following example code:
public class MyHeader
{
    public string Identification { get; set; }
    public DateTime  Date { get; set; }
    public string Description { get; set; }
    public List<MyChild> Children { get; set; }
}

public class MyChild
{
    public string Identification { get; set; }
    public string Description { get; set; }
}

public string GetXML()
    {
        var h = new MyHeader
        {
            Date = DateTime.Now,
            Description = "Something",
            Identification = "AAAAA11111",
            Children = new List<MyChild>
            {
                new MyChild { Identification = "B1", Description = "B1"},
                new MyChild { Identification = "B2", Description = "B2"},
                new MyChild { Identification = "B3", Description = "B3"}
            }
        };
        var xml = "";
        var serializer = new XmlSerializer(h.GetType());
        using (var sww = new StringWriter())
        {
            using (XmlWriter writer = XmlWriter.Create(sww))
            {
                serializer.Serialize(writer, h);
                xml = sww.ToString();
            }
        }
        return xml;
    }

The result is:
<?xml version="1.0" encoding="utf-16"?>
<MyHeader xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Identification>AAAAA11111</Identification>
    <Date>2020-09-09T11:55:04.2457349+02:00</Date>
    <Description>Something</Description>
    <Children>
        <MyChild>
            <Identification>B1</Identification>
            <Description>B1</Description>
        </MyChild>
        <MyChild>
            <Identification>B2</Identification>
            <Description>B2</Description>
        </MyChild>
        <MyChild>
            <Identification>B3</Identification>
            <Description>B3</Description>
        </MyChild>
    </Children>
</MyHeader>

Now the question: what is the easiest solution to produce the final XML without showing the <Children> node, but merging the children in the Header?
Result that I am looking for:
<?xml version="1.0" encoding="utf-16"?>
<MyHeader xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Identification>AAAAA11111</Identification>
    <Date>2020-09-09T11:55:04.2457349+02:00</Date>
    <Description>Something</Description>
    <MyChild>
        <Identification>B1</Identification>
        <Description>B1</Description>
    </MyChild>
    <MyChild>
        <Identification>B2</Identification>
        <Description>B2</Description>
    </MyChild>
    <MyChild>
        <Identification>B3</Identification>
        <Description>B3</Description>
    </MyChild>
</MyHeader>

A: Add an XmlElementAttribute above the list declaration:
[XmlElement(ElementName = "MyChild")]
public List<MyChild> Children { get; set; }

This will treat each child as its own item in the parent MyHeader object.
Example


text:
Q: yaml multi nested and python dictionary I am new to yaml the output is in the expected format but wondering if there is a better way to construct the below nested objects in yaml.
import yaml
yaml.load ("""
test1:
    a:
      a1:
        a2:
          a3: 0
          b3: 0
          c3: 0
        b2:
          a3: 0
          b3: 0
          c3: 0
        c2:
          a3: 0
          b3: 0
          c3: 0
      b1:
        a2:
          a3: 0
          b3: 0
          c3: 0
        b2:
          a3: 0
          b3: 0
          c3: 0
        c2:
          a3: 0
          b3: 0
          c3: 0
      c1:
        a2:
          a3: 0
          b3: 0
          c3: 0
        b2:
          a3: 0
          b3: 0
          c3: 0
        c2:
          a3: 0
          b3: 0
          c3: 0
    b:
      a1:
        a2:
          a3: 0
          b3: 0
          c3: 0
        b2:
          a3: 0
          b3: 0
          c3: 0
        c2:
          a3: 0
          b3: 0
          c3: 0
      b1:
        a2:
          a3: 0
          b3: 0
          c3: 0
        b2:
          a3: 0
          b3: 0
          c3: 0
        c2:
          a3: 0
          b3: 0
          c3: 0
      c1:
        a2:
          a3: 0
          b3: 0
          c3: 0
        b2:
          a3: 0
          b3: 0
          c3: 0
        c2:
          a3: 0
          b3: 0
          c3: 0
    c:
      a1:
        a2:
          a3: 0
          b3: 0
          c3: 0
        b2:
          a3: 0
          b3: 0
          c3: 0
        c2:
          a3: 0
          b3: 0
          c3: 0
      b1:
        a2:
          a3: 0
          b3: 0
          c3: 0
        b2:
          a3: 0
          b3: 0
          c3: 0
        c2:
          a3: 0
          b3: 0
          c3: 0
      c1:
        a2:
          a3: 0
          b3: 0
          c3: 0
        b2:
          a3: 0
          b3: 0
          c3: 0
        c2:
          a3: 0
          b3: 0
          c3: 0

""")

output:
'test1': {'a': {'a1': {'c2': {'c3': 0, 'a3': 0, 'b3': 0}, 'a2': {'c3': 0, 'a3': 0, 'b3': 0}, 'b2': {'c3': 0, 'a3': 0, 'b3': 0}}, 'c1': {'c2': {'c3': 0, 'a3': 0, 'b3': 0}, 'a2': {'c3': 0, 'a3': 0, 'b3': 0}, 'b2': {'c3': 0, 'a3': 0, 'b3': 0}}, 'b1': {'c2': {'c3': 0, 'a3': 0, 'b3': 0}, 'a2': {'c3': 0, 'a3': 0, 'b3': 0}, 'b2': {'c3': 0, 'a3': 0, 'b3': 0}}}, 'c': {'a1': {'c2': {'c3': 0, 'a3': 0, 'b3': 0}, 'a2': {'c3': 0, 'a3': 0, 'b3': 0}, 'b2': {'c3': 0, 'a3': 0, 'b3': 0}}, 'c1': {'c2': {'c3': 0, 'a3': 0, 'b3': 0}, 'a2': {'c3': 0, 'a3': 0, 'b3': 0}, 'b2': {'c3': 0, 'a3': 0, 'b3': 0}}, 'b1': {'c2': {'c3': 0, 'a3': 0, 'b3': 0}, 'a2': {'c3': 0, 'a3': 0, 'b3': 0}, 'b2': {'c3': 0, 'a3': 0, 'b3': 0}}}, 'b': {'a1': {'c2': {'c3': 0, 'a3': 0, 'b3': 0}, 'a2': {'c3': 0, 'a3': 0, 'b3': 0}, 'b2': {'c3': 0, 'a3': 0, 'b3': 0}}, 'c1': {'c2': {'c3': 0, 'a3': 0, 'b3': 0}, 'a2': {'c3': 0, 'a3': 0, 'b3': 0}, 'b2': {'c3': 0, 'a3': 0, 'b3': 0}}, 'b1': {'c2': {'c3': 0, 'a3': 0, 'b3': 0}, 'a2': {'c3': 0, 'a3': 0, 'b3': 0}, 'b2': {'c3': 0, 'a3': 0, 'b3': 0}}}}}

A: I can think of two ways that will save you some typing on the yaml front.
Use the short mapping syntax:

test1:
    a:
      a1:
        a2: {a3: 0, b3: 0, c3: 0}
        b2: {a3: 0, b3: 0, c3: 0}
        c2: {a3: 0, b3: 0, c3: 0}
      b1:
        a2: {a3: 0, b3: 0, c3: 0}
        b2: {a3: 0, b3: 0, c3: 0}
        c2: {a3: 0, b3: 0, c3: 0}
      c1:
        a2: {a3: 0, b3: 0}

Use aliases:

entry: &aliasentry
  a2: {a3: 0, b3: 0, c3: 0}
  b2: {a3: 0, b3: 0, c3: 0}
  c2: {a3: 0, b3: 0, c3: 0}

test1:
    a:
      a1: *aliasentry
      b1: *aliasentry
      c1: {a2: {a3: 0, b3: 0}}


text:
Q: Trimming batch of videos using timestamp I want to cut multiple videos in folder based on their starting and ending time which is stored in a csv file: annotations.csv
The format of the csv file is:
video_name | starting time | ending time
I think the pseudo code may look something like this:
`for i in video_names
 do: cut video according to time frame`

ffmpeg -ss 00:01:00 -i input.mp4 -to 00:02:00 -c copy output.mp4
This is something I found for a single video while hardcoding the input names and start and end time.
How can I make this dynamic to correspond with my annotations file?

A: Figured it out. In the below code snippet, just add your path instead of "your_file_path/annotations.csv"
pip install moviepy
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
import csv
# name of output file
naming = 'trim_'
def get_sec(time_str):
    """Get Seconds from time."""
    h, m, s = time_str.split(':')
    return int(h) * 3600 + int(m) * 60 + int(s)

sample = open('your_file_path/annotations.csv', 'r')
csv1 = csv.reader(sample,delimiter=',')
next(csv1, None)
for eachline in csv1:
    file_name = str(eachline[0])
    out_file = naming + file_name
    start = eachline[1]
    start = get_sec(start)
    end = eachline[2]
    end = get_sec(end)

    ffmpeg_extract_subclip(file_name, start, end, targetname=out_file)


text:
Q: How can I capture emails without creating customer accounts? A lot of the activity on our Magento store (eyewear) will involve active customer engagement (entering Rx info) and I believe users will be willing to enter their email, but they will bounce if requested to create password.
Is there a Magento best practice to capturing emails like this? I want the ability to follow up on their abandon cart (or abandon Rx) and provide discount, etc.

A: My approach would be: If customer is not logged in, listen for the add to cart event and ask for "email address to associate with this order" and save it to the quote. This was you could both use this information for sending reminders but also pre-populate the login/register {email} field for them. It also might be smart to clear this info if/when the customer logs in.


text:
Q: Scala lifting enums to native types with path-dependent types A couple of times now I've encountered an issue that I think should be resolvable by path dependent types, but I'm not sure that I've been able to do so in the most complete or correct way. It's not uncommon in the Java world to have an enumeration (or more often even a pseudo-enumeration in the form of a bunch of static values) that define a closed set that map to native types. java.sql.Types is a good example:
public class Types {

    /**
     *
The constant in the Java programming language, sometimes referred
     * to as a type code, that identifies the generic SQL type
     * BIT.
     */
    public final static int BIT             =  -7;

    /**
     *
The constant in the Java programming language, sometimes referred
     * to as a type code, that identifies the generic SQL type
     * TINYINT.
     */
    public final static int TINYINT         =  -6;

    /**
     *
The constant in the Java programming language, sometimes referred
     * to as a type code, that identifies the generic SQL type
     * SMALLINT.
     */
    public final static int SMALLINT        =   5;
    // ...
}

I'd like to provide some mapping that will take me from these enums to their native types. So far I have something like this:
import java.sql.{Types, ResultSet}

trait SqlType {
  def typeValue:Int
  type Value
  def getValue(rs:ResultSet, idx:Int):Value
}

object SqlType {

  object SqlInt extends SqlType {
    type Value = Int
    def typeValue = Types.INTEGER
    def getValue(rs:ResultSet, idx:Int) = rs.getInt(idx)
  }

  object SqlString extends SqlType {
    type Value = String
    def typeValue = Types.NVARCHAR
    def getValue(rs:ResultSet, idx:Int) = rs.getString(idx)
  }

  def getSqlType(typeValue:Int):SqlType = typeValue match {
    case Types.INTEGER => SqlInt
    case Types.NVARCHAR => SqlString
  }

  implicit class ResultSetExtras(rs:ResultSet) {
    def getCell(idx:Int, sqlType:SqlType):sqlType.Value = sqlType.getValue(rs, idx)
  }
}

This is a bit wonky however, as I need to get the concrete SqlType instance before hand and pass it in as an argument of the function to get the proper path-dependent type. So it doesn't seem like I can do something like this, which is what I'd really like:
  implicit class ResultSetExtras2(rs:ResultSet) {
    def getCell2(idx:Int):SqlType#Value = getSqlType(rs.getMetaData.getColumnType(idx)).getValue(rs, idx)
  }

(note the return type of SqlType#Value rather than the path-dependent sqlType.Value. Is there a (better) way to achieve this in pure scala? I suspect that something like shapeless or macros might help, but if possible I'd like to know if it's possible with path dependent types (or macros indeed in preference to shapeless).

A: The problem is that it is impossible at compilation time for rs.getCell(2) to know what the exact concrete type of value will be produced. Path-dependent types won't help here. The type of the result can only be known at runtime. It's not a problem if you select the abstract type of SqlType as the return value (as would be the case with java). You just can't get the actual type represented by SqlType#Value.


text:
Q: Importance of CS degree when applying for development jobs?
Possible Duplicate:
Is a university education really worth it for a good programmer?

I'm currently looking for a job as a web developer, and I have ~3 years experience in the field and know PHP and Ruby on Rails fairly well, and HTML/CSS like the back of my hand. I'm also well-versed in jQuery. I'm self-taught in all of these disciplines and I am a voracious learner.
I've found several jobs which I think might be good fits, but they all list a BS in Computer Science as a prerequisite to applying, which I don't have. I have a BA in English with an emphasis on Creative Writing. I consider this an asset--not a hindrance--but I'm worried that I won't even be considered since I don't have a BS in CS.
How important is a BS in CS when applying for a job for which that is the only prerequisite I don't satisfy? How can I sell myself to these positions not having a BS?

A: I am in a very similar situation. I have a BA in History and 3 years .NET experience.
I'd say its hit or miss on whether the requirement matters. On my resume I don't specify what my degree is in and also list relevant course work (i took some programming in college). Most of the time I've been able to land an interview with someone who has a tech background before the question of education comes up. A couple points that might help.

*

*Entering the field with no degree and experience required a strong commitment to personal growth, especially in your free time

*A degree in the language arts puts a lot of stress on effective communication.

*An example goes a long way. You'd be surprised how many people find jobs without even providing evidence of their experiences.

In the end if they do not budge on this being a requirement they either have a very good reason for doing so or none at all. Either way you probably don't want the job.

A: I have a BA in English, and I am about to enter my 20th year as a professional software engineer. During those two decades, I have met and worked with countless top-notch engineers who have degrees that are unrelated to CS. I have never felt that my "non-traditional" degree was a barrier.
Moreover, a great deal of what is written in job postings is utter crap; often they ask for things that are not even possible. Ten years of Ruby on Rails? No sweat!
Submit your resume. Be you own rocking self and the smart companies that you'd want to work for in the first place will call you in for in-persons.

A: It's important enough for companies to list it as a requirement for a job.
If you want a career in web development you must get involved as much as you can in projects related to the area you are interested.
You need to have more practical experience than fresh graduates (BSc) for a company to notice you. Remember that those people spent 4 years (and something) in the field, while you spent 4 years doing something that wasn't related.

A: My guess would that it depends on the company and what kind of process would your resume go through.  If an HR person or automated system is looking for that BS and doesn't find it, then you may go nowhere fast.
Assuming that the company is good enough that you still want the job and don't meet that requirement, I'd suggest getting to know developers or managers in the company that may be able to get your application around some of the hurdles in the process.  Just don't forget that there is that assumption as some may see companies that are rather militant about requirements may not be good workplaces in some cases.
Course I hold a B. Math so I'd also be in among those without a BS even though one of my majors was Computer Science.

A: It depends on the company of course, some will care, some just want to see a college diploma, some couldnt care less.  You have a good deal of actual working experience, so that should trump any undergrad degree requirement.  If you see a job you want to apply for, apply.  Dont worry if you only meet some of the requirements, the company is listing their 'dream candidate'.
That being said, consider that if a company does blindly require a specific degree regardless of your actual work experience, the company culture may not be a good fit for you.

A: I'd suggest applying anyway.  If your resume gets kicked out by HR drones, you likely didn't want to work there anyway.
A lot of job requirements aren't solid, in my experience, and resumes that are close usually are passed on to people who really don't care what your degree was in.
This doesn't apply if you lack a bachelor's degree entirely; if a BS is listed as a requirement non-college grads will probably not be considered.

A: If I were you, I will apply for those jobs with references to your work, if you can site them. It doesn't hurt to apply for a job if you think you can do what the job description and responsibilities specify. If you get a call for to interview, its great. Otherwise, its just the time spent in sending the application and reviewing your resume for this job. Either way you stand to gain. Good luck.

A: As one who has worked in this field with and without a CS degree, I can honestly say that holding a CS degree does make a difference in the long term.

A: Blizzard (Starcraft, Diablo, Warcraft) job requirements for developers are usually "BS in CS or equivalent".
I'm not a hiring manager, so I have a limited perspective... but  - If you don't have a CS degree, I will throw you questions about algorithms and parsing to see how much you are able to learn. I would expect you to have a good handle on context free and regular grammars, as well as ad-hoc algorithm analysis. I would also delve into some of the finer points of language implementations (you know, the points that cause bugs from misunderstanding). I would grill you harder on these points than someone with a CS degree, who I would presume would know them.
my 2c.


text:
Q: Running Sonar Ant Task under Webspahere Application Server 8.5 Backgroud
We have a Java Entreprise Application running in WAS8. This application needs to run a SonarQube AntTask to analyze some classes.
Problem
When executing the Ant task, SonarQube initialize Hibernate. Here is the SystemOut log:
INFO  - Load batch settings
INFO  - User cache: /home/SVCEsDev0066/.sonar/cache
INFO  - Install plugins
INFO  - Install JDBC driver
INFO  - Create JDBC datasource for jdbc:mysql://180.101.185.60:3306/sonar?useUnicode=true&characterEncoding=utf8
INFO  - Initializing Hibernate

After that we've this error message:
 org.sonar.runner.impl.RunnerException: Unable to execute Sonar
 at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:91)
 at org.sonar.runner.impl.BatchLauncher$1.run(BatchLauncher.java:75)
 at java.security.AccessController.doPrivileged(AccessController.java:229)
 at org.sonar.runner.impl.BatchLauncher.doExecute(BatchLauncher.java:69)
 at org.sonar.runner.impl.BatchLauncher.execute(BatchLauncher.java:50)
 at org.sonar.runner.api.EmbeddedRunner.doExecute(EmbeddedRunner.java:102)
 at org.sonar.runner.api.Runner.execute(Runner.java:100)
 at org.sonar.ant.SonarTask.launchAnalysis(SonarTask.java:53)
 at org.sonar.ant.SonarTask.execute(SonarTask.java:48)
 at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
 at sun.reflect.GeneratedMethodAccessor152.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
 at java.lang.reflect.Method.invoke(Method.java:613)
 at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:105)
 at org.apache.tools.ant.Task.perform(Task.java:348)
 at org.apache.tools.ant.Target.execute(Target.java:357)
 at org.apache.tools.ant.Target.performTasks(Target.java:385)
 at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1329)
 at org.apache.tools.ant.Project.executeTarget(Project.java:1298)
 at org.sgb.builder.jobs.BuilderJob.checkoutAndBuild(BuilderJob.java:277)
 at org.sgb.builder.jobs.BuilderJob.execute(BuilderJob.java:90)
 at org.quartz.core.JobRunShell.run(JobRunShell.java:216)
 at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:549)
 Caused by: javax.persistence.PersistenceException: java.lang.ClassNotFoundException: com.ibm.websphere.persistence.PersistenceProviderImpl
 at javax.persistence.Persistence.findAllProviders(Persistence.java:93)
 at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:49)
 at org.sonar.jpa.session.AbstractDatabaseConnector.createEntityManagerFactory(AbstractDatabaseConnector.java:66)
 at org.sonar.jpa.session.AbstractDatabaseConnector.start(AbstractDatabaseConnector.java:46)
 at org.sonar.jpa.session.DefaultDatabaseConnector.start(DefaultDatabaseConnector.java:37)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
 at java.lang.reflect.Method.invoke(Method.java:613)
 at org.picocontainer.lifecycle.ReflectionLifecycleStrategy.invokeMethod(ReflectionLifecycleStrategy.java:110)
 at org.picocontainer.lifecycle.ReflectionLifecycleStrategy.start(ReflectionLifecycleStrategy.java:89)
 at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.start(AbstractInjectionFactory.java:84)
 at org.picocontainer.behaviors.AbstractBehavior.start(AbstractBehavior.java:169)
 at org.picocontainer.behaviors.Stored$RealComponentLifecycle.start(Stored.java:132)
 at org.picocontainer.behaviors.Stored.start(Stored.java:110)
 at org.picocontainer.DefaultPicoContainer.potentiallyStartAdapter(DefaultPicoContainer.java:1015)
 at org.picocontainer.DefaultPicoContainer.startAdapters(DefaultPicoContainer.java:1008)
 at org.picocontainer.DefaultPicoContainer.start(DefaultPicoContainer.java:766)
 at org.sonar.api.platform.ComponentContainer.startComponents(ComponentContainer.java:91)
 at org.sonar.api.platform.ComponentContainer.execute(ComponentContainer.java:77)
 at org.sonar.batch.bootstrapper.Batch.startBatch(Batch.java:92)
 at org.sonar.batch.bootstrapper.Batch.execute(Batch.java:74)
 at org.sonar.runner.batch.IsolatedLauncher.execute(IsolatedLauncher.java:48)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
 at java.lang.reflect.Method.invoke(Method.java:613)
 at org.sonar.runner.impl.BatchLauncher$1.delegateExecution(BatchLauncher.java:87)
 ... 22 more
 Caused by: java.lang.ClassNotFoundException: com.ibm.websphere.persistence.PersistenceProviderImpl
 at java.net.URLClassLoader.findClass(URLClassLoader.java:599)
 at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:743)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:720)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:690)
 at javax.persistence.Persistence.findAllProviders(Persistence.java:79)
 ... 49 more

Sonar is trying to load the class: com.ibm.websphere.persistence.PersistenceProviderImpl which is provider by the Application Server JPA configuration. We've tried to change the provider from WAS  Console to use OpenJPA, but nothing changed: it tries to load the same class once again.
Question/s
Is there anyway to force Sonar to not use this provider?
An alternative could be to force Sonar to load  com.ibm.websphere.persistence.PersistenceProviderImpl class but, where can we find it? and, how can we force it?
More Details
We've started using SonarQube 4.3.2 and after first error we updated it to 4.5.1. The SonarAntTask version is 2.2. This is our AntTask code:
  <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project basedir="." default="sonar" name="SonarAnt">
<target name="sonar">
  <taskdef resource="org/sonar/ant/antlib.xml" uri="antlib:org.sonar.ant" classpath="sonar-ant-task-2.2.jar"/>
    <sonar:sonar xmlns:sonar="antlib:org.sonar.ant"/>
</target>
<property name="sonar.java.source" value="1.7"/>
<property name="sonar.projectVersion" value="build_2"/>
<property name="sonar.jdbc.password" value="******"/>
<property name="sonar.host.url" value="http://***.***.***.***:9000"/>
<property name="sonar.jdbc.username" value="******"/>
<property name="sonar.jdbc.url" value="jdbc:mysql://***.***.***.***:3600/sonar?  useUnicode=true&amp;characterEncoding=utf8"/>
<property name="sonar.projectKey" value="PortalSGS_V01R00F00"/>
<property name="sonar.projectName" value="PortalSGS Desc"/>
<property name="sonar.modules" value="sgs-business-review"/>
<property name="sgs-business-review.sonar.projectName" value="sgs-business-review"/>
<property name="sgs-business-review.sonar.projectBaseDir" value="C:\ARQDISP\tmp\CreavistaBL_xIS10460_20140806_110225\vSGS_Portal\SGS_Business_ALM\sgs-business-review"/>
<property name="sgs-business-review.sonar.sources" value="src"/>

We've also tried to specify a classpath in te ant task definition like this:
  <target name="sonar">
<taskdef resource="org/sonar/ant/antlib.xml" uri="antlib:org.sonar.ant" classpath="sonar-ant-task-2.2.jar"/>
<sonar:sonar xmlns:sonar="antlib:org.sonar.ant"/>

But nothing happened.
Invocating ant task
This is the way our application invokes the task:
1.- Creates an antTask.xml like the showed
2.- Initializes an org.apache.tools.ant.Project object and an org.apache.tools.ant.ProjectHelper
3.-It calls executeTarget method from Project class.
Thanks in advance.


text:
Q: If $f=a_{0}+a_{1}x+...+a_{n}x^{n}\in Z[x]$ has a rational root $r/s$, how to prove $r|a_0$ and $s|a_n$? Let $f(x)=a_{0}+a_{1}x+...+a_{n}x^{n}\in \mathbb{Z}[x]$ be a polynomial with integer coefficients, and suppose that $r/s\in \mathbb{Q}$ is a rational root of $f$. Assume that $r$ and $s$ are relatively prime. Prove that $r|a_{0}$ and $s|a_{n}$.
First thing comes into my mind is to plug in the root, but I could find any relation between coefficients and the root.

A: By hypothesis $r/s$ is a rational root of $f$, so we have:
$$f(r/s)=a_{0}+a_{1}(r/s)+...+a_{n}(r/s)^{n}=0.$$
If we multiply by $s^n$ we get $s^{n}a_{0}+s^{n-1}a_{1}r+\ldots sa_{n-1}r+a_{n}r=0$.
Then $s^{n-1}a_{1}r+\ldots a_{n}r=-s^{n}a_{0}$. Thus $r|s^{n}a_{0}$, since $r$ and $s$ are coprime we get that $r|a_{0}$. On the other hand, $s^{n}a_{0}+s^{n-1}a_{1}r+\ldots sa_{n-1}r=-a_{n}r$, so $s|a_{n}r$, again because $r$ and $s$ are coprime we deduce that $s|a_{n}$.


text:
Q: how to change the directory to save uploaded files in angular 2? I'm using angular 2 and i have an uploader. the default folder to save the file is in /assets folder. is there any way to change this directory to a file server for example?
this is my .ts code:
    uploader: FileUploader = new FileUploader({
    url: '/upload/uploadUserImage',
    isHTML5: true
  });

and this is my .js file in backend:
 const storageUserImage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './src/assets/uploads/profile_images/');
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname);
  }
});

const uploadUserImage = multer({
  storage: storageUserImage
}).single('file');
////////////
  module.exports = (router) => {
  router.post('/uploadUserImage', function (req, res) {
    uploadUserImage(req, res, function (err) {
      if (err) {
        res.json({
          error_code: 1,
          err_desc: err
        });
        return;
      }
      res.json({
        error_code: 0,
        err_desc: null
      });
    });
  });

A: Yes according to multer documentation you have destination function in which you may define your path that where it should be stored.
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/../../tmp/my-uploads') // source folder
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})


text:
Q: CSS Dropdown Same Width

function myFunction() {
    var x = document.getElementById("primaryNavigation");
    if (x.className === "show") {
        x.className = "hide";
    } else {
        x.className = "show";
    }
}
/* NAVIGATION - MENU */

nav {
    background-color: #0000ff;
}

nav button {
    display: block;
    position: absolute;
    top: .5rem;
    right: 2%;
}

nav ul {
    padding: 0;
    margin: 0;
    display: flex;
    flex-wrap: wrap;
}

nav ul.show {
    display: flex;
}

nav ul.hide {
    display: none;
}

nav ul li {
    width: 100%;
    list-style: none;
}

nav ul li a {
    display: block;
    color: white;
    text-decoration: none;
    font-size: 1.1rem;
    font-weight: 450;
    padding: 1rem 0;
    text-align: center;
    border-bottom: 1px solid rgba(0, 0, 0, 0.2);
}

nav ul li.active a {
    background-color: #f52c39;
}

nav ul li a:hover {
    background-color: #4c9bff;
}

.clearfix:after,
.row:after {
    content: "";
    display: table;
    clear: both;
}
/* DROP DOWN MENU */

ul ul {
    position: absolute;
    display: none;
    background-color: #0000ff;
}

li:hover ul {
    display: block;
    background-color: #0000ff;
}

nav ul ul li a:hover {
    background-color: #4c9bff;
}

    <button onclick="myFunction()">☰</button>

Home

Adventures

White Water Rafting

Hiking & Zipline

Camping

Guides

Booking

Contact

I want my dropdown menu to be the same width as the parent. (FYI: It is responsive and changes into a hamburger). I realize this is probably so easy for someone (but I'm just learning). I've tried all the solutions I've seen listed here and other place to no avail. THANK YOU for any help.


text:
Q: @Override annotation error (android prefs) When I was trying to use this code to enable preferences into my app
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class Preferences extends PreferenceActivity {

private RadioButton btn01;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);
    btn01 = (RadioButton)findViewById(R.id.RadioButton01);
    Preference customPref = (Preference) findPreference("customPref");

    customPref.setOnPreferenceClickListener(new OnPreferenceClickListener(){

        public boolean onPreferenceClick(Preference preference) {
            Toast.makeText(getBaseContext(),"The Custom Preference Has Been Clicked",Toast.LENGTH_LONG).show();
            SharedPreferences customSharedPreference = getSharedPreferences("myCutomSharedPrefs", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = customSharedPreference.edit();
            editor.putString("myCustomPref","The preference has been clicked");
            editor.commit();
            return true;
        }

        public void CheckBox() {
            final CheckBox ThisCheckBox = (CheckBox) findViewById (R.id.checkboxPref);
            ThisCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
                @Override
               public void onCheckedChanged(CompoundButton compoundButton,boolean test) {
                    if (ThisCheckBox.isChecked()){
                        btn01.setVisibility(0);
                    } else {
                        btn01.setVisibility(2);
                    }
                }
            });
        };
    });
}
}

An error is generated on this line
 public void onCheckedChanged(CompoundButton compoundButton,boolean test) {

saying:
Multiple markers at this line
- The method onCheckedChanged(CompoundButton, boolean) of type new
 CompoundButton.OnCheckedChangeListener(){} must override a superclass method
- implements
 android.widget.CompoundButton.OnCheckedChangeListener.onCheckedChanged

If i remove the @Override annotation then the code doesn't work and a warning tells me that the that part of the code is not used locally.
Having run this past someone and baffling them I was wondering if you could help?
Are there any common scenarios that causes this error?
I thought it might be my project set up
Thanks

A: just wanted to share,
I wrote a post based on the info I found here. I hope it's helpful!
http://qtcstation.com/2011/05/android-and-jdk-compliance/

A: You can go to Project settings --> Java Compiler, and switch the compiler compliance level to 1.6. I have to do it every time i import an existing project.

A: It's an implementation thing. In Java 5 vs Java 6 they changed whether you could use "Override" with an interface (since Override seems to imply that you are overriding some sort of default behavior, which you are not doing with an interface!). If you so desire, you can search in the Eclipse preferences and change it from a compilation error to a compilation warning. You code inside of the CheckBox() function looks fine to me.
However, you are never calling the CheckBox function, so that's where the 'not used locally' error is coming from. Were you meaning to call that function from within the OnPreferenceClick method?


text:
Q: How to send list inside model - AngularJS i have a problem with my model.
I need send a list of another object to my controller, but i dont know how to create this object using AngularJS.
I have three input field, homePhone, cellphone and contact, all fields are about phone, and my ClientModel has a list of phones. What i want to do, is get this three fields and include in a list inside client model.
**MVC Model "Client"**

    public int Id { get; set; }
    public string Name { get; set; }
    public string Email{ get; set; }
    public IEnumerable<Phone> Phones { get; set; }

**MVC Model "Phone"**

    public int PhoneId { get; set; }
    public int ClientId { get; set; }
    public int PhoneType { get; set; }
    public string Number { get; set; }

View

    Home Phone
    <input class="form-control" ng-model="?">

    Cellphone
    <input class="form-control" ng-model="?">

    Contact Phone
    <input class="form-control" ng-model="?">

<button class="btn btn-primary" style="float: right" ng-click="saveClient(client)">Confirmar</button>

Controller JS
    $scope.saveClient = function(client) {
            clientesAPI.saveCliente(client).success(function() {
                alert('OK');
            }).error(function () {
                alert('Error');
            });`enter code here`
        }

A: What you could do is create actual Constructor functions in JS and consistently model you current Server Side MVC Model.
So is would look something like this ...

angular.module('app', [])
  .factory('Client', function() {
    return Client;

    function Client() {
      this.id = 0;
      this.name = '';
      this.email = '';
      this.phones = [];
    }

    Client.prototype.init = function(client) {
      this.id = client.id;
      this.name = client.name;
      this.email = client.email;
      this.phones = [];
    }

  })
  .factory('Phone', function() {
    return Phone;

    function Phone() {
      this.phoneId = 0;
      this.clientId = 0;
      this.phoneType = 'Default Phone Type';
      this.number = 0;
    }

    Phone.prototype.init = function(phone) {
      this.phoneId = phone.phoneId;
      this.clientId = phone.clientId;
      this.phoneType = phone.phoneType;
      this.number = phone.number;
    }
  })
  .factory('clientService', function($http, $log, Client, Phone) {
    var service = {
      getClient: getClient,
      saveClient: saveClient
    };

    return service;

    //////////////////////////

    function getClient() {
      return $http.get('clientApi')
        .then(success)
        .catch(error)

      // This is where defining actual JS Quote unQuote Classes comes in handy
      function success(response) {
        var clients = response.data;
        angular.forEach(clients, function(client) {
          client = new Client().init(client);

          angular.forEach(client.phones, function(phone) {
            phone = new Phone().init(phone);
          })
        })

        return clients;
      }

      function error(response) {
        $log.error('Error getting Clients: ' + response.data);
      }
    }

    function saveClient(client) {

      return $http.post('clientApi', client)
        .then(success)
        .catch(error)

      // This is where defining actual JS Quote unQuote Classes comes in handy
      function success(response) {
        $log('Saved Client Successfully');
      }

      function error(response) {
        $log.error('Error saving Client: ' + response.data);
      }
    }
  })
  // I would use Controller As Syntax normally
  .controller('clientController', function($scope, clientService, Client, Phone) {
    $scope.client = new Client();
    $scope.client.phones.push(new Phone());
    $scope.savedClient;

    $scope.saveClient = function() {

      $scope.savedClient = $scope.client;
      alert('Yeah we saved some data!!');
      //Unconmment this to access the real service, Nowhere to call here :-)
      //clientService.saveClient($scope.client);
    };
  })

      {{phone.phoneType}}
      <input class="form-control" ng-model="phone.number">

    <button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmation</button>

{{savedClient | json}}

I like the idea of this approach for a couple of reasons.

*

*You can new up a Client or a Phone in you controller and know for a fact that or expected model properties are there when Angular tries to render them. (This avoids the annoying client.phones.phoneId is not defined errors)

*Your model definition is now in one spot on the JS side of the house. Even though this looks like duplication ... well it is, but you will have to define this somewhere to send it back to the server anyways. So I prefer to do it in one reusable spot.

*You get and Arrays of Client and Phone when you are outputting the model properties to the Console. This just make me feel good :-)

This was a bit of an overkill for your question, but I like the clean feel of this approach to Front End Modeling.

A: You can create a new object for your model and add the phones property there.
View

    Home Phone
    <input class="form-control" ng-model="homePhone">

    Cellphone
    <input class="form-control" ng-model="cellPhone">

    Contact Phone
    <input class="form-control" ng-model="contactPhone">

<button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmar</button>

Controller
$scope.saveClient = function() {
    var phones = [
       {ClientId: $scope.client.Id, PhoneType: 1, Number: $scope.homePhone},
       {ClientId: $scope.client.Id, PhoneType: 2, Number: $scope.cellPhone},
       {ClientId: $scope.client.Id, PhoneType: 3, Number: $scope.contactPhone}
    ]; // Not sure about the PhoneTypes. There are multiple ways to implement this, I'll leave it up to you.
    var data = {
       Id: $scope.client.Id,
       Name: $scope.client.Name,
       Email: $scope.client.Email,
       Phones: phones
    };
    clientesAPI.saveCliente(data).success(function() {
        alert('OK');
    }).error(function () {
        alert('Error');
    });
};

A: first you need to define ng-model for your view, suppose -
<input class="form-control" ng-model="hPhone">
<input class="form-control" ng-model="cellPhone">
<input class="form-control" ng-model="contactPhone">

Now you can make a json object and post that, then on server side you can access all the phones by for-each loop -inside your controller -
var vm = this;
var phnList = {
  hphone: vm.hphone,
  cellPhone: vm.cellPhone,
  contactPhn: vm.contactPhone
};

Now u can post using $http service
$(http).({
  url : "urULR",
  data : phnList,
  method :"post"
}).then(fuction(response) {
  vm.message = "save success";
});


text:
Q: I am getting Required argument [HttpServletResponse response] not specified when using HttpServletResponse as argument in my controller in micronaut Hi I am getting Required argument [HttpServletResponse response] not specified when I send request to my controller
public void getData(@QueryValue @NotNull String from,
                    HttpServletResponse response) {
}

Can someone help me around this

A: You can use HttpResponse.ok(T body) instead. This mentioned in documentation

In addition, for full control over the emitted HTTP response you can use the static factory methods of the HttpResponse class which return a MutableHttpResponse.

Micronaut Docs


text:
Q: Session Cookie vs Persistent Cookie I understand the normal application of a persistent cookie vs a session cookie. But if you can specify the expiration time of a session cookie to behave like a persistent cookie and vice-versa. Is there any benefit to using session cookies besides them being obfuscated from the user and the session is stored on the server?
session_set_cookie_params() function allows you to set a specific expiration time for a session. You can set the time in a persistent cookie in the setcookie() function.
I already pulled up the threads
Cookie VS Session and Session cookies and persistent cookies,  and didn't find my answer.

A:
But if you can specify the expiration time of a session cookie to
  behave like a persistent cookie and vice-versa.

Not true, the difference between a session cookie and a persistent cookie is whether or not the an expires value is given. A session cookie can't have an expiration time by definition.

Is there any benefit to using session cookies besides them being
  obfuscated from the user and the session is stored on the server?

A session ID for something like PHP sessions can be stored in either a session cookie or a persistent cookie, and session cookies can contain other information besides session IDs. They both use the word "session" but are separate things.
A session cookie is the right choice if you want the cookie to disappear when the user closes their browser. A good example is online banking - the cookie that authenticates you should be destroyed when you close the browser so someone can't sneak onto your computer, reopen the browser, and start making transfers. Ever had your facebook status or something like that changed as a prank?


text:
Q: Find index of smallest integer value in list containing other datatypes I have a function which creates a list of integers. Under some circumstances it can happen (and will) that I can't determine a value to add to the list, so until now I added a float('nan'):
min_list = []
for obj in objects:
    try:
        min_list.append(obj.foo())
    except Exception as e:
        min_list.append(float('nan')) # I have to add something here,
                                      # to get the correct index later

Then I want to find the index of the min value in the list:
index = min_list.index(min(min_list))

So, as you could imagine, appending float('nan') does not really work and I have no clue, how to solve this problem. Especially I also need to find the case, when every call of foo() raises a Exception(every value is a float('nan')):
nan_list = [e for e in min_list if isinstance(e, float)]
if len(nan_list) == len(min_list):
    return None
else:
    return index

How can I achieve that the None value is returned, if I have the same count of exceptions and objects? (I could also raise a exception or return a negative value). And how can I satisfy the problem to find the correct index, even with a raised exception, when I can't add a correct value to the list?

A: You can do:
def get_min(min_list):
    try:
        return min_list.index(min([np.inf if val is None else val for val in min_list]))
    except ValueError:
        return None

list_a = [None, 3, 5, 7, None, 5]
list_b = [None, None, None]
print(get_min(list_a)) #OUTPUT 1
print(get_min(list_b)) #OUTPUT None

The benefit of this method is that you don't really have to use numpy for it, and just replace np.inf with a very high value, that you know there is no way it will be in the original list (like 99999999999)

A: Numpy-based solution using nanargmin
import numpy as np

min_list = []
for obj in objects:
    try:
        min_list.append(obj.foo())
    except Exception as e:
        min_list.append(np.nan)

# ....

try:
    # Case where there is at least one valid element
    min_i = np.nanargmin(min_list)
except ValueError as e:
    # Case where min_list is full of nan