Q: Transparency between UITableViewCells I want to have transparency between UITableViewCells. Space between the cells.
I user custom created cells and for setting a background i use this code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CustomCell = @"CustomBookingCell";

    currentBooking = [arrayBookings objectAtIndex:indexPath.row];

    CustomBookingCell *cell = (CustomBookingCell *)[tableView dequeueReusableCellWithIdentifier:CustomCell];

    if (cell == nil) {

        UIViewController *c = [[UIViewController alloc] initWithNibName:@"CustomBookingCell" bundle:nil];
        cell = (CustomBookingCell *)c.view;
        [ c release ];
    }

    bookingImage = [[UIImageView alloc] initWithImage:
                     [UIImage imageNamed:currentBooking.imageSource]];

    [cell.imageForBooking addSubview:bookingImage];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    cell.contentView.backgroundColor = [UIColor clearColor];

    UIView* backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    UIImage* bgImage = [UIImage imageNamed:@"Background_300_82.png"];
    UIColor *bgColor = [[UIColor alloc] initWithPatternImage: bgImage];

    backgroundView.backgroundColor = bgColor;
    cell.backgroundView = backgroundView;
    cell.label.text = currentBooking.title;

    [bookingImage release];
    [bgColor release];
    [backgroundView release];

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

The height of the cell is 10 pixels higher that the tableCellBg.png.
My background view has also a image as background (this background is supposed to be shown between the cells of course).
So I tried to add 10 pixels with transparency to my tableCellBg.png in the bottom to fix this. But the space between the cells is black. I can't see the view background between my cells.
What shall I do? Do I have to create a UIView in cellForRowAtIndexPath with the height of the tableCellBg.png and then add the Custom UITableViewCell as subview to the created UIView with a less higher height?
Or is there a much more simplyfied way to accomplish this?

A: Your table view needs a clear background colour. For example
myTableView.backgroundColor = [UIColor clearColor];

A: I solved it by using another method to add the background image to the UITableViewCell:
    UIImage *image = [UIImage imageNamed:@"ny_bg_event.png"];
UIImageView  *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, 300, 84);
cell.backgroundView = imageView;
cell.backgroundColor = [UIColor clearColor];
[imageView release];

[cell setFrame:CGRectMake(0, 0, 300, 84)];

cell.contentView.backgroundColor = [UIColor clearColor];

Instead of creating a UIView I just used a UIImageView instead.


Q: webkit css resize doesn't work with canvas as child? Suppose the following html and css code snippet:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
}
#inner {
  width: 100%;
  height: 100%;
}

  <canvas id="inner"></canvas>

I would expect the div to be resizeable, and in firefox, it is. However in webkit-based browsers such as chrome and opera, it isn't. If I replace the inner canvas with a div however, it works there too. So my question is: why does the canvas element in this case prevent the outer div from beeing resizeable? And how can I work around this?

A: it seems that the canvas is taking the mouse event preventing the resize. If you consider pointer-events:none on canvas it will work:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
}
#inner {
  width: 100%;
  height: 100%;
  pointer-events:none
}

  <canvas id="inner"></canvas>

To better illustrate, decrease the size of the canvas a little to avoid the overlap with the resize widget and it will also work:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
}
#inner {
  width: 100%;
  height: calc(100% - 10px);
  background:red;
}

  <canvas id="inner"></canvas>

You can also play with z-index:

#outer {
  width: 100px;
  height: 100px;
  overflow: hidden;
  resize: both;
  border: 1px solid black;
  position:relative;
  z-index:0; /* mandatory to create a stacking context and keep the canvas inside */
}
#inner {
  width: 100%;
  height: 100%;
  position:relative;
  z-index:-1;
  background:red;
}

  <canvas id="inner"></canvas>


Q: Google play services leak in Main While trying to implement ads into my app I am getting this error upon showing the ad.
The only thing I've added to my app in regards to Google play services is importing into gradle and adding to my manifest. I could not find any information on initialization or any other info where I have to add any code to my main.
Here is the log
06-26 21:53:31.062 E/ActivityThread(15754): android.app.ServiceConnectionLeaked: Activity com.intellidev.bitrich.MainActivity has leaked ServiceConnection com.google.android.gms.common.zza@5db576d that was originally bound here

update
Seems I need to initialize play services builder then connect. However the only reason it is implemented is to work with supersonic ads. So here less my problem on hpw to implement it.

A: Your supersonic ad sdk is causing the bug. The ad view connects to play services and does not disconnect properly.


Q: Content negotiation: how to remove JSON as a supported format? I'm implementing a web service in ASP.NET Core 2.1 based on a specification that exclusively supports XML.  Therefore, the content negotiation process must return a XML document or respond with an error.  Unfortunately ASP.NET Core 2.1 supports JSON by default, and by default the content negotiation process always succeeds if a request is made with Accept: application/json.
Does anyone know if it's possible to configure an ASP.NET Core project so that the content negotiation process throws an error if any media type other than XML is set?

A: Sorry if I am late to the party. This works for me:
        services.AddMvc(options =>
        {
            options.OutputFormatters.RemoveType(typeof(JsonOutputFormatter));
            options.InputFormatters.RemoveType(typeof(JsonInputFormatter));
            options.ReturnHttpNotAcceptable = true;
        })
        .AddXmlSerializerFormatters()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

A: Use MVC input and output formatters:
services.AddMvc(configure =>
{
    // remove JSON formatter
    var outputFormatters = configure.OutputFormatters;
    var jsonOutputFormatter = outputFormatters.First(f => f is JsonOutputFormatter);
    outputFormatters.Remove(jsonOutputFormatter);
    var inputFormatters = configure.InputFormatters;
    var jsonInputFormatter = inputFormatters.First(f => f is JsonInputFormatter);
    inputFormatters.Remove(jsonInputFormatter);
}).AddXmlSerializerFormatters()


Q: WSO2 API Manager - unable to access resource properties I am not able to access resource property test1, mentioned in property section in the screenshot.
I am trying to access it by using the expression. get-property('test1'). I am expecting this result in console as test1-value. But the is showing as null.
Updated
I have tried following options but nothing is working for this test1 property.
<property expression="get-property('registry', 'gov:/data/xml/collectionx@test1')" name="test_property2"/>
<property expression="get-property('registry', 'gov:/_system/governance/apimgt/customsequences/in/Seq1.xml@test1')" name="test_property4"/>
<property expression="get-property('gov:/_system/governance/apimgt/customsequences/in/Seq1.xml@test1')" name="test_property6"/>

A: Try this.
<property name="regProperty" expression="get-property('registry', 'gov:/data/xml/collectionx@abc')"/>

Ref: http://movingaheadblog.blogspot.com/2015/09/wso2-esb-how-to-read-registry-property.html

A: To get the value of test1, use following property.
<property expression="get-property('registry', 'gov:/apimgt/customsequences/in/Seq1.xml@test1')" name="test_property5"/>

From above example the location of resource is showing /_system/governance/apimgt/customsequences/in/Seq1.xml. So to make its path, we will use subpath and leave /_system/governance from the beginning. The path will be gov:/apimgt/customsequences/in/Seq1.xml. Now to access test1 property, simply append @test1 to the path.


Q: Send SMS from SQL Server Integration Services I am new to using SSIS and I am looking for a way to send messages using SMS. Is this possible to do? And if yes, is there a way to use a Web API in SSIS to send SMS messages?

A: After i did more search i found this Question
and his first answer was what i want.
the second part of my  Question was about api to use i found this 2 api

*

*Nexmo

*Infobip but you will have to contact them first

both of them will give you atest account to use it at first , but i used the first one from SQL SSIS.


Q: keyDown function not working with shift key I am trying to hold down the 'shift' key and press the 'down' key using the pyautogui module. But the pyautogui.keyDown() does not function with shift key.
The py.keyDown('shift') does not seem to work. Only the py.press('down') is working without holding down the shift key.
pyautogui.keyDown('shift')
pyautogui.press('down')
pyautogui.press('down')
pyautogui.keyUp('shift')

The thing i would like to do is- hold down the shift key and use the down arrow keys on the key board to move down selecting all items below with the down arrow.

A: #You can try this
#So, you have to make left and right shifts down at the same time to activate this feature which is wired.
pyautogui.keyDown('shiftleft')
pyautogui.keyDown('shiftright')
pyautogui.hotkey('right','right','ctrl','up')
pyautogui.keyUp('shiftleft')
pyautogui.keyUp('shiftright')

#credits:Tian Chu
#https://stackoverflow.com/users/13967128/tian-chu

A: Previous answer is good. I was able to successfully highlight a whole Excel column using:
pyautogui.hotkey('ctrl','shiftright','shiftleft','down')

I tried using both shiftright and shiftleft on their own and it wouldn't work unless they were both used together.

A: Thanks, I lost almost 1 hour to find this answer cause on the documentation this is not specified, for me worked example:
py.keyDown('shiftleft')
py.keyDown('shiftright')
py.press('down', presses=253)
py.keyUp('shiftleft')
py.keyUp('shiftright')
Again, Thanks.


Q: How do I distinguish the users who do not exist now but exit previously? Now I have a user set involving one tweet. But some users do not exit now. I wonder how to distinguish those users from current users.

A: I believe the only thing you can do in this case is to use the users/lookup or users/show endpoints to check whether those user IDs return a Not Found error (or similar) in order to filter them out from your result set.
Note that the Twitter Developer Policy and Agreement explicitly states that if content has been removed from Twitter (if e.g. a user is deleted or suspended) you cannot display that it in app, or store that data, and must take steps to remove it from your system as soon as possible.


