Q: useEffect hook not firing on orientation change I am trying to change the height of a container, when in mobile landscape mode only. I am playing around in the developer tools to swap the orientation of a mobile device but it only works on the first render. I am new to react hooks so not sure if I am implementing it right.
The idea is that I am testing that once in landscape, if it's on mobile the height should be less than 450px (which is the check I am doing for the if statement)
Could someone point me in the right direction, please?
Thanks!

const bikeImageHeight = () => {
    const windowViewportHeight = window.innerHeight;
    const isLandscape = window.orientation === 90 || window.orientation === -90;
    let bikeImgHeight = 0;

    if (windowViewportHeight <= 450 && isLandscape) {
      bikeImgHeight = windowViewportHeight - 50;
    }

    return bikeImgHeight;
  };

  useEffect(() => {
    bikeImageHeight();

    window.addEventListener("resize", bikeImageHeight);

    return () => {
      window.removeEventListener("resize", bikeImageHeight);
    };
  }, []);

A: The useEffect hook is not expected to fire on orientation change. It defines a callback that will fire when the component re-renders. The question then is how to trigger a re-render when the screen orientation changes. A re-render occurs when there are changes to a components props or state.
Lets make use of another related stackoverflow answer to build a useWindowDimensions hook. This allows us to hook into the windows size as component state so any changes will cause a re-render.
useWindowDimensions.js
import { useState, useEffect } from 'react';

function getWindowDimensions() {
  const { innerWidth: width, innerHeight: height } = window;
  return {
    width,
    height
  };
}

export default function useWindowDimensions() {
  const [windowDimensions, setWindowDimensions] = useState(getWindowDimensions());

  useEffect(() => {
    function handleResize() {
      setWindowDimensions(getWindowDimensions());
    }

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return windowDimensions;
}

You can then use that hook in your component. Something like:
BikeImage.js
import React from 'react'
import useWindowDimensions from './useWindowDimensions'

export default () => {
  const windowDimensions = useWindowDimensions();

  // Define these helper functions as you like
  const width = getImageWidth(windowDimensions.width)
  const height = getImageHeight(windowDimensions.height)

  // AppImage is a component defined elsewhere which takes
  // at least width, height and src props
  return <AppImage  width={width} height={height} src="..." .../>
}

A: Here is a custom hook that fires on orientation change,
import React, {useState, useEffect} from 'react';

// Example usage
export default () => {
  const orientation = useScreenOrientation();
  return
{orientation}
;
}

function useScreenOrientation() {
  const [orientation, setOrientation] = useState(window.screen.orientation.type);

  useEffect(() => {
    const handleOrientationChange= () => setOrientation(window.screen.orientation.type);
    window.addEventListener('orientationchange', handleOrientationChange);
    return () => window.removeEventListener('orientationchange', handleOrientationChange);
  }, []);

  return orientation;
}

Hope this takes you to the right direction.

A: You need to trigger a re-render, which can be done by setting state inside of your bikeImageHeight.
  const [viewSize, setViewSize] = useState(0)

    const bikeImageHeight = () => {
        const windowViewportHeight = window.innerHeight;
        const isLandscape = window.orientation === 90 || window.orientation === -90;
        let bikeImgHeight = 0;

        if (windowViewportHeight <= 450 && isLandscape) {
          bikeImgHeight = windowViewportHeight - 50;
        }
        setViewSize(bikeImgHeight)
        return bikeImgHeight;
  };

And per the comments conversation, here's how you'd use debounce:
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

const YourComponent = () => {

  const bikeImageHeight = () => {
    const windowViewportHeight = window.innerHeight;
    const isLandscape = window.orientation === 90 || window.orientation === -90;
    let bikeImgHeight = 0;

    if (windowViewportHeight <= 450 && isLandscape) {
      bikeImgHeight = windowViewportHeight - 50;
    }
    setViewSize(bikeImgHeight)
    return bikeImgHeight;
  };

  const debouncedBikeHeight = debounce(bikeImageHeight, 200)

  useEffect(() => {
    bikeImageHeight();

    window.addEventListener("resize", debouncedBikeHeight);

    return () => {
      window.removeEventListener("resize", debouncedBikeHeight);
    };
  }, []);

  return
some jsx

}

Example debounce taken from here: https://davidwalsh.name/javascript-debounce-function


Q: How to go back to Gimp2.6 (2022) The method from four years ago no longer works:
$ sudo aptitude install gimp
The following NEW packages will be installed:
  gimp{b} gimp-data{a} libbabl-0.0-0{a} libgegl-0.0-0{ab} libgimp2.0{a} liblcms1{a} libmng2{a}
  libopenexr6{ab} libtiff4{a}
0 packages upgraded, 9 newly installed, 0 to remove and 17 not upgraded.
Need to get 11,0 MB of archives. After unpacking 56,2 MB will be used.
The following packages have unmet dependencies:
 libgegl-0.0-0 : Depends: libpng12-0 (>= 1.2.13-4) which is a virtual package and is not provided by any available package

 gimp : Depends: python-gtk2 (>= 2.8.0) which is a virtual package and is not provided by any available package

        Depends: libpng12-0 (>= 1.2.13-4) which is a virtual package and is not provided by any available package

        Depends: libwebkitgtk-1.0-0 (>= 1.3.10) which is a virtual package and is not provided by any available package

 libopenexr6 : Depends: libilmbase12 (>= 2.2.0) which is a virtual package and is not provided by any available package

The following actions will resolve these dependencies:

     Keep the following packages at their current version:
1)     gimp [Not Installed]
2)     libgegl-0.0-0 [Not Installed]
3)     libopenexr6 [Not Installed]

     Leave the following dependencies unresolved:
4)     gimp-data recommends gimp

So how do you install Gimp2.6 now?
$ cat /etc/upstream-release/lsb-release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=20.04
DISTRIB_CODENAME=focal
DISTRIB_DESCRIPTION="Ubuntu Focal Fossa"


Q: Composer debug dependencies I should figure out, how to debug such situations?
I try to send mail throw Mailgun package.
How to figure out why the class is not found? Error: Class 'Mailgun\Messages\MessageBuilder' not found in /vendor/boundstate/yii2-mailgun/Message.php:239
but IDE shows me that class exist in package mailgun/mailgun-php
Take a look on a slice of composer.json:
    "boundstate/yii2-mailgun": "0.0.4",
    "Mailgun/Mailgun-php": "^1.0",

ADD:
I have required autoload.php Also, composer use psr4. I see the correct path to classes. Take a look:
    'boundstate\\mailgun\\' => array($vendorDir . '/boundstate/yii2-mailgun'),
    'Mailgun\\' => array($vendorDir . '/mailgun/mailgun-php/src'),

A: Usually, such things happen when you didn't require vendor/autoload.php, or autoload wasn't generated. IDE may show you that everything is OK just because it parsed your composer.json.
Try to:

*

*composer update

*get sure you required vendor/autoload.php in your script


Q: Handling date from list of times I have a list of time.
time_list = ['7pm', '8pm', '9pm', '10pm', '11pm', '12am', '1am', '2am']

and from there a list of floats as well
fl_list = ['1.0', '0.0', '0.0', '0.0', '0.0', '0.0', '11', '12.0']

Upon inserting in the database,
I set the date of time 7pm-12am to date today, and 1am-2am to date tomorrow.
date_today = datetime.datetime.utcnow()
date_tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1)

My code is like this:
has_tomorrow_record = all(any(x in y for y in time_list) for x in ["12am", "1am"])

then to get the date I have to do the below condition
for t in time_list:
    if has_tomorrow_record and "am" in t:
        if t != "12am":
            date = date_tomorrow

Is there a cleaner way to determine the dates for the time_list?


Q: Include of non-modular header inside framework module 'AppLovinSDK' - Archive only error I get this error only when I try to archive, building for simulator or other test device works. Previously, I had this problem when trying to build for a test device, but I started over and reinstalled the pod and it worked. I have tried setting 'Allow non-modular Includes in Frameworks' to yes in both my project and Target, but this has NOT worked. Any ideas on how to get out of this would be greatly appreciated!

A: I got the same error (for archiving only) for my Swift framework with C code inside.
Only this remedy helped me.
Add -Xcc -Wno-error=non-modular-include-in-framework-module in Other Swift Flags (build settings of framework). This flag forces the compiller count that error as a warning.


Q: Invalid label in mozilla firefox I've a JSP page like this with name test.jsp
<%@ page language="java" contentType="text/json; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%
response.setContentType("application/x-javascript");
%>

{"feed": "test"}

and an html page where i use jquery for reading the json object.
    <html>
    <head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
    <script type='text/javascript'>
    $(function(){

    $.getJSON("localhost:8080/test.jsp?callback=?",{test:"test"}, function(data){alert("here");});

    })

    </script>
    </head>
    </body>
    something here
    </body>
    </html>

but it shows an error as invalid label in firefox. Can anyone explain me the reason for this error.
I've tried google but could not find a solution or explanation to my problem. What needs do be done for this. Please help me out.
Thanks

