text:
Q: execvp appears to change pid of the process I created a program that does:
1. fork
2. from the son, create execvp with csh. The execvp csh runs a script a.sh that prints in infinite loop.
My problem is that I cant stop or kill the process from the father (using kill(SIGKILL,pid) from the father process didn't work).
I think that the problem is in execvp.
when I print the pid from the script(echo $BASHPID ) I get a different pid from the one that I get before the execvp. i know the pid after execvp is supposed to remain the same, but it seems like it doesn't.
here is the problematic code:
int ExeExternal(char* args[MAX_ARG], char* cmdString, int* fg_pid, char** L_Fg_Cmd){
        //int child_status;
        int pID;
        pID = fork();
        switch(pID) {
            case -1:        //error
                    perror("fork");
                    return 1;
            case 0 :        // Child Process
                    setpgrp();
                    printf("son getpid() : %d",getpid());
                    fflush(stdout);
                    char* argument_for_cshs[5];
                    char* cmd="csh";
                    argument_for_cshs[0]="csh";
                    argument_for_cshs[1]="-f";
                    argument_for_cshs[2]="-c";
                    argument_for_cshs[3]=cmdString;
                    argument_for_cshs[4]=NULL;
                    execvp(argument_for_cshs[0],argument_for_cshs);
                    //if return => there is a problem

any solution?


text:
Q: can i use c-like arrays in python instead of lists as list are slow http://www.hackerearth.com/problem/algorithm/little-deepu-and-array/
This is the problem on above link which i solved using python.
but as list are slow i am not able to pass all test cases due to time constraint, whereas when solved using arrays in c++, i passed all test cases.
Python:
n=input()
l=map(int,raw_input().split())
m=input()
for i in range(m):
    x=input()
    for j in range(n):
        if(l[j]>x):
            l[j]-=1
for i in range(n):
    print l[i],

C++:
int main()
{
    int n,numCalls,x,i,j;
    long int arr[1000000];

    cin>>n;

    for(i=0;i<n;i++)
        cin>>arr[i];

    cin>>numCalls;
    for(i=0;i<numCalls;i++)
    {
        cin>>x;
        for(j=0;j<n;j++)
            if(arr[j]>x)
                arr[j]-=1;
    }

    for(i=0;i<n;i++)
        cout<<arr[i]<<" ";
}

Can anyone solve this problem in python efficiently so that all test-cases can be passed!!.

A: Here's your code with one change, initializing l with a Python array:
import array

n=input()
l=array.array('l', map(int, raw_input().split()))
m=input()
for i in range(m):
    x=input()
    for j in range(n):
        if(l[j]>x):
            l[j]-=1
for i in range(n):
    print l[i],

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any to create static page ( html ) on which theme styles are not applied in wordpress I want to make amp based static page like html but whenever i put that in wordpress,
wordpress applies its theme styles and settings
I want that it should not be affected by wordpress atleast not any theme based css or javascript
Thank you all
there must be a better way to do this please help
Thanks again

A: You are looking for Page templates.

Page templates are a specific type of template file that can be applied to a specific page or groups of pages.

You can refer to @ https://developer.wordpress.org/themes/template-files-section/page-template-files/
In short, you can create a new page template page-{slug}.php (save at root). We then need to tell WordPress that this new file is a "template". We can do so through a comment header (bellow is a minimal version of it). You would probably need to include the theme header and footer too.
<?php

/*
 * Template Name: My new template title
*/

get_header();

// Page code here...

get_footer();

A: You could create a dedicated PHP template file for that page, which you only assign to that particular page, and which does not contain the get_header() function.
Since besides not calling the theme stylesheet/s, this will also exclude a lot of other (necessary) functions, you could create a copy of your header.php file (in a child theme, if the theme isn't yours) which contains all the necessary functions and links except the link to the theme stylesheet, and call that "alternative header" file in your template for that page instead of using get_header().


text:
Q: Cannot create SSRS subscription for a report using SSAS as datasource My questions is : how should I config SSRS subscription a report, which consumes SSAS datasource.
I already googled and lookup stackoverflow a lot and still couldn't make it work.
Problems:
I developed and deployed a SSRS report to the server, and next I need to make subscription for that report to send emails.
And the report is using SSAS as datasource.
I learnt that SSAS required to use windows credentials and I already setup
the datasource .

However, when I attempted to click [New subscription], it alerts:

A: I have blogged about this exact issue. The workaround/solution involves expression-based connection strings which can be a bit painful. But I have prototyped a tool to automate the setup of those connection strings after deployment:
Using EffectiveUserName To Impersonate in SSAS

A: Here is my steps to resolve the problem by following GregGalloway's blog.
1 create a parameter called username, and give it a default user name.
2 Edit the datasource and click [Fx] to create a expression as the connection string.

*Key in the following as the value of [Fx], please note that Parameters!username.Value which [username] is the parameter name created in #1
="Data Source=[your ssas server ip];Initial Catalog=[your ssas catalog name];EffectiveUserName=" & Parameters!username.Value

*Deploy the report.

*Open the report on the server on the drop down menu click [Manage], then open data source,
-turn on [credentials stored securely.....]
-key in [user name] , [Password],
-Turn on [Use as Windows credentials when connecting to the datasource.

*Finally create subscription

A: in the report it self, inside "data source" use SQL credential :


text:
Q: How to order dataframe using a list in pandas I have a pandas dataframe as follows.
import pandas as pd
data = [['Alex',10, 175],['Bob',12, 178],['Clarke',13, 179]]
df = pd.DataFrame(data,columns=['Name','Age', 'Height'])
print(df)

I also have a list as follows.
mynames = ['Emj', 'Bob', 'Jenne', 'Alex', 'Clarke']

I want to order the rows of my dataframe in the order of mynames list. In other words, my output should be as follows.
   Name  Age  Height
0   Bob   12     178
1   Alex   10     175
2  Clarke   13     179

I was trying to do this as follows. I am wondering if there is an easy way to do this in pandas than converting the dataframe to list.
I am happy to provide more details if needed.

A: You can do pd.Categorical + argsort
df=df.loc[pd.Categorical(df.Name,mynames).argsort()]
     Name  Age  Height
1     Bob   12     178
0    Alex   10     175
2  Clarke   13     179


text:
Q: Groovy unicode support for MySQL select I am trying to fix a problem in a UTF-8 encoded database. During the migration to the current database system it looks like the data was compressed to Latin-1 encoding. I wrote a quick Groovy script to find and report the encoding errors. But, it fails to match anything.
If I write the analogous code in Java the report works fine!
So, I presume as a rookie with Groovy I'm doing something stupid. Can anyone see the error in my approach? I've tried hard-coding the characters in the select statement but i cannot get any of the special characters to work.
Thanks of course in advance.
aH
Groovy Code
import groovy.sql.Sql

        def dias = ["è": "é", "…": "…"]

        def atk = Sql.newInstance(
            'jdbc:mysql://myURL:3306/myDB?useUnicode=true&characterEncoding=utf8',
            'user',
            'pass',
            'com.mysql.jdbc.Driver'
        )

        dias.each() {x ->
            println x.getKey()
            atk.eachRow("SELECT `noteContent` FROM `ArchDescriptionRepeatingData`"
            + "WHERE `noteContent` LIKE(\"%" + x.getKey() + "%\")"
            ) { y ->
                println y
            }
        }

as requested here is the java code, which I added some extra functionality to:
import java.sql.*;
import java.util.*;
import java.util.regex.*;

    public class Diacritic {
        private Connection connection;
        private HashMap<String, String> dia;

        Diacritic() throws SQLException, ClassNotFoundException {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(
                "jdbc:mysql://myURL:3306/myDB"
                + "?user=user&password=pass");
            dia = new HashMap<String, String>();

            populateArray();

            System.out.println("Component Titles");

            for(Map.Entry e : dia.entrySet()) {
                String st = e.getKey().toString();
                Pattern p = Pattern.compile(st);
                System.out.println();
                System.out.println(st + "\t\t->\t" + e.getValue().toString());
                System.out.println();
                Statement s = connection.createStatement();
                ResultSet r = s.executeQuery("SELECT `itemValue` FROM `ListOrderedItems`"
                    + "WHERE `itemValue` LIKE(\"%" + st + "%\")"
                    //+ "LIMIT 0, 100000"
                );

                int x = 0;

                while (r.next()) {
                    x++;
                    Matcher m = p.matcher(r.getString(1));
                    if(m.find()) {

                    int start = 0;
                    int mstart = m.start();
                    int mend = m.end();
                    int end = r.getString(1).length();
                    if (mstart - start <= 10 || end - mend <= 10) {
                        System.out.println(x + ": " + r.getString(1)
                            + "\t->\t"
                            + "\t"  + r.getString(1).substring(0,mstart)
                            + e.getValue().toString()
                            + r.getString(1).substring(mend)
                            );

                    }
                    else {
                        System.out.println(x + ": " + r.getString(1).substring((mstart - 10), (mend + 10))
                            + "\t->\t"
                            + "\t"  + r.getString(1).substring((mstart - 10),mstart)
                            + e.getValue().toString()
                            + r.getString(1).substring(mend, (mend + 10))
                        );
                    }

                    }
                }

                s.close();
            }

        }

        public static void main (String[] args) throws SQLException, ClassNotFoundException {
            Diacritic d = new Diacritic();
        }

        public void populateArray() {
            dia.put("è", "é");
            dia.put("…", "…");
            dia.put("—", "");
            dia.put("‑"", "-");
            dia.put("é", "é");
            dia.put("æ", "æ");
            dia.put("ë", "ë");
            //etc...
        }
    }


text:
Q: F10 key detection in WPF I am programmatically generating keypressed event in WPF using this code:
 new KeyEventArgs(Keyboard.PrimaryDevice,
        Keyboard.PrimaryDevice.ActiveSource,
        0, args.Key)
    {
       RoutedEvent = Keyboard.KeyDownEvent
    }

where args.Key is the argument of the KeyUphandler of my WPF usercontrol.
Further I am trying to convert this WPF Key into a Win32 Virtual-Key using KeyInterop.VirtualKeyFromKey method like this:
var keyData = (Keys)KeyInterop.VirtualKeyFromKey(e.Key == Key.System ? e.SystemKey : e.Key);

This method is working fine for normal keys but it is not working for F10 key ( I am getting keydata as None for F10).
Any help would be great.


text:
Q: Global.asax events not firing for IHttpHandler I've written a C# HttpHandler in VS2010 and want to do some initialisation in the application_start() event (e.g. set up logging etc.), but for some reason it isn't firing.
I've tried running against  the local VS server using auto-assign port and the event fires, but against IIS the event never hits.
The ProcessRequest() is firing so its hitting the code, but when I run the solution, even after restarting IIS, application_start doesn't fire. I've read that VS cannot hook into the application_start event but I've done it before so do not believe that to be true. The application pool is runing in .net integrated mode and I've set my start URL to ensure that the handler is getting fired, which is is as I'm hitting ProcessRequest().
Is there any reason why it wouldn't fire?
Thanks
Edit. Looks like none of my events in Global.asax are firing. Is there any reason this might happen and how do i 'wire it up'?

A: 1.Did you write Global.asax this way?
using System;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
public class Global : HttpApplication
{
 protected void Application_Start(Object sender, EventArgs e)
 {
   //some code
 }
}

2.Have you tried modifying web.config (i.e. insert a blank row)?  Any config change will cause an Application restart, so the event fires.


text:
Q: Using datepicker.js in Script Editor web part on Sharepoint 2013 does not allow selecting dates I have written a simple html page in Sharepoint 2013 with a text input that is meant to use datepicker.js. When I click into the text box, the calendar correctly pops up, but no dates are selectable. This exact code works when I simply open it in the browser outside of SharePoint.
I have tried using body onload, making sure the datepicker is initialized in an explicit function.
<link rel="stylesheet" href="/sites/###-###-###-###/###/SiteAssets/js/datepicker.material.css">
<script src=/'sites/##-###-###-###/###/SiteAssets/js/datepicker.js'></script>
<script>
function initialize(){
var datepicker = new Datepicker('#datepicker');
}
</script>
<body onload="initialize()">
<form>
    <input type="text" id="datepicker"></input>
</form>
</body>

The calendar pops up and shows today's date highlighted, but I am unable to select any date at all. Any ideas are greatly appreciated!


text:
Q: Oracle - convert char to date I try to convert a old time char(8) column to a new time_conv date column.
The String column have the following format:
Hour (0-99):Minute (0-59):Second (0:59)
For Example: 01:32:56
The following code does not work for me:
update teldat set time_conv=to_date(time,'hh24:mi:ss');

Edit:
CREATE TABLE teldat(
    datum       DATE,
    uhrzeit     CHAR(8),
    time        CHAR(8),
    teilnehmer  NUMBER(3),
    verbart     NUMBER(1),
    aufbauart   CHAR(3),
    ziel        VARCHAR(15));

alter table teldat add (time_conv date);

INSERT INTO TELDAT VALUES (to_date('04.08.2011'),'17:33 ', '00:00:40',10,9, 'K10', NULL);
INSERT INTO TELDAT VALUES (to_date('04.08.2011'),'18:50 ', '00:01:41',13,9, 'K10', NULL);
INSERT INTO TELDAT VALUES (to_date('04.08.2011'),'19:10 ', '00:02:17',21,1, 'G1 ', '01019012896****');
INSERT INTO TELDAT VALUES (to_date('04.08.2011'),'19:31 ', '00:11:01',10,9, 'K10', NULL);
INSERT INTO TELDAT VALUES (to_date('04.08.2011'),'19:52 ', '00:09:47',20,1, 'G11', '077202****');
INSERT INTO TELDAT VALUES (to_date('04.08.2011'),'19:49 ', '10:07:02',21,1, 'G1 ', '01019012896****');
INSERT INTO TELDAT VALUES (to_date('04.08.2011'),'19:58 ', '00:02:41',21,1, 'G1 ', '01019012896****');
INSERT INTO TELDAT VALUES (to_date('04.08.2011'),'20:01 ', '00:02:31',21,1, 'G1 ', '01019012896****');
INSERT INTO TELDAT VALUES (to_date('05.08.2011'),'09:03 ', '00:03:02',11,9, 'K10', NULL);
INSERT INTO TELDAT VALUES (to_date('05.08.2011'),'09:13 ', '00:03:31',10,1, 'G10', '071174****');
INSERT INTO TELDAT VALUES (to_date('05.08.2011'),'09:39 ', '00:06:45',13,1, 'G10', '0711707*****');

A: If you want to convert the value to seconds, then just use arithmetic:
select (to_number(substr(time, 1, 2)) * 60 * 60 +
        to_number(substr(time, 4, 2)) * 60 +
        to_number(substr(time, 7, 2))
       ) as seconds

A: This code works for me :)
  update teldat set time_conv=(to_number(substr(time, 1, 2)) * 60 * 60 +
        to_number(substr(time, 4, 2)) * 60 +
        to_number(substr(time, 7, 2))
       );

Thank you all guys!


text:
Q: Deny acces of private area Phalcon PHP ACL I would like to deny access to the private areas on my website. But I don't know what I am doing wrong.
I don't want to use Acl::DENY as the default rule.
Instead I am using Acl::ALLOW as the global rule and denying access to the private resources.
Here is my code:
<?php
use Phalcon\Acl;
use Phalcon\Acl\Role;
use Phalcon\Acl\Resource;
use Phalcon\Events\Event;
use Phalcon\Mvc\User\Plugin;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Acl\Adapter\Memory as AclList;

class SecurityPlugin extends Plugin {

    public function getAcl() {
        if (!isset($this->persistent->acl)) {

            $acl = new AclList();
            $acl->setDefaultAction(Acl::ALLOW);

            $roles = array(
                'admin' => new Role('Administrators'),
                'guests' => new Role('Guests')
            );
            foreach ($roles as $role) {
                $acl->addRole($role);
            }

            //Private area resources
            $privateResources = array(
                'admin'        => array('index'),
                'products'     => array('index', 'search', 'new');

            foreach ($privateResources as $resource => $actions) {
                $acl->addResource(new Resource($resource), $actions);
            }

            foreach ($privateResources as $resource => $actions) {
                foreach ($actions as $action) {
                    $acl->deny('Guests', $resource, $action);
                }
            }

        }

        return $this->persistent->acl;
    }

    public function beforeDispatch(Event $event, Dispatcher $dispatcher) {

        $auth = $this->session->get('auth');
        if (!$auth) {
            $role = 'Guests';
        } else {
            $role = 'Admin';
        }

        $controller = $dispatcher->getControllerName();
        $action = $dispatcher->getActionName();

        $acl = $this->getAcl();

        $allowed = $acl->isAllowed($role, $controller, $action);
        if ($allowed != Acl::ALLOW) {
            $dispatcher->forward(array(
                'controller' => 'errors',
                'action'     => 'show401'
            ));
            $this->session->destroy();
            return false;
        }
    }
}

Thank you, for trying to help me.

A: You forgot to actually assign your ACL definitions to $this->persistent->acl
public function getAcl() {
    if (!isset($this->persistent->acl)) {

        $acl = new AclList();

        ...

        //The acl is stored in session
        $this->persistent->acl = $acl;
    }

    return $this->persistent->acl;
}

By looking at your code, I am guessing you used the Phalcon INVO example for this SecurityPlugin?
If so, refer to line 88. If not, this is a nice and easy example that can help you.


text:
Q: Can you trust mysql_insert_id? I have a registration page which then inserts data into two tables in MySQL. The first one is technical information like username/password/email, and the other one is for personal information like name/address and such.
My technical information table has a primary key auto incremental ID, and then, once I create the row in this table, I immediately create another row in the general information table with the same id.
To obtain that ID, I use the mysql_insert_id() function right after the first insert query.
My question is rather general: can you really trust this function that it will necessarily return the appropriate index? What if I had a website with many users registering every second, would it still be reliable, and always return the ID? Or does it just return the last primary key of a table generated?

A: Yes, you can.
The function is per-session, but it is also only valid for the very last query.
That is, you'll never have one user "polluting" the last_insert_id of another, but you cannot recover an insert_id from two inserts ago. When you need to do several inserts in a row and don't need the ids until later, set them as variables:
INSERT INTO ...
SET @foo_id = LAST_INSERT_ID();
INSERT INTO ...
SET @bar_id = LAST_INSERT_ID();
INSERT INTO some_join_table VALUES (@foo_id, @bar_id);


text:
Q: How to merge or convert JSONArray to JSONObject Java/ Spring Boot? I am trying to achieve of converting or merging JSONArray and JSONObject together.
This is my original JSON response that I get from using RestTemplate.
   {
     "links": {
                "RCDSO - Production Environment Cost": {
                    "href": "href 1"
                },
                "RCDSO - Development & UAT Environment Cost": {
                    "href": "href 2"
                },
                "RCDSO - Total Cost for Prod - Compugen Managed": {
                    "href": "href 3"
                },
                "RCDSO - Virtual Machine Cost": {
                    "href": "href 4"
                },
                "RCDSO - Azure File Storage Cost": {
                    "href": "href 5"
                },
                "RCDSO - Azure Backup and Site Recovery": {
                    "href": "href 6"
                },
                "RCDSO - Azure App Services Cost": {
                    "href": "href 7"
                }
          }
    }

I wan above JSON data to look like below :
{
  "links": [
    {
      "RCDSO - Development & UAT Environment Cost": {
        "href": "href 1"
      },
      "RCDSO - Virtual Machine Cost": {
        "href": "href 2"
      },
      "RCDSO - Azure File Storage Cost": {
        "href": "href 3"
      },
      "RCDSO - Azure Backup and Site Recovery": {
        "href": "href 4"
      },
      "RCDSO - Total Cost for Prod - Compugen Managed": {
        "href": "href 5"
      },
      "RCDSO - Azure App Services Cost": {
        "href": "href 6"
      },
      "RCDSO - Production Environment Cost": {
        "href": "href 7"
      }
    }
  ]
}

Is there any way to convert or merge JSONArray and JSONObject together in Java?
I tried to have it this way but getting JSONException:
public CustomOlapReports getReportListByClientId(String clientId) {
        ResponseEntity<String> responseEntity = null;
        String jsonResponse = null;
        CustomOlapReports reportList = null;
        try {
            List<String> list = new ArrayList<String>();
            OlapCustomReportResponse reportResponse = null;
            final String uri = "https://chapi.cloudhealthtech.com/olap_reports/custom?client_api_id="+clientId;
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders header = new HttpHeaders();
            header.set(HttpHeaders.AUTHORIZATION, "Bearer "+apiKey);
            header.set(HttpHeaders.ACCEPT, "application/json");

            HttpEntity<String> requestEntity = new HttpEntity<String>("body",header);
            responseEntity = restTemplate.exchange(uri, HttpMethod.GET, requestEntity, String.class);
            jsonResponse =  responseEntity.getBody();

            JSONObject jsonObj = new JSONObject(jsonResponse);

            JSONObject obj = jsonObj.getJSONObject("links");

            JSONArray jsonArr = new JSONArray();
            jsonArr.put(obj);

            System.out.println("Response : "+jsonArr);

            JSONObject ob = jsonArr.toJSONObject(jsonArr);
            System.out.println("OBJECT : "+ob);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reportList;
    }

I am getting below error:
org.json.JSONException: JSONArray[0] is not a String (class org.json.JSONObject).
    at org.json.JSONArray.wrongValueFormatException(JSONArray.java:1689)
    at org.json.JSONArray.getString(JSONArray.java:500)
    at com.example.apidemo.service.CspPartnerCustomerService.getReportListByClientId(CspPartnerCustomerService.java:137)
    at com.example.apidemo.controller.CustomerRestController.getReportListByClientId(CustomerRestController.java:115)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)........and so on.


text:
Q: How to set multiple styles for one Div? I am having some problems with my CSS external style sheet. I am trying to make a unordered list into navigation bar. I am attempting to do this by adding multiple styles to my navbar div but none of the changes are having any effect on the page when they are inside the navbar div.
#navbar{
    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
    }
    li {
        display: inline;
    }
}

Thanks in advance

A: You can't nest them like that, try this:
The space between tags/identifiers means the right option is inside the left.
#navbar ul{
    list-style-type: none;
    margin: 0;
    padding: 0;
}

#navbar ul li {
    display: inline;
}

A: The syntax you're currently using is only valid if you're using the Sass/SCSS preprocessor. While Sass is super-awesome, you'd probably be better off using vanilla CSS for now to build a solid CSS foundation. But whenever you want to get some exposure to Sass, check out their docs here: http://sass-lang.com/guide.
In the meantime, this should work for you:
#navbar ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

#navbar li {
  display: inline;
}


text:
Q: For existing entity on Google Cloud Datastore I would like to add a new property as a Blob? For existing entity on Google Cloud Datastore I would like to add a new property "s11_data" for all of the keys within that entity. I click on a key and click on New Property and name it appropriately, save, and voila. It is now a property column [set to null] for all of the keys. But I want this property to be a Blob (like some of the existing entries are already). If I click one of the existing entries, then "Blob" is an option in the drop-down menu of the property pane.
But it is not an option for the new property. I thought the resolution was to be sure to turn off indexing. But nope, even with Index unchecked the Blob option does not appear.
I'm happy to set it via Python is that is best way forward, but I can't work that out either (I can client.put() a property value but cannot find how to assign a property type.
Suggestions appreciated. Thanks,
Edit: here is the drop-down menu showing "Blob"

A: If you wish to do it in code via Python, then I don't believe blob is a property if you're using the datastore library (see types). But you can get it as a property if you're using the ndb library

*

*If you're using the bundled ndb library, then you can set the property type in your model definition (see documentation for property types) e.g.

    s11_data = ndb.BlobProperty()

*If you're using cloud ndb library, you also define it in model definition (see documentation) e.g.

    class YourModel(Model):
        s11_data = BlobProperty()

*It looks like you can also specify a blob if you're directly making REST API calls. Refer to documentation (see blobValue field)

A: Actually easier than I thought. Just write a bytes class and Google automatically sets it as a Blob
json_data = {}
json_data["V"] = 0.123
json_data["Q"] = 4.
a = codecs.encode(json.dumps(json_data).encode('utf-8'), encoding='zlib_codec')

with client.transaction():
   task = client.get(key)
   task["s11_data"] = a
   client.put(task)


text:
Q: Open activity by datepick Android It is possible to open an activity by datepick?
eg: i mean the date come from DB and the activity will be only avaible when the date is correct 12/10 will not opne 12/12  now the user can access the activity.

A: Yes you can do it with OnDateChangedListener
e.g.
Calendar calendar = Calendar.getInstance();
datePicker.init(calendar.get(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {

                @Override
                public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
                    startActivity(new Intent(YourActivity.this,OtherActivity.class));

                }
            });

A: Yes, that's possible. Not sure what your plan is exactly, so here's some pseudocode on how you might implement that:
pickDateListener
    Intent for DateActivity
    add extra to intent(picked date)
    startActivity(intent)

And then on the DateActivity:
getIntent.getExtras("date")

With the date that you get from the extras you can do whatever you want to do for that specific date!


text:
Q: How come imagemagick output has nasty glitchy squares instead of smooth gradients? I'm trying to create filters like instagraph (https://github.com/webarto/instagraph), but the output images have nasty square-shaped transitions instead of smooth gradients. Why and how do I fix this?
The command I'm running is this: convert \( /home/trusktr/Pictures/hawaii_aug-2013/test/DSC05767.JPG -auto-gamma -modulate 120,50,100 \) \( -size 4240x2832 -fill rgba\(255,153,0,0.5\) -draw 'rectangle 0,0 4240,2832' \) -compose multiply /home/trusktr/Pictures/hawaii_aug-2013/test/DSC05767.JPG.kelvin.jpg
Here's the input image:
http://ghz.me/oY
And here's the output (notice the sky isn't a gradient any more):
http://ghz.me/oZ
Here's another example.
input image:
http://ghz.me/p0
output image:
http://ghz.me/p1
You can see in the arms some nast discolorization. Why? How do we defeat this evil magic?

A: Your version of ImageMagick probably contains a bug. I just tried it with the latest version (6.8.7-8) and it created an image without the strange artifacts.


text:
Q: error of importing DBI in Perl I am writing the code in Perl and try to save it in the extension .pm not .pl
and I use use DBI; to import the DBI in order that I can execute the query.
and the error is compilation failed in require.
However, I did use in script.pl , it s okay.. it works..
Please help and thank you very much

A: You probably simply miss the "1;" at the end of the .pm file.
Perl modules always have to return a "true" value. This is accomplished by simply putting "1;" at the end of the file.
More information can be found in the example code of Perl Modules in the perlmod documentation.

A: "Compilation failed in require" indicates compilation cannot continue beyond that point due to an earlier error. Solve the earlier error and this one will go away.


text:
Q: CoreMotion framework I recently was doing a compass, to involve CoreMotion framework, but I checked for a long time did not find information on how to implement this framework the effect of the compass, hoping to get everyone's help.

A: *

*Apple's Core Motion Framework Reference

*Apple's Event Handling Guide for iOS: Core Motion

*Apple's CoreMotionTeaPot from WWDC '10 Sample Code

*Get Moving with Core Motion — Jonathan Blocksom

*Getting you started with CoreMotion — Ludwig Schubert

*A similar question: make a compass application in iPad

A: My "Helloworld" CoreMotion:
1) Add CoreMotion.framework
2) in .h file:
#import <CoreMotion/CoreMotion.h>