Q: AWS Amplify Graphql query on @connection I am using AWS Amplify (with Cli and Angular 7 for front end) for Graphql/AppSync and wondering how to get all connected items when it exceeds 10 items?
Let's say I have created a schema.graphql like this:
type User @model {
  id: ID!
  firstname: String
  lastname: String
  project: Project @connection(name: "ProjectUsers")
}

type Project @model {
  id: ID!
  title: String
  task: String
  members: [User] @connection(name: "ProjectUsers")
}

When running amplify push it generates queries and mutations. When running the GetProject query with the id of a project (from the generated API.service.ts file) it returns the Project item with the connected Users. But if the project have more than 10 Users, it only gives me the 10 first users and a next token:
{
  id: "67b1fc0a-fd1f-4e8b-9bd7-b82b2aea5d3b",
  title: "Test",
  task: "test",
  members: {
    items: {
      0: {__typename: "User", id: "f245809a...}
      1: ...
      (2-8: ...)
      9: ...
      nextToken: "qwerj23r2kj....3223oop32kjo",
       __typename: "ModelUserConnection";
    }
  }
  __typename: "Project"
}

I can see multiple solutions for this, but not how to do them:

*

*Is it possible to change schema.grapql to change the codegen so that it can generate the ability to change the limit, ex. 100 instead of the standard 10?

*Use the nextToken to paginate the results, from the generated API.service.ts file?

*Change the schema.graphql file so that the generated ModelUserFilterInput has the userProjectId field (to use in the generated ListUsers query)?
Or are there any other solutions to get all the Users of a Project with the queries in the automatically generated file (API.service.ts)?
As of now the only solution I can see is to first run the ListUsers query (without any filters), and then loop through all of them to check if it has the correct project id. But if the users database is large this can grow to be a lot of data and be really slow, and the benefits to use @connection isn't really there.
Sorry for long post and I hope I have explained the problem enough.

A: A) Change your query
query {
  getProjet(id: "123") {
    id
    members(limit: 50) {
      items {
        firstname
      }
    }
 }

B) Attach a Resolver
In the AWS AppSync console, at the right end side of the Schema section. Filter by UserConnection or similar find UserConnection.items and click Attach.
1) DataSource: UserTable0
2) Request mapping template: ListItems
{
    "version" : "2017-02-28",
    "operation" : "Scan",
    "limit": $util.defaultIfNull(${ctx.args.limit}, 50),
    "nextToken": $util.toJson($util.defaultIfNullOrBlank($ctx.args.nextToken, null))
}

Use the limit coming as an argument ctx.args.limit or if its null use 50.
3) Response mapping template
$util.toJson($ctx.result.items)

By doing this you can change how the underlying table is being scanned/fetched.
C) Paginate
Another solution would be to paginate at the application level and leave the 10 items limit.
Note: I may be missing other solutions.
Update: to use this solution together with Amplify Console.
Now, you can update your resolvers locally and use the Amplify CLI to push the updates into your account. Here’s how it works.
After creating your AWS AppSync API, you will now have a new empty folder called resolvers created in your Amplify project in the API folder. To create a custom resolver, create a file (i.e.
Query.getTodo.req.vtl) in the resolvers directory of your API project. The next time you run amplify push or amplify api gql-compile, your resolver template will be used instead of the auto-generated template. You may similarly create a Query.getTodo.res.vtl file to change the behavior of the resolver’s response mapping template.
<amplify-app>
    |_ amplify
      |_ .config
      |_ #current-cloud-backend
      |_ backend
        |_ api
          |_ resolvers
             Query.getProject.req.vtl
             Query.getProject.res.vtl
      team-provider-info.json

More details, 11 Feb 2019


Q: Select only specific properties from an array of objects Let's  say I create object like this:
updates.push({
      id: this.ids[i],
      point: point,
      value: value
    });

Later on I want to use JSON.stringify on updates object, however I need only
point and value  like:
updates[{point: 1, value: 12}, {point: 2, value: 24}]

What's the best ES6 solution for that?
I looked at some examples with delete, but that's not what I actually need, as I do not want to delete ids.

A: Try the following :
JSON.stringify(updates.map(({point,value})=>({point,value})));

let updates = [{id : 1, point : 1, value: 2},{id : 1, point : 1, value: 2}];
console.log(JSON.stringify(updates.map(({point,value})=>({point,value}))));

