Q: Does Facebook allow CORS headers? How can I discover if Facebook allowes cross domain requests? Can I make a JavaScript which can handle a Cross Domain Request to Facebook?

A: Are you talking about the Facebook API? Anyway:
http://www.test-cors.org


Q: How to bulk load JSON with values into Synapse SQL dedicated pool I'm attempting to bulk load json files, along with their filenames and paths into a synapse analytics dedicated sql table but I'm just stumped on how to accomplish it. I can load the json files solo without a problem, but I really need the additional values as well.
This is what I'm trying but it doesn't work:
Copy INTO dbo.PolicyStagingJsonOnly
SELECT  jsonContent,
        [result].filename() as fn,
        [result].filepath() as fp
FROM
    OPENROWSET(
        BULK 'https://datalakexxxx.blob.core.windows.net/staging/policy/*.json',
        FORMAT = 'CSV',
        FIELDQUOTE = '0x0b',
        FIELDTERMINATOR ='0x0b',
        rowterminator = '0x0c'
    )
    WITH (
        jsonContent varchar(MAX)
    ) AS [result]


Q: How to check for bounced emails in rails? I'm currently creating an email app that is able to send emails to many users. However, I want to know whether there are bounced emails. I'm currently using Amazon SES to notify me if the email is bounced. However, I want the bounced email's data to be automatically entered into my Rails application instead of typing it manually based to the mailer daemons I get from Amazon. Is there are way to do so?

A: If you are willing to pay, this SaaS site called bouncely seems to provide an interface and an api wrapper around SES bounces.

A: send_email() returns a response object which can be interrogated for the response metadata.
Compare the status of this with the code you are interested in, perhaps a 550.

A: I couldn't find any clean existing solution for this, so I wrote a gem (email_events) that allows you to put a email event handler method (including for bounce events) right in your mailer class:  https://github.com/85x14/email_events.  It supports SES and Sendgrid, so should work for you if you still need it.


Q: Sql view from multiple tables I am stuck in a query, please help.
I want to create view.
Table1
ID | Acode | Bcode | Ccode |
1  | 10    | 101   | 102   |
2  | 11    | 100   | 101   |
3  | 10    | 100   | 102   |

Table2
Acode | Adescription |
10    | English      |
11    | Math         |

Table3
Bcode | Bdescription |
100   | Grade A      |
101   | Grade B      |

Table4
Ccode | Cdescription |
 100  | Level A      |
 101  | Level B      |
 102  | Level C      |

I want to print all rows in Table1 with description from other tables based on code in table1.
Output should be:
data
NewView
ID | Acode |Adescription | Bcode | Bdescription | Ccode | Cdescription |
1  | 10    | English     | 101   |   Grade B    |  102  |   Level C    |
2  | 11    | Math        | 100   |   Grade A    |  101  |   Level B    |

    3  | 10    | English     | 100   |   Grade A    |  102  |   Level C    |
I created left join but it returns more rows than actual in table1. I want to have only all records from table1 with description from other tables.
Please help

A: Below is an example.  Since you didn't post your original query attempt, we can't really say why you were getting multiple rows.  No need for a LEFT JOIN unless you are missing codes in the joined tables.
SELECT  Table1.ID
      , Table1.Acode
      , Table2.Adescription
      , Table1.Bcode
      , Table3.Bdescription
      , Table1.Ccode
      , Table4.Cdescription
FROM    dbo.Table1
        JOIN dbo.Table2 ON Table2.Acode = Table1.Acode
        JOIN dbo.Table3 ON Table3.Bcode = Table1.Bcode
        JOIN dbo.Table4 ON Table4.Ccode = Table1.Ccode;

A: Thanks for help
LEFT Join worked well. I tried to narrow down the tables one by one and found the table where I was getting duplicate records. After finding table I found that I forgot to add Unique key and 1 record (Description) was entered twice which was giving duplicate records and total number of rows were increased.
Thanks all to help me out,and Dan Guzman to point me for duplicate codes.


Q: How to get artist and title information using python-vlc? I'm trying to record and get song information (title and artist) from web radios using python-vlc lib.
The recording functionality is working well but the media parse to get the song information doesn't work!
This is my code:
inst = vlc.Instance() # Create a VLC instance

p = inst.media_player_new() # Create a player instance
cmd1 = "sout=file/ts:%s" % outfile
media = inst.media_new("http://playerservices.streamtheworld.com/api/livestream-redirect/JBFMAAC1.aac", cmd1)
media.get_mrl()

p.set_media(media)
p.play()

media.parse()

for i in range(13):
    print("{} - {}".format(i, media.get_meta(i)))

It's always returning "MediaParsedStatus.skipped" status. And all song information returns "None". I tested the same radio in VLC App and there it works fine.
Anyone can help me?
thanks in advance

A: Since this is a stream, libvlc will not parse it by default (only local files).
You need to use a flag to tell libvlc to parse the media even if it is a network stream.
Use libvlc_media_parse_with_options with MediaParseFlag set to network (1).


Q: badimageformatexception dynamic code generation I'm trying to dynamically generate an executable with the CSharpCodeProvider whose only purpose is to invoke one single method from a specific dll. When I execute the generated file I get a BadImageFormatException.
I already set the platform to x86. When I manually write the code which invokes the method and debug it in Visual Studio, it works perfectly fine.
This is the code for the executable:
using DLLName;

namespace ExampleNamespace
{
    class Program
    {
        public static void Main(string[] args)
        {
            MyClass obj = new MyClass();
            obj.MyMethod();
        }
    }
}

Before dynamically compiling the code I add the assembly via
compilerParameters.ReferencedAssemblies.Add("PathToDLL");

I write the executable to the same directory as the dll.
EDIT
This is the code that I use to invoke the compiler:
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();

parameters.GenerateExecutable = true;
parameters.GenerateInMemory = false;
parameters.OutputAssembly = @"DirectoryOfDLL\MyMethod.exe";
parameters.ReferencedAssemblies.Add("PathToDLL");

provider.CompileAssemblyFromSource(parameters, code);


Q: Distinguish swipe and click in Angular I use ng-click to show details of an item in a list and also I attach jQuery mobile swipe event to the list item to show delete button when a user swipes to the left.
The problem is that when I swipe on the element, it doesn't only emit swipe event, but click event as well. So, when I want to swipe to delete an element, it shows the delete button and opens details view.
What can I do about this? It would be cool to have something like ng-swipe.

A: The most recent unstable angularjs (1.1.4+) builds include both an ngSwipeLeft and ngSwipeRight directive. You must take care to reference the angular-mobile.js library.
https://github.com/angular/angular.js/blob/master/src/ngMobile/directive/ngSwipe.js


Q: iOS - How to set nil in UITextField (It should be visible) I know this is tricky question.
Is there any way to visible nil value in UITextField?
I tried with this code but TextField showing blank.
myTextField.text = nil;

For this task we can't use  myTextField.text = @"nil"; (Without using @"nil" I need to complete this task)
But It should be look like.

A: Your requirement isn't valid. The only way to get the text nil to appear in the text field is to assign the actual text @"nil" to the text field.
It makes no sense that you to see nil without using @"nil" to do so.
Perhaps setting the placeholder to @"nil" is a compromise.

A: i think you can use only myTextField.text = @"nil"; or instead of showing nil you can show proper message inside uitextfield or bellow textfiled input is not valid. showing nil is doesn't helps to user. you can use alert to show no input.

A: As others have said, this seems like a strange requirement, but you could create a subclass of UITextField that overrides the getter of the text property so that it returns @"nil" if text was actually nil.

A: Try This self.textFieldName.placeholder  = @"nil";


Q: MacOS Application Reopens After the User Quits I have an app on the Mac App Store and over the last few weeks some people have complained that when they quit the app, it will reopen again.
Since the app is sandboxed, it should be technically impossible for my app to reopen itself (even if I want it to) after the user choose to quit it. So, I have no clue what went wrong and I can't reproduce this issue.
Any ideas?

A: We figured out what went wrong and how to fix it.
First off, since the app is sandboxed it's technically impossible that we caused this with our code. However, according to a user, there was a plist file (named after our app) in the LauchAgents directory that caused the restarting of our app. After deleting that file, everything was fine again. As to why this entry existed in the first place and how it got there:   ¯\ _(ツ)_/¯
Hope this helps anyone who has the same problem.

A: We haven't seen this exact issue, but something similar where we overrode the - (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender method.
And in certain circumstances we were returning NSTerminateLater or 'NSTerminateCancelinstead ofNSTerminateNow`. In turn, the application would continue running even after the user told us to quit.


Q: Make nested API call to fetch all list In my scenario, I've got an API call to hit and on the response of the API, I've to call the final API to get records of list.
From the first API, I'll get a flag on which I've to make the conditional API call to get the records.
The problem is, GET_LIST gets called by react-admin and in that, I cannot handle two asynchronous API call.
I tried with Query and custom DataSource.
This is the API type called by the react-admin to fetch list.
GET_LIST: {
      request(params: GetListParams): Ticket {
        return {
          method: 'GET',
          url: `${base}/q`,
          headers: makeHeaders(token),
          query: mapQueryParams(params, universalFilters)
        }
      },

      response(res: Object): {total: number, data: Array<Contact>} {
        const {hits, rows} = res
        return {
          total: hits,
          data: rows.map(row => {
            return {...row, id: getId(row)}
          })
        }
      }
    },

This is the component that is called for the list.
export const ContactList = (props) => {
  return (
    <List {...props} filters={<Search />} bulkActionButtons={<PostBulkActions />}>
      <Datagrid className="data-grid">
        <GravatarField source="email" label="" sortable={false} />

        <LinkField
          source="first"
          label="First Name"
          text={ ({first}) => first }
          deriveUrl={ ({id}) => `/#/contacts/${id}` }
          target='' />

        <LinkField
          source="last"
          label="Last Name"
          text={ ({last}) => last || '(unknown name)' }
          deriveUrl={ ({id}) => `/#/contacts/${id}` }
          target='' />

        <DateField source="lastActivity" />
        <TextField source="email" />
        <PhoneNumberField source="primaryPhone" label="Phone" sortable={false} />
        <MultiTagField source="tags" sortable={false} deletable={false} />
        {/* <DeleteButton /> */}
      </Datagrid>
    </List>
  )
}