3) in .m file:
CMMotionManager *myMotionManager= [[CMMotionManager alloc] init];
myMotionManager.deviceMotionUpdateInterval = 1/60;
[myMotionManager startDeviceMotionUpdatesUsingReferenceFrame:CMAttitudeReferenceFrameXMagneticNorthZVertical  toQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
     double x = myMotionManager.deviceMotion.magneticField.field.x;
     double y = myMotionManager.deviceMotion.magneticField.field.y;
     double z = myMotionManager.deviceMotion.magneticField.field.z;
    NSLog(@"Strength of Earth's magnetic field= %8.2f",sqrt(x*x+y*y+z*z));
    myLabel.text = [NSString stringWithFormat:@"%8.2f", sqrt(x*x+y*y+z*z)];
}];


text:
Q: Is there API for Esri Story Maps? I want to create an Esri Story Map and integrate/include an own web map. I would prefer to create both the web map and story map using an API so that I can programmatically develop the maps.
Is there an API for Esri Story Maps and is it the same as for creating web maps (there it is the ArcGIS API for Javascript)?

A: This seems to be covered in the Story Maps Frequently Asked Questions:

While most story maps are created using one of the Story Map app
  templates we provide, story maps can also be created from scratch by
  developers using the developer APIs and tools in ArcGIS for
  Developers.