A: If updates is an array. Then you might want something like this:
const newArrayWithoutId = updates.map(({ point, value }) => {
  return {
    point,
    value,
  }
}

A: Just ({id, ...rest}) => ({...rest}) is too short for an answer, so how about this?

const withoutId = ({id, ...rest}) => ({...rest})

const vals = [
  {id: 'a', point: 1, value: 'foo'},
  {id: 'b', point: 2, value: 'bar'},
  {id: 'c', point: 3, value: 'baz', meaning: 42}
]

const reduced = vals.map(withoutId)

console.log(reduced)


Q: Docker for Windows: "Operation not permitted" trying to run an executable inside a container (bind-mount only) I'm pretty sure that the last update of Docker for Windows has broken something.
Here is the thing. I have a custom image named toolbox, built from alpine, with a bounch of script inside it (bind-mount the local folder ./mnt/):
version: '3'

services:
    # ...

    toolbox:
        build:
            context: ./.docker/toolbox
        restart: always
        volumes:
            - ./mnt/etc/periodic/daily:/etc/periodic/daily

Files have the right permissions:
/ # ls -la /etc/periodic/daily/
total 4
drwxrwxrwx    1 root     root          4096 Mar 16 17:49 .
drwxr-xr-x    7 root     root          4096 Jan 16 22:52 ..
-rwxr-xr-x    1 root     root           332 Mar  1 23:57 backup-databases
-rwxr-xr-x    1 root     root            61 Mar  1 23:51 cleanup-databases-backups

When I try to execute backup-databases I get the following error:

/ # /etc/periodic/daily/backup-databases /bin/sh:
  /etc/periodic/daily/backup-databases: Operation not permitted

The strange thing is, if I create a script (from inside the container) it works:
echo "echo Hello" > /etc/periodic/daily/test
chmod +x /etc/periodic/daily/test
/etc/periodic/daily/test


Q: Scraping html data from a web site with
* tags I am trying to to get data from this lottery website:
https://www.lotterycorner.com/tx/lotto-texas/2019
The data I would like scrape is the dates and the winning numbers for 2017 to 2019. Then I would like to convert the data into a list and save to a csv file or excel file.
I do apologize if my question isn't understandable i am new to python. Here is a code I tried, but I don't know what to do after this
page = requests.get('https://www.lotterycorner.com/tx/lotto-texas/2017')
soup = BeautifulSoup(page.content,'html.parser')
week = soup.find(class_='win-number-table row no-brd-reduis')
dates = (week.find_all(class_='win-nbr-date col-sm-3 col-xs-4'))
wn = (week.find_all(class_='nbr-grp'))

I would like my result to be something like this:

A: Code below create csv files by year with data with all headers and values, in example below will be 3 files: data_2017.csv, data_2018.csv and data_2019.csv.
You can add another year to years = ['2017', '2018', '2019'] if needed.
Winning Numbers formatted to be as 1-2-3-4-5.
from bs4 import BeautifulSoup
import requests
import pandas as pd

base_url = 'https://www.lotterycorner.com/tx/lotto-texas/'
years = ['2017', '2018', '2019']

with requests.session() as s:
    for year in years:
        data = []

        page = requests.get(f'https://www.lotterycorner.com/tx/lotto-texas/{year}')
        soup = BeautifulSoup(page.content, 'html.parser')
        rows = soup.select(".win-number-table tr")

        headers = [td.text.strip() for td in rows[0].find_all("td")]
        # remove header line
        del rows[0]
        for row in rows:
            td = [td.text.strip() for td in row.select("td")]
            # replace whitespaces in Winning Numbers with -
            td[headers.index("Winning Numbers")] = '-'.join(td[headers.index("Winning Numbers")].split())
            data.append(td)

        df = pd.DataFrame(data, columns=headers)
        df.to_csv(f'data_{year}')

To save only Winning Numbers, replace df.to_csv(f'data_{year}') with:
df.to_csv(f'data_{year}', columns=["Winning Numbers"], index=False, header=False)

Example output for 2017, only Winning Numbers, no header:

9-14-16-27-45-51 2-4-15-38-48-53 8-22-23-29-34-36
  6-10-11-22-30-45 5-10-16-22-26-46 12-14-19-34-39-47
  4-5-10-21-34-40 1-25-35-42-48-51

A: This should export the data you need in a csv file:
from bs4 import BeautifulSoup
from csv import writer
import requests

page = requests.get('https://www.lotterycorner.com/tx/lotto-texas/2019')

soup = BeautifulSoup(page.content,'html.parser')

header = {
    'date': 'win-nbr-date col-sm-3 col-xs-4',
    'winning numbers': 'nbr-grp',
    'jackpot': 'win-nbr-jackpot col-sm-3 col-xs-3',
}

table = []

for header_key, header_value in header.items():
    items = soup.find_all(class_=f"{header_value}")
    column = [','.join(item.get_text().split()) if header_key=='winning numbers'
                       else ''.join(item.get_text().split()) if header_key == 'jackpot'
    else item.get_text() for item in items]
    table.append(column)

rows = list(zip(*table))

with open("winning numbers.csv", "w") as f:
    csv_writer = writer(f)
    csv_writer.writerow(header)
    for row in rows:
        csv_writer.writerow(row)

header is a dictionary mapping what will be your csv headers to their html class values
In the for loop we're building up the data per column. Some special handling was required for "winning numbers" and "jackpot", where I'm replacing any whitespace/hidden characters with comma/empty string.
Each column will be added to a list called table.  We write everything in a csv file, but as csv writes one row at a time, we need to prepare our rows using the zip function (rows = list(zip(*table)))

A: Don't use BeautifulSoup if there are table tags. It's much easier to let Pandas do the work for you (it uses BeautifulSoup to parse tables under the hood).
import pandas as pd

years = [2017, 2018, 2019]

df = pd.DataFrame()
for year in years:
    url = 'https://www.lotterycorner.com/tx/lotto-texas/%s' %year
    table = pd.read_html(url)[0][1:]
    win_nums = table.loc[:,1].str.split(" ",expand=True).reset_index(drop=True)
    dates = pd.DataFrame(list(table.loc[:,0]), columns=['date'])

    table = dates.merge(win_nums, left_index=True, right_index=True)

    df = df.append(table, sort=True).reset_index(drop=True)

df['date']= pd.to_datetime(df['date'])
df = df.sort_values('date').reset_index(drop=True)

df.to_csv('file.csv', index=False, header=False)

Output:
print (df)
          date   0   1   2   3   4   5
0   2017-01-04   5   7  36  39  40  44
1   2017-01-07   2   5  14  18  26  27
2   2017-01-11   4  13  16  19  43  51
3   2017-01-14   7   8  10  18  47  48
4   2017-01-18   6  11  17  37  40  49
5   2017-01-21   2  13  17  39  41  46
6   2017-01-25   1  14  19  32  37  46
7   2017-01-28   5   7  30  48  51  52
8   2017-02-01  12  19  26  29  37  54
9   2017-02-04   8  13  19  25  26  29
10  2017-02-08  10  15  47  49  51  52
11  2017-02-11  24  25  26  29  41  53
12  2017-02-15   1   4   5  43  53  54
13  2017-02-18   5  11  14  21  38  44
14  2017-02-22   4   8  21  27  52  53
15  2017-02-25  16  37  42  46  49  54
16  2017-03-01   3  24  33  34  45  51
17  2017-03-04   2   4   5  17  48  50
18  2017-03-08  15  19  24  33  34  47
19  2017-03-11   5   6  24  28  29  37
20  2017-03-15   4  11  19  27  32  46
21  2017-03-18  12  15  16  23  38  43
22  2017-03-22   3   5  15  27  36  52
23  2017-03-25  21  25  27  30  36  48
24  2017-03-29   7   9  11  18  23  43
25  2017-04-01   3  21  28  33  38  52
26  2017-04-05   8  20  21  26  51  52
27  2017-04-08  10  11  12  47  48  52
28  2017-04-12   5  26  30  31  46  54
29  2017-04-15   2  11  36  40  42  53
..         ...  ..  ..  ..  ..  ..  ..
265 2019-07-20   3  35  38  45  50  51
266 2019-07-24   2   9  16  22  46  49
267 2019-07-27   1   2   6   8  20  53
268 2019-07-31  20  24  34  36  41  44
269 2019-08-03   6  17  18  20  26  34
270 2019-08-07   1   3  16  22  31  35
271 2019-08-10  18  19  27  36  48  52
272 2019-08-14  22  23  29  36  39  49
273 2019-08-17  14  18  21  23  40  44
274 2019-08-21  18  28  29  36  48  52
275 2019-08-24  11  31  42  48  50  52
276 2019-08-28   9  21  40  42  49  53
277 2019-08-31   5   7  30  41  44  54
278 2019-09-04   4  26  36  37  45  50
279 2019-09-07  22  23  31  33  40  42
280 2019-09-11   8  11  12  30  31  49
281 2019-09-14   1   3  24  28  31  41
282 2019-09-18   3  24  26  29  45  50
283 2019-09-21   2  20  31  43  45  54
284 2019-09-25   5   9  26  38  41  44
285 2019-09-28  16  18  39  45  49  54
286 2019-10-02   9  26  39  42  47  49
287 2019-10-05   6  10  18  24  32  37
288 2019-10-09  14  18  19  27  33  41
289 2019-10-12   3  11  15  29  44  49
290 2019-10-16  12  15  25  39  46  49
291 2019-10-19  19  29  41  46  50  51
292 2019-10-23   4   5  11  35  44  50
293 2019-10-26   1   2  26  41  42  54
294 2019-10-30  10  11  28  31  40  53

[295 rows x 7 columns]

A: Here is a concise way with bs4 4.7.1+ that uses :not to exclude header and zip to combine columns for output. Results are as on page. Session is used for efficiency of tcp connection re-use.
import requests, re, csv
from bs4 import BeautifulSoup as bs

dates = []; winning_numbers = []

with requests.Session() as s:
    for year in range(2017, 2020):
        r = s.get(f'https://www.lotterycorner.com/tx/lotto-texas/{year}')
        soup = bs(r.content)
        dates.extend([i.text for i in soup.select('.win-nbr-date:not(.blue-bg)')])
        winning_numbers.extend([re.sub('\s+','-',i.text.strip()) for i in soup.select('.nbr-list')])

with open("lottery.csv", "w", encoding="utf-8-sig", newline='') as csv_file:
    w = csv.writer(csv_file, delimiter = ",", quoting=csv.QUOTE_MINIMAL)
    w.writerow(['date','numbers'])
    for row in zip(dates, winning_numbers):
        w.writerow(row)

A: This one works:
import requests
from bs4 import BeautifulSoup
import io
import re

def main():
    page = requests.get('https://www.lotterycorner.com/tx/lotto-texas/2018')
    soup = BeautifulSoup(page.content,'html.parser')
    week = soup.find(class_='win-number-table row no-brd-reduis')
    wn = (week.find_all(class_='nbr-grp'))
    file = open ("vit.txt","w+")
    for winning_number in wn:
        line = remove_html_tags(str(winning_number.contents).strip('[]'))
        line = line.replace(" ", "")
        file.write(line + "\n")
    file.close()

def remove_html_tags(text):
    import re
    clean = re.compile('<.*?>')
    return re.sub(clean, '', text)

This part of the code loops through the wn variable and writes every line to the "vit.txt" file:
    for winning_number in wn:
        line = remove_html_tags(str(winning_number.contents).strip('[]'))
        line = line.replace(" ", "")
        file.write(line + "\n")
    file.close()
The "stripping" of the <li> tags could be probably done better, e.g. there should be an elegant way to save the winning_number to a list and print the list with 1 line.


Q: Datepicker submit format In the new version of materialize the new 'datepicker' seems to have lost the option for 'formatSubmit'
format: 'dd/mm/yyyy'
formatSubmit: 'yyyy-mm-dd'
You use to be able to display the date in the page in one format and submit it in another.
Anyone have a way round this?


Q: What is the good way to provide an authentication in FASTAPI? what is the best way to provide an authentication for API. I read about authentication, Given an approach to write user: str = Depends(get_current_user) for each every function. I don't think so this is the good way to write an authentication. Can we erite a middleware for it, and add a userid to request object, so that we can take that in the API request processing. Could you any send me the middleware if some one already written.

A: There is already good implementations in:

*

*fastapi_contrib

*fastapi-users


Q: retrieve appointment from OWA(on premises outlook web Access) using C# How to retrieve calendar meetings and appointments list from OWA(outlook web Access) using C#. without using exchange web services

A: You can use Microsoft Graph Api:
https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/user_list_events
Or Outlook Api:
https://msdn.microsoft.com/en-us/office/office365/api/calendar-rest-operations
Simple googling will get you the above results...


Q: flask-sqlalchemy count function Consider a table named result with the following schema
+----+-----+---------+
| id | tag | user_id |
+----+-----+---------+
|  0 | A   |       0 |
|  1 | A   |       0 |
|  2 | B   |       0 |
|  3 | B   |       0 |
+----+-----+---------+

for user with id=0 I would like to count they number of times a result with tag=A has been appeared. For now I have implemented it using raw SQL statement
db.session.execute('select tag, count(tag) from result where user_id = :id group by tag', {'id':user.id})

How can I write it using flask-sqlalchemy APIs?
Most of results I get mention the sqlalchemy function db.func.count() which is not available in flask-sqlalchemy or has a different path which I am not aware of.

A: I was using PyCharm as my IDE and it was not showing module members correctly, hence I thought count is missing. Here is my solution for the above
user.results.add_columns(Result.tag, db.func.count(Result.tag)).group_by(Result.tag).all()


Q: Removing Title Bar on Android App So I know there are a ton of these questions, but every time I try what they say, my app does not seem to remove the title bar. I have done the style change:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowNoTitle">true</item>   <!-- This should work but it does not -->
</style>

I have also tried:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getSupportActionBar().hide(); //This guy here
    setContentView(R.layout.activity_title);

The above works but I still want to use the space the title bar takes for content in my app, which is why I want to be able to modify the XML code rather than use java. Any suggestions?

A: You can either:
<style name="noActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

and in your layout(at the root layout)
android:theme="@theme/noActionBar"

Or
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

However, the last one also hides the Statusbar. You can also set the theme to a default theme(look through the themes and find those with NoActionBar). The last one is useful if you have no plans to style the activity(for an instance if you use SurfaceView) with custom colors, etc.
For an instance you can change AppBaseTheme to have the parent Holo.Light.NoActionBar or any similar theme, but the name has to contain NoActionBar, othervise it has an actionbar

A: Add the below theme to style.xml:
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

Then set this theme to your Activity in manifest:
<activity
   android:name=".MainActivity"
   android:theme="@style/AppTheme.NoActionBar" />


Q: List of properties not changing when set In a class constructor I have a instantiate a list containing properties:
public MDInstrument() : base()
{
    // bidss = new TickData[] {Bid0};
    Bids = new List<TickData> { Bid0, Bid1, Bid2, Bid3, Bid4, Bid5, Bid6, Bid7, Bid8, Bid9, Bid10, Bid0, Bid11, Bid13, Bid14, Bid15, Bid6, Bid17, Bid18, Bid19};
    Offers = new List<TickData> { Ask0, Ask1, Ask2, Ask3, Ask4, Ask5, Ask6, Ask7, Ask8, Ask9, Ask10, Ask0, Ask11, Ask13, Ask14, Ask15, Ask6, Ask17, Ask18, Ask19};
}

A method in the class updates the object in the list but why is the object always null ?

I must be missing something

A: Your problem is that to begin with Bid{x} and Ask{x} have not been instantiated, i.e. they're null, and then you store a reference to those values, and of course the reference is null.  When you then later on update Bid0 (for example), then that reference is updated, but nothing can know that this is intended to be stored within your set.
Suggest that you change your list to be an array of a fixed known size (here, 20) which will be all nulls to begin with.  Then change your getter/setter accessors for the individual Bid items to actually the array internally.  Then you also don't need all of those separate Bid{x}/Ask{x} variables.


Q: Creating POJO/beans dynamically and set values using CGLib I have a requirement to parse a text file and generate JSON document. The text file has a pattern of text which contains a key which is a name and the value is a huge text of TSV with headers.
I could parse the text file and generate bean classes using the headers and now i want to set the data to this generated bean class. I am using reflection to do this.
Class<?> beanClass = BeanClassGenerator.beanGenerator(k, mapForBeanGeneration);
            try {
                Object beanClassObject = beanClass.newInstance();
                lines.forEach(line -> {
                    if (line != null && !line.isEmpty() && !line.equals("null")) {
                        String[] lineData = line.split("\t");
                        System.out.println("LineData length :: " + lineData.length);
                        Method[] methods = beanClass.getMethods();
                        System.out.println("Methods length :: " + methods.length);
                        int index = 0;
                        for (Method m : methods) {
                            m.setAccessible(true);
                            if (m.getName().startsWith("set")) {
                                try {
                                    if ((lineData.length <= index) && lineData[index] != null) {
                                        m.invoke(beanClassObject, lineData[index]);
                                        index++;
                                    } else {
                                        m.invoke(beanClassObject, " ");
                                    }
                                } catch (IllegalAccessException | InvocationTargetException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                });
                ObjectMapper om = new ObjectMapper();
                System.out.println(om.writeValueAsString(beanClassObject));
            } catch (InstantiationException | IllegalAccessException | JsonProcessingException e) {
                e.printStackTrace();
  }});

The problem with the approach is that most of the times all the column values may not have data it can be nulled.
I am wondering if there is an easier way of doing this. Any help is appreciated.
Here is the bean generation method.
public static Class<?> beanGenerator(final String className, final Map<String, Class<?>> properties) {
        BeanGenerator beanGenerator = new BeanGenerator();
        beanGenerator.setNamingPolicy(new NamingPolicy() {
            @Override
            public String getClassName(String prefix, String source, Object key, Predicate names) {
                return className;
            }
        });

        BeanGenerator.addProperties(beanGenerator, properties);
        return (Class<?>) beanGenerator.createClass();
    }

Here is the sample text file which needs to be converted to the JSON output.
<Data1>
Col1  col2 col3 col4 col5
even    sense   met has
root    greatest    spin    mostly
gentle  held    introduced  palace
cold    equator remember    grandmother
slightly    butter  depth   like
distant second  coast   everyone

<Data2>
Col1  col2 col3 col4 col5 col6 col7 col8
greatest    rope    operation   flies   brown   continent   combination read
slightly    diagram he  grandfather where   party   fifty   pour
well    put plastic anyway  refer   careful correct furniture
how since   army    tongue  birthday    been    clock   official
table   command specific    distant cutting hill    movie   experience
national    though  stopped youth   army    underline   five    know

<Data3>
Col1 col2 col3 col4 col5 col6 col7 col8 col9 col9 col10
vessels characteristic  ship    joy than    tomorrow    high    seven   future  trade
try gray    fourth  advice  week    stream  motion  musical whom    tin
limited daughter    large   rice    came    home    chicken wheat   engine  box
easy    city    pair    strange stage   visitor coach   announced   allow   simple
jet therefore   single  during  construction    flag    bigger  muscle  complex pleasure
income  several coat    range   dull    cattle  damage  jump    present shake

JSON output:
[{
    "<Data1>": [{
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": ""
        }
    ]

}, {
    "<Data2>": [{
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        },
        {
            "col1": "",
            "col2": "",
            "col3": "",
            "col4": "",
            "col5": "",
            "col6": "",
            "col7": "",
            "col8": ""
        }
    ]

}]

I came up with a solution using the Maps.
Map<String, List<Map<String, String>>> finalMap = new HashMap<>();
        metadataMap.forEach((k, v) -> {

            List<Map<String, String>> datamap = new ArrayList<>();

            String key = k;
            String[] fields = v.getFields();
            List<String> lines = v.getLines();

            lines.forEach(line -> {
                if (line != null && !line.isEmpty() && !line.equals("null")) {
                    String[] fieldData = line.split("\t");
                    Map<String, String> eachLineMap = new HashMap<>();
                    for (int index = 0; index < fields.length; index++) {
                        if (index < fieldData.length && (fieldData[index] != null && !fieldData[index].isEmpty())) {
                            eachLineMap.put(fields[index], fieldData[index]);
                        } else {
                            eachLineMap.put(fields[index], " ");
                        }
                        datamap.add(eachLineMap);
                    }
                }
            });
            finalMap.put(key, datamap);
        });

        try {
            output = new ObjectMapper().writeValueAsString(finalMap);
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }

A: You don't need to write all that logic, you can just use Apache Commons BeanUtils; which provides a utility method (among MANY other utilities), that takes a Map of field names versus field values and populate a given bean with it:
    BeanUtils.populate(target, fieldNameValueMap);

Then the only thing you need to implement is the logic to create the fieldNameValueMap Map; which you can do with this simple method:
    Map<String, String> createFieldNameValueMap(String headerLine, String valuesLine) {
        String[] fieldNames = headerLine.split("\t");
        String[] fieldValues = valuesLine.split("\t");

        return IntStream.range(0, fieldNames.length)
            .mapToObj(Integer::new)
            .collect(Collectors.toMap(idx -> fieldNames[idx], idx -> fieldValues[idx]));
    }

You can test this solution with the following working demo:
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.apache.commons.beanutils.BeanUtils;

import lombok.Data;

public class DynamicBeanUtils {

    static Map<String, String> createFieldNameValueMap(String headerLine, String valuesLine) {
        String[] fieldNames = headerLine.split("\t");
        String[] fieldValues = valuesLine.split("\t");

        return IntStream.range(0, fieldNames.length)
            .mapToObj(Integer::new)
            .collect(Collectors.toMap(idx -> fieldNames[idx], idx -> fieldValues[idx]));
    }

    public static void main(String[] args) {
        String headerLine = "booleanValue\tintValue\tstringValue\tdoubleValue\totherValue";
        String valuesLine = "true\t12\tthis bean will be populated\t22.44\ttest string!!!";

        Object target = new MyBean();
        try {
            BeanUtils.populate(target, createFieldNameValueMap(headerLine, valuesLine));
        } catch (IllegalAccessException | InvocationTargetException e) {
            // HANDLE EXCEPTIONS!
        }

        System.out.println(target);
    }

    @Data
    public static class MyBean {
        private String stringValue;
        private double doubleValue;
        private int intValue;
        private boolean booleanValue;
        private String otherValue;
    }
}

This is the maven repository page for this dependency, so you can include it in your build: https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils/1.9.3
I used Lombok in this solution as well, only to save me the pain of writing getter/setters/toString to test this solution; but it is not required for your solution.
Complete code on GitHub
Hope this helps.

A: You are going way overboard with your solution.
Your data is organized as an array of variable length arrays;
and does not require some crazy on-the-fly class generation solution.
As a side note,
on-the-fly class generation is not inherently crazy;
it is crazy to use on-the-fly class generation in this situation.
Do this:

*

*Look at your data;
it is organized as follows:

*

*first: outer key

*second: exactly one line containing a variable number of space separated array of inner keys.

*third: some number of lines containing values.

*Design a solution to fix your problem

*

*Read the outer key.
Use that value to create the outer key portion of your JSON.

*Read the inner keys.
Store these in an array;
use LinkedList,
not ClownList (ArrayList).

*Do this until the next empty line:

*

*Read a line of values.

*Write the inner JSON; use the inner keys as the keys for this.

*Skip empty lines until one of the following:

*

*If at end of file, write the ending portion of the JSON.

*If you read the next outer key, goto to line 2 (Read the inner keys) above.

*Write the code.

A: I realized that instead of creating the POJOs with a complex approach. It is better to use the Maps and convert them to JSON using Jackson ObjectMapper. Posting for others who think this might be a useful approach.
public String convert(Map<String, ? extends Metadata> metadataMap) {
        String output = "";
        Map<String, List<Map<String, String>>> finalMap = new HashMap<>();
        metadataMap.forEach((k, v) -> {

            List<Map<String, String>> datamap = new LinkedList<>();

            String key = k;
            String[] fields = v.getFields();
            List<String> lines = v.getLines();

            lines.forEach(line -> {
                if (line != null && !line.isEmpty() && !line.equals("null")) {
                    String[] fieldData = line.split("\t",-1);
                    Map<String, String> eachLineMap = new HashMap<>();
                    for (int index = 0; index < fields.length; index++) {
                        if (index < fieldData.length && (fieldData[index] != null && !fieldData[index].isEmpty())) {
                            eachLineMap.put(fields[index], fieldData[index]);
                        } else {
                            eachLineMap.put(fields[index], " ");
                        }
                        datamap.add(eachLineMap);
                    }
                }
            });
            finalMap.put(key, datamap);
        });

        try {
            output = new ObjectMapper().writeValueAsString(finalMap);
        }catch(JsonProcessingException e){
            e.printStackTrace();
        }

        return output;
    }


Q: Angular can't navigate to other component I'm new in Angular.
I'm trying to build a simple application with a list page and a detail page.
The issues are multiple:
1- the search page shows the the th twice and shows it in all pages.
2- when I try to use route link, the app doesn't load the detail page.
I've spent hour searching solution in order to fix this issues...
Here my code:
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
import { SearchService } from './home/search.service';
import { SearchComponent } from './home/search.component';
import { CharDetailComponent } from './char-detail/char-detail.component';
import { RouterModule } from '@angular/router';

@NgModule({
  declarations: [
    AppComponent,
    SearchComponent,
    CharDetailComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    AppRoutingModule,
    RouterModule,
  ],
  providers: [SearchService],
  bootstrap: [
    AppComponent
  ]
})
export class AppModule { }

export class MyTemplatesModule { }

app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SearchComponent } from './home/search.component';
import { CharDetailComponent } from './char-detail/char-detail.component';

const routes: Routes = [
  {path:'', component: SearchComponent},
  {path:'showDetails', component: CharDetailComponent},

];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

search.component.ts
import { Component, OnInit } from '@angular/core';
import { SearchService } from './search.service';
import { MovieCharacter } from './movie-character';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit{
  people: MovieCharacter[];
  constructor(private searchService: SearchService,
    private router: Router,
    private route: ActivatedRoute
    ) {
      console.log('data');
     }

  ngOnInit() {
    this.searchService.getPeople().subscribe(data=>{
      console.log(data);
      this.people = data.results;
    });
  }

  ngAfterViewInit(){
    this.searchService.getPeople().subscribe(data=>{
      console.log(data);
      this.people = data.results;
    });
  }

  onSelect(name: string){
    this.router.navigate(['/showDetails/'+name]);
  }
}

search.component.html

        name
        description
        url

        {{person.name}}
        {{person.description}}

        {{person.url}}
        <button >
            Go to master Page
        </button>

<router-outlet></router-outlet>

char-detail.component.ts
import { Component, OnInit } from '@angular/core';
import { MovieCharacter } from '../home/movie-character';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-char-detail',
  templateUrl: './char-detail.component.html',
  styleUrls: ['./char-detail.component.css']
})
export class CharDetailComponent implements OnInit{
  people: MovieCharacter[];
  param : string;