A: From what I understand about your code, this should be the job of your dataprovider. As it should return a promise, you can make the two api calls in it and resolve only after you get the second call response


Q: "The SQL statement is not valid. There are no columns detected in the statement" I am merging data from one file that contains six different sheets or tabs. All sheets contain the same headers. For the task I am using PowerPivot.
1st I created a connection using Excel and selected the file/imported Sheet1
2nd I activated my PowerPivot > Design > Existing Connections
3rd Table properties Table Name [Sheet1] > Switch to [Query Editor]
Here's my SQL that resulted the error in the title:
  Select [Sheet1$].* From [Sheet1$]
  UNION ALL
  Select [Sheet2$].* FROM `C:\_TEST\HG.xlsx`.[Shee2$]
  UNION ALL
  Select [Sheet3$].* FROM `C:\_TEST\HG.xlsx`.[Shee3$]
  UNION ALL
  Select [Sheet4$].* FROM `C:\_TEST\HG.xlsx`.[Shee4$]
  UNION ALL
  Select [Sheet5$].* FROM `C:\_TEST\HG.xlsx`.[Shee5$]
  UNION ALL
  Select [Sheet6$].* FROM `C:\_TEST\HG.xlsx`.[Shee6$]

When I validated the statement had the error:

The SQL statement is not valid. There are no columns detected in the statement.

A: To answer and share how I resolved my question I found that when I created the connection I can still select sheets 2 to 6 in the dropdown from existing connections. So I tried this code .........and resolved the error :).
 Select [Sheet1$].* From [Sheet1$]
  UNION ALL
  Select [Sheet2$].* FROM [Shee2$]
  UNION ALL
  Select [Sheet3$].* FROM [Shee3$]
  UNION ALL
  Select [Sheet4$].* FROM [Shee4$]
  UNION ALL
  Select [Sheet5$].* FROM [Shee5$]
  UNION ALL
  Select [Sheet6$].* FROM [Shee6$]


Q: Pandas boolean dataframe search returns False but should be True The Problem
I'm attempting to search through a pandas dataframe to find a single value. The dataframe columns I'm searching through are of type float64.
Working Example
Here is a working example of what I'd like, with a dataframe of type int64.
myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
myseries

The output is the following:
0    1
1    4
2    0
3    7
4    5
dtype: int64

Now for the search:
myseries == 4

Results:
0    False
1     True
2    False
3    False
4    False
dtype: bool

Not Working Example
Here is a sample of my data.
df['difference']

Result
0    -2.979296
1    -0.423903
2     0.396515
...
48    0.450493
49   -1.216324
Name: priceDiff1, dtype: float64

As you can see, it is of type float64.
Now here's the issue. If I copy the value on row 2, and create a conditional statement like before, it doesn't return the True.
df['difference'] == 0.396515

Output
0     False
1     False
2     False
...
48    False
49    False
Name: priceDiff1, dtype: bool

Row 2 should be True.
Any assistance at this issue with this issue would be great.
What I believe is happening, is that my query isn't setting the type to float64 and might be assuming it's a different type. I've tested this by downcasting the column type from float64 to float32, with no luck.

A: You want to use Numpy's isclose
np.isclose(s, 0.396515)

array([False, False,  True, False, False, False], dtype=bool)

A: Your python series stores, or points to, numeric data represented as floats, not decimals.
Here is a trivial example:-
import pandas as pd

s = pd.Series([1/3, 1/7, 2, 1/11, 1/3])

# 0    0.333333
# 1    0.142857
# 2    2.000000
# 3    0.090909
# 4    0.333333
# dtype: float64

s.iloc[0] == 0.333333  # False
s.iloc[0] == 1/3       # True

As @piRSquared explains, use np.isclose for such comparisons. Or, alternatively, round your data to a fixed number of decimal places.


Q: Infinite loop through array of strings in React New to programming, and I'd really appreciate some help in rendering a React component. I have an array of strings, and I'd like to display each string in that array every 5 seconds on an infinite loop. The error I'm running into when trying to set the state is 'this.setState is not a function'. I'm inclined to think I'm using the wrong lifecycle method or there is a binding issue, but I'm lost. Below is the code. I'd really appreciate some help.
import React, {Component} from 'react';

class Home extends Component{
  constructor(props){
    super(props);
    this.state = {
      service: ''
    }
  }
  componentDidMount(){
    var services = ['Delivering professional and personalized care to your loved ones','Home visits with a personalized health plan', 'Transition Assistace', 'Advocacy and Guidance', 'Respite Care']
    let i=0;
    setInterval(function(){
      console.log('set interval working');
      const currentService = services[i];
      this.setState({
        service: currentService
      })
      i++;
      if(i>=services.length){
        i = 0;
      }
    }, 5000);
  }
  render(){
    console.log('this', this.state.service);
    return(

{this.state.service}

    )
  }
}
export default Home;

A: The this in your function in the setInterval isn't the this from ComponentWillMount .. that's why it fails. Do something like:
var that = this;

before you call setInterval and then
that.setState()

You can read more about the this keyword here.


Q: Error when plotting using ggplot2: Error in validate_facets(x) : object 'set' not found I want to plot data in R but I keep getting an error related to facet_grid(-set) which is: Error in validate_facets(x) : object 'set' not found
install.packages('Tmisc')
library(Tmisc)
data(quartet)
View(quartet)

quartet %>%
    group_by(set) %>%
    summarize(mean(x), sd(x), mean(y), sd(y), cor(x,y))
    ggplot(quartet,aes(x,y))
        + geom_point()
        + geom_smooth(method=lm,se=FALSE)
        + facet_wrap(-set)

> Error in validate_facets(x) : object 'set' not found

A: Try this code:
install.packages('Tmisc')
library(Tmisc)
data(quartet)
View(quartet)

    quartet %>%
        group_by(set) %>%
        summarize(mean(x), sd(x), mean(y), sd(y), cor(x,y)) %>%
        ggplot(quartet,aes(x,y))
            + geom_point()
            + geom_smooth(method=lm,se=FALSE)
            + facet_wrap(~set)

you have to use tilde not dash in front of set because set is an independent variable in the quartet dataset. dash is used to remove a column from selection

A: It works with the code:
ggplot(quartet,
       aes(x,y)) +
  geom_point() +
  geom_smooth(method=lm,
              se=FALSE) +
  facet_wrap(~set)

A: Try to install the tidyverse package and then this command supposed to be work. since ggplot function is under the tidyverse package


Q: How to delete data from the list view after checked in android Hi the issue is that the selected data's are appearing in the list view, but actually we would like to delete the data's from the list view which is checked means position deletion
can anybody join us to resolve the problem
coding
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
        super.onActivityResult(requestCode, resultCode, data);
        if(data!=null){enter code here
            Bundle bundle = data.getExtras();
            if(requestCode ==1){
                selectedConatcts = bundle.getStringArrayList("sel_contacts");
                Log.v("", "Selected contacts-->"+selectedConatcts);
                if(selectedConatcts.size()<0){

                }else{
                    for(int i =0;i<selectedConatcts.size();i++){
                        RelativeLayout lnr_inflate = (RelativeLayout)View.inflate(thisActivity, R.layout.contacts_inflate, null);

                        // EditText edt = (EditText)lnr_inflate.findViewById(R.id.edt_contact);

                        String selectednames =selectedConatcts.get(i) ;

                        List<String> stringList = new ArrayList<String>(Arrays.asList(selectednames));

                        final ListView edt = (ListView)lnr_inflate.findViewById(R.id.edt_contact);

                        ArrayAdapter<String> adaptercon = new ArrayAdapter<String>(thisActivity, android.R.layout.select_dialog_multichoice,stringList);
                        edt.setAdapter(adaptercon);
                        edt.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
                        edt.setOnItemClickListener(new OnItemClickListener() {

                            @Override
                            public void onItemClick(AdapterView<?> arg0,
                                    View arg1, int arg2, long arg3) {
                                // TODO Auto-generated method stub
                                 final int len = edt.getCount();
                                    final SparseBooleanArray checked = edt.getCheckedItemPositions();

                                    for(int i =0;i<len;i++){

                                        if (checked.get(i)) {
//                                            selectedContacts.add(names[i]);
//                                          selectedConatcts.get(i);
//                                          selectedConatcts.remove(i);
                                            selectedConatcts.remove(phone_nos[i]);
                                            contactdisp.removeViewAt(i);

                                           //you can you this array list to next activity
//                                         do whatever you want with the checked item
                                         }
//                                      selectedConatcts.get(i);
                                        System.out.println("i m in check button cheked"+selectedConatcts.get(i));

                                    }
                                selectedConatcts.remove(phone_nos[arg2]);
                                contactdisp.removeViewAt(arg2);

                            }
                        });

                        contactdisp.addView(lnr_inflate);
}}}}

A: *

*Better check whether the checkbox is checked or not code  write under the button_click

*Remove Items
remove selectedConatcts.remove(phone_nos[arg2]);    contactdisp.removeViewAt(arg2);


Q: How to do restful ajax routes to methods in Laravel 5? So I have a route that looks like this:
Route::any('some/page', ['as' => 'some-page', 'uses' => 'SomePageController@index']);

However, I also have ajax calls at the same URL (using a request parameter called ajax like: some/page/?ajax=my_action) that I want to hit methods on my controller:

index                   already routes:   'SomePageController@index'
ajax = my_action        needs to route:   'SomePageController@ajaxMyAction'
ajax = my_other_action  needs to route:   'SomePageController@ajaxMyOtherAction'
ajax = blah_blah        needs to route:   'SomePageController@ajaxBlahBlah
...

What's the elegant solution to setting this up in my routes.php file?

A: After inspection of Laravel's Http Request and Route classes, I found the route() and setAction() methods could be useful.
So I created a middleware to handle this:
<?php namespace App\Http\Middleware;

class Ajax {

    public function handle($request, Closure $next)
    {
        // Looks for the value of request parameter called "ajax"
        // to determine controller's method call
        if ($request->ajax()) {
            $routeAction = $request->route()->getAction();
            $ajaxValue = studly_case($request->input("ajax"));
            $routeAction['uses'] = str_replace("@index", "@ajax".$ajaxValue, $routeAction['uses']);
            $routeAction['controller'] = str_replace("@index", "@ajax".$ajaxValue, $routeAction['controller']);
            $request->route()->setAction($routeAction);
        }

        return $next($request);
    }

}