text:
Q: javascript: Callback function code considered as string Am a newbie in javascript, please help me understand below case where the callback function code is being considered as a string and passed as argument instead of passing the value of the callback function as an argument:

//Case3: Create Callback function in the argument section of calling statement.

function child3(callback,arg2=3) {
     return console.log("Case3: callback function - parent function out:", callback+arg2,"\n");
}

child3(parent3=()=>{
   let a=1;
   let b=1;
   return a+b;
},2);

Output:
Case3: callback function - parent function out: ()=>{
   let a=1;
   let b=1;
   return a+b;
}2

A: When you use +, there are two possibilities:

*

*If both operands are numbers or BigInts, they are added together

*Otherwise, both operands are concatenated together into a string

If you do
callback+arg2

and callback isn't a number, the result will be a concatenation of it and arg2. In your code, callback is not a number; it's a function. You probably wanted to call the callback instead of concatenating it - eg, callback().
Another issue is that
child3(parent3=()=>{

should almost certainly be
child3(()=>{

unless you deliberately wanted to both create a new global function named parent3 and pass that to child3.

function child3(callback, arg2 = 3) {
  console.log(callback() + arg2);
}

child3(() => {
  let a = 1;
  let b = 1;
  return a + b;
}, 2);

A: It's not a string, but a parameter. It has a name in the function's parameter list, which is callback, so, inside the function it is referred to as callback and when you pass
"Case3: callback function - parent function out:", callback+arg2,"\n"

to console.log, you convert the function to string. By the way, you can do that without passing the function as parameter as well

function foo(a, b) {
    return a + b;
}

console.log(foo);

So, you do not pass it as a string, you pass it as a function instead, but it is converted into a string, i.e. the function definition when you call console.log.


text:
Q: Verify success of Azure Resource Mover? I am using Azure Resource Mover to move a VM between Azure regions.  So far, the VM and its dependencies have all transitioned through the following states:
Prepare pending --> Prepare in progress --> initiate Move pending --> initiate move in progress --> commit move pending --> commit move in progress
And now they are all in the "delete source pending" state.  The documentation about this step states:
"After committing the move, and verifying resources in the target region, you can delete the source resource."
My question is about "verifying resources in the target region".  When I click on the individual resources and view their properties, the "location" value is still the old region.  This almost suggests to me that the move didn't work.  But I'm not sure.  I certainly don't want to delete the source resources until I can confident they moved properly.  Can anyone advise how to properly "verify" the resources in the target region?

A: Ok, so I figured this out.  If you merely click on your individual resources from within the Resource Mover UI (as I did), you will view the "source" copy of these resources, which of course is still in the source region.  If instead you remember that the Resource Mover created a new Resource Group in your target region, and navigate thither, you will see the new "target" copy of your resources, right where you expect to see them.


text:
Q: Why var.constant is not allowed for an enum class? Suppose we have an enum class:
enum class E
{
    constant
};

To refer to the enumerator in E, we can write E::constant, while the following is illegal:
E e;
e.constant;

But consider this:
struct S
{
    enum {constant};
};

Both S::constant and s.constant are legal, wouldn't it be more consistent to allow e.constant for an enum class? Is the inability intentional?


text:
Q: Can't find org.zkoss.bind.BindComposer I use Eclipse with ZK plugin. Project also was created using zk plugin.
Trying to get started with bindings stucked with error "java.lang.ClassNotFoundException: org.zkoss.bind.BindComposer"... I see that the library with this class is in the build path and web app libraries. I am going through tutorial http://books.zkoss.org/wiki/ZK%20Developer%27s%20Reference/MVVM/Data%20Binding/BindComposer

A: To avoid this type of problem try ZK Studio
Rather than manually adding jar file..Now You can create a ZK Project Jar automatically added to the project lib folder.


text:
Q: When i am deploying shopizer.war in tomcat i am getting below error SEVERE: Exception sending context initialized event to listener instance
    of
    class org.springframework.web.context.ContextLoaderListener
    org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'categoryDao': Injection of
    persistence dependencies failed; nested exception
    is org.springframework.beans.factory.CannotLoadBeanClassException:
    Error loading class [com.shopizer.modules.shipping.distance.
    ShippingDistancePreProcessorImpl] for
    bean with name 'shippingDistancePreProcessor' defined
    in class path resource
    [spring/processors/shopizer-core-shipping-processors.xml]:
    problem with class file or dependent class; nested exception
    is java.lang.NoClassDefFoundError:
    com/salesmanager/
    core/modules/integration/shipping/model/
    ShippingQuotePrePostProcessModule
    Related cause:
    org.springframework.beans.factory.CannotLoadBeanClassException:
    Error     loading class

A: Its hard to answer based on the stack trace above,
but I see a java.lang.NoClassDefFoundError:  , which is an indication that you are mising a dependency at run time. I'm not sure how your project is set up , but check you container settings for missing dependencies.

A: Check if you have defined all the beans in your version of the spring-config.xml and in case if you are Autowiring annotations, please check if your bean classes are annotated.


text:
Q: Is the Visual Studio Code Extension Generator broken? I'm following the instructions to build a "hello world" extension for Visual Studio as outlined here. I've got the Yeoman generator installed, but it seems buggy. For one thing, unless I immediately select one of the initial options when generating a new extension, I'm unable to select an option. Further, if I do immediately select an option (i.e. before enter stops working), I'm prompted to give a name to the extension. However, no matter how furiously I pound on my keyboard, no characters shows seem to be registered by the generator application.
Has anyone else experienced these issues with the generator? I'd really like to start experimenting with VS Code extensions, but if the generator doesn't work I'm not sure where to start.

A: This is an issue with yo in node 7.1.0. You have to upgrade or downgrade node.js.


text:
Q: Modes of free vibration in a fixed-fixed beam I am trying to find the mode shapes of vibration on a fixed-fixed beam.
this can be characterised as a PDE:
$$ EI \frac{\partial^4 v(x,t)}{\partial x^4} + \rho A \frac{\partial^2 v(x,t)}{\partial t^2} = 0 $$
with the boundary conditions
$$v(0,t) = 0  \hspace{2mm} \hspace{2mm} v_x(0,t) = 0 $$
$$v(l,t) = 0 \hspace{2mm}  \hspace{2mm} v_{x}(l,t) = 0 $$
We know that $E$, $I$, $\rho$ and $A$ are constant along the length
I have used the separation of variables method and then substituted in my boundary conditions and reached two different solutions:
$$\text{Re}\left[e^{ItB^2} (\cosh[Bx] - \cos[Bx]) + \frac{\sinh[Bl] + \sin[Bl]}{\cosh[Bl] -\cos[Bl]} (\sin[Bx] - \sinh[Bx])\right]$$
Plot of above showing fixed at l
$$\text{Re}\left[e^{ItB^2} \left((\sinh[Bx] - \sin[Bx]) - \frac{\sinh[Bl] - \sin[Bl]}{\cosh[Bl]
+ \cos[Bl]} (\cosh[Bx] - \cos[Bx])\right) \right]$$
Plot of above showing no slope at l
where $B$ is a constant that combines the natural frequency and the other constants
Each of these solutions satisfies a different three of the boundary conditions but I cant work out how to satisfy them all at the same time

A: The procedure to extract the modes of a linear PDE that is solvable by separation of variables is standard.
First separate the variables setting $\omega^4=\frac{\rho A}{EI}$ and set $u=X(x)T(t)$, where $X,T$ can be shown to satisfy the equations:
$$X''''-(\lambda\omega)^4X=0\\T''+\lambda^4T=0$$
where $\lambda$ is an, as of now, undetermined real constant. We choose to parametrize the separated solutions this way, since we would like to obtain a wave-like solution to the equations. Solving these equations we find that:
$$X(x)=A\cos(\lambda\omega x)+B\sin(\lambda\omega x)+C\cosh(\lambda\omega x)+D\sinh(\lambda\omega x)\\T(t)=A'\cos(\lambda^2t)+B'\sin(\lambda^2t)$$
However $X(x)$ must satisfy some constraints:
$$X(0)=X(l)=X'(0)=X'(l)=0$$
which must be simultaneously satisfied for them to be a solution to the fixed fixed beam problem (note the close analogy to the modes of oscillation of a string fixed on both ends). From this we obstain a linear system of equations for the parameters $A,B,C,D$:
$$M\begin{pmatrix}A\\B\\C\\D\end{pmatrix}=\begin{pmatrix}1&0&1&0\\\cos(\lambda\omega l)&\sin(\lambda\omega l)&\cosh(\lambda\omega l)&\sinh(\lambda\omega l)\\0&1&0&1\\-\sin(\lambda\omega l)&\cos(\lambda\omega l)&\sinh(\lambda\omega l)&\cosh(\lambda\omega l)\end{pmatrix}\begin{pmatrix}A\\B\\C\\D\end{pmatrix}=0$$
From basic linear algebra, we know that for this system to have a solution a necessary and sufficient condition is:
$$\det M=\cos (\lambda\omega l)\cosh(\lambda\omega l)+\sin (\lambda\omega l)\sinh (\lambda\omega l)-1=0$$
and therefore the eigenvalues can be written $\lambda_n=\frac{x_n}{\omega l}$, where $x_n$ represents the solutions to the equation
$$\cos x\cosh x+\sin x \sinh x=1$$
There doesn't seem to be a analytical solution for this equation, but it is easy to show that there is an infinite number of solutions to it as follows. Set $f(x)=\cos(x)\cosh(x)+\sin(x)\sinh(x)-1$. Since this function is even, we will restrict our attention to positive eigenvalues. Then $f'(x)=2\cos x\sinh x$. It is easy to see that this posesses minima at $2n\pi-\pi/2,n\geq1, n\in \mathbb{N} $ and maxima at $2n\pi+\pi/2, n\geq0$. Since
$$f(2n\pi-\pi/2)=-\sinh(2n\pi-\pi/2)-1<0~~,~~f(2n\pi+\pi/2)=\sinh(2n\pi+\pi/2)-1>0, f(0)=0$$
we find that it possesses exactly one root in each one of those intervals. Specifically, we see that:
$$x_1\in(\pi/2,3\pi/2), x_{n+1}\in(2n\pi-\pi/2, 2n\pi+\pi/2), n>0$$

A: If you use the separation of variables, such that:
$$v(x,t)=V(x)\exp(i\omega t),$$
it is only necessary to write the space equation
$$\frac{d^4}{dx^4}V(x)+k^4V(x)=0$$
where $k=\left(\omega^2 \frac{\rho A}{EI}\right)^{1/4}$.
the solution can be written as
$$V(x)=A\cos(kx)+B\sin(kx)+C\cosh(kx)+D\sinh(kx)$$
and applying your boundary conditions:
$$V(0)=0, V'(0)=0, V(l)=0, V'(l)=0$$
The four equations can be written in matrix format:
$$\begin{pmatrix}1 & 0 & 1 & 0\\
\cos{\left( kl\right) } & \sin{\left( kl\right) } & \cosh{\left( kl\right) } & \operatorname{sinh}\left( kl\right) \\
0 & 1 & 0 & 1\\
-\sin{\left( kl\right) } & \cos{\left( kl\right) } & \operatorname{sinh}\left( kl\right)  & \cosh{\left( kl\right) }\end{pmatrix}\begin{pmatrix} A\\B\\C\\D\end{pmatrix}=0$$
For nontrival solution, the determinant of the matrix in this system of equations reduces to
$$\cos(kl)\cosh(kl)-1=0$$
which needs to be solved numerically. For numerical computation of the solution is better to rewrite this equation as
$$\cos(kl)=\frac{1}{\cosh(kl)}$$
so you can also plot a graph of the functions on the both sides of equation and check where they are equal. The first root, for instance, occurs when $kl\approx 4.73004$. It is possible to check that for large $kl$, the roots approximate to $\cos(kl)=0$.
Now, to calculate the mode shapes, it is necessary to use three of the four equations and write the mode shape as a function of one of the constants ($A,B,C$ or $D$).
If we choose to write the constants in terms of $A$, it is found that
$$B=-\frac{\cosh{\left( kl\right) }-\cos{\left( L k\right) }}{\operatorname{sinh}\left( kl\right) -\sin{\left( kl\right) }}A $$
$$C=-A$$
$$D=\frac{\cosh{\left( kl\right) }-\cos{\left( kl\right) }}{\operatorname{sinh}\left(  kl\right) -\sin{\left( kl\right) }}A $$
The expression for $B,C$ and $D$ are than replaced in the solution $V(x)$
$$V(x)=\left[\cos(kx)-\cosh(kx) + \frac{\cosh(kl)-\cos(kl)}{\sinh(kl)-\sin(kl)}\left(\sinh(kx)-\sin(kx)\right)\right]A$$
since $V(x)$ is a mode shape, it can be scaled by making $A=1$, to give:
$$\Psi(x)=\cos(kx)-\cosh(kx) + \frac{\cosh(kl)-\cos(kl)}{\sinh(kl)-\sin(kl)}\left(\sinh(kx)-\sin(kx)\right)$$
which is not unique.
The first mode shape is shown:

A: Too long for a late comment.
Starting from @DinosaurEgg's answer, if we look for the positive zero's of
$$f(x)=\cos (x) \cosh (x)+\sin (x) \sinh (x)-1$$
$$f'(x)=2 \cos (x) \sinh (x)$$ we have minima and maxima for $x=(2n+1)\frac \pi 2$.
Building the $[2,2]$ Padé approximant round these points, we just need to solve a quadratic equation in $\big[x-(2n+1)\frac \pi 2\big]$ to have a rather good estimate. For the first solutions
$$\left(
\begin{array}{ccc}
n & \text{approximation} & \text{solution} \\
 0 & 2.19426 & 2.18354 \\
 1 & 5.52114 & 5.50353 \\
 2 & 8.65614 & 8.63913 \\
 3 & 11.7980 & 11.7810
\end{array}
\right)$$ and
$$x_{n+1} \sim x_n+\pi$$ One iteration of Newton method is more than sufficient.


text:
Q: full_join() two data frames in segments/batches in r I have two data frames that I am trying to merge.
df1 has dimensions  20015 rows and 7 variables.
df2 has dimensions 8534664 rows and 29 variables.
When I do full_join(df1, df2, by = "KEY") I get the Error: cannot allocate vector of size 891.2 Mb so I set memory.limit(1000000) and I still get the same error. I run the full_join() whilst looking at my CPU usage graph in the windows task manager and it increases exponentially. I have also used gc() through out my code.
My question is, is there a function out there which can join the first 1,000,000 rows. Take a break, then join the next 1,000,000 rows etc. until all rows have been joined.
Is there a function to run the full_join() in batches?

A: This is just to report the time it takes running with full_join and merge from data.table in a 64 bit Windows system(Intel ~3.5 Ghz, RAM 120GB). Hope it will help at least as a reference for your case.
library(data.table)
df1 <- data.table(KEY=sample(1:800,20015,replace = TRUE),
                  matrix(rnorm(20015*7),20015,7))#1.1MB
df2 <- data.table(KEY=sample(1:800,8534664,replace = TRUE),
                  matrix(rnorm(8534664*29),8534664,29))#1.9GB
library(dplyr)
tick <- Sys.time()
df_join <- full_join(df1, df2, by = "KEY") #~58.1 GB in memory
tock <- Sys.time()- tick #~1.85min
#With data.table merge.
tick <- Sys.time()
df_join<- merge(df1, df2, by = "KEY", allow.cartesian = TRUE)#~58.1 GB in memory
tock <- Sys.time() - tick #~5.75 mins


text:
Q: Django Channels after sending message, current tab showing 2 messages(sender + receiver) but other tab does not show anything? I am following this tutorial Channels Tutorial Link
My Goal was to make a simple asgi chat server. But It is showing weird behaviour. The message sent from one tab..should print "HI" in  current tab..and also "HI" in the tab connected in the same room. but its printing the both "HI" in the current tab, no message is shown in the other tab connected in the same room.

my consumers.py is simeple, just from the tutorials file...
import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = 'chat_%s' % self.room_name

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))

my settings file is configured to receive redis connection in 127.0.0.1. I am using docker redis image just s the tutorial said.
ASGI_APPLICATION = 'mysite.asgi.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

my asgi.py file...configured like the tutorial said-->
# mysite/asgi.py
import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import chat.routing

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = ProtocolTypeRouter({
  "http": get_asgi_application(),
  "websocket": AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})

A: This is the issue of the latest release.
I solved it by reinstalling the package: channels == 2.4.0
Then I changed the file asgi.py, commented out the line there: "http": get_asgi_application(),
also I removed as_asgi() from file routing.py
Here is the tutorial of the previous version.


text:
Q: Best/more standard graph representation file format? (GraphSON, Gexf, GraphML? ) What's the standard graph representation file format or otherwise the most used one?
I would say one of these three:

*

*GraphSON

*GEXF

*GraphML
but it would be great if anyone could point out the advantages/weaknesses from each of them.

A: The answer ultimately lies with the size of your problem and what your are trying to achieve.
For example, none of those formats can handle billions of vertices whereas some dedicated large-scale graph analytics frameworks such as Spark or GraphLab-Create can.
GraphML and GEXF are roughly equivalent, both XML based. GraphML is standard and supported in a lot of graph librairies such as NetworkX, igraph, Boost Graph Library, Graph-tool, JGraphT, Gephi. GraphSon is not popular.
To draw your GraphML or GEXF graphs, you can use Gephi or Tulip (GEXF only).

A: I think JGF is a good candidate here too.
I evaluated a lot for a recent project and this came out on top. Specifically, I liked:

*

*Trivial to parse and generate

*Able to include arbitrary extra data for any node, edge, or graph.

*Well specified, and can be parsed by more than one existing project.

http://jsongraphformat.info/
https://github.com/jsongraph/json-graph-specification

A: Ideally you want something supported by major third-party software. I'm currently looking into exporting to Gephi, and it supports:

*

*GEXF

*GDF

*GML

*GraphML

*Pajek NET

*GraphViz DOT

*CSV

*UCINET DL

*Tulip TPL

*Netdraw VNA

I'd love to see an analysis of the benefits of each format. Gephi's sample datasets includes a lot of GEXF and GML.

A: GNU Bison outputs Graphviz DOT files to help visualize the parser automaton, which usually are very big graphs. Here you can find a small sample.
I think that DOT is a de-facto standard at least for for open source projects, also because there are many excellent open source tools for producing images from DOT files (e.g. dot, neato, sfdp).
At the moment i'm writing this, Gephi and Tulip don't plot edges labels, which could be a problem for some applications.


text:
Q: how to use asp pages in asp.net I want to use asp page in my asp.net application without any  modification in asp pages.
further I want to add master page in my .net application.So i need the changes to be reflected in the asp page also.
is it possible....any how?  or any alternative to use this..?
pls suhggest me .....thanx in advance...

A: ASP does not have master pages, so you can't use them. The most sensible thing to do is to rewrite the ASP page in ASP.NET, while there are still people around who understand what the ASP page was meant to do. There will otherwise come a time when nobody understands that page.
The closest thing I've seen to what you're looking for is to write an ASP.NET page that refers to the ASP page through an IFRAME. The ASP.NET page can be a content page, referring to the master page, and the ASP page can stay the same.

A: Classic ASP files run without any problems in a ASP.NET website. As soon as you want to mix classic ASP and ASP.NET functionality in one file you will get errors.
Applying master pages to classic ASP files can't be done.
[EDIT]
An alternative could be to rewrite the functionality of the ASP pages into ASP.NET.
There is a SO question about tools for converting from ASP to ASP.NET here.

A: i have used asp and asp.net vb together when i was learning
my method was to use jquery to put my asp classic generated html into
designated divs... as my leaning increased i needed to use this method less and less
its a great way to pick up asp.net C# when moving from a VB background when you dont really have time to learn, like at work.

A: A dirty way: Make a HTTP request from the ASP.NET code to the .asp page and store the response in a web control. It's not pretty, but it works.


text:
Q: Run an EXE from MSI Installation Script C# Hi all
How do i run a EXE file straight after my MSI has executed and successfully installed.
Have been looking the the postbuildevent with the MSI but it does't seem to work. Tried just putting in the full path and filemame, without much success

A: Assuming that the exe is the primary output from one of the projects in your solution that is being built by the MSI, you should be able to do this in the Post Install Event by selecting the "Primary output" from that project.  (Link coming with instructions if I can find it.)
Edit
I did find this previously asked question that gives a workaround for doing iut in the post-build event: VS .Net: Post build events for "Primary Output from <myProject>" in installer project
And I found the instructions I was looking for originally here: http://support.microsoft.com/kb/827018


text:
Q: PrimeFaces 5.3 Datatable gets Data but shows only no records found So I just want to get some Data from the Backend to the Frontend and show it to the user. The first part of this is working, I get the data to the Frontend but it wont show through ui:repeat, c:forEach or p:dataTable.
GetData.java
private List<Category> categoryList;

public List<Category> getCategoryList() {
    return categoryList;
}

public void loadCategoryList() {
    categoryList = getAllCategories().getCategoryList();
    System.out.println("LOAD: " + categoryList.size());
    System.out.println("GET: " + getCategoryList().size());
}

public void setCategoryList(List<Category> categoryList) {
    this.categoryList = categoryList;
}

public Categories getAllCategories() {
    Delegate delegate = new Delegate();
    Categories dto = delegate.getAllCategories();
    System.out.println(dto.getCategoryList().size());
    return dto;
}

Delegate.java
public Categories getAllCategories() {
    EntityManager em = getEntityManager();
    List<Category> categoryList = Logic.getAllCategories(em);
    Categories dto = new Categories(categoryList);
    closeEntityManager(em);
    return dto;
}

Logic.java
public static List<Category> getAllCategories(EntityManager em) {
    try{
        em.getTransaction().begin();
        List<Category> categoryList = em.createQuery(allCategories,Category.class).getResultList();
        em.getTransaction().commit();
        return categoryList;
    }
    catch(Exception e){
        System.out.println("Could not get all Categories! Error: " + e);
        return null;
    }
}

open.xhtml

        <ui:include src="/old/templates/menu.xhtml" />

            <h:form id="nav-form">

                    <f:facet name="header">

                    </f:facet>

                    <f:facet name="footer">

                    </f:facet>

            </h:form>

When loading the page, it uses the #{getData.loadCategoryList()} and my log shows me: found 3 Categories, but thats just it. The Table says only no records found. What am I doing wrong here?


text:
Q: Deriving optimal time to change I am working in economics and I am trying to build a model that take into account the fact that indivudal can take a decision once in their life time that changes the value of a parameter R.
To be more clearer:
Time t is discrete and goes from 0 to T
I have a vector of parameters Xt (for example, temperature, population etc.) to whose probablistic law is known (let say that probability of X(t+1) given X(t) is known, but we can imagine other ideas).
The individual is maximizing a value function which is the sum over t of V(Rt, Xt)*a(t) where a decreasing function acting like a discount factor.
The maximization is done over R, which you can only change once at some time t < T.
I'd like to find a good way to derive the optimal time and the optimal new value of R.
If someone has seen this kind of problem somewhere I will be more than glad to be redirected to the appropriate literature.
Thanks a lot for your helps
Best
Tochoka

A: You have a 2D nonlinear minimization problem.  The two parameters are the time of change $t$ and the new value of $R$.  These problems are cast as minimization, so you want to minimize the negative of your value function.  Routines are available in any numerical analysis text.  I like the discussion in chapter 10 of Numerical Recipes.  You should probably create a number of datasets for the $Xt$ and use the same datasets at each $t,R$ point


text:
Q: Round robin in C# I'm having a problem (possibly due to lack of sleep!) where I'm trying to solve a maths problem in C#.
Let's say I have a drinks machine, and I have three empty rows that can be filled with Cola. I have 17 cans of Cola in my hand and I have to fill each row one at a time.
For example...
Pass 1:

Add Cola to Row 1. Drinks = 1
  Add Cola to Row 2. Drinks = 1
  Add Cola to Row 3. Drinks = 1

Pass 2:

Add Cola to Row 1. Drinks = 2
  Add Cola to Row 2. Drinks = 2
  Add Cola to Row 3. Drinks = 2

...
Pass 6

Add Cola to Row 1. Drinks = 6
  Add Cola to Row 2. Drinks = 6
  Add Cola to Row 3. Drinks = 5 (no more drinks left at this point)

For some reason, I'm completely lost. Can anyone help?!

A: Pretty quick and painless, and only requires one loop, not two nested loops. All you need is a little bit of math to get the correct index of the array:
int[] Cola = {0,0,0};
int Rows = Cola.Length;
int Drinks = 17;

for (int i = Drinks; i > 0; i--)
{
   Cola[(Drinks - i) % Rows]++;
}

Console.WriteLine("Row 1 has " + Cola[0] + " cans.");
Console.WriteLine("Row 2 has " + Cola[1] + " cans.");
Console.WriteLine("Row 3 has " + Cola[2] + " cans.");

This produces this as output:
Row 1 has 6 cans.
Row 2 has 6 cans.
Row 3 has 5 cans.

A: Instead of looping to add a can at a time, you can calculate how many cans each row will get:
int cans = 17;
cans += machine.Rows.Count;
for(int i = 1; i <= machine.Rows.Count; i++) {
   Console.WriteLine("Row {0} has {1} cans.", i, --cans / machine.Rows.Count);
}

A: Shooting from the hip:
int numDrinks = /* Your constant here */
int[] drinksInRow = new int[NUM_ROWS];
for(int i = 0; i < drinksInRow.Length; i++)
{
  drinksInRow[i] = numDrinks / NUM_ROWS;
  if(i < numDrinks % NUM_ROWS) drinksInRow[i]++;
}

number of drinks in each row is in drinksInRow, indexed by row number starting from 0.
This is faster than doing repeated passes; basicallys its O(NUM_ROWS) [if playing really loose with Big-O].


text:
Q: How to iterate over column values in a dataframe, take the mean, and create a new dataframe? I have a large dataframe in R and I want to plot the change in temperature over time. I've tried this before but since there is so much data the graph is really noisy and impossible to read.
I experimented with other plot types to try and get around this but they didn't really work. So I decided instead I will plot the mean temperature for each hour.
I've uploaded the data from a csv file and there are about 56k rows, an hour is about 720 rows give or take.
> head(wormData)
 Time     Date Day.of.Week Humidity.1 Temp.1 Vapor.Density.1 Base.Temp.1
1 0:18:44 1/7/2016      Friday       69.7   26.4           17.43       85.00
2 0:18:49 1/7/2016      Friday       69.7   26.4           17.43       27.44
3 0:18:54 1/7/2016      Friday       69.6   26.4           17.40       27.44
4 0:18:59 1/7/2016      Friday       69.6   26.4           17.40       27.44
5 0:19:05 1/7/2016      Friday       69.5   26.4           17.38       27.44
6 0:19:10 1/7/2016      Friday       69.5   26.4           17.38       27.44

The column I am interested in is Temp.1 so what I want to do is take the mean of every 720 values in the Temp.1 column, then put each of those mean values into a new dataframe so I can plot a cleaner graph.
I thought of just doing it by hand but that would be about 50 data points and I have many more csv files to do, so any help on how I could do this would be appreciated. I've tried subsetting the data or making vectors with the mean values as well as writing some loops, but I'm struggling to tell R that I want the mean of every 720 rows.
Thanks so much :)

A: Here is a solution with dplyr, assuming your row number is a multiple of 720. We create a grouping variable and then compute the mean by group.
library(dplyr)
n <- 2 # replace with n <- 720 with your actual data
mutate(d,group = rep(1:(nrow(d)/n), each=n)) %>%
  group_by(group) %>%
  summarize(mean=mean(Temp.1))

data
d <- read.table(text = " Time     Date Day.of.Week Humidity.1 Temp.1 Vapor.Density.1 Base.Temp.1
1 0:18:44 1/7/2016      Friday       69.7   26.4           17.43       85.00
2 0:18:49 1/7/2016      Friday       69.7   26.4           17.43       27.44
3 0:18:54 1/7/2016      Friday       69.6   26.4           17.40       27.44
4 0:18:59 1/7/2016      Friday       69.6   26.4           17.40       27.44
5 0:19:05 1/7/2016      Friday       69.5   26.4           17.38       27.44
6 0:19:10 1/7/2016      Friday       69.5   26.4           17.38       27.44",stringsAsFactor=FALSE,head=TRUE)

A: A kind of basic solution on top of matrix:
 set.seed(123)
 x<-sample(1:10,(720*5),replace=TRUE) # generate dummy data

 > str(x)
 int [1:3600] 3 8 5 9 10 1 6 9 6 5 ...

 # Use wormData$Temp.1 instead of x for your actual datas
 z<-matrix(x,nrow=length(x)/719) # divide by 719 to get 720 values per row
 rowMeans(z) # 'loop' over each row to get the mean

Output:
[1] 5.654167 5.375000 5.358333 5.477778 5.618056

If your dataset is not a multiple of 720, you'll get a warning and the last point would be false (recycling of the vector to fill the last line).

A: Here is a more complete answer using dplyr. This uses the actual dates and times you have so that you aren't approximating 720 values per hour.
library(tidyverse)

worm_data <- data_frame(time = c("0:18:44","0:18:49","2:18:54",
                                 "0:18:59","0:19:05","2:19:10"),
                        date = c("2016-07-01","2016-07-01","2016-07-01",
                                 "2016-07-02", "2016-07-02", "2016-07-02"),
                        temp_1 = c(25,27,290,30,20,2))

worm_data_test <- worm_data %>%
   mutate(
      date = paste(date, time),
      date = as.POSIXct(date, tz="GMT", format="%Y-%m-%d %H:%M:%S")
   ) %>%
   group_by(
      datetime = as.POSIXct(cut(date, breaks='hour')) # creates a new variable
   ) %>%
   summarize(
      temp_1 = mean(temp_1, na.rm=T)
   ) %>%
   ungroup()

In this case, you are grouping by the hour, then summarizing over those hours. I chose strange values and modified the dates and times to show that it works.
For more on datetime, I suggest: https://www.stat.berkeley.edu/~s133/dates.html


text:
Q: Synchronizing ETL and reads on the Data Warehouse I have the following scenario:

*

*ETL loads data into the DW.

*Reports run on demand, maybe at the same time with the ETL, consuming data from the DW.

And this my problem: I need to make sure the reports do not contain partial data:

*

*If reports are running when ETL is ready to load data, ETL must wait for reports to complete.

*If ETL is loading and a report is requested, report must wait for ETL to finish.

*If ETL is waiting to load and a report is requested, report must wait for ETL to run and finish - ETL always has priority over reports.

What is the best mechanism to get this? Database locks do not seem to be intelligent enough to manage the priorities I need.
Should I implement my own locking mechanism? If yes, is there a well-known design for it? Many things must be taken into account: keep track of currently running reports (lock-for-reads), implement lock expiration for cases when the ETL fails notifying it finished, etc.

A: If you are using Cognos, then I think you're basically out of luck from a "prevent report from running if ETL is running" kind of set up, unless you want to muck about in badly-documented APIs.
Your best bet is to probably identify the specific reports, usually ones that are run against aggregates, and make sure that you set up your ETL process to update the facts and aggregates last, and as one big "update" transaction. If you use a dbms that gives you read-consistency, you should be able to do this without a report showing up with only half the data loaded to it.
Reports that access multiple facts / multiple aggs will be more troublesome. It may even be that you may have to set up some kind of "table swap" where you build what you need then alter table rename to swap out the tables.

A: You could make the etl process set a flag in a record in a table when it starts and unset it when it completes?  The Reporting system can then query this table to see if the flag is set and notify the user that the warehouse is running and either put the report in a queue that is processed on completion of the ETL process or tell the user to try later.  If you want to allow users to use facts that have been processed, your flag table would need to be at the table grain - i.e. on flag record per table.


text:
Q: Are there any unpublished downsides in Windows 8 Regular? I intend to buy new notebook and I have two options either buy one with Windows 8 Regular or one with FreeDOS which is ~100USD cheaper, while retaining the specs. Because I'm in academia I have an option to get Window 8 Pro for free through academic program.
I have checked the comparison chart at Microsoft webpage and it seems that I would not miss the features not included. On the other hand my colleague reported that e.g. for Windows Phone development you need W8 Pro or higher.
I'm a developer myself, although I do not intend to do any work for mobile devices, I was concerned if there are any other potential troubles with the regular edition of W8.
I most interested in limitations concerning development in Visual Studio et. al. and running virtual machines under W8.
PS: The academic license is only valid while I'm in academia, so when I leave I will be left without Windows license, thus having one on hand would be nice. On the other if there are any major downsides with regular edition I would use the money saved on laptop purchase to get a proper W8 Pro in future.


text:
Q: Fine perimeter of trapezium $EDBC$? Consider the figure below.
$ED$ is parallel to $BC$. $EC=6, DB=8$, and $\angle CAB=90
$ degree.
I want to find the perimeter of trapezium $EDBC$.

How should I proceed here?
Thanks.

A: HINT: the radius of the circle is $24/5$. To see why, drop a perpendicular from $D$ to $BC$: the triangle thus created is similar to $ABC$ and $ADE$, and its sides are then in the ratio $3:4:5$.

A: Let 's denote angles to vertices; we have:
$\tan b=6/8$,  so,  $\cos(b)=4/5$
Drop a perpendicular  from O to BC at point E then:
$r= 6 \times (4/5)=24/5$ is the radius of circle. Drop another perpendicular from O to AB at point F we have:
$FD=(24/5)/ \tan (b)=(24/5)/(3/4)=\frac{32}{5} $ so:
$ AB=8+32/5+24/5=96/5$
$CB= (96/5)/(4/5)=24$
$ED=(56/5)/(4/5)=14$
So perimeter is:
$24+14+6+8=52$

A:
Let [.] denote areas. Then,
$$[ADE] = \frac12 r(AE+AD),\>\>\>\>\>[ABC] = \frac12 r(AC+AB+BC),\>\>\>\>\>
[EDBC] = \frac12r(DE+BC)$$
Recognize $[ABC]-[ADE] = [EDBC]$ to get
$$DE = (AC-AE) + (AB-AD) = 6+8 =14$$
Then, $BC = ED + FB = 14+\sqrt{6^2+8^2}=24$. Thus, the perimeter is $6+8+14+24=52$.


text:
Q: Accounting Software? I have asked before and am still trying to find a decent accounting program for Linux/Ubuntu.  Not a checkbook program but something for small business accounting.  I need to generate year end tax reports and things like a P&L
I have been struggling with Gnucash for years.  The program is generally OK but the transactions importer is a nightmare.  It adds hours of work to balancing accounts, due to things like mis-categorized transactions, transactions not being imported, and erasing already cleared transactions.  And support is difficult to get, the mailing list is only occasionally helpful.
I have searched multiple times and the list of software only reflects Checkbook programs.  I am looking for an alternative, not cloud based.  If someone has a suggestion of ANY kind, I would appreciate it.

A: I use mmex (Money Manager Ex) downloadable from the Ubuntu Software Center.
I don't use it in a business environment but in a private capacity to handle multi-currency accounts (GBP + Euro) which it does really well.
There are good reporting facilities within the program and I am certain that it can be used to good effect. Sadly not double entry book keeping as a paid business accounting system would be but effective all the same.
There are options as to where the data can be saved - either local drive or (as in my case) Dropbox but the main thing is, the program set is located locally, not in the cloud.
There are options to export the data and it wouldn't take too much effort to export the data to a spreadsheet to provide a Balance Sheet and P&L leaving you more in control of your reuirements.

A: There's loads of accounting software for Linux out there. This webpage should provide at least one suitable accounting package, which isn't all 'checkbook'.

A: idempiere and dolibarr is ERP but they have proper account maintenance and all the reports that you might be needing .


text:
Q: Bind custom attribute value I have a json with current settings. Its structure is something like this:
{
    color: '#111111',
    opacity: '0.1',
    text_area: {
        color: "#222222"
        opacity: "0.2"
    },
    something_else: {
        color: "#333333",
        opacity: "0.3"
    }
}

Then I have some inputs on my page where user can select color values. Selection is performed by a MiniColors. When you define that user should select not only a color but an opacity as well, minicolors stores selected opacity value as attribute in input tag called "data-opacity". The color value (hex one) is stored similar way as any text in input.
To test things out, I have added to my html this:
{{settings.text_area.color}}
{{settings.text_area.opacity}}

My input tag looks like this:
<input id="ta" ng-model="settings.text_area.color" data-opacity="0.8"></input>

Of course, I can see only that the color value is displayed when I change a color, but how do I bind data-opacity attribute value (that will be changes each time user will select a new opacity value) to settings.text_area.opacity variable? It seems that I do have to make my own directive for that, no?

A: As easy as setting the {{ settings.text_area.opacity }} inside data-opacity! It'll update as soon as your opacity model is changed by whatever other input you have.
<input id="ta" ng-model="settings.text_area.color"
               data-opacity="{{ settings.text_area.opacity }}" />

A: Yes I think so. Of what I know you'll just have to listen to changes made to #ta with angulars dirty checking (watch) with a custom method that looks at the attribute data-opacity. Just make sure that angular is triggered when choosing opacity/color so that the watch is triggered to check if the value changed. Maybe you'll have to do it with a manual  scope apply().
watch('watchForOpacityChange', function() {
  // do the stuff you want to do with the new data here
});

function watchForOpacityChange() {
  return $element.attr('data-opacity'); //jquery light method attr is available on $element
}

That was just some sample code for what you would want and need in you directive. You could wrap the whole jquery functionality but that would mean more work.
Regards
Tobias


text:
Q: Operadores en javascript Necesito crear una condición, que me retorne "true", si "number" es divisible entre 3 y 5 (ambos). intenté hacerlo como se muestra, pero el test me da error.  creo que no es la forma de hacerlo. ayuda por favor.
function fizzBuzz(number) {
 if(number%3 == 0 && number%5 == 0) {
  return true;
  }
}

A: El código está bien. Solo que te falta devolver falso cuando la condición no se cumple.
Algunas opciones:
function fizzBuzz(){
     if (number % 3 == 0 && number % 5 == 0){
         return true
     }
     else {
         return false
     }
}

function fizzBuzz(){
     if (number % 3 == 0 && number % 5 == 0){
         return true
     }

     return false
}

O como el resultado depende solo de esa única condición:
function fizzBuzz(){
    return number % 3 == 0 && number % 5 == 0
}


text:
Q: Rails 4 and grape - undefined method `call' when splitting API file I've got a vanilla rails 4 application and I'm trying to add a versioned Grape API. The rails server starts up fine, but when I try to access the API URL (http://localhost:3000/v1/user/ping), I get the error:
undefined method `call' for V1:Module

So far, the API I have setup is very simple, but I can't figure out why it is not working
root/app/api/api.rb:
# root/app/api/api.rb
class API < Grape::API
  mount V1
end

Within the version folder, I want to have all the classes that the version of the API supports: root/app/api/v1/user.rb:
# root/app/api/v1/user.rb
module V1
  class user < Grape::API
    get :ping do
      { :ping => params[:pong] || 'pong' }
    end
  end
end

root/config/routes:
TestApp::Application.routes.draw do
  mount API => '/'
end

A: I split my api up into folders:
v1/resources/users.rb
v1/resources/orders.rb
v1/entities/order.rb
v2/resources/orders.rb

and then in api.rb just mount the individual files ...
mount V1::Resources::Users
mount V1::Resources::Orders
mount V2::Resources::Orders

And then:
version ['v2','v1'], cascade: true
version 'v2', cascade: true


text:
Q: How to send LocationResult with last location to PendingIntent How can I send a PendingIntent with a LocationResult?
I wanted to use same PendingIntent I setup for receiving location changes to also receive the last location.
See the last lines in the code:
// Create pending intent for a service which received location changes
Intent locationIntent = new Intent(getApplicationContext(), LocationIntentService.class);
PendingIntent pendingIntent = PendingIntent.getService(
        getApplicationContext(),
        0,
        locationIntent,
        PendingIntent.FLAG_UPDATE_CURRENT
    );

// Start listening to location changes
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, pendingIntent);

// Get last location
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

// Send last location
if(lastLocation != null) {
   // How to send it to the pending intent?
   // Result result = LocationResult.create( ... )
   // pendingIntent.send(result)
}

A: Inspecting the code for LocationResult.extractResult(intent) it is possible to see that LocationResult is nothing more than a Parcelable extra inserted in the Intent with a specific Id. The following Kotlin function inserts a List<Location> in a given Intent as a LocationResult
private const val EXTRA_LOCATION_RESULT = "com.google.android.gms.location.EXTRA_LOCATION_RESULT"

@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun insertResult(intent: Intent, locations: List<Location>) {
    val result = LocationResult.create(locations)
    intent.putExtra(EXTRA_LOCATION_RESULT, result)
}

Note: FusedLocationApi has been deprecated and FusedLocationProviderClient should be used instead. I have applied the solution above to unit test the BroadcastReceiver receiving updates from FusedLocationProviderClient


text:
Q: How can I sort the values in a custom Keras / Tensorflow Loss Function? Introduction
I would like to implement a custom loss function to Keras. I want to do this, because I am not happy with the current result for my dataset. I think the reason for this is because currently the built-in loss functions focuses on the whole dataset. And I just want to focus on the top values in my dataset. That is why I came up with the following idea for a custom loss function:
Custom Loss Function Idea
The custom loss function should take the top 4 predictions with the highest value and subtract it with the corresponding true value. Then take the absolute value from this subtraction, multiply it with some weights and add it to the total loss sum.
For better understanding of this custom loss function I programmed it with a list input. Hopefully it is better understandable with this example:
The following example calculates the loss = 4*abs(0.7-0.5)+3*abs(0.5-0.7)+2*abs(0.4-0.45) +1*abs(0.4-0.3) = 1.6 for i=0
Then it divides it by div_top which in this example is 10 (for i=0 it would be 0.16), repeats everything for all other i and finally takes the average over all samples.
top = 4
div_top = 0.5*top*(top+1)

def own_loss(y_true, y_pred):
    loss_per_sample = [0]*len(y_pred)
    for i in range(len(y_pred)):
        sorted_pred, sorted_true = (list(t) for t in zip(*sorted(zip(y_pred[i], y_true[i]))))
        for k in range(top):
            loss_per_sample[i] += (top-k)*abs(sorted_pred[-1-k]-sorted_true[-1-k])
    loss_per_sample = [t/div_top for t in loss_per_sample]
    return sum(loss_per_sample)/len(loss_per_sample)

y_pred = [[0.1, 0.4, 0.7, 0.4, 0.4, 0.5, 0.3, 0.2],
          [0.3, 0.8, 0.5, 0.3, 0.1, 0.0, 0.1, 0.5],
          [0.5, 0.6, 0.6, 0.8, 0.3, 0.6, 0.7, 0.1]]

y_true = [[0.2, 0.45, 0.5, 0.3, 0.4, 0.7, 0.22, 0.1],
          [0.4, 0.9, 0.3, 0.0, 0.2, 0.1, 0.11, 0.8],
          [0.4, 0.7, 0.4, 0.3, 0.4, 0.7, 0.6, 0.05]]

print(own_loss(y_true, y_pred)) # Output is 0.196667

Implementation to Keras
I would like to use this function in Keras as a custom loss function. This would look like this:
import numpy as np
from keras.datasets import boston_housing
from keras.layers import LSTM
from keras.models import Sequential
from keras.optimizers import RMSprop

(pre_x_train, pre_y_train), (x_test, y_test) = boston_housing.load_data()
"""
The following 8 lines are to format the dataset to a 3D numpy array
4*101*13. I do this so that it matches my real dataset with is formatted
to a 3D numpy array 47*731*179. It is not important to understand the following
8 lines for the loss function itself.
"""
x_train = [[0]*101]*4
y_train = [[0]*101]*4
for i in range(4):
    for k in range(101):
        x_train[i][k] = pre_x_train[i*101+k]
        y_train[i][k] = pre_y_train[i*101+k]
train_x = np.array([np.array([np.array(k) for k in i]) for i in x_train])
train_y = np.array([np.array([np.array(k) for k in i]) for i in y_train])

top = 4
div_top = 0.5*top*(top+1)

def own_loss(y_true, y_pred):
    loss_per_sample = [0]*len(y_pred)
    for i in range(len(y_pred)):
        sorted_pred, sorted_true = (list(t) for t in zip(*sorted(zip(y_pred[i], y_true[i]))))
        for k in range(top):
            loss_per_sample[i] += (top-k)*abs(sorted_pred[-1-k]-sorted_true[-1-k])
    loss_per_sample = [t/div_top for t in loss_per_sample]
    return sum(loss_per_sample)/len(loss_per_sample)

model = Sequential()
model.add(LSTM(units=64, batch_input_shape=(None, 101, 13), return_sequences=True))
model.add(LSTM(units=101, return_sequences=False, activation='linear'))
# compile works with loss='mean_absolute_error' but not with loss=own_loss
model.compile(loss=own_loss, optimizer=RMSprop())

model.fit(train_x, train_y, epochs=16, verbose=2, batch_size=1, validation_split=None, shuffle=False)

Obviously this above Keras example won't work. But I also have no clue how I could this get to work.
Ways to solve the Problem
I read the following articles, trying to solve the problem:
Keras custom metric iteration
How to use a custom objective function for a model?
I also read the Keras backend page:
Keras Backends
And Tensorflow Top_k page:
tf.nn.top_k
Which seems for me the most promising approach, but after many different ways to implement it still does not work. I could get the correct pred_y values when sorting with top_k but I could not get the corresponding true_y values.
Does anybody have an idea how I could implement the custom loss function?

A: Assumption

*

*Use tf.nn.top_k for sorting tensors. It means that "If two elements are equal, the lower-index element appears first" as explained in the API document.

Suggested solution
top = 4
div_top = 0.5*top*(top+1)

def getitems_by_indices(values, indices):
    return tf.map_fn(
        lambda x: tf.gather(x[0], x[1]), (values, indices), dtype=values.dtype
    )

def own_loss(y_true, y_pred):
    y_pred_top_k, y_pred_ind_k = tf.nn.top_k(y_pred, top)
    y_true_top_k = getitems_by_indices(y_true, y_pred_ind_k)
    loss_per_sample = tf.reduce_mean(
        tf.reduce_sum(
            tf.abs(y_pred_top_k - y_true_top_k) *
                tf.range(top, 0, delta=-1, dtype=y_pred.dtype),
            axis=-1
        ) / div_top
    )
    return loss_per_sample

model = Sequential()
model.add(LSTM(units=64, batch_input_shape=(None, 101, 13), return_sequences=True))
model.add(LSTM(units=101, return_sequences=False, activation='linear'))
# compile works with loss='mean_absolute_error' but not with loss=own_loss
model.compile(loss=own_loss, optimizer=RMSprop())

model.train_on_batch(train_x, train_y)

Comment

*

*Is there any better implementation of getitems_by_indices()?

*The current implementation of getitems_by_indices() used Sungwoon Kim's idea.


text:
Q: How to handle google play app with CI build and RC Build I have one android app (e.g MyApp) in the Google Play Store, and at the moment the package is from the RC build in our pipeline, but we also want to publish package from CI build for testers. Is it better to create a new app called MyAppTest in play store which receives the package from CI build? Or is it better to just upload the package from CI build to "MyApp" under internal testing track? In the package from RC build, the version is like 1.0.0-RC1, and the package from CI build the version is like 1.1.0.1.
What is the best practice for this problem?

A: You should keep all into a single project! And use the different levels of testing of google play (alpha, closed beta, open beta).
Usually there are some levels of testing:

*

*Internal testing (Release Candidates)

*Open Beta for selected users

You should try to scale the same version from internal, to open beta to production. Most versions will be transitory, and won't reach production at all.
But you should keep the semantic versions all the way, some devs like to add -RC or -beta after the version to name, to tag as "in testing" version.


text:
Q: Laravel route model binding: return json response when model id not found I'm developing a REST API in Laravel. I'm using route model binding to update an item. I want to return a JSON not found response when the id is not found in the database.
This is the entry in the route api.php file:
   Route::get('product/{product}', 'ProductController@show')->name('products.show');

The controller update function looks as follows:
   public function update(Request $request, Product $product)
    {
        $request->validate([
            'user_id'       =>  'required',
            'name'          =>  'nullable',
            'description'   =>  'nullable',
            'price'         =>  'nullable'
        ]);

        // check if currently authenticated user is the owner of the listing

        if (auth::user()->id !== $product->user_id) {
            return response()->json(['error' => 'You can only edit your own products.'], 403);
        }

        $product->update($request->only(['name', 'description', 'price']));

        return new ProductResource($product);
    }

With this code,  Laravel automatically returns a 404 Not found view but I would like it to be a JSON response instead.
Any elegant solution to accomplish this?

A: You can try to modify app/Exceptions/Handler.php file with something like that:
// add this before the class declaration
use Illuminate\Database\Eloquent\ModelNotFoundException;
//....
// modify the render() function as follows
public function render($request, Exception $exception)
{
    if ($exception instanceof ModelNotFoundException && $request->wantsJson()) {
        return response()->json(['message' => 'Not Found'], 404);
    }
    return parent::render($request, $exception);
}

Let me know if it works I didn't have the time to try the code.

A: In the recent Laravel version (9) you can solve this by putting the below code inside the register function in app/Exceptions/Handler.php
  $this->renderable(function (NotFoundHttpException $exception) {
         return response()->json([
                'status' => false,
                'message' => 'Your message here',
           ], 404);
     });

Ensure to import the namespace of NotFoundHttpException.
If your own error is ModelNotFoundException then do it this way
  $this->renderable(function (ModelNotFoundException $exception) {
         return response()->json([
                'status' => false,
                'message' => 'Your message here',
           ], 404);
     });


text:
Q: Monkeyrunner activity I have one problem, I has started 2 activities via monkeyrunner.
How I can close one of them?
I try to used device.stopActivity(package/activity), but monkeyrunner have not these command.
And also i want to recieve all working activities how i can do that?

A: As far as I know, Android manages the activities on his own. But there's a way to stop the activities via the kill command. Use a python script to do this:
First, simulate the touch of the home button:
device.press('KEYCODE_HOME', MonkeyDevice.DOWN_AND_UP)

Then use the ps command to list the open processes:
processes = str(device.shell('ps'))

Then look in the processes variable to see if you package is still there. If it's there, find the line which contains the package and retrieve it's PID. Then use the PID to kill the process:
if package in processes:
    for line in processes.splitlines():
        if package in line:
            pid = line.split()[1]
device.shell('kill ' + pid)

Later edit:
I have found another way in which you can close/ stop a package:
device.shell('am force-stop package')

The am force-stop command needs the package name only as an argument. It closes the respective package.

A: Hi better option is to stop the process
device.press('KEYCODE_HOME', MonkeyDevice.DOWN_AND_UP)
kill_command = 'am force-stop %s' % package_name
device.shell(kill_command)


text:
Q: Transcoding with ffmpeg libfaac reduces the audio duration I have to transcode  a mpegts file: input.ts(H.264 and AAC)
So I use the following command line:
ffmpeg -y -i input.ts -acodec libfaac -vcodec copy out.ts
But I find that the duration of output.ts's audio is shorter than that of the input.ts!
If I do the following iterations, the output's audio will be shorter and shorter.
ffmpeg -y -i out.ts -acodec libfaac -vcodec copy out-iter1.ts
ffmpeg -y -i out-iter1.ts -acodec libfaac -vcodec copy out-iter2.ts
ffmpeg -y -i out-iter2.ts -acodec libfaac -vcodec copy out-iter3.ts
ffmpeg -y -i out-iter3.ts -acodec libfaac -vcodec copy out-iter4.ts
ffmpeg -y -i out-iter4.ts -acodec libfaac -vcodec copy out-iter5.ts

My ffmpeg's version is 0.6.6. libfaac's version is 1.28.
input.ts's audio duration is 10.432 seconds. out-iter5.ts's audio duration is 10.56 seconds
And I have also tried ffmpeg with version 0.11.
And it makes the audio longer than the original input.
So my question is: how to make sure the output's audio duration is same as the input's audio.
Since libfaac will make the audio shorter, how can I compensate for it?
(For some reason I can't use -acodec copy directly.) Any suggestions?


text:
Q: Entity - how to get only one column Is there any possibility to get only one column from .Where statement? For example - ID.
List<testB> test = db.testB.Where(x => x.UserID == userId).ToList();

Here I get all entites testB.
And I just want to return List<int> with testB.ID instead of List<testB>. How can I do this?

A: db.testB.Where(x => x.UserID == userId).Select(x => x.ID).ToList();

should return a List<int>

A: Try using .select like this
var test = db.testB.Where(x => x.UserID == userId)
    .Select(a => new {
          column = a.column
    }).ToList();

this creates an anonymous type class of only on attribute. Try it out.


text:
Q: Convert web based database management application into mobile app to make it work offline We have no knowledge of mobile applications. We need to convert a basic web-based database management application in Laravel into a mobile application. Is there a way to do it without having mobile application developers. The application has the following views
1. Form
2. Edit form
2. All forms
3. Users
4. Edit Users
There are two user type - Admin and data entry operator

A: Yes, you can do it using webview. Start a project in android studio, create a class extending from Activity, a xml layout file in res/layout, and take a look on your AndroidManifest file in the manifests folder.
It will look more or less like this:
The image also shows you the basic structure of the activity, though you don't really need the onCreateOptionsMenu part. Now to make the webview put this in the xml:
<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
/>

And call it on your onCreate method like the one shown in the image:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com"); //change the link to your

In your manifest add permission for the application to use internet:
<manifest ... >
    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>

If you want to make your webview work offline you could use webview cache.
But since it is a database managing application, you probably will need to make a full app, and for that you will need an mobile developer. But you could use other approaches, like using xamarin, ionic or other transpilers, though that will still require learning, it is easier for programmers of other areas to adapt, then maybe you could avoid hiring a mobile programmer.


text:
Q: Broken ux(cards) in skype I am trying to build my own bot and I am using c#(vs2017). My bot works perfectly in my emulator and it works even in test panel after publishing it to azure. In skype it got published successfully but I get a broken card with two lines displayed. I am trying to display a herocard with 6-7 lines of text.
Do we have a limit of no of words??

A: Yes, the text is limited. Skype is more variable than say Messenger, which has a documented hard limit: the amount of text shown by Skype varies on whether you have a title and/or subtitle or neither.
Back when I ran some tests on Skype I found a limit was around 200 characters, if there was no title or subtitle.
You may be able to get more by not having an image. I didn't test that.


text:
Q: Daily reputation cap: points subtracted Hi,
I reached for the first time the daily reputation cap. The day after I have seen my reputation level down to -150/-200 I don't remember.
Are points awarded to get d.r.c. subtracted when cap reached?

A: I agree with ChrisF -- I think you had some votes that were invalidated as statistically anomalous.
We have a process that runs every 24 hours and checks for voting anomalies, and removes any votes that are far outside statistical norms.