  constructor(private route: ActivatedRoute) { }

  ngOnInit():void {
    this.showDetails();
  }

  showDetails(){
    this.param = this.route.snapshot.paramMap.get('name');

  }
}

char-detail.component.html

my name is {{param}}

<router-outlet></router-outlet>

I know the code is very dirty and there are a lot of mistake, but please help me!

A: Welcome to the world of Angular!
To begin with, remove the <router-outlet></router-outlet> from all pages except app.component.html.
After you have done this, retest your pages. If the details page still doesn't show, look at your console for any Javascript errors and please post here :)

A: There are few issues in your code. Here is the solution:

*

*Remove the <router-outlet></router-outlet> from all pages except app.component.html

*If you need to pass name parameter in showDetails page then you need to specify that in app-routing.module.ts so instead of {path:'showDetails', component: CharDetailComponent}, you need to put {path:'showDetails/:name', component: CharDetailComponent}
After this change, ng serve your application again and you are good to go :). Hope this help you.


Q: isnull function vs IS NULL as part of a case statement in a wider sql script, I have the following:
WHEN KWB.ASYCONDTYPE IN ('CIVIL','CIVIL2') AND KWB.CIVCONDGRADE is null THEN 'NO CIVIL CG'
This will set the field to 'NO CIVIL CG' for 1405 records
WHEN KWB.ASYCONDTYPE IN ('CIVIL','CIVIL2') AND ISNULL(KWB.CIVCONDGRADE,'') = '' THEN 'NO CIVIL CG'
This will set the field for 1410 records, which would appear to be the right answer,
as the 5 fields not set in the first instance have ASYCONDTYPE = 'CIVIL' and CIVCONDGRADE is indeed NULL
Slightly worrying, as I'd expect them to produce the same result, and if it wasn't for excel filtering, it might have gone unnoticed.
Can anyone provide an explanation or at least somewhere I can check in the dataset or database to enable me to understand what's going on?