Now my route looks like:
Route::any('some/page/', ['as' => 'some-page', 'middleware'=>'ajax', 'uses' => 'SomePageController@index']);

And correctly hits my controller methods (without disturbing Laravel's normal flow):
<?php namespace App\Http\Controllers;

class SomePageController extends Controller {

    public function index()
    {
        return view('some.page.index');
    }

    public function ajaxMyAction(Requests\SomeFormRequest $request){
        die('Do my action here!');
    }

    public function ajaxMyOtherAction(Requests\SomeFormRequest $request){
        die('Do my other action here!');
    }
    ...

I think this is a fairly clean solution.

A: You can't make this dispatch in the routing layer if you keep the same URL. You have two options :

*

*Use different routes for your AJAX calls. For example, you can prefix all your ajax calls by /api. This is a common way :
Route::group(['prefix' => 'api'], function()
{

    Route::get('items', function()
    {
        //
    });

});

*If the only different thing is your response format. You can use a condition in your controller. Laravel provides methods for that, for example :
public function index()
{
    $items = ...;

    if (Request::ajax()) {
        return Response::json($items);
    } else {
        return View::make('items.index');
    }
}

You can read this http://laravel.com/api/5.0/Illuminate/Http/Request.html#method_ajax and this http://laravel.com/docs/5.0/routing#route-groups if you want more details.


Q: How can I scaffold with bootstrap different number of columns? Is there a way to scaffold on a fluid layout two rows with the one having 3 the other 4 and have those centered on my page.
            _________________  __________________  ______________________
            ______________ _______________  ______________  _____________

The problem is that I use the first and the last grid column to center and then I have 10 columns and not been
able to separate them properly.

A: Have you tried using the offset*classes?
http://twitter.github.io/bootstrap/scaffolding.html


Q: How to sort by texture? Now and then the phrase "sort by texture" appears in OpenGL-related posts. While I see how this sort could be implemented for a single texture bound to a certain texture unit, I am not certain how this might be done for multiple textures bound to arbitrary texture units. Perhaps by capturing the state of the TUs into an integer id, then use the id as an index into either an array or a map? How to best do the "sort by texture" in an OpenGL application?

A: Treating texture units as levels in a tree and do a sorted depth-first traversal is a good starting point.
Ideally what you want to do is minimize the number of texture unit state changes which may mean that the same texture gets selected and deselected multiple times in the optimal case. You suggestion of sorting the tuples of texture IDs is a good idea as well.


Q: Spread two rows to one with tidyr I've seen this, this and this but still don't know how to solve the following problem within the tidyr::spread() function.
Here's my example data frame:
libary(tidyverse)

df <- structure(list(Jaar = c(2014L, 2018L), Gemeente = c("Stichtse Vecht",
"Stichtse Vecht"), GMcode = c("GM1904", "GM1904"), Partij = c("VVD",
"VVD"), Aantal_stemmen = c(4347L, 0L)), .Names = c("Jaar", "Gemeente",
"GMcode", "Partij", "Aantal_stemmen"), row.names = c(NA, -2L), class = c("tbl_df",
"tbl", "data.frame"))

result:
# A tibble: 2 x 5
   Jaar Gemeente       GMcode Partij Aantal_stemmen
  <int> <chr>          <chr>  <chr>           <int>
1  2014 Stichtse Vecht GM1904 VVD              4347
2  2018 Stichtse Vecht GM1904 VVD                 0

When I run the following code I don't get the desired one row but two with NA's:
df %>%
  rowid_to_column() %>% # Without this in my original dataframe I'll get an error: Error: Duplicate identifiers for rows
  spread(Jaar, Aantal_stemmen)

result:
# A tibble: 5,938 x 6
   rowid Gemeente       GMcode Partij   `2014` `2018`
   <int> <chr>          <chr>  <chr>     <int>  <int>
 1     1 Stichtse Vecht GM1904 VVD        4347     NA
 2     2 Stichtse Vecht GM1904 VVD          NA      0

A: I am not exactly sure what you want as you didn't provide the wanted output. I hope the following is of help to you.
The call to rowid_to_column generates a column with 2 rows. That is what it is intended to do. Dropping it solves your problem:
df %>%
  # rowid_to_column() %>%
  spread(Jaar, Aantal_stemmen)

which gives
# A tibble: 1 x 5
  Gemeente       GMcode Partij `2014` `2018`
  <chr>          <chr>  <chr>   <int>  <int>
1 Stichtse Vecht GM1904 VVD      4347      0

Please let me know whether this is what you want.


Q: PyInstaller and EasyOCR I have a ocr gui application which has easyocr in it. When I ran the project from pyCharm, it works without any problem. However when I build the project with pyinstaller to an exe form, other ocr algorithms work but easyOCR terminates without showing any error.
python -m PyInstaller --paths "fullpath-to-custom-libraries" --add-data "C:\Program Files\Tesseract-OCR;Tesseract-OCR" --collect-all easyocr --onedir -w main.py

Following warning messages appear after PyInstaller command :
13048 INFO: Determining a mapping of distributions to packages...
40136 WARNING: Unable to find package for requirement opencv-python-headless from package easyocr.
40136 WARNING: Unable to find package for requirement Pillow from package easyocr.
40137 WARNING: Unable to find package for requirement scikit-image from package easyocr.
40137 WARNING: Unable to find package for requirement python-bidi from package easyocr.
40137 WARNING: Unable to find package for requirement PyYAML from package easyocr.
40137 INFO: Packages required by easyocr:
['torch', 'torchvision', 'scipy', 'numpy']

EXE file is generated successfully. But, when I distribute the bundle, application terminates without any error in easyOCR operation. Other OCR's work.
I noticed that dist info folder name and library folder name differ for these below in "venv" environment. I have many other packages installed. However, their library and dist info folder names are same. Can this cause the warnings in PyInstaller ?
cv2
opencv_python_headless-4.5.1.48.dist-info
PIL
Pillow-8.2.0.dist-info
skimage
scikit_image-0.19.2.dist-info
bidi
python_bidi-0.4.2.dist-info
yaml
PyYAML-6.0.dist-info

I cannot pass easyOCR to PyInstaller. How to add required libraries for easyOCR properly then?


Q: Adding views with controllers to a view with controller - proper way? I have to add several views (each having own controller) to a main view (with controller). I am following MVC. Should the code to add these subviews be written in view class or controller class? Also, what is proper way,
MyViewController1 *myViewController1 = [[MyViewController1 alloc] init];
[myMainViewController.view addSubview:myViewController1.view];

Or, some other way?
There is another option - container view controller (with addChildViewController method), but that is tough to manage, so I need the simple way.

A: If you're adding view controllers to the view of another view controller, then you need to use container containment. You can do that in IB with container views. That makes it easier, than making custom container controllers in code.

A: The Absolute best way is to maintain ViewControllers according to their functionality (ex. one might be dashboardView one might be settingsView). Now when moving from one view controller to another is to use navigationController.
The practice I follow is to declare one navigationController in appDelegate when your app starts and then keep reusing this. Example -
YourAppDelegate *delegate=(YourAppDelegate *)[[UIApplication sharedApplication] delegate];
MyViewController1 *myVC = [[ FLOHome alloc ]initWithNibName:@"MyViewController1" bundle:[NSBundle mainBundle]];
[delegate.navigationController pushViewController:myVC animated:NO];

This is the absolute best way when dealing with viewControllers. navigationController handles whole lot of stuff like memory management, caching views to make them snappy. You could keep pushing viewcontrollers and poping them when you exit from them...


Q: What's wrong with my camera? I'm using VS2010 together with C# and XNA 4.0. I'm following the book "Learning XNA 4.0" by Aaron Reed. I added the camera game component to my project but this camera behaves really weird. Moving mouse makes it "jump" and then crash. I don't know what is causing this. It looks that the code is almost identical to that in book. It worked earlier, but now it isn't, although I can't remember whether I change anything in it (I think not). Note that I am only registering this component in game, nothing more. It should work, but it does not. Any help would be great. Here's the code:
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace MyGame
{
    public class Camera : Microsoft.Xna.Framework.GameComponent
    {

        public Matrix View { get; protected set; }
        public Matrix Projection { get; protected set; }
        public Vector3 CameraPosition { get; protected set; }
        public Vector3 CameraDirection { get; protected set; }
        public Vector3 CameraUp { get; protected set; }
        private MouseState prevMouseState;

        public Camera(Game game, Vector3 pos, Vector3 target, Vector3 up)
            : base(game)
        {
            // Some initialization of camera.
            CameraPosition = pos;
            CameraDirection = target - pos;
            CameraDirection.Normalize();
            CameraUp = up;
            CreateLookAt();

            Projection = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4,
                (float)Game.Window.ClientBounds.Width /
                (float)Game.Window.ClientBounds.Height,
                1f, 3000f);
        }

        public override void Initialize()
        {
            // Set mouse position and do initial get state.
            Mouse.SetPosition(Game.Window.ClientBounds.Width / 2,
                Game.Window.ClientBounds.Height / 2);
            prevMouseState = Mouse.GetState();

            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            // Standard WSAD keyboard movement.
            if (Keyboard.GetState().IsKeyDown(Keys.W))
                CameraPosition += CameraDirection;
            if (Keyboard.GetState().IsKeyDown(Keys.S))
                CameraPosition -= CameraDirection;
            if (Keyboard.GetState( ).IsKeyDown(Keys.A))
                CameraPosition += Vector3.Cross(CameraUp, CameraDirection);
            if (Keyboard.GetState().IsKeyDown(Keys.D))
                CameraPosition -= Vector3.Cross(CameraUp, CameraDirection);

            // Yaw rotation (via mouse).
            CameraDirection = Vector3.Transform(CameraDirection,
                Matrix.CreateFromAxisAngle(CameraUp, (-MathHelper.PiOver4 / 150) *
                (Mouse.GetState().X - prevMouseState.X)
                ));

            // Pitch rotation (via mouse).
            CameraDirection = Vector3.Transform(CameraDirection,
                Matrix.CreateFromAxisAngle(Vector3.Cross(CameraUp, CameraDirection),
                (MathHelper.PiOver4 / 100) *
                (Mouse.GetState().Y - prevMouseState.Y)
                ));

            CameraUp = Vector3.Transform(CameraUp,
                Matrix.CreateFromAxisAngle(Vector3.Cross(CameraUp, CameraDirection),
                (MathHelper.PiOver4 / 100) *
                (Mouse.GetState().Y - prevMouseState.Y)
                ));

            prevMouseState = Mouse.GetState();

            CreateLookAt();
            base.Update(gameTime);
        }

        private void CreateLookAt()
        {
            View = Matrix.CreateLookAt(CameraPosition,
                CameraPosition + CameraDirection, CameraUp);
        }
    }
}

Can someone please check whether this code works for him? Any idea would be great!
//EDIT 1:
In game's initialization I use code:
Camera cam = new Camera(this, new Vector3(0, 0, 100), Vector3.Zero, Vector3.Up);
Components.Add(cam);

and then I draw model. I use cam's view and projection matrices in model's BasicEffect.
//EDIT 2:
Something's seriously wrong. I did some debuging and it seems that at some point those Vector3 objects have their X,Y,Z properties set to NaN. I couldn't find out how and when. Also (perhaps this is nothing) after running for some time gameTime shows that the elapsed game time is ONLY 16 miliseconds (like it skips frames?) and that the game is running slowly. This 16 miliseconds is always the same, no matter when I debug.
Is it possible that I somehow messed up XNA/C# settings? If so, can someone give me any hint what to do now?

A:     // Pitch rotation (via mouse).
    CameraDirection = Vector3.Transform(CameraDirection,
        Matrix.CreateFromAxisAngle(Vector3.Cross(CameraUp, CameraDirection),
        (MathHelper.PiOver4 / 100) *
        (Mouse.GetState().Y - prevMouseState.Y)
        ));

    CameraUp = Vector3.Transform(CameraUp,
        Matrix.CreateFromAxisAngle(Vector3.Cross(CameraUp, CameraDirection),
        (MathHelper.PiOver4 / 100) *
        (Mouse.GetState().Y - prevMouseState.Y)
        ));

Whenever you use CreateFromAxisAngle, the first param (the axis) needs to be a unit length vector. If it isn't a unit length vector, it will result in a distorted (skewed) Matrix and one that is over (or under) rotated.
Whenever you cross two vectors the result in rarely a unit length vector. To make a result of a cross unit length. try this:
Vector3.Transform(CameraDirection, Matrix.CreateFromAxisAngle(Vector3.Normalize(Vector3.Cross(CameraUp, CameraDirection)), ...

by adding the 'Normalize', it makes the result of the cross a unit length vector. Don't forget to do the same to the yaw line as well.


Q: How to use SharedPreferences value to fill EditText? I'd like to know how to fill EditText field with the values of SharedPreferences. My code is as follows:
 protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(this);
        sharedPreferences = getSharedPreferences(getString(R.string.preference_file_key),MODE_PRIVATE);
        textViewCheck();
    }

    public void textViewCheck()
    {
        EditText sil_key = (EditText)findViewById(R.id.silent_key);
        String silent_mode_key = sil_key.getText().toString();
        EditText gen_key = (EditText)findViewById(R.id.general_key);
        String general_mode_key = gen_key.getText().toString();
        EditText vib_key = (EditText)findViewById(R.id.vibrate_key);
        String vibrate_mode_key = vib_key.getText().toString();
        SharedPreferences.Editor editor = sharedPreferences.edit();
        if((sharedPreferences.contains("silent")) && (sharedPreferences.contains("general")) && (sharedPreferences.contains("vibrate")))
        {
            sil_key.setText(sharedPreferences.getString("silent","silent1"));
            gen_key.setText(sharedPreferences.getString("general","general1"));
            vib_key.setText(sharedPreferences.getString("vibrate","vibrate1"));
        }
        editor.putString("silent",silent_mode_key);
        editor.putString("general",general_mode_key);
        editor.putString("vibrate",vibrate_mode_key);
        editor.apply();
    }

I keep getting the same values even after changing in the EditText fields. I would like to know why I keep getting this and how to overcome this. ( I am so sorry for the previous error with getString() method, didn't notice that.Please clarify this one)

A: i think you may be messing when creating the strings
EditText sil_key = (EditText)findViewById(R.id.silent_key);
String silent_mode_key = sil_key.toString();

I think you meant to make it a string from the content of the edit text
like this
    String silent_mode_key = sil_key.getText().toString();

try this
    EditText sil_key = (EditText)findViewById(R.id.silent_key);
    String silent_mode_key = sil_key.getText().toString();
    EditText gen_key = (EditText)findViewById(R.id.general_key);
    String general_mode_key = gen_key.getText().toString();
    EditText vib_key = (EditText)findViewById(R.id.vibrate_key);
    String vibrate_mode_key = vib_key.getText().toString();
    SharedPreferences.Editor editor = sharedPreferences.edit();
    if((sharedPreferences.contains("silent")) && (sharedPreferences.contains("general")) && (sharedPreferences.contains("vibrate")))
    {
        sil_key.setText(sharedPreferences.getString("silent","silent"));
        gen_key.setText(sharedPreferences.getString("general","general"));
        vib_key.setText(sharedPreferences.getString("vibrate","vibrate"));
    }
    editor.putString("silent",silent_mode_key);
    editor.putString("general",general_mode_key);
    editor.putString("vibrate",vibrate_mode_key);
    editor.apply();

A: try to add  getText() like below for all the strings:
EditText sil_key = (EditText)findViewById(R.id.silent_key);
    String silent_mode_key = sil_key.getText().toString();

A: I think that you have to add this before sharedPreferences.getString
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);


Q: OCI with long double I'm developing a C++ library with oracle OCI library. I'm loading from a Oracle Database 11g database. Here I need to load large values with decimal places. In this case I need to use long double instead of double. I'm not sure whether OCI supports for long double.
According to the documentation SQLT_FLT is for float and double only. Can someone let me know whether OCI supports for long double and if so how to retrieve them

A: Yes and no.
According to the server docs on floats, the 'native' C types support up to double precision (BINARY_DOUBLE). However, the NUMBER type can store:

*

*Positive numbers in the range 1 x 10-130 to 9.99...9 x 10125 with up to 38 significant digits

*Negative numbers from -1 x 10-130 to 9.99...99 x 10125 with up to 38 significant digits

which is more precision than long double on x86/amd64.
So, you'd need to use that type instead of BINARY_*. Sadly, the developer docs say:

You should not need to use NUMBER as an external datatype. If you do use it, Oracle returns numeric values in its internal 21-byte binary format and will expect this format on input. The following discussion is included for completeness only.

On the other hand, there are also docs on:

*

*using the OCINumber type;

*OCI NUMBER Functions.

AFAICS OCINumberFromReal() supports long double; and if you want even more precision, then you could use OCINumberFromText() with decimal string.


Q: Android Resolve Host I am getting the following error while trying to access the web-service.
Error in http connection java.net.UnknownHostException: Unable to resolve host "192.168.1.109"
Web-service is working fine, when checked using browser.
I am using AsyncTask to access web-service, so it cannot be a background thread issue.
Missed this permission:
<uses-permission android:name="android.permission.INTERNET" />
as identified in the answer below.

A: Mostly I doubt it has to do with the permission you need to give while running the app. Are you making sure you are setting the the network permission in manifest?
More information or code could help you get better answers though.


Q: Azure Table Storage Not saving Property I have an abstract class that inherits from Table Entity.
public abstract class AzureEntityBase : TableEntity
{
    public AzureEntityBase()
    {

    }
    public virtual string TableName
    {
        get
        {
            return string.Empty;
        }
    }
    private string ObjectHash { get; set; }

    public bool IsBackedUp { get; set; }

}

I then have a class that implements this abstract class
public class DepartmentTotalEntity : AzureEntityBase
{
    public override string TableName
    {
        get
        {
            return "DepartmentTotals";
        }
    }
    public Int64 SessionDateTimeInteger { get; set; }
    public string StoreID { get { return PartitionKey; } set { PartitionKey = value; } }
    public string DetailKey { get; set; }
    public string RangeString { get; set; }
    public string DateStart { get; set; }
    public string DateEnd { get; set; }
    public Int64 DateStartInt { get; set; }
    public Int64 DateEndInt { get; set; }
    public string Dept_ID { get; set; }
    public string DepartmentDescription { get; set; }
    public decimal Quantity { get; set; }
    public decimal TotalPrice { get; set; }
}

I am submitting a revised entity to Azure table storage with the IsBackedUp value set to false.
I then have a service that runs on an Azure Compute instance that copies the row from one table storage account to another.  The other Azure table storage account is at a different Azure datacenter.  After all the rows are copied, I want to limit what I grab when I copy the next round and the IsBackedUp field is supposed to do this.
I run a function that loops the rows already inserted, checks to see if they exist at the destination, if they do exist, then update the source table row to reflect that it was backed up and write that to azure via the following code.
   foreach (DepartmentTotalEntity row in CopiedRows)
       {
           DepartmentTotalEntity find = dst.BrowseSingle(row.PartitionKey, row.RowKey);
           if (find != null)
           {
               row.IsBackedUp = true;
               int tmp = src.InsertOrReplace(row);
            }
       }

The return integer from the InsertOrReplace is the HttpStatusCode of the tableoperation and it always reads 204.  This is expected for a successful write the ATS.
For completeness here is the InsertOrReplaceRow function.
public int InsertOrReplace(DepartmentTotalEntity input)
        {
            if (input.PartitionKey.IsNull())
            {
                throw new ArgumentNullException("PartitionKey");
            }
            if (input.RowKey.IsNull())
            {
                throw new ArgumentNullException("RowKey");
            }

            TableOperation replaceOperation = TableOperation.InsertOrReplace(input);
            TableResult result = table.Execute(replaceOperation);
            return result.HttpStatusCode;
        }

The main problem is that the IsBackedUp field is not being updated when the InsertOrReplace command is being called in the third block of code.
Banging me head against a wall here trying to figure out why ATS will not accept my revision.
I can successfully change the value of IsBackedUp using Azure Table Storage Explorer.  I have confirmed that the datatype of the column is Boolean.
Any help would be greatly appreciated.  Let me know if I have posted enough of the code to be of assistance.  The only class that is not posted is the rest of the class that surrounds the last code block. It is over 2000 lines so I omitted it for brevity.  That class has the CloudTable, CloudTableClient and CloudStorageAccount variables.


Q: Weird error when initializing SKView
I have this block of code on my project to practice SpriteKit. But, for some unexpected reason, it gives me this error(compiles fine).

Just for the reference, I don't have anything on my HelloScene.h file. I hope this doesn't matter. There's nothing else other than these code. So, I can't see why this is happening. Can anyone tell me why? Thanks.

A: Check your storyboard, the view inside your ViewController should be SKView instead of UIView.


Q: Go create struct from XML Please see this playground: https://play.golang.org/p/FOMWqhjdneg
As you can see I have a XML response which I want to unmarshal into a Product struct. The XML has an "assetBlock" which contains nested nodes and extract data to Product struct. Any help would be appreciated

A: You need to make a struct for AssetBlock and all of the types below it, I've done it up to group to show you what I mean:
https://play.golang.org/p/vj_CkneHuLd
type Product struct {
    GlobalID   string     `xml:"globalId"`
    Title      string     `xml:"title"`
    ChunkID    int        `xml:"gpcChunkId"`
    AssetBlock assetBlock `xml:"assetBlock"`
}
type assetBlock struct {
    Images images `xml:"images"`
}
type images struct {
    GroupList groupList `xml:"groupList"`
}
type groupList struct {
    Groups []group `xml:"group"`
}
type group struct {
    Usage string `xml:"usage"`
    Size string `xml:"size"`
}


Q: Forcing UTF8 Format with PHP's XMLReader, DOM and SimpleXML We have a script that parses XML feeds from user generated sources which from time to time contain improperly formated entries with special characters.
While I would normally just run utf8_encode() on the line, I'm not certain how to do this as DOM is progressively reading the file and the error is thrown as the expand command takes place.
Since simple_xml chokes on the code, subsequent lines are also off.
Here's the code.
$z = new XMLReader;
$z->open($filename); $doc = new DOMDocument('1.0','UTF-8');
while ($z->read() && $z->name !== 'product');
while ($z->nodeType == XMLReader::ELEMENT AND $z->name === 'product'){
$producti = simplexml_import_dom($doc->importNode($z->expand(), true));
print_r($producti);
}

Errors:

Message:  XMLReader::expand(): foo.xml:29081: parser error : Input is
  not proper UTF-8, indicate encoding ! Bytes: 0x05 0x20 0x2D 0x35
Severity: Warning Message:  XMLReader::expand(): An Error
  Occured while expanding  Filename: controllers/feeds.php
Line Number: 106
Message:  Argument 1 passed to DOMDocument::importNode() must be an
  instance of DOMNode, boolean given Filename:
  controllers/feeds.php Line Number: 106

A: Use HTML Tidy library first to clean your string.
Also I'd better use DOMDocument instead of XMLReader.
Something like that:
        $tidy = new Tidy;

        $config = array(
                'drop-font-tags' => true,
                'drop-proprietary-attributes' => true,
                'hide-comments' => true,
                'indent' => true,
                'logical-emphasis' => true,
                'numeric-entities' => true,
                'output-xhtml' => true,
                'wrap' => 0
        );

        $tidy->parseString($html, $config, 'utf8');

        $tidy->cleanRepair();

        $xml = $tidy->value; // Get clear string

        $dom = new DOMDocument;

        $dom->loadXML($xml);

        ...


Q: Value are showing different results can anybody explain why this below code is showing different values
class ABC: UIViewController

    {
        var Distance : Int!

        override func viewDidLoad()
        {
            super.viewDidLoad()

            var obj_A = ABC()
            obj_A.Distance = 10
            var obj_B =  objVR_A
            obj_A.Distance = 30

            print(obj_A.Distance) // 30
            print(obj_B.Distance) // 30

            var x = 10
            let y = x
            x = 30
            print(x) //30
            print(y) //10
    }}

Why the value of Obj_B is 30 while value of Y is 10.
Thanks.

A: From Apple documentation:
// Reference type example
class C { var data: Int = -1 }
var x = C()
var y = x                       // x is copied to y
x.data = 42                     // changes the instance referred to by x (and y)
println("\(x.data), \(y.data)") // prints "42, 42"

Copying a reference implicitly creates a shared instance. After a copy, two variables then refer to a single instance of the data.

A: This is because primitives are value-based types, and classes are reference-based. You can find detailed explanation on Apple's blog.
// Value type example
struct S { var data: Int = -1 }
var a = S()
var b = a                       // a is copied to b
a.data = 42                     // Changes a, not b
println("\(a.data), \(b.data)") // prints "42, -1"

// Reference type example
    class C { var data: Int = -1 }
    var x = C()
    var y = x                       // x is copied to y
    x.data = 42                     // changes the instance referred to by x (and y)
    println("\(x.data), \(y.data)") // prints "42, 42"


Q: Lit-html not found when using polymer build I have a fairly basic lit-html app that works locally when it's not build.
However when I build it using polymer build using the following config:
{
    "entrypoint": "index.html",
    "shell": "src/school-home.js",
    "sources": [
    "src/**.js",
    "package.json"
    ],
    "extraDependencies": [
    "node_modules/@webcomponents/webcomponentsjs/bundles/**"
    ],
    "builds": [
    {"preset": "es6-bundled"}
    ]
}

This results in a successful build but for some reason I keep getting an error:

I just don't get why it doesn't work. This like the basics of the basics yet it doesn't get found?
Aside: I use nginx for windows since I want to test E2E with my developed APIs.
An additional issue is that I keep getting CORS error for my API calls even though they are on the exact same location?!!
Please help.
Edit:
My NGINX config:
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       cors-settings.conf;
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    keepalive_timeout  65;

    map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
    }

    server {
        listen       8000;
        server_name  localhost;

    location /school {
        root /html/ing-school;
        try_files $uri $uri/ $uri.html /index.html;
    }

    location ~ ^/(api|login|logout) {
        proxy_pass http://localhost:8080;
        proxy_set_header Connection "";

     if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
     }
     if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
     }
    if ($request_method = 'GET') {
            add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-    With,If-Modified-Since,Cache-Control,Content-Type,Range';
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-    Range';
     }
       }

        location /ws {
            proxy_pass http://127.0.0.1:8080;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}


Q: 'Can't find' repo error - missing a repo and can't move past it
I'm new to git/github.  A few months ago, I put an old wordpress site as a repo on there, that I've since deleted from my computer.  Had alot of trouble since then with github.  When I try and put a new repo on github, it won't let me, and says it's missing the original repo (see attached pic).  I thought this might be a github issue for my account, so I tried creating a brand new github profile from scratch to bypass the error.  But even logged into the new github (with no repos), I still get this error.  It's like my computer is stuck on this git issue for this one old repo.  I'm using a M1 macbook pro if that matters.  Can anyone help?
I have a copy of the wordpress site that it was originally linked to, but it's a different version.  I don't know if I need to put this in a specific location and that will make the error go away?


Q: Radio buttons are circle on PC, but square on mobile I have coded some simple radio buttons (with no styling)
<input onclick="calcAdult()" type="radio" name="age">Adult
<input onclick="calcPup()" type="radio" name="age">Puppy (younger than 1 year)

On pc they show as normal circles, but on mobile they are check boxes, how can I change this?

A: You can make customize.
Simple example
<!DOCTYPE html>

Custom Radio Buttons

One
  <input type="radio" checked="checked" name="radio">

Two
  <input type="radio" name="radio">

Three
  <input type="radio" name="radio">

Four
  <input type="radio" name="radio">


Q: How to make Youtube videos play from code without having the user to switch to that tab I am making a chrome extension where user can make playlists of songs. For that when I click on play button I need that new tab should open and the video should start playing but youtube video doesn't play without switching over to that tab. I tried to use the 'canplay' eventlistener but it also is called only when I switch over to that tab in which video is played. Can somebody help?

console.log("Hello from content script!");
var video = document.getElementsByTagName("video")[0];
if(video) {
  video.addEventListener("ended", function() {
    console.log("Video ended");
    //alert('Ended');
    chrome.runtime.sendMessage(
        "ended"
    );
  })
  video.addEventListener("canplay", function(event) {
      alert("noted");
      //video.play();
      let playbtn = document.getElementsByClassName('ytp-play-button ytp-button')[0];
      playbtn.click();
  })
} else {
  //console.error("Video element not found");
}

A: Have you tried adding I?&autoplay=1 to the end of the youtube links?


Q: Is there a way to channel some HTTP server events into a single javascript function? I have a C# webserver which provides some html/js/css and images to a browser-based client.
I create the page dynamically using javascript, filling images and divs while receiving messages from a websocket C# server.
Sometimes, I receive a message from the websocket and I try to access a resource in the webserver which might be protected.
I have some custom http server events for this (say, 406) because otherwise the browser pops up a dialog box for digest auth login.
I was wondering whether there is a way to channel all 406 events into the same function, say
RegisterHttpEventHandler(406,myFunction);

I guess I could just wrap any request/dynamic load in try and catches, although I'd love a cleaner way of doing this.
EDIT
Here is an example of the workflow which I implemented so far, and which works fine.
// Websocket definition
var conn = new WebSocket('ws://' + addressIP);
// Websocket receiver callback

conn.onmessage = function (event) {
        // my messages are json-formatted
        var mObj = JSON.parse(event.data);
        // check if we have something nice
        if(mObj.message == "I have got a nice image for you"){
        showImageInANiceDiv(mObj.ImageUrl);
        }
    };

// Dynamic load image
function showImageInANiceDiv(imgUrl )
{
    var imgHtml = wrapUrlInErrorHandler(imgUrl);
    $("#imageBox").html(imgHtml);
}

// function to wrap everything in an error handler
function wrapUrlInErrorHandler(Url)
{
    return '<img src="' + Url + '" onerror="errorHandler(\''+ Url +'\');"/>';
}

// function to handle errors
function errorHandler(imgUrl)
{
     console.log("this guy triggered an error : "  + imgUrl);
}

//

A:
the onerror does not tell me what failed, so I have to make an XHR just to find it out. That's a minor thing

You could first try the XHR. If it fails, you know what happened, if it succeeds you can display the image from cache (see also here). And of course you also could make it call some globally-defined custom hooks for special status codes - yet you will need to call that manually, there is no pre-defined global event source.

I'd like to have something like a document.onerror handler to avoid using the wrapUrlInErrorHandler function every time I have to put an image in the page

That's impossible. The error event (MDN, MSDN) does not bubble, it fires directly and only on the <img> element. However, you could get around that ugly wrapUrlInErrorHandler if you didn't use inline event attributes, but (traditional) advanced event handling:
function showImageInANiceDiv(imgUrl) {
    var img = new Image();
    img.src = imgUrl;
    img.onerror = errorHandler; // here
    $("#imageBox").empty().append(img);
}
// function to handle errors
function errorHandler(event) {
     var img = event.srcElement; // or use the "this" keyword
     console.log("this guy triggered an "+event.type+": "  + img.src);
}


Q: Selecting records based on maximum value of another field I am trying to pull a list of distinct city names with their latitudes and longitudes based on the maximum value of the land area field.   The best I get is a "SQL: Error correlating fields" error.
SELECT a.primary_city as city ;
    , a.state as state_id ;
    , SPACE(30) as state_name ;
    , a.approximate_latitude as latitude ;
    , a.approximate_longitude as longitude ;
FROM citystate a ;
WHERE a.area_land = ;
    (SELECT MAX(VAL(b.area_land)) ;
    FROM citystate b ;
    WHERE (b.primary_city = a.primary_city ;
        AND b.state = a.state)) ;
GROUP BY a.primary_city ;
    , a.state ;
    , a.approximate_latitude ;
    , a.approximate_longitude

Not sure this will even work so hoping for some help.
Thanks.

A: Such SQL is not supported in VFP. You can write that as:
SELECT csa.primary_city as city ;
    , csa.state as state_id ;
    , SPACE(30) as state_name ;
    , csa.approximate_latitude as latitude ;
    , csa.approximate_longitude as longitude ;
FROM citystate csa ;
INNER JOIN ;
    (SELECT primary_city, state, MAX(VAL(area_land)) as maxALand ;
    FROM citystate ;
    GROUP BY primary_city, state ) csb ;
  ON csb.primary_city = csa.primary_city ;
        AND csb.state = csa.state ;
WHERE VAL(csa.area_land) = csb.maxALand

A: VFP has not problem at all with 'such SQL', contrary to the pronouncement of master Basoz on the matter.
Normally you should get a type mismatch error because of the comparison of land_area to max(val(land_area)). Fox is nowhere near as eager with implicit conversions as, for example, MS SQL Server, and hence you have to match data types correctly.
However, not knowing what your table structures are it is difficult to offer specific pointers as to where the problem may be. Here are two similar queries using sample data available in VFP (using the freight cost as a stand-in for land_area value):
_VFP.DoCmd("set path to " + set("PATH") + ";" + _SAMPLES)

use Northwind/orders alia nw_orders in sele("nw_orders") shar noup agai

sele o.shipcountry, o.shipcity, o.shipname, o.orderid, o.freight ;
   from nw_orders o ;
   wher o.freight == ( ;
      sele max(x.freight) from nw_orders x wher x.shipcountry == o.shipcountry ) ;
   orde by 1 ;
   into curs nw_result
brow last nowa

use Tastrade/orders alia tt_orders in sele("tt_orders") shar noup agai

sele o.ship_to_country, o.ship_to_city, o.ship_to_name, o.order_number, o.freight ;
   from tt_orders o ;
   wher o.freight == ( ;
      sele max(x.freight) from tt_orders x wher x.ship_to_country == o.ship_to_country ) ;
   orde by 1 ;
   into curs tt_result
brow last nowa

Tastrade and Northwind are very similar in structure and contain very similar data; one or the other should be available in your VFP installation. However, neither sample database seems to in the public domain, at least not in the VFP incarnation. That is why I put Northwind first, since it is publicly available in versions for MS SQL Server etc. pp., and dumping its orders table to Fox format should not present insurmountable difficulties.
Here's a C# LINQPad script for running the Northwind query via OLEDB:
const string DIR = @"d:\dev\sub\FoxIDA\data\Northwind\";
const string SQL = @"
sele o.shipcountry, o.shipcity, o.shipname, o.orderid, o.freight
   from orders o
   wher o.freight == (sele max(x.freight) from orders x wher x.shipcountry == o.shipcountry)
   orde by 1";

using (var con = new System.Data.OleDb.OleDbConnection("provider=VFPOLEDB;data source=" + DIR))
{
    using (var cmd = new System.Data.OleDb.OleDbCommand(SQL, con))
    {
        con.Open();
        cmd.ExecuteReader().Dump();
    }
}

Obviously, you'd need to adapt the DIR definition to where the data is located on your machine. Equally obviously you'd have to use a 32-bit version of LINQPad, since there is no 64-bit OLEDB driver for VFP. Here's the result:


Q: jquery closest() or children not working jquery code :-
$('.cycle-status-update')
  .on('mouseenter', (function(){
    $(this).closest('.delete-status-update-link').show();
  }))
  .on('mouseleave', (function(){
    $(this).closest('.delete-status-update-link').hide();
  }))

html code :-
.status-partial
    -@user.status_updates.latest.limit(5).each do |status_update|
        .row-fluid.cycle-status-update{:class => cycle("dark", "light")}
            .row-fluid
                .span11
                    = status_update.status
                .span1
                    .delete-status-update-link
                        %strong= link_to "X", [@user,status_update], :remote => true, :method => :delete, :class => "delete-status-update"
            .row-fluid
                .time-ago-in-words
                    ="#{time_ago_in_words(status_update.created_at)} ago"

what could be the issue here ?

A: use find()
$(this).find('.delete-status-update-link').show();

A: You have issues with your code, (function extra ( before function and after ):
$('.cycle-status-update')
     .on('mouseenter', (function(){
     $(this).closest('.delete-status-update-link').show();
}))//<----here
.on('mouseleave', (function(){ //<--before function
    $(this).closest('.delete-status-update-link').hide();
}))
//^----here

try this:
$('.cycle-status-update').on('mouseenter', function(){
  $('.delete-status-update-link').show();
}).on('mouseleave', function(){
  $('.delete-status-update-link').hide();
});


Q: Dynamically Populate the linear layout depending upon Markers on the Map I am working on the android project in which I need to draw a UI something like below. I need to divide the android screen in two half. In the Top Half I need to show the google maps. And in the Bottom Half I need to show the user information as soon as anyone clicked on the Google Maps. Top Half part is done and its working for me.
Problem Statement:-
I need to dynamically keep on creating the linear layout in the bottom half part depending on how many markers(users) are there on the maps. Below is the screen shot in which I have created two layouts in the bottom half part considering two user's are there on the google maps. But how can I make this thing to work dynamically, suppose if I have three user's on the google maps currently, then in the bottom half part three layout will get plotted automatically. I hope I am clear enough.

A: Yes you can do use a listview and create custom adapter. set your map as header in listview and use your listview rows for data representation.
Another thing which you can do is create listview and maps seperate. Align your listview just below to the map
Here i am giving you a simple example the code below will create listview. You may need to I have created custom adapter for your purpose.
public class my_map_activity extends Activity {

    ArrayList<String> name = null;
    ArrayList<String> gender = null;
    ArrayList<String> latitude = null;
    ArrayList<String> longitude = null;
    Context activity_context = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView user_listview = (ListView) findViewById(R.id.user_listview);

        name = new ArrayList<String>();
        gender = new ArrayList<String>();
        latitude = new ArrayList<String>();
        longitude = new ArrayList<String>();

        for (int i = 0; i < 10; i++) {
            name.add ("test user " + i);
            gender.add ("Male");
            latitude.add (""+ i);
            longitude.add (""+ i);
        }

        custom_adapter list_adapter = new custom_adapter (this, android.R.layout.simple_list_item_1, name, gender, latitude, longitude);
        user_listview.setAdapter(list_adapter);
    }
}

Here is my main.xml file. Which will tell you how to create that layout. I am using Relative layout as my parent layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="250dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_launcher" />

    <ListView
        android:id="@+id/user_listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/imageView1" >
    </ListView>

</RelativeLayout>

here i am posting you my custom adapter code which you can use for your listview purpose.
public class custom_adapter extends ArrayAdapter<String>{

    ArrayList<String> name = null;
    ArrayList<String> gender = null;
    ArrayList<String> latitude = null;
    ArrayList<String> longitude = null;
    Context activity_context = null;

    public custom_adapter(Context context,
                          int resource,
                          ArrayList<String> name ,
                          ArrayList<String> gender,
                          ArrayList<String> latitude,
                          ArrayList<String> longitude) {
        super(context, resource, name );
        this.name = name;
        this.gender = gender;
        this.latitude = latitude;
        this.longitude = longitude;
        activity_context = context;
    }

    static class ViewHolder
    {
        public TextView txt_name;
        public TextView txt_gender;
        public TextView txt_latitude;
        public TextView txt_longitude;
        public ImageView img_view;
    }

    @Override
    public View getView (final int position,
                         View      convertView,
                         ViewGroup parent)
    {
        View rowView = convertView;
        ViewHolder holder = null;

        if (rowView == null) {
            LayoutInflater inflater = (LayoutInflater)activity_context.getSystemService(
                                               Context.LAYOUT_INFLATER_SERVICE);
            rowView = inflater.inflate(R.layout.row_file, null, false);
            holder = new ViewHolder();
            holder.txt_name = (TextView) rowView.findViewById(R.id.textView1);
            holder.txt_gender = (TextView) rowView.findViewById(R.id.textView2);
            holder.txt_latitude = (TextView) rowView.findViewById(R.id.textView3);
            holder.txt_longitude = (TextView) rowView.findViewById(R.id.textView4);
            holder.img_view = (ImageView) rowView.findViewById(R.id.imageView1);
            rowView.setTag(holder);

        } else {
            holder = (ViewHolder) rowView.getTag();
        }

        if (holder != null) {
            holder.txt_name.setText(name.get(position));
            holder.txt_gender.setText(gender.get(position));
            holder.txt_latitude.setText(latitude.get(position));
            holder.txt_longitude.setText(longitude.get(position));
        }
        return rowView;
    }
}

Here is the layout which you can inflate in your custom adapter and set it on listview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_launcher" android:layout_marginTop="10dp" android:layout_marginLeft="10dp" android:contentDescription="TODO"/>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_toRightOf="@+id/imageView1"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView1"
        android:layout_toRightOf="@+id/imageView1"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView2"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/textView3"
        android:text="Medium Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

So i have given you all four files. Here i am explaining what every file will do.

*

*my_map_activity : This is the main activity which contains listivew and map both. I am using a big imageview. Instead of that imageview you can place your map.

*main.xml : This is layout file which contains both listview and map.

*custom_adapter : This is the custom adapter which i have created for you. I am extending array adapter. In this i am taking data from arraylist and inflating the row layout and the i am setting respective values.

*row_layout : This is the row layout which will contain imageview for user, name, gender and all other thing.
So i have created several things for you if you need any help then you can ask and try to get the concept of each file how i am using.


Q: Is this a bug in Power BI? I have several .pbix files where I mostly consume live from SSAS. Last week I was able to see the model, (I downloaded today the december 2022 version) and after I installed it, I can't see them anymore... why? Is this the expected behavior? it seems like a bug...


Q: How can I detect if in Android , soft-keyboard's delete has been long pressed when a particular TextInputLauout field is in focus I have many custom TextInputLayout with custom TextInputEditText views in the XML.
For some TextInputFields I need to give the below feature:

*

*When the field is in focus

*Soft keyboard should launch

*When the user presses the delete button for long approx (2 secs)

*It should clear the content in TextInputEditText
I tried --> Implementing onKeyPreIme(int keyCode, KeyEvent event) in Fragment


Q: Conditional Left Join I'm trying to figure out how to return columns only when needed.
Data will only exists in the 1_finance_add_details and the addresses e tables when t.trans_type=2
SELECT t.*,
 a.company,
 a.house_number,
 a.flat_number,
 a.house_name,
 a.address1,
 a.address2,
 a.address3,
 a.town,
 a.county,
 a.post_code,
 a.country,
 f.*,
 e.company,
 e.house_number,
 e.flat_number,
 e.house_name,
 e.address1,
 e.address2,
 e.address3,
 e.town,
 e.county,
 e.post_code,
 e.country
FROM 1_transactions t
LEFT JOIN addresses a ON a.id=t.fk_addresses_id
LEFT JOIN 1_finance_add_details f ON t.id=f.fk_transactions_id
LEFT JOIN addresses e ON e.id=f.employ_fk_addresses_id
WHERE trans_location=1 AND t.id=19;

A: Not sure if this is the result that you want, but you can just add another condition in your left join like this:
FROM 1_transactions t
LEFT JOIN addresses a ON a.id=t.fk_addresses_id
LEFT JOIN 1_finance_add_details f ON t.id=f.fk_transactions_id
LEFT JOIN addresses e ON e.id=f.employ_fk_addresses_id AND t.trans_type=2
WHERE trans_location=1 AND t.id=19;

Note: this would render the field of addresses e NULL on every t with type != 2.


Q: Hibernate enableFilter not working when loading entity by id I have 3 classes:

*

*Event

*PublicEvent extends Event

*PersonalEvent extends Event
my hibernate mapping file is somethings like bellow. i wanna add one filter for PersonalEvent and before loading this object, i was enabled that's filter. but this is not working. my hibernate version is 4.3.11.Final.
Event.hbm.xml
<hibernate-mapping>
    <class name="org.calendar.Event">
        ...
        <filter name="personalEventAuthorize" condition="person_ID = :personId" />
    </class>
    <joined-subclass name="org.calendar.PersonalEvent" extends="org.calendar.Event">
        <key column="id" property-ref="id" />
        ...
        <many-to-one name="person" column="person_ID" entity-name="org.person.Person" />
     </joined-subclass>
     <joined-subclass name="org.calendar.PublicEvent" extends="org.calendar.Event">
        <key column="id" property-ref="id" />
        ...
     </joined-subclass>
     <filter-def name="personEventAuthorize">
        <filter-param name="personId" type="integer" />
     </filter-def>
</hibernate-mapping>

PersonalEventRepository
@Override
public PersonalEvent load(Long id) {
    Filter filter = getSession().enableFilter("personEventAuthorize");
    filter.setParameter("personId", getAuthenticatedPersonId());
    return super.loadById(id);
}

hibernate generated SQL Query without my filter. what is my problem? why hibernate can not enabled filter for joined-subclass?
thanks for all...

A: This is not a bug, it's the intended behavior. I updated the Hibernate User Guide to make it more obvious.
The @Filter does not apply when you load the entity directly:
Account account1 = entityManager.find( Account.class, 1L );
Account account2 = entityManager.find( Account.class, 2L );

assertNotNull( account1 );
assertNotNull( account2 );

While it applies if you use an entity query (JPQL, HQL, Criteria API):
Account account1 = entityManager.createQuery(
    "select a from Account a where a.id = :id",
    Account.class)
    .setParameter( "id", 1L )
.getSingleResult();
assertNotNull( account1 );
try {
    Account account2 = entityManager.createQuery(
        "select a from Account a where a.id = :id",
        Account.class)
    .setParameter( "id", 2L )
    .getSingleResult();
}
catch (NoResultException expected) {
    expected.fillInStackTrace();
}

So, as a workaround, use the entity query (JPQL, HQL, Criteria API) to load the entity.


Q: Node Js Firestore accessing a database value with a space new to node Js expecting this to be very easy!
in node JS with Firestore i want to access  "display name": James, "Age": 22
Age has no space so i can just put
const newValue = doc.data();
             const age = newValue.Age;

but display name contains a space
how to you type this?
 const displayName = newValue.displayName;

A: You'll need to use [] notation to get at the property.
So:
const displayName = newValue["display name"];


Q: Control Android LED from shell I have seen several questions (and blog posts, elsewhere) with Java code for controlling the notification LED on an Android device. That's not what I'm looking for.
I'm wondering if there is any way to access the appropriate commands / controls / frameworks from the shell (Perl, ruby).
What I want, ultimately, is a very simple "heartbeat" pulse - when the device is on and the display is off, blink at me.
Alternatively, if anyone has written a really simple "toy" app that blinks the LED, I'd love to play with it.

A: You can find all leds of your device under
/sys/class/leds/

In my case, I have the following leds
amber
button-backlight
flashlight
green
lcd-backlight

If I have a look inside "green", I see
> cd green
> ls
blink
brightness
currents
device
lut_coefficient
max_brightness
off_timer
power
pwm_coefficient
subsystem
trigger
uevent

These files are interfaces to the kernel module, which controls leds. In this case, I think they are char-devices. You can use the command "echo" and "cat" to communicate with the kernel module. Here an example..
echo 1 > brightness  # Turn on led
echo 0 > brightness  # Turn off led

For implementing a "heartbeat" pulse as you mentioned, I would have a look into "blink". If you not want to perform reverse engineering, this could be a good entry point to check what happens in the kernel leds-gpio.c


Q: How to use palettes in SDL 2 I'm updating a program from SDL 1 to SDL 2 and need to use color palettes. Originally, I used SDL_SetColors(screen, color, 0, intColors); but that does't work in SDL 2. I'm trying to use:
SDL_Palette *palette = (SDL_Palette *)malloc(sizeof(color)*intColors);
SDL_SetPaletteColors(palette, color, 0, intColors);
SDL_SetSurfacePalette(surface, palette);

But SDL_SetPaletteColors() returns -1 and fails. SDL_GetError gives me no information.
How can I make a palette from a SDL_Color and then set it as my surface's palette?

A: It's hard to tell what your variables are and how you intend to use them without seeing your declarations.
Here's how I set up a grayscale palette in SDL_gpu:
SDL_Color colors[256];
int i;

for(i = 0; i < 256; i++)
{
    colors[i].r = colors[i].g = colors[i].b = (Uint8)i;
}

#ifdef SDL_GPU_USE_SDL2
SDL_SetPaletteColors(result->format->palette, colors, 0, 256);
#else
SDL_SetPalette(result, SDL_LOGPAL, colors, 0, 256);
#endif

The result SDL_Surface already has a palette because it is has an 8-bit pixel depth (see note in https://wiki.libsdl.org/SDL_Palette).

A: It has been awhile since the OP posted the question and there has been no accepted answer. I ran into the same issue while trying to migrate a SDL 1.2 based game into using 2.0. here is what I did hoping it could help other who may be facing similar issue:
    Replace:
SDL_SetColors(screen, color, 0, intColors);
With:
SDL_ SDL_SetPaletteColors(screen->format->palette, color, 0, intColors);
David


Q: Trouble predicting with tensorflow model I've trained a Deep Neural Network on the MNIST dataset. Here is the code for training.
n_classes = 10
batch_size = 100

x = tf.placeholder(tf.float32, [None, 784],name='Xx')
y = tf.placeholder(tf.float32,[None,10],name='Yy')

input = 784
n_nodes_1 = 300
n_nodes_2 = 300

def neural_network_model(data):
    variables = {'w1':tf.Variable(tf.random_normal([input,n_nodes_1])),
               'w2':tf.Variable(tf.random_normal([n_nodes_1,n_nodes_2])),
               'w3':tf.Variable(tf.random_normal([n_nodes_2,n_classes])),
                 'b1':tf.Variable(tf.random_normal([n_nodes_1])),
                 'b2':tf.Variable(tf.random_normal([n_nodes_2])),
                 'b3':tf.Variable(tf.random_normal([n_classes]))}
    output1 = tf.add(tf.matmul(data,variables['w1']),variables['b1'])
    output2 = tf.nn.relu(output1)
    output3 = tf.add(tf.matmul(output2, variables['w2']), variables['b2'])
    output4 = tf.nn.relu(output3)
    output5 = tf.add(tf.matmul(output4, variables['w3']), variables['b3'],name='last')
    return output5

def train_neural_network(x):
    prediction = neural_network_model(x)
    name_of_final_layer = 'fin'
    final = tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction,
                                                       labels=y,name=name_of_final_layer)
    cost = tf.reduce_mean(final)
    optimizer = tf.train.AdamOptimizer().minimize(cost)
    hm_epochs = 3
    saver = tf.train.Saver()
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples/batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                _,c=sess.run([optimizer,cost],feed_dict={x:epoch_x,y:epoch_y})
                epoch_loss += c
            print("Epoch",epoch+1,"Completed Total Loss:",epoch_loss)
            correct = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
            accuracy = tf.reduce_mean(tf.cast(correct,'float'))
            print('Accuracy on val_set:',accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))
        path = saver.save(sess,"net/network")
        print("Saved to",path)