A: I've found the solution to the problem by some hit & trial.
It is because when we make getJSON() call on cross domain then response should be wrapped inside a function name. This function is our callback handler for the response in the script.eg
html file :
 <html>
    <head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
    <script type='text/javascript'>
    $(function(){
       $.getJSON("localhost:8080/test.jsp?callback=?");
    }
   function test(data){
      alert(data.feed);
    }

And the jsp test.jsp
<%@ page language="java" contentType="text/json; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%
response.setContentType("application/x-javascript");
out.write("test({\"feed\": \"test\"})");
%>

hope if anybody has the same problemm this will help.you can pass the callback function name as a parameter and make jsp at the server such that it uses that name to wrap the response.

A: I have encountered the same issue which was actually because of the some issue with json or ajax call. In your json call it should be {"test":"test"} instead of {test:"test"}.
Try it should work if this is the issue.


Q: Importing Json field from csv to MySQL 5.7.19-0ubuntu0.16.04.1 I have MySQL table consisting of 3 columns having type of (cookie vachar, userdata json, userprefernce json). I am trying to load the data from csv but it gives the following error :
Error:
Error Code: 3140 Invalid JSON text: Invalid value at position 0 in value for column userdata'
I have tried to validate the JSON it looks fine. Now I couldn't understand what is the problem
Sample Row:
ZwpBHCrWObHE61rSOpp9dkUfJ, '{"bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}, "models": {"Grand Cherokee": 1, "XC90": 1}}', '{"bodystyle": "SUV/MUV", "budgetsegment": "EP", "models": "Grand Cherokee,XC90"}'

A: I can't reproduce the problem:
File: /path/to/file/data.csv
ZwpBHCrWObHE61rSOpp9dkUfJ, '{"bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}, "models": {"Grand Cherokee": 1, "XC90": 1}}', '{"bodystyle": "SUV/MUV", "budgetsegment": "EP", "models": "Grand Cherokee,XC90"}'

MySQL Command Line:
mysql> \! lsb_release --description
Description:    Ubuntu 16.04.2 LTS

mysql> SELECT VERSION();
+-----------+
| VERSION() |
+-----------+
| 5.7.19    |
+-----------+
1 row in set (0.00 sec)

mysql> DROP TABLE IF EXISTS `table`;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `table` (
    ->   `cookie` VARCHAR(25) NOT NULL,
    ->   `userdata` JSON NOT NULL,
    ->   `userprefernce` JSON NOT NULL
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> LOAD DATA LOCAL INFILE '/path/to/file/data.csv'
    ->   INTO TABLE `table`
    ->   FIELDS TERMINATED BY ', '
    ->          OPTIONALLY ENCLOSED BY '\''
    ->   LINES TERMINATED BY '\n';
Query OK, 1 row affected (0.00 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> SELECT
    ->   `cookie`,
    ->   `userdata`,
    ->   `userprefernce`
    -> FROM
    ->   `table`\G
*************************** 1. row ***************************
       cookie: ZwpBHCrWObHE61rSOpp9dkUfJ
     userdata: {"models": {"XC90": 1, "Grand Cherokee": 1}, "bodystyle": {"SUV/MUV": 2}, "budgetsegment": {"EP": 2}}
userprefernce: {"models": "Grand Cherokee,XC90", "bodystyle": "SUV/MUV", "budgetsegment": "EP"}
1 row in set (0.00 sec)


Q: Makefile and Shell Script (Bash) What is the relationship between Makefile and Bash?
Example in Makefile you have:
CC = gcc

But if you type this in the shell, you get error:
~# CC = gcc
-bash: CC: command not found

Understandably, because there are spaces. But it works in Makefile.
Also, in Makefile you use command substitution $()
$(CC) $(LDFLAGS) -o $@ $(OBJS) $(LIBS)

which should be variable substitution $CC or ${CC} in bash.
So Makefile syntax and bash syntax are different, but they do seem related, for example $@.

A: There's no relationship - make and bash are two separate programs that parse distinct syntaxes. That they have similar or overlapping syntactic elements is likely due to having been developed around the same time and for some similar purposes, but they don't rely on the same parser or grammar.
Many distinct languages have shared language features either for ease of adoption or from imitation. Most languages use + to mean addition, for example, but that doesn't make the languages related.


Q: Python: run python script as subprocess and get the output I have a python script calculate.py with a function in it like below
def mytest():
    Y_pred = {}
    Y_pred['a'] = [1,2,3]
    Y_pred['b'] = [45,54,77]
    return Y_pred

Now from python console I want to run the python script using subprocess and get the return value `Y_pred' into a variable. So I want something like the pseudocode below from the terminal
python3
>>> import subprocess
>>> returned_val =  subprocess.call([run calculate.py here and call mytest() ])

In the end, I want the returned value of mytest() to a variable returned_val.

A: You need to do a few things.
First, in calculate.py call the mytest function, add the following at the end:
if __name__ == '__main__':
    print(mytest())

Now when you execute the calculate.py script (e.g. with python3 /path/to/calculate.py), you'll get the mytest's return value as output.
Okay, now you can use subprocess.check_output to execute the script, and get output:
returned_bin =  subprocess.check_output('/usr/bin/python3 /path/to/calculate.py'.split())

Replace the paths accordingly.
The value of returned_val would be binary string. You need to decode it to get the respective text string:
returned_val = returned_bin.decode('utf-8')  # assuming utf-8

Now, as the returned value from myfunc is a dict and in returned_val is a string,
you can use json.loads(returned_val) to get the same dict representation back.

A: subprocess.check_output
import subprocess
[ print(i) for i in subprocess.check_output(['ls']).split() ]

output, my current directory:
b'a.sh'
b'app'
b'db'
b'old.sh'


Q: Get all edges of a cuboid (3D NumPy array) Having a 3-dimensional numpy array A I want to get all the edges (imagine this array as a cuboid).
Well, A[0, 0, :] would give me one edge, A[0, -1, :] second one and A[:, -1, -1] yet another one... so all I'd have to do is get all permutations of 0, -1 and : and use them as indices. Zero and minus one are easy, but how would I do this with colon?
I can solve it the long way, but it's ugly and I bet there is some neat numpy solution to this. Something like:
for indices in permutations([0, -1, ':']):
    edge = A[indices]
    ...

What I want to do in the end is numpy.any() on the set of all edges to see if all edge-values are zero.

A: : is same as slice(None, None, None)
A[0, -1, :] is same as
obj = (0, -1, slice(None, None, None))
A[obj]


Q: Get only git diff output in tab I want to get only output of git diff of whole repository, not just a file, in a tab, Not Split With The Commit Message!
In the issues I found a:
command GdiffInTab tabedit %|Gdiff

But this one opens an split view with commit message, the thing I want is to show only git diff in new tab when editing git commit message.
Is it possible? Or should I try doing it myself, something like:
function GitDiffTab()
  exe "tab new %"
  exe "%!git diff"
  exe "se ft=diff"
endfunction

But it doesn't work when editing commit message.

A: Use :terminal (requires Vim 8.1+)
:-tab terminal git --no-pager diff

Using fugitive.vim we can create a command:
command! -bang Tdiff execute '-tab terminal ' . call(fugitive#buffer().repo().git_command, ['--no-pager', 'diff'] + (<bang>0 ? ['--cached'] : []))

Use :Tdiff to do git diff and :Tdiff! to do git diff --cached
For more help see:
:h :tab
:h :terminal


Q: SQL Query, get only the line where a value appear 4 time I've got a table Customer (ID, Ref, LastName, FirstName).
I have to bring out all lines whose reference is the same at least four times.
I tried this unsuccessfully :
SELECT * from MyTable Where (select count(ref) from MyTable Group By ref) >= 4

Of course it is wrong, but I don't know how to do this in one query.

A: You need to use HAVING clause like below
SELECT * from Customer
Where ref in (select ref from Customer Group By ref having count(*) >= 4)

SQL Demo

A: If I understand correctly, you can use the Having clause in the query:

SELECT Ref, LastName, FirstName
from MyTable
group by Ref, LastName, FirstName
having count(*) >= 4

I have omitted ID, since this is possibly a primary key and probably not required here as the grouping wouldn't work.
EDIT: Since the above query will not return your result...You can also use a join...
    SELECT  *
    FROM    Customer c
        INNER JOIN ( SELECT ref
                     FROM   Customer
                     GROUP BY ref
                     HAVING COUNT(*) >= 4
                   ) t ON c.ref = t.ref

A: SELECT * from MyTable Group By ref HAVING COUNT(*) >= 4

A: SELECT Ref, LastName, FirstName
from YourTable
group by Ref, LastName, FirstName
having count(*) >= 4

A: assuming records with the same Reference associate to the same customer then something meaningful can be got from :
select ID , max(Ref) as the_Ref , count(Ref) as count_ref  from Customer group by Ref having count(Ref) >= 4;

If , however ,  Ref refers to something which occurs independently of the existence of customers ( maybe its used to refer to customer orders ) I'd recommend you consider normalising (http://en.wikipedia.org/wiki/Database_normalization) the data model a little more into two tables instead of one viz :
Customer( ID , firstName , LastName )
Customer_Order ( Ref , Customer_ID)

whats known as a foreign key relationship can then be set up between these two tables

A: As a lover of INNER JOIN, I would prefer the following way.
SELECT *
FROM Customer C
INNER JOIN (
    SELECT Ref, LastName, FirstName, COUNT(1) AS NumberOfRef
    FROM Customer
    GROUP BY Ref, LastName, FirstName
) T ON T.Ref = C.Ref AND T.LastName = C.LastName AND T.FirstName = C.FirstName AND T.NumberOfRef >= 4

However, after I did it, I started to feel the table Customer to be a bit strange. Even though we normalize it, as @diarmuid suggested, what should we use as the primary key for Customer_Order?
Customer(ID , FirstName, LastName )
Customer_Order (Ref, CustomerID)


Q: Linq ToDictionary Not Defined? I have this code
var contacts = dr.mktDoctorContacts
    .GroupBy(x => x.ContactType)
    .Select(zb => new
     {
         Key = zb.Key,
         GroupWiseContacts = zb.Select(x => x.Contact).ToList()
     })
    .ToDictionary<string,List<string>>(y => y.Key, y => y.GroupWiseContacts)

I don't know what is wrong with this code.
Compile time error msg says:System.Generic.IEnumerable does not contain definition of and best extension method overloads has some invalid arguments. i can see only two overloads of ToDictionary Method in my visual studio tooltip sort of documentation whereas i have come across more than two overloads of ToDictionary on the web
Edit Here is exact Error message at compile time

Error 13  'System.Collections.Generic.IEnumerable<AnonymousType#1>'
  does not contain a definition for
  'ToDictionary' and the best extension
  method overload
  'System.Linq.Enumerable.ToDictionary<TSource,TKey>(System.Collections.Generic.IEnumerable<TSource>,
  System.Func<TSource,TKey>,
  System.Collections.Generic.IEqualityComparer<TKey>)'
  has some invalid arguments

A: The compiler message makes the error clear: There is no method ToDictionary which can accept the arguments and types specified.
The mistake here is in specifying the type arguments on ToDictionary. The MSDN documentation defines the extension method as ToDictionary<TKey, TSource>. The source in your example is IEnumerable<AnonymousType#1>, but you have specified a type of List<string>.
To correct the error, omit the type arguments; the compiler will infer the correct types. You can additionally combine the Select and ToDictionary transformations into a single statement:
var contacts = dr.mktDoctorContacts
    .GroupBy(x => x.ContactType)
    .ToDictionary(
        y => y.Key,
        y => y.Select(x => x.Contact).ToList());

A: Rewrote your code (and added .AsEnumerable()):
var dictionary = dr.mktDoctorContacts
    .GroupBy(x => x.ContactType)
    .AsEnumerable()
    .ToDictionary(
        i => i.Key,
        i => i.Select(x => x.Contact).ToList()
    )
);

A: Don't run that group operation in the database, it'll cause the elements of each group to be fetched in separate roundtrips.
ILookup<string, string> contacts = dr.mktDoctorContacts
  .ToLookup<Contact, string, string>(x => x.ContactType, x => x.Contact);


Q: Scaffolding feature for winforms or wpf application I'd like to build a new winforms or wpf application, in which I'd like to use the concept of scaffolding like I saw for the Asp.net mvc5 application
Introduction To Scaffolding in Visual Studio 2013 RC
I need to know if this feature exists for the desktop applications like winforms or wpf

A: It is not possible to make common code for all application. There are various type of windows application for example Database Application, Client Server Application, System Utilities, etc So, the mechanism of all applications are different then how we can define a common code template for all application. It is up to you that what you want to use Database or TcpIP Socket for your application. I know my answer is not clear. Because it is very hard to define that why we could not create scaffolding.


Q: Insert value in variable I have a really easy (maybe stupid) question. I have following code to detect aruco markers with the aruco library:
MarkerDetector MDetector;
vector<Marker> Markers;

this->TheCameraParameters.readFromXMLFile(CAMERA_PARAM_FILE);
this->TheCameraParameters.resize(frame.size());
MDetector.detect(frame,Markers, this->TheCameraParameters, MARKER_SIZE);

This code gives me a vector (Markers) that consists of different detected markers. If I print Markers out I get following:
24=(304.631,14.2414) (358.085,12.8291) (358.957,69.6651) (306.197,71.0909) Txyz=0.0540816 -0.892379 2.30182 Rxyz=-2.99629 0.0430742 -0.0213533

But now I want to get the pixel values of the marker. With Markers[0].id,Markers[0].Tvec,Markers[0].Rvec I can extract the id, translation and rotation matrix, but I cant find a way to get the pixel values. Can someone help me with this?

A: I found the answer after an intensive search in the library.
In following output
24=(304.631,14.2414) (358.085,12.8291) (358.957,69.6651) (306.197,71.0909) Txyz=0.0540816 -0.892379 2.30182 Rxyz=-2.99629 0.0430742 -0.0213533

The first element (24) is the id of the marker. The next 4 elements are the pixel coordinates of the 4 corners. With Markers[0][0].x and Markers[0][0].y you get the x- and y-coordinate of the top left corner.


Q: Dynamic string parsing in C# I'm implementing "type-independent" method for filling DataRow with values.
Intended functionality is quite straight forward - caller passes the collection of string representations of column values and DataRow that needs to be filled:
private void FillDataRow(List<ColumnTypeStringRep> rowInput, DataRow row)

ColumnTypeStringRep structure contains the string representation of value, column name, and - what's of most importance - column data type:
private struct ColumnTypeStringRep
{
    public string columnName; public Type type; public string stringRep;
    public ColumnTypeStrinRep(string columnName, Type type, string stringRep)
    {
        this.columnName = columnName; this.type = type; this.stringRep = stringRep;
    }
}

So what's that "type-independency"? Basically I don't care about the data row schema (which always be a row of some typed data table), as long as passed column names match DataRow's colum names and column data types match those of DataRow I'm fine. This function needs to be as flexible as possible (and as simple as possible - just not simpler).
Here it is (almost):
private void FillDataRow(List<ColumnTypeStrinRep> rowInput, DataRow row)
{
Debug.Assert(rowInput.Count == row.Table.Columns.Count);

foreach (ColumnTypeStrinRep columnInput in rowInput)
{
    Debug.Assert(row.Table.Columns.Contains(columnInput.columnName));
    Debug.Assert(row.Table.Columns[columnInput.columnName].DataType == columnInput.type);

    // --> Now I want something more or less like below (of course the syntax is wrong) :

    /*
    row[columnInput.columnName] =  columnInput.type.Parse(columnInput.stringRep);
    */

    // --> definitely not like below (this of course would work) :

    /*
    switch (columnInput.type.ToString())
    {
        case "System.String":
            row[columnInput.columnName] = columnInput.stringRep;
            break;
        case "System.Single":
            row[columnInput.columnName] = System.Single.Parse(columnInput.stringRep);
            break;
        case "System.DateTime":
            row[columnInput.columnName] = System.DateTime.Parse(columnInput.stringRep);
            break;
        //...
        default:
            break;
    }
    */
}

}
Now You probably see my problem - I don't want to use the switch statement. It would be perfect, as in the first commented segment, to somehow use the provided column type to invoke Parse method of particular type that returns the object of that type constructed from string representation.
The switch solutions works but it's extremely non flexible - what if in future I'll be filling not the DataRow but some other custom type with "columns" that can be of custom type (of course every such type will need to expose Parse method to build itself from string representation).
Hope you got what I mean - its like "dynamic parsing" kind of functionality. Is there a way to achieve this in .NET?
Example of FillDataRow call could look like this:
List<ColumnTypeStrinRep> rowInput = new List<ColumnTypeStrinRep>();
rowInput.Add(new ColumnTypeStringRep("colName1", Type.GetType("System.Int32"), "0"));
rowInput.Add(new ColumnTypeStringRep("colName2", Type.GetType("System.Double"), "1,11"));
rowInput.Add(new ColumnTypeStringRep("colName3", Type.GetType("System.Decimal"), "2,22"));
rowInput.Add(new ColumnTypeStringRep("colName4", Type.GetType("System.String"), "test"));
rowInput.Add(new ColumnTypeStringRep("colName5", Type.GetType("System.DateTime"), "2010-01-01"));
rowInput.Add(new ColumnTypeStringRep("colName6", Type.GetType("System.Single"), "3,33"));

TestDataSet.TestTableRow newRow = this.testDataSet.TestTable.NewTestTableRow();
FillDataRow(rowInput, newRow);
this.testDataSet.TestTable.AddTestTableRow(newRow);
this.testDataSet.TestTable.AcceptChanges();

Thank You!

A: The TypeConverterclass is the generic .NET way for converting types. The System.ComponentModel namespace includes implementation for primitive types and WPF ships with some more (but I am not sure in which namespace). Further there is the static Convert class offering primitive type conversions, too. It handles some simple conversions on itself and falls back to IConvertible.

A: First off, your using a struct to pass a complex data around. That is a really bad idea. Make that a class instead.
That said, it sounds like you need a factory to create instances of a parser interface:
interface IColumnTypeParser
{
    // A stateles Parse method that takes input and returns output
    DataColumn Parse(string input);
}

class ColumnTyeParserFactory
{
    IColumnTypeParser GetParser(Type columnType)
    {
        // Implementation can be anything you want...I would recommend supporting
        // a configuration file that maps types to parsers, and use pooling or caching
        // so you are not constantly recreating instances of your parsers (make sure your
        // parser implementations are stateless to support caching/pooling and reuse)

        // Dummy implementation:
        if (columnType == typeof(string)) return new StringColumnTypeParser();
        if (columnType == typeof(float)) return new FloatColumnTypeParser();
        // ...
    }
}

Your FillDataRow implementation would hten use the factory:
m_columnTypeParserFactory = new ColumnTypeParserFactory();

private void FillDataRow(List<ColumnTypeStrinRep> rowInput, DataRow row)
{
    foreach (ColumnTypeStrinRep columnInput in rowInput)
    {
        var parser = m_columnTypeParserFactory.GetParser(columnInput.type);
        row[columnInput.columnName] parser.Parse(columnInput.stringRep);
    }
}

A: In short there is nothing like that - no automagical conversion. You have to specify conversion yourselves. That said
static class Converters{
    static Dictionary<Type, Func<string, object>> Converters = new ...

    static Converters{
        Converters.Add(typeof(string), input => input);
        Converters.Add(typeof(int), input => int.Parse(input));
        Converters.Add(typeof(double), double => double.Parse(input));
    }
}

void FillDataRow(IList<string> rowInput, row){
    for(int i = 0; i < rowInput.Length; i++){
       var converter = Converters.Converters[Column[i].DataType];
       row[i] = converter(rowInput[i])
    }
}

A: How about Convert.ChangeType?
You might consider something fancy with generics btw.
foreach (ColumnTypeStrinRep columnInput in rowInput)
{
    Debug.Assert(row.Table.Columns.Contains(columnInput.columnName));
    Debug.Assert(row.Table.Columns[columnInput.columnName].DataType == columnInput.type);
    ...
    row[columnInput.columnName] = Convert.ChangeType(columnInput.stringRep, columnInput.type);
}

More on Convert.ChangeType:
http://msdn.microsoft.com/en-us/library/dtb69x08.aspx


Q: DataBindingUtil plus NavHostFragment back navigation not working I had posted a question earlier regarding NavHostFragment not working on back press. The question was not answered by anyone, hence putting a couple of days effort into it, I finally managed to figure out the issue.(I am only adding new code missing in the earlier question and changed code here, to reduce question length)
The navigation graph is changed to following:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            xmlns:tools="http://schemas.android.com/tools" android:id="@+id/launch_navigation_graph"
            app:startDestination="@id/splashFragment">

    <fragment android:id="@+id/splashFragment" android:name="com.myapp.android.SplashFragment"
              android:label="fragment_splash" tools:layout="@layout/fragment_splash">
        <action android:id="@+id/action_splashFragment_to_fragment1"
                app:destination="@id/fragment1"
        app:popUpTo="@+id/splashFragment"
                app:popUpToInclusive="true"/>
    </fragment>
    <fragment android:id="@+id/fragment1"
              android:name="com.myapp.android.Fragment1"
              android:label="fragment1" tools:layout="@layout/fragment_register_msisdn">
        <action android:id="@+id/action_fragment1_to_fragment2"
                app:destination="@id/fragment2" app:popUpTo="@+id/fragment1"
                app:popUpToInclusive="false"/>
    </fragment>
    <fragment android:id="@+id/fragment2"
              android:name="com.myapp.android.Fragment2"
              android:label="fragment_fragment2" tools:layout="@layout/fragment_fragment2"/>
</navigation>

Some information which was missing from the previous question. The fragment binding was earlier done like this(Code below is for Fragment1, same is done in Fragment2):
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    val binding: Fragment1Binding =
        DataBindingUtil.setContentView(activity!!, R.layout.fragment1)
    binding.lifecycleOwner = this
    val fragment1ViewModel = ViewModelProviders.of(this).get(Fragment1ViewModel::class.java)
    binding.viewModel = fragment1ViewModel
}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    return inflater.inflate(R.layout.fragment1, container, false)
}

The above code, with the navigation graph, now doesn't crash, but the back button simply refuse to work. It doesn't pop fragment, just exit on second back press.
Now I figured out that inflating the UI using DataBindingUtil.setContentView was the reason why my code was not working. I figured it out by creating another sample project step by step until I figured out when it stops working. I made the sample project work using data binding by using DataBindingUtil to bind to view inflated in OnCreateView like following. I remove the oncreate override.
override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val rootView = inflater.inflate(R.layout.fragment1, container, false)
    val binding = DataBindingUtil.bind<Fragment1Binding>(rootView)
    binding?.lifecycleOwner = viewLifecycleOwner
    val fragment1ViewModel = ViewModelProviders.of(this).get(Fragment1ViewModel::class.java)
    binding.viewModel = fragment1ViewModel
    return rootView
}

Now, this code works in the sample project, but when I place the same on my final project(In sample project I simply place buttons and click to navigate where as in my original project I have webservice calls and view model observing for navigating), the above code crashes with following exception when pressing back from Fragment2(similar crash in Fragment1 back press as well if I press back from Fragment1).
2019-04-30 14:00:47.043 18087-18087/com.selfcare.safaricom E/InputEventSender: Exception dispatching finished signal.
2019-04-30 14:00:47.043 18087-18087/com.selfcare.safaricom E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
2019-04-30 14:00:47.047 18087-18087/com.selfcare.safaricom E/MessageQueue-JNI: java.lang.IllegalArgumentException: navigation destination com.selfcare.safaricom:id/action_fragment1_to_fragment2 is unknown to this NavController
        at androidx.navigation.NavController.navigate(NavController.java:803)
        at androidx.navigation.NavController.navigate(NavController.java:744)
        at androidx.navigation.NavController.navigate(NavController.java:730)
        at androidx.navigation.NavController.navigate(NavController.java:718)
        at com.myapp.android.Fragment2.handleLaunchStatus(Fragment2.kt:53)
        at com.myapp.android.Fragment2.access$handleLaunchStatus(Fragment2.kt:18)
        at com.myapp.android.Fragment2$attachLaunchObserver$1.onChanged(Fragment2.kt:46)
        at com.myapp.android.Fragment2$attachLaunchObserver$1.onChanged(Fragment2.kt:18)
        at androidx.lifecycle.LiveData.considerNotify(LiveData.java:113)
        at androidx.lifecycle.LiveData.dispatchingValue(LiveData.java:126)
        at androidx.lifecycle.LiveData$ObserverWrapper.activeStateChanged(LiveData.java:424)
        at androidx.lifecycle.LiveData$LifecycleBoundObserver.onStateChanged(LiveData.java:376)
        at androidx.lifecycle.LifecycleRegistry$ObserverWithState.dispatchEvent(LifecycleRegistry.java:361)
        at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:188)
        at androidx.lifecycle.LiveData.observe(LiveData.java:185)
        at com.myapp.android.Fragment2.attachLaunchObserver(Fragment2.kt:45)
        at com.myapp.android.Fragment2.onViewCreated(Fragment2.kt:37)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:895)
        at androidx.fragment.app.FragmentManagerImpl.addAddedFragments(FragmentManagerImpl.java:2092)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1866)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1822)
        at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:298)
        at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:241)
        at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:288)
        at androidx.fragment.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:241)
        at androidx.fragment.app.FragmentActivity$1.handleOnBackPressed(FragmentActivity.java:144)
        at androidx.activity.OnBackPressedDispatcher.onBackPressed(OnBackPressedDispatcher.java:136)
        at androidx.activity.ComponentActivity.onBackPressed(ComponentActivity.java:283)
        at android.app.Activity.onKeyUp(Activity.java:3083)
        at android.view.KeyEvent.dispatch(KeyEvent.java:2716)
        at android.app.Activity.dispatchKeyEvent(Activity.java:3366)
        at androidx.core.app.ComponentActivity.superDispatchKeyEvent(ComponentActivity.java:80)
        at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:84)
        at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:98)
        at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:558)
        at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
        at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2736)
        at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:342)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:5037)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4905)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4426)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4479)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4445)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4585)
        at android.view.ViewRootImpl$InputStage.apply(Vie

I googled with the exception but found nothing useful in this particular context that can solve my issue. Please help.


Q: What are the private method responsibilities when we design class in OOP? In different design books I have read that

*

*First identify the purpose of class (abstraction).

*Class should only do one thing (SRP).

*methods are defined as responsibility of the class.

As per my understanding public methods handle the responsibilities of the class which require other class [ie interacting classes]
My question is what responsibilites private members of the class do? and how to decide which method to be made private?
Have a look at my code
class calculator
 {
    private:
    long double operand_1;
    long double operand_2;
    long double result;

    int optr;
    int multiplier;

    Button One;
    Button Two;
    Button Three;
    Button Four;
public:
    calculator();

    const long double get_number_operator(const int=0);
    const long double calculate_number(const int [],const int);

    void show_calculator( );
    void calculations( );
    void clear_screen( );
    void show_back(const int);
    void show_about( );
    void show_time( );

The method in public are really public or we can put those in private?

A: Private members come in two flavours:

*

*Private data members are used to store the internal state of the object

*Private methods can be seen as named blocks of code that can be used by other methods of the class to fulfill their responsibility.
Private methods are typically used when several methods need to do the exact same work as part of their responsibility (like notifying external observers that the object has changed), or when a method is split in smaller steps for readability.

A method should be made private if other classes would have no reason to know that the method exists.

A: The public members are the interface through which the outside world interacts with this object.
The private members are implementation details that describe how a class fulfils its purpose. Since they are private they do not affect how other code interacts with our class and are therefore not part of a larger design. The private members are used to implement the public methods. So basically: any member you create should be private if it is not needed for the external interface of that class.
Sometimes private methods implement some functionality that could be modelled as a responsibility in its own right, could be re-used in another context, or is so complex that you want to unit-test it directly. It can then make sense to extract these methods into free functions or into a class of its own. You often end up with a number of utility classes that have nothing to do directly with the core business logic of your software, but are needed by that business logic to get the job done. For example: methods for loading data from files, abstract algorithms, or adapters to other systems. Quite often, you can use existing libraries for these tasks.

A: If you want either inherit these methods in derived class or reuse by other classes then declare them as Public. And if you protect it from being used by any other class then declare them as Private.
Because methods that are private can only be called by methods within the same class or within the same "module". Methods are not commonly made private; usually they're made protected so that children can call them, or public so that other code can call them.

A: If someone else needs to call a method, it must be public. If nobody else needs to call it, you make it private. And the opposite of course: Only code inside your class can call private methods; anyone can call public methods.
Imagine your boss tells you what your class needs to be able to do, and how and with which interface this functionality is called. That gives you your public methods. Everything else is private.


Q: Rest with spring-boot : Content Negotiation failed! No converter found for return value of type I am trying to get the content of a java POJO on the browser in JSON format using spring-boot 2.1.9 and spring REST. Very basic example! But I get the exception shown on the title of this post. When I annotate the POJO class with @XmlRootElement, I get the XML content on the browser. But when I try to get a list of POJOs on the browser I get the same error as with JSON. Why is the content negotiation working partially for XML and not working at all for JSON ? Thanks for every Answer.
Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Oct 03 15:17:06 CEST 2019
There was an unexpected error (type=Internal Server Error, status=500).
No converter found for return value of type: class com.mayo.vina.restapi4.domain.Limit
org.springframework.http.converter.HttpMessageNotWritableException: No converter found for return value of type: class com.mayo.vina.restapi4.domain.Limit
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:234)
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:181)
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:82)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:123)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:893)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:798)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)

I've already tried all the answers provided in Stackoverflow. Extending the POM file with jackson-databind, using @ResponseBody, @GetMapping instead of @RequestMapping, using produces = "application/json"...
Nothing worked for me.
package com.mayo.vina.restapi4;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Restapi4Application {

    public static void main(String[] args) {
        SpringApplication.run(Restapi4Application.class, args);
    }

}
-------------------------------------------------------------------------
package com.mayo.vina.restapi4.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mayo.vina.restapi4.domain.Limit;

@RestController
public class LimitController
{

    @RequestMapping("/limit")
    public Limit limit()
    {
        return new Limit(1, 10000);
    }
}
---------------------------------------------------------------------------
package com.mayo.vina.restapi4.domain;

//@XmlRootElement
public class Limit
{
    private int minimum;
    private int maximum;

    public Limit()
    {
    }

    public Limit(int minimum, int maximum)
    {
        this.minimum = minimum;
        this.maximum = maximum;
    }

    public int getMinimum()
    {
        return minimum;
    }

    public void setMinimum(int minimum)
    {
        this.minimum = minimum;
    }

    public int getMaximum()
    {
        return maximum;
    }

    public void setMaximum(int maximum)
    {
        this.maximum = maximum;
    }
}
--------------------------------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.mayo.vina</groupId>
    <artifactId>restapi4</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>restapi4</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

A: You can  try with :
@GetMapping(value = '/limit')
@ResponseBody
public Limit limit()
{
    return new Limit(1, 10000);
}

A: The following solved my problem:
So yes, just to reiterate, going into my maven repo and deleting the fasterxml folder and re-running maven is what fixed the issue for me.


Q: Latest modified row for each item I have a sql table containing multiple rows with a memberid and lastmodified date. I need to get latest modified row for each member id. This is what I have tried in EFCore 3.1.1:
var a = context.Members
    .Include(m => m.Histories.OrderByDescending(h => h.LastModifiedDate)
    .FirstOrDefault());

and it gives error: Lambda expression used inside Include is not valid
What am I missing?
UPDATE:
I tried this as well that didn't work either:
 var a = context.Histories
              .GroupBy(h => h.MemberId)
              .Select(g => g.OrderByDescending(p => p.LastModifiedDate).FirstOrDefault()).ToList();

The LINQ expression '(GroupByShaperExpression:
KeySelector: (o.MemberId),
ElementSelector:(EntityShaperExpression:
    EntityType: History
    ValueBufferExpression:
        (ProjectionBindingExpression: EmptyProjectionMember)
    IsNullable: False
)
)
    .OrderByDescending(p => p.LastModifiedDate)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

A: While newer versions of EF Core do support some filtering via adding Where clauses, it's best to think of entities as a "complete" or "complete-able" representation of your data state. You either use the complete state of data, or you project to get the details you want.
For example, if you just want the last modified date for each member:
var lastModifiedDetails = context.Members
    .Select(m => new
    {
        m.MemberId,
        LastModifiedDate = m.Histories.OrderByDescending(h => h.LastModifiedDate)
            .Select(h => h.LastModifiedDate)
            .FirstOrDefault()
    }).ToList();

This would give you a collection containing the MemberId and it's LastModifiedDate.
Alternatively, if you want the complete member and a quick reference to the last modified date:
var memberDetails = context.Members
    .Select(m => new
    {
        Member = m,
        LastModifiedHistory = m.Histories.OrderByDescending(h => h.LastModifiedDate)
            .FirstOrDefault()
   }).ToList();

Here instead of trying to get the last modified date or the latest history through a Member entity, you get a set of anonymous types that project down that detail. You iterate through that collection and can get the applicable history and/or modified date for the associated Member.


Q: tar over ssh to IPv6 host I want to tar to a remote host using the remote host's IPv6 address. I can ssh and scp to the host but GNU tar does not accept the IPv6 address.
I tried:
tar -cjvf root@2001:DB8::1234:5678:/backup.tar.bz2 *

and
tar -cjvf root@[2001:DB8::1234:5678]:/backup.tar.bz2 *

and
tar -cjvf root@\[2001:DB8::1234:5678\]:/backup.tar.bz2 *

but none of these work. All of these give address errors from tar. My Ubuntu system has tar version 1.25-3.

A: Since it works over SSH, you can use:
tar cjvf - /folder/to/backup | ssh root@ipv6 "cat > data.tar.bz2"

A: I think you're imputing powers to tar that it doesn't actually have.  No version of tar to which I have immediate access suggests that the -f flag takes an argument which is a remote user/machine pair.
Could you say why you think this will work?

A: I found the answer (actually already had the answer before asking but figured this would help others and I did learn something). Breaking the tar and ssh into two different steps worked.
tar cvjf - * | ssh root@2001:DB8::1234:5678 "dd of=/backup/backup.tar.bz2"

Note: I tried using cat instead of dd but cat did not work for me - tar gave write errors. May be if I was using ssh key authentication instead of password it would have worked.
Reference:
http://www.astrouw.edu.pl/~jskowron/tar-ssh/
http://www.cyberciti.biz/faq/howto-use-tar-command-through-network-over-ssh-session/


Q: Moving WPF application to Android Im not sure if this is the best place for this question so please let me know if not. I have recently created a pretty simple WPF application that has a link to a SQL Database and allows information to be added, updated and deleted.
I want to port the application so I can use it on my Android phone but am unsure about the easiest way to do this. Im aware I could write a completely new application but Im wondering if there is a way I could easily use all the code ive already written or my Windows app? That way it would also make any updates/code changes easier?
Any thoughts


Q: Can't drop foreign key (using constraint name) check column/key exists I've tried to find a solution myself but haven't had any luck. I'm using MySQL version 8.0.14 and my problem is:
When trying to drop a foreign key...
alter table Employee drop foreign key fk_Employee_Contact1;

It fails...
Error Code: 1091. Can't DROP 'fk_Employee_Contact1'; check that column/key exists

I search for the constraint...
SELECT * FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME='Employee';

Which brings up (partial table)...
CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME, CONSTRAINT_TYPE
'fk_Employee_Contact1', 'RRAS Test Database', 'Employee', 'FOREIGN KEY'

But if I search...
SHOW CREATE TABLE Employee;

It shows it as a key...
KEY `fk_Employee_Contact1_idx` (`idContactDets`),

But not as a CONSTRAINT.
I have also tried...
alter table Employee drop foreign key fk_Employee_Contact1_idx;

Which fails with the same error code. And...
alter table Employee drop column idContactDets;

Which gives...
Error Code: 1828. Cannot drop column 'idContactDets': needed in a foreign key constraint 'fk_Employee_Contact1'

Is there any way to fix this? I'm very new to databases so please explain in simple terms if possible. Thank you. :)


Q: PHP Webhook Request I am running a WordPress site with a WooCommerce checkout. At the checkout page I am using the webhook woocommerce_thankyou as a boarding point for my code. At this Point I am selecting some data from the new my order to send the data to another website via a webhook.
I integrated the code over a custom WordPress plugin. At the moment the webhook gives me back this following error: "DigiMember - Webhook Checkout (#1): the E-Mail-Adress would not send as GET- or POST-Parameter."
What could be the problem?
<?php
    function test ($order_id) {
?>

<span>
            woocommerce_thankyou
             <?php echo $order_id;
             $order=wc_get_order($order_id);
             echo $order->get_meta('digi_first_name');
             echo $order->get_meta('digi_last_name');
             echo $order->get_meta('digi_email');

             ?>
        </span>
        <?php
//The url you wish to send the POST request to
$url = 'https://traumjob-campus.de/member?dm_webhook=1_DCqtx6Xre1oM7tuKyon5rVzAIUWvVVXofMqTRQjE9JVDgf7gLI3M198bIeD5';

//The data you want to send via POST
$fields = [
    'digi_first_name'      => 'user',
    'digi_last_name' => 'test',
    'digi_email'         => 'test@user.de'
];

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//So that curl_exec returns the contents of the cURL; rather than echoing it
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

//execute post
$result = curl_exec($ch);
echo $result;
?>


Q: Marketing Cloud - Join query not able to Join Two DE There are two separate DEs in Marketing Cloud - 'ts2__Placement__c_Salesforce' and 'Contact_Salesforce'. I have created a 3rd DE same using exactly same fields as in 'Contact_Salesforce' and added couple more fields ('Placement_Country__c' and 'candidate_ID__c') which are there in 'ts2__Placement__c_Salesforce'. This 3rd DE has 'Id' as primary key.
Now I am trying to join these two tables into the third one using the following query:
Select
c.Id,
c.SS_Disciplines__c,
c.MailingCountry,
p.Placement_Country__c,
p.candidate_ID__c

From ts2__Placement__c_Salesforce p

JOIN Contact_Salesforce c
ON c.Id = p.candidate_ID__c

(Id is the primary key in 'Contact_Salesforce' but 'candidate_ID__c' is not primary key in 'ts2__Placement__c_Salesforce')
This query is not showing any error but also not fetching any records. Problem is somewhere with the 'join' only as if I run the query on any one of the DE without using 'join', it works.


Q: Search specific words in pdf and return only pdf link where words were found (Python) I am trying to search for multiple words in many PDFs. Links to these PDFs are saved in a dataframe. The goal is for python to return a text stating "The words are located in pdf link"). Here is the code I have so far: (FYI g7 is the name of the dataframe where the links are saved).The issue here is that the code returns the same link multiple times for every time the word is found.
The dataframe (named g7) looks like this:
    URL
0   https://westafricatradehub.com/wp-content/uploads/2021/07/RFA-WATIH-1295_Senegal-RMNCAH-Activity_English-Version.pdf
1   https://westafricatradehub.com/wp-content/uploads/2021/07/RFA-WATIH-1295_Activit%C3%A9-RMNCAH-S%C3%A9n%C3%A9gal_Version-Fran%C3%A7aise.pdf
2   https://westafricatradehub.com/wp-content/uploads/2021/08/Senegal-Health-RFA-Webinar-QA.pdf
3   https://westafricatradehub.com/wp-content/uploads/2021/02/APS-WATIH-1021_Catalytic-Business-Concepts-Round-2.pdf
4   https://westafricatradehub.com/wp-content/uploads/2021/02/APS-WATIH-1021_Concepts-d%E2%80%99Affaires-Catalytiques-2ieme-Tour.pdf
5   https://westafricatradehub.com/wp-content/uploads/2021/06/APS-WATIH-1247_Research-Development-Round-2.pdf

The code is as follows:
import glob
import pathlib
import PyPDF2
import re
import os
for i in range(g7.shape[0]):
    pdf_link=g7.iloc[i,0]
    download_file(pdf_link, f"pdf_{i}")
    text = textract.process(f"/Users/fze/pdf_{i}.PDF")
    # open the pdf file
    object = PyPDF2.PdfFileReader(f"/Users/fze/pdf_{i}.PDF")
    all_files = glob.glob('/Users/fze/*.pdf') #User input: give path to your downloads folder file path
    latest_pdf_path = max(all_files, key=os.path.getctime)

    path = pathlib.PurePath(latest_pdf_path)
    latest_pdf_name=path.name
    print(latest_pdf_name)

    # get number of pages
    NumPages = object.getNumPages()
    # define keyterms
    search_word = 'organization'
    # extract text and do the search
    for i in range(0, NumPages):
            page = object.getPage(i)
            text = page.extractText()
            search_text = text.lower().split()
            for word in search_text:
                if search_word in word:
                    print("The word '{}' was found in '{}'".format(search_word,pdf_link))

Thank you !


Q: Apache 404 Error While PHP File Exists I am getting 404 error while the file exist.  I gave the file (chmod 755) still the file does not show up.  Strange part it only happens to few files.  I am certain the file exists on the directory and PHP file have no script errors.  My .htaccess file says
ErrorDocument 404 http://mydomain.com/404.shtml

This only happens on my Google Chrome browser and it works fine on Safari.

A: If it only happens in some browsers but not in others, have you tried clearing the browser cache? ErrorDocument with an absolute URL will send a redirect, which might be cached in your browser.

A: Do you have access to your servers log files? Can you check if your browser actually made a request, and if your server sent out a 404 error? This should be the first thing to check, to decide if it was a server-side error, or just a problem with the browser/proxy caching pages, and serving a cached 404 error page.


Q: Change a View with a procedure This is the source of a view , i use this view as the base of a procedure named buscacancelados:
 SELECT     NUMERO  FROM dbo.CTRC
 WHERE     (EMITENTE = 504) AND (MONTH(EMISSAODATA) = 3)
 AND (YEAR(EMISSAODATA) = 2013)

This procedure returns the missing numbers in a set
alter   proc buscarcancelado  (@emp int) as
 begin
 set nocount on;
 declare @min int   --- declare the  variavels to be used
 declare @max int
 declare @I int

 IF OBJECT_ID ('TEMP..#TempTable') is not null --  Controls if  exists this table
 begin
        drop table #TempTable -- If exist delete
 end

 create table #TempTable
              (TempOrderNumber int)-- create a temporary table

 SELECT @min = ( SELECT MIN (numero)
                 from controlanum  with (nolock))  -- search the min value of the set

 SELECT @max =  ( SELECT Max (numero)
                  from controlanum  with (nolock)) -- search the max value of the set

 select @I = @min  -- control where begins the while

 while @I <= @max --  finish with the high number
       begin
             insert into #TempTable
             select @I
             select @I = @I + 1
       end
 select tempordernumber from #TempTable
 left join controlanum O with (nolock)
 on TempOrderNumber = o.numero where o.numero is null
 end

I want to change the view controlanum with this procedure
        create proc filtraperiodo (@emp int,@mes int,@ano int)as
        select numero from ctrc where
        EMITENTE = 504
        and MONTH (EMISSAODATA ) = 3 and YEAR (EMISSAODATA)=2013

I want something like this
          SELECT @min = ( SELECT MIN (numero) from  filtraperiodo 504,2,2013

A: Create controlanum as a table-valued function instead of a view
    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE ID = OBJECT_ID('[dbo].[controlanum]') AND XTYPE IN ('FN', 'IF', 'TF'))
        DROP FUNCTION [dbo].[controlanum]
    GO

    CREATE FUNCTION [dbo].[controlanum] (
        @emp int
       ,@mes int
       ,@ano int
    )

    RETURNS @numeros TABLE (numero int)

    AS
    BEGIN

      INSERT @numeros
      SELECT numero
        FROM ctrc WITH (NOLOCK)
       WHERE EMITENTE               = @emp
         AND MONTH (EMISSAODATA )   = @mes
         AND YEAR (EMISSAODATA)     = @ano

      RETURN

    END
    GO

Everywhere you reference controlanum, pass it your 3 filter values.  For instance:
    --...other code here...

    SELECT @min = MIN(numero)
      FROM dbo.controlanum(@emp, @mes, @ano)

    SELECT @max = MAX(numero)
      FROM dbo.controlanum(@emp, @mes, @ano)

    --...other code here...

    SELECT tempordernumber
      FROM #TempTable A
      LEFT JOIN dbo.controlanum(@emp, @mes, @ano) O
        ON A.TempOrderNumber <> O.numero
     WHERE O.numero IS NULL


Q: Python method to get integers from a string with limitation (in some range) Is there a module in python to get integers from string in given range (with limit/restriction) ?
It can be useful to make code cleaner.
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int | bool: # (or False directly)
    try:
        number = int("".join(filter(str.isdigit, string)))
        if low_boundary < number < high_boundary:
            return number
        else:
            return False
    except ValueError:  # Empty message or out of limit
        return False

Usage:
...
if not amount := get_int_from_str(string=input(), low_boundary = 10, high_boundary = 20)
    ...
...

A: Don't fight exceptions. If you can't parse a string as an integer, let the ValueError be raised. If the number is out of range, raise a different ValueError. Otherwise, return a value that is guaranteed to be in the requested range.
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int:
    x = int(str)  # May raise
    if x < low_boundary or x > high_boundary:
        raise ValueError(f"Value '{x}' is out of range {low_boundary}-{high_boundary}")
    return x

The caller knows better than your function what to do if the string cannot produce an in-range integer, and raising an exception forces them to consider the worst-case scenario, rather than letting them assume the function worked and encountering an error later.

As a conventional alternative, you can return None to indicate the lack of a suitable int value. Unlike False, None cannot be confused with 0, but it can still be ignored altogether to cause problems later. (And None by itself doesn't tell you if the string wasn't parseable or if the parsed number was simply out of range.)
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]:
    try:
        x = int(str)
    except ValueError:
        return None

    if x < low_boundary or x > high_boundary:
        return None

    return x

or, to avoid repeating the return None statement:
def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> Optional[int]:
    try:
        x = int(str)
        if x < low_boundary or x > high_boundary:
            raise ValueError
    except ValueError:
        return None

    return x

A: def get_int_from_str(string: str, low_boundary: int = 0, high_boundary: int = 100) -> int | False:
    number = "".join(filter(str.isdigit, string))
    if number:
        number = int(number)
        if low_boundary < number < high_boundary:
            return number
    return False

Note: Using not operator with the output of the function does not distinguish between False and 0 as not False and not 0 will evaluate to True. Here you can differentiate by checking the output with amount is not False condition.


Q: How do I make links that were in the menu be on the nav bar on bigger screens? There are links that were shown on the side of the page as a menu when a button that was in the header was clicked. I want the button to be hidden and for those links to show up in the header instead. But if hide the button, the links do not show up, regardless of if I make the display: block or not. The only thing that happens is that the button is gone, but so are the links.
I have JavaScript code that hides and shows the links when the button is clicked
How do I change the position of the links?

header {
  height: 3.4rem;
  display: grid;
  align-items: center;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right i {
  margin-right: 1rem;
}

.menu {
  display: none;
  position: fixed;
  top: 0;
  right: 0;
  z-index: 1;
  background-color: #000;
  /* margin-left: 4rem; */
  margin-top: 0;
}

@media screen and (min-width: 992px) {
  .right i {
    display: none;
  }
  .menu {
    display: block;
  }
  .top-menu {
    display: flex;
    top: 0;
  }
  .header-container {
    display: flex;
  }
}

      Premium
      Support
      Download

      Account
      Log out

A: You want links on Nav Bar to show when the site is viewed via PC or Laptop screen. And you want the links to collapse in button when site is viewed via mobile.
When viewed on PC Screen:

I did it with Bootstrap, you can also use jQuery for simplicity.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

      <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarToggler1" aria-controls="navbarToggler1" aria-expanded="false" aria-label="Toggle navigation">

      </button>

              Features

              Blog

              About

              Contact

Using simple jQuery

#show{
  display:none;
}
#content{
  display:none;
}
@media only screen and (max-width: 600px)
{
  div{
    display:none;
  }
  #show{
    display:inline;
  }
}
<button id="show">Show</button>

      pricing

      features

      pricing

      features

Live Result with Code


Q: How to stop thinking "relationally" At work, we recently started a project using CouchDB (a document-oriented database).  I've been having a hard time un-learning all of my relational db knowledge.
I was wondering how some of you overcame this obstacle?  How did you stop thinking relationally and start think documentally (I apologise for making up that word).
Any suggestions?  Helpful hints?
Edit: If it makes any difference, we're using Ruby & CouchPotato to connect to the database.
Edit 2: SO was hassling me to accept an answer.  I chose the one that helped me learn the most, I think.  However, there's no real "correct" answer, I suppose.

A: It's all about the data. If you have data which makes most sense relationally, a document store may not be useful. A typical document based system is a search server, you have a huge data set and want to find a specific item/document, the document is static, or versioned.
In an archive type situation, the documents might literally be documents, that don't change and have very flexible structures. It doesn't make sense to store their meta data in a relational databases, since they are all very different so very few documents may share those tags. Document based systems don't store null values.
Non-relational/document-like data makes sense when denormalized. It doesn't change much or you don't care as much about consistency.
If your use case fits a relational model well then it's probably not worth squeezing it into a document model.
Here's a good article about non relational databases.
Another way of thinking about it is, a document is a row. Everything about a document is in that row and it is specific to that document. Rows are easy to split on, so scaling is easier.

A: In CouchDB, like Lotus Notes, you really shouldn't think about a Document as being analogous to a row.
Instead, a Document is a relation (table).
Each document has a number of rows--the field values:
ValueID(PK)  Document ID(FK)   Field Name        Field Value
========================================================
92834756293  MyDocument        First Name        Richard
92834756294  MyDocument        States Lived In   TX
92834756295  MyDocument        States Lived In   KY

Each View is a cross-tab query that selects across a massive UNION ALL's of every Document.
So, it's still relational, but not in the most intuitive sense, and not in the sense that matters most: good data management practices.

A: Document-oriented databases do not reject the concept of relations, they just sometimes let applications dereference the links (CouchDB) or even have direct support for relations between documents (MongoDB). What's more important is that DODBs are schema-less. In table-based storages this property can be achieved with significant overhead (see answer by richardtallent), but here it's done more efficiently. What we really should learn when switching from a RDBMS to a DODB is to forget about tables and to start thinking about data. That's what sheepsimulator calls the "bottom-up" approach. It's an ever-evolving schema, not a predefined Procrustean bed. Of course this does not mean that schemata should be completely abandoned in any form. Your application must interpret the data, somehow constrain its form -- this can be done by organizing documents into collections, by making models with validation methods -- but this is now the application's job.

A: may be you should read this
http://books.couchdb.org/relax/getting-started
i myself just heard it and it is interesting but have no idea how to implemented that in the real world application ;)

A: I think, after perusing about on a couple of pages on this subject, it all depends upon the types of data you are dealing with.
RDBMSes represent a top-down approach, where you, the database designer, assert the structure of all data that will exist in the database.  You define that a Person has a First,Last,Middle Name and a Home Address, etc.  You can enforce this using a RDBMS.  If you don't have a column for a Person's HomePlanet, tough luck wanna-be-Person that has a different HomePlanet than Earth; you'll have to add a column in at a later date or the data can't be stored in the RDBMS.  Most programmers make assumptions like this in their apps anyway, so this isn't a dumb thing to assume and enforce.  Defining things can be good.  But if you need to log additional attributes in the future, you'll have to add them in.  The relation model assumes that your data attributes won't change much.
"Cloud" type databases using something like MapReduce, in your case CouchDB, do not make the above assumption, and instead look at data from the bottom-up.  Data is input in documents, which could have any number of varying attributes.   It assumes that your data, by its very definition, is diverse in the types of attributes it could have.  It says, "I just know that I have this document in database Person that has a HomePlanet attribute of "Eternium" and a FirstName of "Lord Nibbler" but no LastName."  This model fits webpages:  all webpages are a document, but the actual contents/tags/keys of the document vary soo widely that you can't fit them into the rigid structure that the DBMS pontificates from upon high.  This is why Google thinks the MapReduce model roxors soxors, because Google's data set is so diverse it needs to build in for ambiguity from the get-go, and due to the massive data sets be able to utilize parallel processing (which MapReduce makes trivial).  The document-database model assumes that your data's attributes may/will change a lot or be very diverse with "gaps" and lots of sparsely populated columns that one might find if the data was stored in a relational database.  While you could use an RDBMS to store data like this, it would get ugly really fast.
To answer your question then:  you can't think "relationally" at all when looking at a database that uses the MapReduce paradigm.  Because, it doesn't actually have an enforced relation.  It's a conceptual hump you'll just have to get over.

A good article I ran into that compares and contrasts the two databases pretty well is MapReduce: A Major Step Back, which argues that MapReduce paradigm databases are a technological step backwards, and are inferior to RDBMSes.  I have to disagree with the thesis of the author and would submit that the database designer would simply have to select the right one for his/her situation.

A: One thing you can try is getting a copy of firefox and firebug, and playing with the map and reduce functions in javascript. they're actually quite cool and fun, and appear to be the basis of how to get things done in CouchDB
here's Joel's little article on the subject : http://www.joelonsoftware.com/items/2006/08/01.html


Q: Why would you use Ramda's lenses over evolve/path? Is there some functionality that lenses offer that you cannot get with path/assocPath/evolve/adjust?


Q: rx_polarity inversion in USB3.x As per USB3.x specification there is provision of
rx_polarity_inversion
can any one exactly says, what is the reason behind it?
Edit:
Normally connection of Host and Device's Data +/- line connection is like shown in figure. But polarity inversion gives facility, if connected wires are reversed any how, or intentionally reverse connected then also it can work.
But apart from this, it is used for something else, it has some advantage or importance. What was that?

A: The receiver inversion is available primarily for ease of PCB routing to maintain signal integrity.
This feature is also available on PCI express.
Consider an interconnect where you have this situation:

As you can see, we can have a situation where the polarity of the receiver port is physically the opposite of the polarity of the transmitter port; this is not an unusual thing to find, incidentally.
Without the receiver inversion facility, you would need to make these tracks take a circular path at one end or the other (to name one potential solution); with the facility, you can do a simple, clean direct connection.
This means that the path is as short as possible (always a good thing at high speed) and simplest to actually implement.
Edit: Added some details on why SI is better
Lets see what you would need to do if the receiver inversion is not available:

This is one way of attaining an interconnect without a receiver inversion capability; note that the tracks are a slightly different length - this could be fixed by adding some Serpentine adjustment, but:
If you do not add the length match, there will be a differential to common mode conversion due to the fact that the signals take a different amount of time to propagate which will cause some of the signal to radiate (so you have radiated emissions and you lose some of the signal from the tracks) and you will need to ensure that the lengths are still close enough for the receiver to operate.
If you do add the serpentine, then the differential impedance of the pair will not be the same everywhere (the traces will need to separate and the distance between the tracks is a part of the calculation of differential impedance) which will cause discontinuities, which will also cause a differential to common mode conversion.
By not having to do this, we avoid complicated tracking that has the potential to degrade the signal.
Note that serpentining can also have crosstalk implications (depending on the specific application).
Updated to include (and expand on) the excellent point from Alex:
Depending on the location of the parts, it may not be possible to route around the PCB properly, and as high speed signals of this nature should really be given single layer routing (i.e. there are vias at the break-out points at the IC only if an internal layer is used so that the signals do not change layers going across the board: it can be done with layer changes, but can cause all manner of 'interesting' effects).
Note that when changing layers with high speed signals, there is guaranteed to be some impedance discontinuity as no two layers on a real PCB will actually have the same impedance on a controlled impedance board. There are also issues with ensuring the return path also transitions through the PCB near the signals (taking up even more PCB real estate).
Taking the references through the board to maintain controlled impedance through vias is somewhat of an art form, incidentally.
To achieve single layer routing may require adding layers (and therefore cost) to the PCB.


Q: Cocos2D: Multiple actions: CCMoveTo CCAnimate I don´t understand, I absolutely cannot get this to work, I want a sequence of actions that plays an animation and moves the sprite using the CCAnimate ans CCMoveTo classes. Is there a bug or something special about these classes, cause it will not move nor animate when stringing it together in a CCSequence of actions like this.
    action = [CCSequence actions:
                              [CCMoveTo actionWithDuration:moveDuration position:touchLocation],
                              [CCAnimate actionWithAnimation:self.walkingAnim],
                              [CCCallFunc actionWithTarget:self selector:@selector(objectMoveEnded)], nil];
 [self runAction:action];

I

A: If you want the move and animate action to run paralel you can use:
Option1:  use CCSpawn instead of a CCSequence. CCSequence is needed because you would like to call a function after completion.
id action = [CCSpawn actions:
                              [CCMoveTo actionWithDuration:moveDuration position:touchLocation],
                              [CCAnimate actionWithAnimation:self.walkingAnim],
                               nil];

id seq = [CCSequence actions:
                              action,
                              [CCCallFunc actionWithTarget:self selector:@selector(objectMoveEnded)],
                               nil];

[self runAction:seq];

Option2: just add any action multiple times and will be run in paralel. Because of the func-call a CCSequence again needed:
id action = [CCSequence actions:
                              [CCMoveTo actionWithDuration:moveDuration position:touchLocation],
                              [CCCallFunc actionWithTarget:self selector:@selector(objectMoveEnded)],
                               nil];
[self runAction:action];
[self runAction:[CCAnimate actionWithAnimation:self.walkingAnim]];

A: What this sequence does is:

*

*move self to the destination

*once arrived at destination, play the walking animation

*when the walk animation is finished, run the selector

I bet you meant to run the move and animate actions separately and at the same time (each with their own call to runAction) and not within a sequence.


Q: Theoretical framework for a divergent random series Consider the following random variables

*

*The $\{m_n\}_{n\geq 1}$ are iid and satisfy
$$\mathbb{P}(m_{n}\leq x)\leq C x$$
for $x>0$ and some $C>0$.

*The $\{L_{n,m}\}_{m\geq n\geq 1}$ satisfy $L_{n,m}\stackrel{law}{=}L_{1,m-n+1}$ and the concentration
$$\mathbb{P}(L_{n,m}\geq u)\leq \frac{1}{u^{q}}\rho^{(m-n-\frac{1}{2})b},$$
where $0<\rho<1$, $q>1$ and $b>1$. The $L_{n_{1},m_{1}}$ and $L_{n_{1},m_{1}}$ are independent iff $n_{1}>m_{2}$ or $n_{2}>m_{1}$. Let
$$\sigma_{n}:=(1+\sum_{m=n+1}^{\infty}L_{n,m})^{-1}.$$

*The $\{t_{n,k}\}_{n> k \geq 0}$ satisfy $t_{n,k}\stackrel{law}{=}t_{n-k+1,1}$ and the concentration
$$\mathbb{P}(t_{n,k}\geq u)\leq c \exp\left(-\frac{u^{2}}{c \rho^{n-k-\frac{1}{2}}}\right),$$
where $0\leq k< n$, $0<\rho<1$ and $c>0$. The $t_{n_{1},k_{1}}$ and $t_{n_{2},k_{2}}$ are independent iff $k_{1}\neq k_{2}$. Let
$$s_{n}:=\exp\left(-\sum_{k=0}^{n-1}t_{n,k}\right).$$
Then we have the result
$$\mathbb{P}\left[\sum_{n=1}^{N}m_{n}\sigma_{n}s_{n}\leq c_{0}N\right]\leq \rho^{pN},$$
where $p>1$ and $\rho\in (0,1)$.

Q: The proof of this is a long brute force computation without the use of any theorems. However, we are hoping to find some theoretical framework that will reveal why this statement is true.

You can find the computation in section 4.3 pg 25 of the random conformal weldings paper.


Q: Could not display data from php mysql in listview java Please help im new in java...
im not able to display data in listview
PHP side
    <?
    $objConnect = mysql_connect("my server","username here"," my password");
    $objDB = mysql_select_db("db");

    $strSQL = "SELECT * FROM image WHERE 1  ";
    $objQuery = mysql_query($strSQL);
    $intNumField = mysql_num_fields($objQuery);
    $resultArray = array();
    while($obResult = mysql_fetch_array($objQuery))
    {
        $arrCol = array();
        for($i=0;$i<$intNumField;$i++)
        {
            $arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
        }
        array_push($resultArray,$arrCol);
    }

    mysql_close($objConnect);

    echo json_encode($resultArray);
?>

I have 3 layout
main layout
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F3E70D" >

   <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:orientation="vertical"
         android:padding="10dip" >

       <TextView
           android:id="@+id/tvordername"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textColor="#000000"
           android:textStyle="bold"
           android:text="TextView" />

       <TextView
           android:id="@+id/textView2"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="TextView" />

       <ListView
           android:id="@+id/listView1"
           android:layout_width="match_parent"
           android:layout_height="wrap_content" >
       </ListView>

   </LinearLayout>

</ScrollView>

Second layout
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tableLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TableRow
        android:id="@+id/tableRow3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <ImageView
            android:id="@+id/ColImgPath"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <TextView
            android:id="@+id/ColImgID"
            android:text="Column 1" />
        <TextView
            android:id="@+id/ColImgDesc"
            android:text="Column 2" />
    </TableRow>
</TableLayout>

Third layout is use to display more detail and single record
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/fullimage"
        android:layout_width="match_parent"
        android:layout_height="245dp"/>
    <TextView
        android:id="@+id/custom_full_order"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        >

    </TextView>
</LinearLayout>

Java side my complete code
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.android.library.DatabaseHandler;
import com.example.android.library.UserFunctions;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class OrderActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order);

        //listview
        final ListView lstview1 = (ListView)findViewById(R.id.listView1);

        String url = "my server address http:";

        try{
            JSONArray data = new JSONArray(getJSONUrl(url));

            final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String>map;

            for(int i= 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);
                map = new HashMap<String, String>();
                map.put("ImageID", c.getString("ImageID"));
                map.put("ImageDesc", c.getString("ImageDesc"));
                map.put("ImagePath", c.getString("ImagePath"));
                MyArrList.add(map);
            }

            lstview1.setAdapter(new ImageAdapter(this,MyArrList));

            final AlertDialog.Builder imageDialog = new AlertDialog.Builder(this);
            final LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);

            lstview1.setOnItemClickListener(new OnItemClickListener(){

                public void onItemClick(AdapterView<?> parent, View v,
                        int position, long id) {
                    // TODO Auto-generated method stub
                    View layout = inflater.inflate(R.layout.custom_fullorder_dialog, (ViewGroup) findViewById(R.id.fullimage));
                    ImageView image = (ImageView) layout.findViewById(R.id.fullimage);
                try
                {
                    image.setImageBitmap(loadBitmap(MyArrList.get(position).get("Imagepath")));
                } catch (Exception e){
                    //if get error
                    image.setImageResource(android.R.drawable.ic_menu_report_image);
                }
                imageDialog.setIcon(android.R.drawable.btn_star_big_on);
                imageDialog.setTitle("View : " + MyArrList.get(position).get("comment"));
                imageDialog.setView(layout);
                imageDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                });
                    imageDialog.create();
                    imageDialog.show();
                }

            });
        } catch(JSONException e){
            e.printStackTrace();
        }

    }

    public class ImageAdapter extends BaseAdapter
    {
        private Context context;
        private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

        public ImageAdapter(Context c, ArrayList<HashMap<String, String>> list){

            context = c;
            MyArr = list;
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return MyArr.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if(convertView == null){
                convertView = inflater.inflate(R.layout.activity_column, null);
            }
            //colimage
            ImageView imageView =(ImageView) convertView.findViewById(R.id.ColImgPath);
            imageView.getLayoutParams().height= 100;
            imageView.getLayoutParams().width= 100;
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            try
            {
                imageView.setImageBitmap(loadBitmap(MyArr.get(position).get("ImagePath")));

            } catch (Exception e){
                //if get error
                imageView.setImageResource(android.R.drawable.ic_menu_report_image);
            }

            //colposition
            TextView txtPosition = (TextView) convertView.findViewById(R.id.ColImgID);
            txtPosition.setPadding(10, 0, 0, 0);
            txtPosition.setText("ID : " + MyArr.get(position).get("ImageID"));

            //colpicname
            TextView txtPicName = (TextView) convertView.findViewById(R.id.ColImgDesc);
            txtPicName.setPadding(50, 0, 0, 0);
            txtPicName.setText("DEesc : " + MyArr.get(position).get("ImageDesc"));

            return convertView;
        }

    }
    //get json code from url
    public String getJSONUrl(String url){
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try{
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if(statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while((line = reader.readLine()) != null){
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download file...");
            }
        } catch (ClientProtocolException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

    //get image resource from url
    private static final String TAG = "ERROR";
    private static final int IO_BUFFER_SIZE = 4 * 1024;
    public static Bitmap loadBitmap(String url){
        Bitmap bitmap = null;
        InputStream in = null;
        BufferedOutputStream out = null;

        try {
            in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

            final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
            out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
            copy(in,out);
            out.flush();

            final byte[] data = dataStream.toByteArray();
            BitmapFactory.Options options = new BitmapFactory.Options();
            //options.inSamplesize=1;

            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);
        } catch (IOException e){
            Log.e(TAG, "Could not load Bitmap from: " + url);
        } finally {
            closeStream(in);
            closeStream(out);
        }
        return bitmap;
    }

    private static void closeStream(Closeable stream){
        if(stream != null) {
            try{
                stream.close();
            } catch (IOException e){
                android.util.Log.e(TAG, "Could not close stream", e);
            }
        }
    }

    private static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[IO_BUFFER_SIZE];
        int read;
        while ((read = in.read(b)) != -1){
            out.write(b, 0, read);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.order, menu);
        return true;
    }

}

my logcat
01-26 21:58:35.594: W/System.err(14298): org.json.JSONException: Value <? of type java.lang.String cannot be converted to JSONArray
01-26 21:58:35.594: W/System.err(14298):    at org.json.JSON.typeMismatch(JSON.java:111)
01-26 21:58:35.594: W/System.err(14298):    at org.json.JSONArray.<init>(JSONArray.java:96)
01-26 21:58:35.594: W/System.err(14298):    at org.json.JSONArray.<init>(JSONArray.java:108)
01-26 21:58:35.594: W/System.err(14298):    at com.example.androidjhfong.OrderActivity.onCreate(OrderActivity.java:77)
01-26 21:58:35.594: W/System.err(14298):    at android.app.Activity.performCreate(Activity.java:5231)
01-26 21:58:35.599: W/System.err(14298):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.access$800(ActivityThread.java:144)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
01-26 21:58:35.599: W/System.err(14298):    at android.os.Handler.dispatchMessage(Handler.java:102)
01-26 21:58:35.599: W/System.err(14298):    at android.os.Looper.loop(Looper.java:136)
01-26 21:58:35.599: W/System.err(14298):    at android.app.ActivityThread.main(ActivityThread.java:5139)
01-26 21:58:35.599: W/System.err(14298):    at java.lang.reflect.Method.invokeNative(Native Method)
01-26 21:58:35.599: W/System.err(14298):    at java.lang.reflect.Method.invoke(Method.java:515)
01-26 21:58:35.599: W/System.err(14298):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
01-26 21:58:35.599: W/System.err(14298):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
01-26 21:58:35.599: W/System.err(14298):    at dalvik.system.NativeStart.main(Native Method)
01-26 21:58:35.719: I/Timeline(14298): Timeline: Activity_idle id: android.os.BinderProxy@423fd758 time:785573323

A: You have real mess in your code. Firstly you shouldn't connect to web in main thread (it blocks app, cause "application not responding"). For fetching JSON I would recommend RoboSpice.
Secondly in ImageAdapter.getItem you should return MyArr.get(position) not position.

A: I think greenapps and MAGx2 have the right hints for the solution.
I'd like to add that it might be better to use a few open source libraries for the other things.

*

*picasso for image downloading + displaying

*gson for json parsing

*okhttp for normal downloads

Also, don't use things like this:
imageView.getLayoutParams().height= 100;

It really messes up when you view on other devices with different DPI