A: That should be becouse you got 1405 records where "KWB.CIVCONDGRADE" is actually NULL and 5 records where "KWB.CIVCONDGRADE" isn't NULL but simply an empty field.
Try to check with this query if it results 5 records:
WHEN KWB.ASYCONDTYPE IN ('CIVIL','CIVIL2') AND KWB.CIVCONDGRADE = '' THEN 'NO CIVIL CG'


Q: Annotated bean config doesnt see bean from XML config Im really confused. I have web-app with Spring Security. I have database.xml config with embedded database:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <jdbc:embedded-database id="dataSource" type="H2" />

</beans>

I have also PersistenceJpaConfig:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories("pl.springsecurity.repositories")
public class PersistenceJpaConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        entityManager.setDataSource(dataSource);
        entityManager.setPackagesToScan(new String[] { "pl.springsecurity.domain" });

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        //vendorAdapter.setShowSql(true);
        entityManager.setJpaVendorAdapter(vendorAdapter);
        return entityManager;
    }

    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(emf);
        return transactionManager;
    }

That works fine when my Spring Security configuration is in xml bean file, and Spring Security filters are declared in web.xml.
But... Since Im trying move Spring Security config to Java class, which means that filters are no longer needed in web.xml, and since I created AbstractSecurityWebApplicationInitializer, Spring can't find DataSource bean delcared in database.xml and bind it into my Jpa Configuration. im really confused why...
Here is my stack trace:
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceJpaConfig': Injection
 of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could no
t autowire field: private javax.sql.DataSource pl.springsecurity.config.PersistenceJpaConfig.dataSource; nested exceptio
n is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource]
found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency ann
otations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(Autowire
dAnnotationBeanPostProcessor.java:334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBea
nFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java
:368)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractA
utowireCapableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapa
bleBeanFactory.java:1014)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationCo
ntext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4914)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5201)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3746)
    at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:292)
    at org.apache.catalina.core.StandardContext.backgroundProcess(StandardContext.java:5528)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1349)
    at java.lang.Thread.run(Unknown Source)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSour
ce pl.springsecurity.config.PersistenceJpaConfig.dataSource; nested exception is org.springframework.beans.factory.NoSuc
hBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found for dependency: expected at least 1 be
an which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factor
y.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(Autow
iredAnnotationBeanPostProcessor.java:561)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(Autowire
dAnnotationBeanPostProcessor.java:331)
    ... 40 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSo
urce] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependen
cy annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultLista
bleBeanFactory.java:1301)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.
java:1047)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.ja
va:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(Autow
iredAnnotationBeanPostProcessor.java:533)
    ... 42 more

sty 29, 2016 1:40:12 PM org.apache.catalina.core.StandardContext loadOnStartup
SEVERE: Servlet [dispatcher] in web application [/SpringSecurity] threw load() exception
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] found
 for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotati
ons: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultLista
bleBeanFactory.java:1301)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.
java:1047)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.ja
va:942)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(Autow
iredAnnotationBeanPostProcessor.java:533)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(Autowire
dAnnotationBeanPostProcessor.java:331)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBea
nFactory.java:1210)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:537)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java
:368)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractA
utowireCapableBeanFactory.java:1119)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapa
bleBeanFactory.java:1014)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBea
nFactory.java:504)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanF
actory.java:476)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.jav
a:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationCo
ntext.java:747)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1231)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1144)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1031)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4914)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5201)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardContext.reload(StandardContext.java:3746)
    at org.apache.catalina.loader.WebappLoader.backgroundProcess(WebappLoader.java:292)
    at org.apache.catalina.core.StandardContext.backgroundProcess(StandardContext.java:5528)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1377)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.processChildren(ContainerBase.java:1381)
    at org.apache.catalina.core.ContainerBase$ContainerBackgroundProcessor.run(ContainerBase.java:1349)
    at java.lang.Thread.run(Unknown Source)

Any ideas guys?