Here is my code for evaluating a single datapoint
def eval_neural_network():
    with tf.Session() as sess:
        new_saver = tf.train.import_meta_graph('net/network.meta')
        new_saver.restore(sess, "net/network")
        sing = np.reshape(mnist.test.images[0],(-1,784))
        output = sess.run([y],feed_dict={x:sing})
    print(output)
eval_neural_network()

The error that popped up is :
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'Yy' with dtype float and shape [?,10]
     [[Node: Yy = Placeholder[dtype=DT_FLOAT, shape=[?,10], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

I've researched this online for multiple days now and still could not get it to work. Any advice?

A: This complete example based on tensorflow github worked for me:
(I modified few lines of code by removing name scope for x, keep_prob and changing to tf.placeholder_with_default. There's probably a better way to do this somewhere.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas as pd
import argparse
import sys
import tempfile

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

def deepnn(x):
  """deepnn builds the graph for a deep net for classifying digits.

  Args:
    x: an input tensor with the dimensions (N_examples, 784), where 784 is the
    number of pixels in a standard MNIST image.

  Returns:
    A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
    equal to the logits of classifying the digit into one of 10 classes (the
    digits 0-9). keep_prob is a scalar placeholder for the probability of
    dropout.
  """
  # Reshape to use within a convolutional neural net.
  # Last dimension is for "features" - there is only one here, since images are
  # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  with tf.name_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.

  keep_prob = tf.placeholder_with_default(1.0,())
  h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  return y_conv, keep_prob

def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

# Import data
mnist = input_data.read_data_sets("/tmp")
# Create the model
x = tf.placeholder(tf.float32, [None, 784],name='x')
# Define loss and optimizer
y_ = tf.placeholder(tf.int64, [None])
# Build the graph for the deep net
y_conv, keep_prob = deepnn(x)
with tf.name_scope('loss'):
    cross_entropy = tf.losses.sparse_softmax_cross_entropy(
        labels=y_, logits=y_conv)
    cross_entropy = tf.reduce_mean(cross_entropy)

with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), y_)
    correct_prediction = tf.cast(correct_prediction, tf.float32)
    accuracy = tf.reduce_mean(correct_prediction)

graph_location = tempfile.mkdtemp()
print('Saving graph to: %s' % graph_location)
train_writer = tf.summary.FileWriter(graph_location)
train_writer.add_graph(tf.get_default_graph())

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(1000):
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

    sing = np.reshape(mnist.test.images[0],(-1,784))
    output = sess.run(y_conv,feed_dict={x:sing,keep_prob:1.0})
    print(tf.argmax(output,1).eval())
    saver = tf.train.Saver()
    saver.save(sess,"/tmp/network")

Extracting /tmp/train-images-idx3-ubyte.gz
Extracting /tmp/train-labels-idx1-ubyte.gz
Extracting /tmp/t10k-images-idx3-ubyte.gz
Extracting /tmp/t10k-labels-idx1-ubyte.gz

Saving graph to: /tmp/tmp17hf_6c7
step 0, training accuracy 0.2
step 100, training accuracy 0.86
step 200, training accuracy 0.8
step 300, training accuracy 0.94
step 400, training accuracy 0.94
step 500, training accuracy 0.96
step 600, training accuracy 0.88
step 700, training accuracy 0.98
step 800, training accuracy 0.98
step 900, training accuracy 0.98
test accuracy 0.9663
[7]

If you want to restore from a new python run:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
import numpy as np

import argparse
import sys
import tempfile
from tensorflow.examples.tutorials.mnist import input_data

sess =  tf.Session()
saver = tf.train.import_meta_graph('/tmp/network.meta')
saver.restore(sess,tf.train.latest_checkpoint('/tmp'))
graph = tf.get_default_graph()
mnist = input_data.read_data_sets("/tmp")
simg = np.reshape(mnist.test.images[0],(-1,784))
op_to_restore = graph.get_tensor_by_name("fc2/MatMul:0")
x = graph.get_tensor_by_name("x:0")
output = sess.run(op_to_restore,feed_dict= {x:simg})
print("Result = ", np.argmax(output))

A: The losses are oscillating like this but the predictions don't seem to be bad. It works.
It also extracts the mnist archive repeatedly. Accuracy also can reach 0.98 with a simpler network.
Epoch 1 Completed Total Loss: 47.47844
Accuracy on val_set: 0.8685
Epoch 2 Completed Total Loss: 10.217445
Accuracy on val_set: 0.9
Epoch 3 Completed Total Loss: 14.013474
Accuracy on val_set: 0.9104
[2]

import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
import numpy as np
import matplotlib.pyplot as plt

n_classes = 10
batch_size = 100

x = tf.placeholder(tf.float32, [None, 784],name='Xx')
y = tf.placeholder(tf.float32,[None,10],name='Yy')

input = 784
n_nodes_1 = 300
n_nodes_2 = 300

mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)

def neural_network_model(data):
    variables = {'w1':tf.Variable(tf.random_normal([input,n_nodes_1])),
               'w2':tf.Variable(tf.random_normal([n_nodes_1,n_nodes_2])),
               'w3':tf.Variable(tf.random_normal([n_nodes_2,n_classes])),
                 'b1':tf.Variable(tf.random_normal([n_nodes_1])),
                 'b2':tf.Variable(tf.random_normal([n_nodes_2])),
                 'b3':tf.Variable(tf.random_normal([n_classes]))}
    output1 = tf.add(tf.matmul(data,variables['w1']),variables['b1'])
    output2 = tf.nn.relu(output1)
    output3 = tf.add(tf.matmul(output2, variables['w2']), variables['b2'])
    output4 = tf.nn.relu(output3)
    output5 = tf.add(tf.matmul(output4, variables['w3']), variables['b3'],name='last')
    return output5

def train_neural_network(x):
    prediction = neural_network_model(x)
    name_of_final_layer = 'fin'
    final = tf.nn.softmax_cross_entropy_with_logits_v2(logits=prediction,
                                                       labels=y,name=name_of_final_layer)
    cost = tf.reduce_mean(final)
    optimizer = tf.train.AdamOptimizer().minimize(cost)
    hm_epochs = 3
    saver = tf.train.Saver()
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        for epoch in range(hm_epochs):
            for _ in range(int(mnist.train.num_examples/batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                _,c=sess.run([optimizer,cost],feed_dict={x:epoch_x,y:epoch_y})
            print("Epoch",epoch+1,"Completed Total Loss:",c)
            correct = tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))
            accuracy = tf.reduce_mean(tf.cast(correct,'float'))
            print('Accuracy on val_set:',accuracy.eval({x:mnist.test.images,y:mnist.test.labels}))
        #path = saver.save(sess,"net/network")
        #print("Saved to",path)
    return prediction

def eval_neural_network(prediction):
    with tf.Session() as sess:
        new_saver = tf.train.import_meta_graph('net/network.meta')
        new_saver.restore(sess, "net/network")
        singleprediction = tf.argmax(prediction, 1)
        sing = np.reshape(mnist.test.images[1], (-1, 784))
        output = singleprediction.eval(feed_dict={x:sing},session=sess)
        digit = mnist.test.images[1].reshape((28, 28))
        plt.imshow(digit, cmap='gray')
        plt.show()
        print(output)

prediction = train_neural_network(x)

eval_neural_network(prediction)


Q: Azure Table Storage - Entity Design Best Practices Question Im writing a 'proof of concept' application to investigate the possibility of moving a bespoke ASP.NET ecommerce system over to Windows Azure during a necessary re-write of the entire application.
Im tempted to look at using Azure Table Storage as an alternative to SQL Azure as the entities being stored are likely to change their schema (properties) over time as the application matures further, and I wont need to make endless database schema changes. In addition we can build refferential integrity into the applicaiton code - so the case for considering Azure Table Storage is a strong one.
The only potential issue I can see at this time is that we do a small amount of simple reporting - i.e. value of sales between two dates, number of items sold for a particular product etc.
I know that Table Storage doesnt support aggregate type functions, and I believe we can achieve what we want with clever use of partitions, multiple entity types to store subsets of the same data and possibly pre-aggregation but Im not 100% sure about how to go about it.
Does anyone know of any in-depth documents about Azure Table Storage design principles so that we make proper and efficient use of Tables, PartitionKeys and entity design etc.
there's a few simplistic documents around, and the current books available tend not to go into this subject in much depth.
FYI - the ecommerce site has about 25,000 customers and takes about 100,000 orders per year.

A: I think there are three potential issues I think in porting your app to Table Storage.

*

*The lack of reporting - including aggregate functions - which you've already identified

*The limited availability of transaction support - with 100,000 orders per year I think you'll end up missing this support.

*Some problems with costs - $1 per million operations is only a small cost, but you can need to factor this in if you get a lot of page views.

Honestly, I think a hybrid approach - perhaps EF or NH to SQL Azure for critical data, with large objects stored in Table/Blob?
Enough of my opinion! For "in depth":

*

*try the storage team's blog http://blogs.msdn.com/b/windowsazurestorage/ - I've found this very good

*try the PDC sessions from Jai Haridas (couldn't spot a link - but I'm sure its there still)

*try articles inside Eric's book - http://geekswithblogs.net/iupdateable/archive/2010/06/23/free-96-page-book---windows-azure-platform-articles-from.aspx

*there's some very good best practice based advice on -  http://azurescope.cloudapp.net/ - but this is somewhat performance orientated

A: Have you seen this post ?
http://blogs.msdn.com/b/windowsazurestorage/archive/2010/11/06/how-to-get-most-out-of-windows-azure-tables.aspx
Pretty thorough coverage of tables

A: If you have start looking at Azure storage such as table, it would do no harm in looking at other NOSQL offerings in the market (especially around document databases). This would give you insight into NOSQL space and how solution around such storages are designed.
You can also think about a hybrid approach of SQL DB + NOSQL solution. Parts of the system may lend themselves very well to Azure table storage model.
NOSQL solutions such as Azure table have their own challenges such as

*

*Schema changes for data. Check here and here

*Transactional support

*ACID constraints. Check here

A: All table design papers I have seen are pretty much exclusively focused on the topics of scalability and search performance. I have not seen anything related to design considerations for reporting or BI.
Now, azure tables are accessible through rest APIs and via the azure SDK. Depending on what reporting you need, you might be able to pull out the information you require with minimal effort. If your reporting requirements are very sophisticated, then perhaps SQL azure together with Windows Azure SQL Reporting services might be a better option to consider?