A: Use @ImportResource to load your xml file.
@Configuration
@ImportResource(locations = "classpath:/database.xml")
....
public class PersistenceJpaConfig {

Change the location appropriately.

A: You have to load the xml. See docs
You can use @ImportXml("classpath:com/company/app/datasource-config.xml")
on your configuration class


Q: Not showing from folder So guys I have made a admin system which saves images to a specific folder with specific id according to rows in database.
The picture is in the folder but its not showing..
MY index.php CODe:
    <?php
    include 'admin/connect.php';
        $sql = "SELECT * FROM products";
        $run = mysqli_query($conn, $sql);
        while ($row = $run->fetch_assoc()) {
            $id = $row['id'];

    ?>
    <img src="inventory_images/"<?php echo $id; ?> />
    <?php

}
?>

A: Try removing the " before you echo the id and adding it at the end:
<img src="inventory_images/<?php echo $id; ?>" />

(otherwise your image link is inventory_images/"54 for example)


Q: SQL to HiveQL in Hive Hadoop I am trying to write a HiveQL query which joins two data sets by a BAN column where one datasets timestamp is 72+ hours after the other datasets timestamp.  I can write this in SQL but the syntax isn't the same in HiveQL.  Can anyone help?
For example :
SELECT * FROM Session_Step_Table, Case_Table
WHERE Session_Step_Table.BAN = Case_Table.BAN AND
  DATEADD(hour, 72, Session_Step_Table.timestamp) <= Case_Table.timestamp

A: I think you should use date_add() function provided in Hive. Look here


Q: Put something in article in random place with PHP I am trying to put random text in an article so I use explode to make every word an array:
$article = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lectus urna, tempor nec dui eget, ullamcorper interdum ex. Sed velit velit, sodales non eros eu, porttitor ultricies risus. Morbi semper ultrices tortor non vestibulum. Vestibulum eu lorem odio. Duis placerat dapibus lorem sit amet viverra. Nam at sagittis augue, sit amet interdum metus. Curabitur quis diam pellentesque, auctor magna eget, cursus orci. Proin et fringilla mi. Vivamus egestas sed turpis vel scelerisque. Proin sit amet commodo urna, vel pulvinar lacus. Praesent tincidunt ut diam at interdum.';

$words = explode(' ', $article);
// a new array to hold the string we are going to create
$newString = array();
// loop all words of the original string
foreach ($words as $i => $w) {
    // add every word to the new string
    $newString[] = $w;
}

$inserted = array('ad this in random place'); // Not necessarily an array
$ilejest = count($newString); // count all words from array
$wstawwloowo = rand(1, $ilejest); // random number from 1 to max number of values in array
$newString = array_splice( $newString, $wstawwloowo, 0, $inserted ); //

// create a string from the array of words we just composed
$contenttre = implode(' ', $newString);

How to make it works?

A: array_splice get first argument by reference, so don't assign result to the same variable name $newString.
array_splice($newString, $wstawwloowo, 0, $inserted); it's enough.

A:   $article = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lectus urna, tempor nec dui eget, ullamcorper interdum ex. Sed velit velit, sodales non eros eu, porttitor ultricies risus. Morbi semper ultrices tortor non vestibulum. Vestibulum eu lorem odio. Duis placerat dapibus lorem sit amet viverra. Nam at sagittis augue, sit amet interdum metus. Curabitur quis diam pellentesque, auctor magna eget, cursus orci. Proin et fringilla mi. Vivamus egestas sed turpis vel scelerisque. Proin sit amet commodo urna, vel pulvinar lacus. Praesent tincidunt ut diam at interdum.';

  $words = explode(' ', $article);
                    // a new array to hold the string we are going to create
  $randId = rand(0, sizeOf($words));
  array_splice($words, $randId, 0, array('Random string in random place'));
  $newString = implode(',', $words);
  echo $newString; // Will print the new string


Q: Infinite House of Pancakes Here's a link to the problem in question: https://code.google.com/codejam/contest/6224486/dashboard#s=p1
Okay, so I got a bit hung up on this problem. Now that the quals are over, does anyone know why this wouldn't work? I've checked against about 50 different cases and haven't been able to find one that doesn't work. Here's my full code below.
Basically, looking for any cases where my algorithm could break.
//Includes
#include <iostream>
#include <fstream>
#include <list>
#include <algorithm>
#include <stdlib.h>

using namespace std;

//Functions
int solve(list<int>);

//Main
int main() {
    int minutes = 0;
    int numTestCases = 0;
    int initNonEmpty = 0;
    char tempChar;
    int tempInt;
    list<int> people;

    //Import Data
    //Get number of Test cases
    ifstream infile;
    infile.clear();
    infile.open("B-small-attempt5.in");

    //get NumTestCases
    infile >> numTestCases;
    int solution[numTestCases];

    //Solve it
    for(int i=0; i<numTestCases; i++){
        //Reset vars
        initNonEmpty=0;
        infile >> initNonEmpty;
        people.clear();

        //Input data
        for(int j=0; j<initNonEmpty; j++){
            infile >> tempInt;
cout << tempInt;
        people.push_back(tempInt);
        }
cout << endl;

        //Solve the set
        people.sort();
        people.reverse();
        tempInt = solve(people);
cout << "Solve returns: " << tempInt << endl << endl;
        solution[i] = tempInt;
    }

    //Output
    ofstream outfile;
    outfile.open("RealCase6.out");
    for (int i=0; i < numTestCases; i++){
        cout << "Case #" << i+1 << ": " << solution[i] << endl;
        outfile << "Case #" << i+1 << ": " << solution[i] << endl;
    }

}

int solve( list<int> data){
cout << "Starting Solve functions." << endl;
    int tempMax;
    int max =data.front();
    int test=0;

cout << "Max: " << max << endl;

    //Test if base case
    if(max<=3){
cout << "Reached base case." << endl;
        return max;
    }
    else if (max % 2 == 0 ){
cout << "Max is even" << endl;
        tempMax = max/2;
        data.pop_front();
        data.push_back(tempMax);
        data.push_back(tempMax);
        data.sort();
        data.reverse();
        test=solve(data);
        test=test+1;
cout << "test is:" << test << endl;
cout << "max is:" << max << endl;
        if( test<=max){
            return test;
        } else {
            return max;
        }
    }
    else {
cout << "Max is odd" << endl;
        tempMax = max/2;
        data.pop_front();
        data.push_back(tempMax);
        data.push_back(tempMax+1);
        data.sort();
        data.reverse();
        test=solve(data);
        test=test+1;
cout << "test is:" << test << endl;
cout << "max is:" << max << endl;
        if(test<=max){
            return test;
        } else {
            return max;
        }
    }

}

And here's my input/output for 6 different cases.
https://www.dropbox.com/sh/55wq52lzuygd82s/AABYxJJ7zaeoMhgCmymJcwnAa?dl=0
I'll remove this if this is too early to start asking about the problems. Sorry about eh formatting, but I was trying to get this done quickly.
Edit1: Added Link to problem.
Edit2: Someone else found the error. I only thought to divide things into groups of 2, which gives a case of one person with 9 pancakes, where dividing it into a group of 6 and 3 and then 3 3 3 works best.

A: This breaks in cases where it's more efficient to divide into non-equivalent stacks. For example, the case

1
  9

where one person has 9 pancakes. Dividing as evenly as possible into groups of 2 gives the solution:

min 1: 9
  min 2: 5 4
  min 3: 4 3
  min 4: 3 2
  min 5: 2 1
  min 6: 1 0
  min 7: 0 0

where as dividing unevenly gives the solution

min 1: 9
  min 2: 3 6
  min 3: 3 3 3
  min 4: 2 2 2
  min 5: 1 1 1
  min 6: 0 0 0

which is more efficient.


Q: How to declare function in typeScript within class? How does one declare function like this in typescript within class? What I am trying to achieve is to declare all members first, and then provide implementation of the function later. I want to be able to quickly scan class to see all members. This does not work for me.
class myClass {
this.myFunction = myFunction;

function myFunction(){
}

}

A: TypeScript is just a superset of JavaScript. This means that you can write ES5 or ES6 code, it will be perfectly compiled by tsc.
In TypeScript, even if you do not use type checking, it is OK:
function myFunction () {
  // Your code...
}

var myFunction = function () {
  // Your code...
};

let myFunction = function () {
  // Your code...
};

const myFunction = () => {
  // Your code...
};

// etc.


Q: Unable to group data in Reducer I am trying to write a MapReduce application in which the Mapper passes a set of values to the Reducer as follows:
Hello
World
Hello
Hello
World
Hi
Now these values are to be grouped and counted first and then some further processing is to be done. The code I wrote is:
public void reduce(Text key, Iterable<Text> values, Context context)
        throws IOException, InterruptedException {

    List<String> records = new ArrayList<String>();

    /* Collects all the records from the mapper into the list. */
    for (Text value : values) {
        records.add(value.toString());
    }
    /* Groups the values. */
    Map<String, Integer> groupedData = groupAndCount(records);
    Set<String> groupKeys = groupedData.keySet();

    /* Writes the grouped data. */
    for (String groupKey : groupKeys) {
        System.out.println(groupKey + ": " + groupedData.get(groupKey));
        context.write(NullWritable.get(), new Text(groupKey + groupedData.get(groupKey)));
    }
}

public Map<String, Integer> groupAndCount(List<String> records) {
    Map<String, Integer> groupedData = new HashMap<String, Integer>();
    String currentRecord = "";

    Collections.sort(records);
    for (String record : records) {
        System.out.println(record);

        if (!currentRecord.equals(record)) {
            currentRecord = record;
            groupedData.put(currentRecord, 1);
        } else {
            int currentCount = groupedData.get(currentRecord);
            groupedData.put(currentRecord, ++currentCount);
        }
    }

    return groupedData;
}

But in the output I get a count of 1 for all. The sysout statements are printed something like:
Hello
World
Hello: 1
World: 1
Hello
Hello: 1
Hello
World
Hello: 1
World: 1
Hi
Hi: 1
I cannot understand what the issue is and why not all records are received by the Reducer at once and passed to the groupAndCount method.

A: As you note in your comment, if each value has a different corresponding key then they will not be reduced in the same reduce call, and you'll get the output you're currently seeing.
Fundamental to Hadoop reducers is the notion that values will be collected and reduced for the same key - i suggest you re-read some of the Hadoop getting started documentation, especially the Word Count example, which appears to be roughly what you are trying to achieve with your code.


Q: AutoMapper requiring mapping members and constructor I am brand new to AutoMapper and am just trying to get my head around the best way to do things.
I quickly ran into a hairy issue mapping between two simple, but realistic, object models. The first is for a service layer:
public sealed class GeoLocation
{
    public GeoLocation(
        double latitude,
        double longitude)
    {
        this.Latitude = latitude;
        this.Longitude = longitude;
    }

    public double Latitude { get; private set; }

    public double Longitude { get; private set; }
}

public sealed class Location
{
    public Location(
        string name,
        GeoLocation geoLocation)
    {
        this.Name = name;
        this.GeoLocation = geoLocation;
    }

    public string Name { get; private set; }

    public GeoLocation GeoLocation { get; private set; }
}

And the second is a simplified representation of the above for a database layer:
public sealed class LocationEntity
{
    public LocationEntity(
        string name,
        double latitude,
        double longitude)
    {
        this.Name = name;
        this.Latitude = latitude;
        this.Longitude = longitude;
    }

    public string Name { get; }

    public double Latitude { get; }

    public double Longitude { get; }
}

If I attempt to map the types with a simple CreateMap<Location, LocationEntity>().ReverseMap() call, I predictably get a problem when validating the mappings:
AutoMapperConfigurationException:
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
===============================================
Location -> LocationEntity (Destination member list)
UserQuery+Location -> UserQuery+LocationEntity (Destination member list)

No available constructor.
===============================================
LocationEntity -> Location (Destination member list)
UserQuery+LocationEntity -> UserQuery+Location (Destination member list)

Unmapped properties:
GeoLocation
No available constructor.

Fair enough. I didn't feel like mapping every constructor parameter, so I tried calling ConstructUsing:
Mapper.Initialize(
    config =>
    {
        config
            .CreateMap<Location, LocationEntity>()
            .ConstructUsing((source, _) => new LocationEntity(source.Name, source.GeoLocation?.Latitude ?? 0.0, source.GeoLocation?.Longitude ?? 0));
        config
            .CreateMap<LocationEntity, Location>()
            .ConstructUsing((source, _) => new Location(source.Name, new GeoLocation(source.Latitude, source.Longitude)));
    });

However, this still complains about the LocationEntity -> Location mapping:
AutoMapperConfigurationException:
Unmapped members were found. Review the types and members below.
Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
For no matching constructor, add a no-arg ctor, add optional arguments, or map all of the constructor parameters
===============================================
LocationEntity -> Location (Destination member list)
UserQuery+LocationEntity -> UserQuery+Location (Destination member list)

Unmapped properties:
GeoLocation

Unsure what else to do, I added a ForMember call to the LocationEntity -> Location mapping:
config
    .CreateMap<LocationEntity, Location>()
    .ConstructUsing((source, _) => new Location(source.Name, new GeoLocation(source.Latitude, source.Longitude)))
    .ForMember(
        x => x.GeoLocation,
        options => options.MapFrom((source, target, _, context) => new GeoLocation(source.Latitude, source.Longitude)));

Whilst this solves the problem, it seems to me that my mappings are already becoming somewhat complex. I'm wondering: is there a better way to go about this that doesn't sacrifice the design of my object models?

A: Your object model design basically allows mapping (converting) only via construction, hence can't benefit the most of the AutoMapper automatic and explicit mapping capabilities.
ConstructUsing is used to select a non default constructor for creating destination instances, but still requires member mapping.
What you need is the ConvertUsing method:

Skip member mapping and use a custom expression to convert to the destination type

Mapper.Initialize(config =>
{
    config.CreateMap<Location, LocationEntity>()
        .ConvertUsing(source => new LocationEntity(source.Name, source.GeoLocation?.Latitude ?? 0.0, source.GeoLocation?.Longitude ?? 0));
    config.CreateMap<LocationEntity, Location>()
        .ConvertUsing(source => new Location(source.Name, new GeoLocation(source.Latitude, source.Longitude)));
});

A: ConvertUsing is helpful if you really want to take over the mapping. But more idiomatic in this case would be to map through constructors. By adding another constructor to Location (private if needed) you could even remove ForCtorParam.
CreateMap<Location, LocationEntity>().ReverseMap().ForCtorParam("geoLocation", o=>o.MapFrom(s=>s));

class LocationEntity
{
public LocationEntity(string name, double geoLocationLatitude, double geoLocationLongitude)
{
    this.Name = name;
    this.Latitude = geoLocationLatitude;
    this.Longitude = geoLocationLongitude;
}
public string Name { get; }
public double Latitude { get; }
public double Longitude { get; }
}


Q: PySpark 2.4.5 is not compatible with Python 3.8.3, how do I solve this? Code
from pyspark import SparkContext,SparkConf

conf=SparkConf().setMaster('local').setAppName('Test App')
sc=SparkContext(conf)

Error Message
    Traceback (most recent call last):
      File "C:\Users\Test\PycharmProjects\python-test\MainFile.py", line 5, in <module>
        from pyspark import SparkContext,SparkConf
      File "C:\Test\Python_3.8.3_Latest\lib\site-packages\pyspark\__init__.py", line 51, in <module>
        from pyspark.context import SparkContext
      File "C:\Test\Python_3.8.3_Latest\lib\site-packages\pyspark\context.py", line 31, in <module>
        from pyspark import accumulators
      File "C:\Test\Python_3.8.3_Latest\lib\site-packages\pyspark\accumulators.py", line 97, in <module>
        from pyspark.serializers import read_int, PickleSerializer
      File "C:\Test\Python_3.8.3_Latest\lib\sit`enter code here`e-packages\pyspark\serializers.py", line 72, in <module>
        from pyspark import cloudpickle
      File "C:\Test\Python_3.8.3_Latest\lib\site-packages\pyspark\cloudpickle.py", line 145, in <module>
        _cell_set_template_code = _make_cell_set_template_code()
      File "C:\Test\Python_3.8.3_Latest\lib\site-packages\pyspark\cloudpickle.py", line 126, in _make_cell_set_template_code
        return types.CodeType(
    TypeError: an integer is required (got type bytes)

A: Although latest Spark doc says that it has support for Python 2.7+/3.4+, it actually doesn't support Python 3.8 yet. According to this PR, Python 3.8 support is expected in Spark 3.0. So, either you can try out Spark 3.0 preview release (assuming you're not gonna do a production deployment) or 'temporarily' fall back to Python 3.6/3.7 for Spark 2.4.x.

A: Spark 3.0 has been released for a while now and is compatible with Python 3.8.+.
The error you experienced is no longer reproducible.


Q: Python language support for pipes I would like to implement in python something like this:
def producer():
    while True:
        sys.stdout.write("this is my data\n")

def consumer():
    while True:
        data = sys.stdin.read()
        print data

producer | consumer

The pipe actually needs to create two processes, connect stdout and stdin, and run them until both terminate.
Is there syntactical support for that in python, as the shell has, or do I need to recurse to the Popen object?
What is the simplest implementation in terms of Popen?
Could somebody offer a generic class which can be used to implement this piping pattern? The class would have a signature similar to this:
Class Pipe:

    def __init__(self, process1, process2, ...):

So that, in my case, could be used as follows:
mypipe = Pipe(producer, consumer)

A: You can use the pipes module:

The pipes module defines a class to abstract the concept of a pipeline — a sequence of converters from one file to another.

Sure, the syntax won't be the same as a shell pipe, but why reinvent the wheel?

A: You may be thinking of coroutines.  Check out this very interesting presentation by David Beazley.


Q: Kotlin with hibernate java.io.NotSerializableException I have the following classes in kotlin
@Entity
@Cacheable
@Table(name = "fine")
@EntityListeners(FineSpecificationListener::class)
class FineSpecification (
    @EmbeddedId
    val id: FineSpecificationId,

    @Column(name = "fine")
    val fine: Int,

    @Column(name = "min_fine")
    val minimumFine: Int
): ValueObject<FineSpecification> {

    @Transient
    lateinit var algorithm: FineCalculationAlgorithm

    override fun sameValueAs(other: FineSpecification): Boolean {
        return Objects.equal(id, other.id) &&
            Objects.equal(fine, other.fine) &&
            Objects.equal(minimumFine, other.minimumFine)
    }

    override fun equals(other: Any?): Boolean {
        if (other == null || this::class != other::class)
            return false

        val compareTo = other as FineSpecification
        return sameValueAs(compareTo)
    }

    override fun hashCode(): Int {
        return Objects.hashCode(id, fine, minimumFine)
    }

    override fun toString(): String {
        return "FineSpecification(id=$id, fine=$fine, minimumFine=$minimumFine)"
    }

    fun calculateFine(dues: Long, dueDate: Date, currentDate: Date): Long {
        return algorithm.calculateFine(arrears = dues, dueDate = dueDate, currentDate = currentDate)
    }
}
class FineSpecificationId (
    @Column(name = "effect_from")
    val effectFrom: Date,

    @Column(name = "effect_to")
    val effectTo: Date,

    @Column(name = "cat_code")
    @Convert(converter = CategoryConverter::class)
    val category: Category
): Serializable {
    companion object {
        private const val serialVersionUID = 20190819075136L
    }
    override fun toString(): String {
        return "FineSpecificationId(effectFrom=$effectFrom, effectTo=$effectTo, category=$category)"
    }
}

enum class Category (
    val code: String
): Serializable {
    DOMESTIC("D"),
    NON_DOMESTIC("N"),
    INDUSTRIAL("I"),
    SPECIAL("S");

    companion object {
       private const val serialVersionUID = 20190819075150L
    }

    override fun toString(): String {
        return code
    }

}

I am using Spring Data with Hibernate and using hibernate ehcache. I want to cache FineSpecification, but when I do that I am getting the following exception
18 Aug 2019; 18:56:50.563 ERROR n.s.e.store.disk.DiskStorageFactory - Disk Write of domain.model.bill.fine.FineSpecification#FineSpecificationId(effectFrom=Thu Apr 01 00:00:00 IST 1999, effectTo=Thu Dec 31 00:00:00 IST 2020, category=D) failed:
java.io.NotSerializableException: org.hibernate.metamodel.model.convert.internal.JpaAttributeConverterImpl

As I can understand it is relating to FineSpecificationId as well as with the Category enum class. I have implemented the Serializable interface, but nothing works.
What should I do, to implement caching in this scenario ?


Q: Android Studio Preview is different from the real device I have installed an AVD for my Samsung Galaxy S7 Edge.
When I look to a layout at the android studio preview it fits the screen perfect. But it looks different on the real phone.
Device resolution is also at 2560x1440
What is the problem?
Screen settings AVD:

Preview settings Android Studio:

Screenshot Phone:

A: You are using a RelativeLayout with too many Views to fit the screen. Either you want to use ConstraintLayout to set the Views in a direct relation to each other or you put a ScrollView around your root layout. Either case there is only so much space to fill.


Q: How to remove scrollbars from canvas on Firefox Firefox is adding scrollbars to the canvas even with the body set to overflow:hidden and the execution of FB.Canvas.setAutoResize();. Every other browser hides the scrollbars. When I remove all content from the page the scrollbars persist.
Sample: https://apps.facebook.com/fbtestapppb/

A: With the introduction of Facebook Timeline the way to remove scroll bars and control page margins has changed.  First (and most importantly) your body padding and margins MUST all be set to zero.  This ensures all browsers process your canvas settings off absolute zero.
Depending on the 'Page Tab Width' (520px or 810px) option you set in your Apps/Page settings you will need to adjust the width in the following code.  This block should be placed in the page Head:

Just below the Body tag add the following code:

Remember to change 'YOUR APP ID'.  Also width: should equal either 520 or 810.  Set height: slightly larger than you require to allow overflow.
This solution has been tested in IE, FF, Safari and Chrome!

A: I added this to my css and it seemed to work:
body {
    margin-top: -20px;
    padding-top: 20px;
}

If you already have padding added to the top of your body, you will likely need to add 20px to it.
I assume it's because firefox measures the body height differently than other browsers.
Tested in ff8, chrome16 and ie9 with no negative repercussions.

A: I had solved this problem that way:
  (function(d){
     var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
     if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     ref.parentNode.insertBefore(js, ref);
  }(document));

  window.fbAsyncInit = function() {
        FB.init({
          appId      : app_id, // App ID
          status     : true, // check login status
          cookie     : true, // enable cookies to allow the server to access the session
          xfbml      : true  // parse XFBML
        });

       var height_doc = $(document).height()+20;
       FB.Canvas.setSize({height: height_doc});
  };

It's works for me. I hope that help.

A: This is a known issue with canvas apps and page tabs, and has annoyingly been around for quite a while.
https://developers.facebook.com/bugs/309917422436936
Some people mention being able to use FB.Canvas.setSize({ width: 700, height: 800 }); or something like FB.Canvas.setAutoResize(500); and it gets around the issue.
Have you definitely set the iframe auto resize option in the apps control panel too?

A: Forget about body and html margins (I mean set them to zero).
Just place all your content (including header and footer) into a table with single cell.
At least all browsers will agree on how to calculate the height of the table...
like this:

and do this :
setTimeout(function() {FB.Canvas.setSize({height:(document.getElementById('m_table').offsetHeight+40)})}, 1000);

works in IE,FireFox and Chrome/Safari...
Here is FB initialization code if you need it:
window.fbAsyncInit = function() {
      FB.init({appId:'your_app_id',status:true,cookie:true,xfbml:true});fbApiInit = true;
      }

 function fbEnsureInit(callback)
  {
    if(!window.fbApiInit) setTimeout(function() {fbEnsureInit(callback);}, 50);
        else if(callback) callback();
  }
 fbEnsureInit(function() {
    FB.Canvas.scrollTo(0,0);
    var h = document.getElementById('m_table').offsetHeight+40;
   // console.log('setting size to '+h);
    FB.Canvas.setSize({height:h});
     setTimeout(function() {FB.Canvas.setSize({height:(document.getElementById('m_table').offsetHeight+40)})}, 1000);
  });


Q: Rack middleware server crash I am trying to write simple rack middleware like this:
class NewMiddleWare
  NEW_STRING = <<BEGIN
     my new content
  BEGIN

  def initialize(app)
    @app = app
  end

  def call(env)
    status, headers, response = @app.call(env)
    response_body = ""
    response.each {|part| response_body += part}
    response_body += "#{NEW_STRING}"
    headers["Content-Length"] = response_body.length.to_s
    [status, headers, response_body]
  end
end

when I run rackup, I got:
Unexpected error while processing request: undefined methodeachfor #<String:0x007fad313bdb30> in terminal.
I couldn't figure out the reason for this error. Response object
should be able to respond each right? Coz I saw some sample code doing
that.

A: From the Rack spec:

The Body must respond to each and must only yield String values. The Body itself should not be an instance of String, as this will break in Ruby 1.9.

In Ruby 1.8 Strings did respond to each, but that changed in 1.9.
The simplest solution would be to just return an array containing the string:
[status, headers, [response_body]]


Q: Display new list item onclick with ReactJS I have a problem with updating and displaying an array as list items on the click of a button. From below code, I get error message:

list.map is not a function

import React from "react";

export default class InputPushToList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      ActiveText: "",
      li: ["First Item"]
    };

    this.handleOnClick = this.handleOnClick.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.setState({
      ActiveText: e.target.value
    });
  }

  handleOnClick(e) {
    e.preventDefault();

    const newListItem = [this.state.ActiveText];

    this.setState({
      li: this.state.li.push(newListItem)
    });
  }

  render() {
    const list = this.state.li;
    return (
      <React.Fragment>

{this.props.inputTitle}

        <input type="text" onChange={this.handleChange} />

{this.state.ActiveText}

        <button onClick={this.handleOnClick}>Add to list</button>

          {list.map(e => (

{e}

          ))}

      </React.Fragment>
    );
  }
}

In my mind list.map is a function but apparently not, so why? And how would you go about displaying one more (that which is the active state of the input, this.state.ActiveText) list item when clicking the button? Thanks for the help.

A: First thing first, you don't use this.state inside this.setState, instead use a function to update state. Check this for reference: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous
Your code should be as follows:
this.setState((state) => ({
  li: state.li.concat([newListItem])
}));

Second, why are you assigning an array to newlistitem by doing: const newListItem = [this.state.ActiveText]; ?
It should be const newListItem = this.state.ActiveText;

A: Problem is this line:
this.setState({
      li: this.state.li.push(newListItem)
    });

example:
var arr = [];
console.log(arr.push({}))// it will print 1.

in your case:
this.setState({
      li: this.state.li.push(newListItem)// here you assigned `li`1.
    });

Fix the above.

A: 1. Don't mutate this.state
In handleOnClick(), do not write this.state.li.push(newListItem).
Instead, make a clone of this.state.li, add newListItem into that clone, and set the state of li to the new clone:
handleOnClick(e) {
  e.preventDefault();
  this.setState({
    li: [
      ...this.state.li, // spread out the existing li
      this.state.ActiveText // append this newListItem at the end of this array
    ]
  });
}

2. Consider destructuring
In your render(), you could destructure this.state.li:
render() {
  const { li } = this.state
  return (
    <React.Fragment>
      ...other stuffs

        {li.map(e => (

{e}

        ))}

    </React.Fragment>
  );
}


Q: Create an object before calling the save method I want to create an object in Django before calling the save method. This object will be created from a ForeignKey Value, I've changed the foreignkey field to look like an input field in order to write a value instead of selecting it.
I have 2 classes in 2 different model files
class Category(models.Model):
    title = models.ForeignKey(Title, verbose_name="Title")
and
class Title(models.Model):
    title = models.CharField("Title", primary_key=True, max_length=200)
When I create a category, I have to pick or write a title that already exists in the database and when I try to create a category with a new title I get this error :
Select a valid choice. That choice is not one of the available choices.
What I want to do is creating a title based on what I write in the ForeignKey field before creating the category so it can be used immediately.
I tried to redefine the save method to save the title object before saving the category but it didn't work.
Any help will be really appreciated.
Thank you

A: The save is performed after the form validation, you can make the category obj creation during the validation.
Have a look at the form fields' clean methods that you can override on django docs http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

A: Thank you for your code, I've just tested it. But it's not exactly what I'm looking for, I will explain what I want to do.
Let's say that we have Category and Article classes in our model, each one has a title. To make this title reusable, I created another application that will manage fields, I created the class Title and I added it as foreignkey to Category and Article forms.
I switched the select box to an input field using raw_id_fields.
Now, when I create a category or an article, I have to select or write a title, when this title exists, it works perfectly but when it doesn't exist I want to create it before creating the category so it can use it.
I tried to do that in the save method, in the pre_save signal and in the clean method but I always get the error "Select a valid choice. That choice is not one of the available choices."
I'm using a hard coded solution to create the title now, I want just to see if it will work, these are the lines that I inserted in the different methods to create the title before creating the category :
t = Title(title = "MyTitle")
t.save()
I tried to create a Category with MyTitle as title but I get the same error, when I try to create another one using an existing title, it works and the title "MyTitle" is created. That's mean that the creation of the object happens after the form verification. What I want is just doing this before. The title object should be created before the verification.
Thank you very much for your help

A: You should probably consider putting the code to create Category entries in the model's manager:
class CategoryManager(Manager):
    def create_category(category, title):
        t = Title.objects.get_or_create(title=title)
        return self.create(title=t)

class Category(models.Model):
    title = models.ForeignKey(Title, verbose_name="Title")
    objects = CategoryManager()

Then use create_category every time you want to create a Category.