Q: Cucumber ordering of Given, When, Then (Given, When, Then, When, Then) As an End-to-end Automation Tester I have always assumed that Given, When, Then statements (incorporated in the Gherkin Language when using Cucumber) should only ever appear in the order of 1. Given, 2. When, 3. Then.
i.e. A test should not follow, for example, Given, When, Then, When, Then.  And instead should follow Given, When, Then only.
The reason for this assumption was along the lines of a single test only testing one area of the application.
However, I noticed on some gherkin examples on the web, that they use the following ordering sometimes: Given, When, Then, When, Then.
Does anyone know if this moving back to Whens after writing a Then is acceptable best practice?  I appreciate the test will still work, just wondering if this is good or bad practice.

A: Although scenarios can be written in that way, it is not best practice. I for one, have made that mistake and it can cause problems in reports and maintenance.
One reason would be that When declares an action and Then verifies the result of that action. Having When - Then twice goes against the individual behavior of a scenario.
Can also get confusing for someone who reads the scenario :)
Here's a little post regarding this

A: There is alot of really bad Gherkin on the web. Also there is a range of opinions about what good Gherkin is.
My opinion is that When Then When Then is an anti-pattern. Its likely that one of the following is required

*

*You need a better Given to incorporate the first When Then

or

*You need to split the scenario in two.

In general most When's in scenario's become Given's in later scenario's, as you build on existing behaviour to define and create new behaviour.

A: Syntactically Interchangeable; Linguistically Different
The Gherkin syntax currently includes six keywords for describing feature steps:

*

*Given

*When

*Then

*And

*But

**
The keywords are there for human consumption and the ease of conveying business logic. However, the Gherkin language itself treats the keywords as interchangeable symbols, so you could just as grammatically (from a Gherkin point of view) write tortured English like:

But for a dollar held
  Then another dollar more
  Given ownership of two dollars am I.

This is perfectly valid Gherkin, but a terrible representation of counting money. So, if all the words are interchangeable, why have so many of them?
The wiki is quite clear that they provide a set of conventions to facilitate communication in a more natural style, and the wiki even gives a few examples of how the words are meant to be differentiated. The wiki also specifically says:

Cucumber doesn’t technically distinguish between these...[kinds] of steps. However, we strongly recommend that you do! These words have been carefully selected for their purpose, and you should know what the purpose is to get into the BDD mindset.

In other words, use the Gherkin terms to communicate in (relatively) natural language about your feature, and bury the arcana in step definitions. Use whatever keyword fits most naturally in the linguistic flow, and don't sweat a well-written scenario that doesn't rigidly adhere to a convention that may not apply in all cases.


Q: Template or function arguments as implementation details in doxygen? In doxygen is there any common way to specify that some C++ template parameters of function parameters are implementation details and should not be specified by the user ?
For example, a template parameter used as recursion level counter in metaprogramming technique or a SFINAE parameter in a function ?
For example :
/// \brief Do something
/// \tparam MyFlag A flag...
/// \tparam Limit Recursion limit
/// \tparam Current Recursion level counter. SHOULD NOT BE EXPLICITELY SPECIFIED !!!
template<bool MyFlag, unsigned int Limit, unsigned int Current = 0> myFunction();

Is there any doxygen normalized option equivalent to "SHOULD NOT BE EXPLICITELY SPECIFIED !!!" ?

A: It seems to me that the whole template is an implementation detail of a different interface:
template<bool MyFlag, unsigned int Limit, unsigned int Current = 0> myFunctionImpl();

template<bool MyFlag, unsigned int Limit> myFunction() {
   myFunctionImpl<MyFlag, Limit, 0>();
}

Now it becomes easier to document: myFunction() (and all it's arguments) are part of the interface, which does not include the iteration counter. myFunctionImpl() is the implementation of that interface and does not need to be documented at all (or only minimally with a comment stating that it is an implementation detail and user code should not depend on it or use it directly). If you want, you can enclose the implementation in an #ifdef block so that the doxygen preprocessor removes it and it does not appear in the generated documentation.

A: One option to convey that a parameter should not be specified would be to hide it in the documentation. For example you could conditionally compile out the internal parameters:
/// \brief Do something
/// \tparam MyFlag A flag...
/// \tparam Limit Recursion limit
template<bool MyFlag, unsigned int Limit
#if !defined(DOXYGEN)
        , unsigned int Current = 0
#endif
> myFunction();

This would prevent them from appearing in the documentation, but they would still be available to the implementation.


Q: How to remove black canvas from image in TensorFlow I'm currenly trying working with tensorflow dataset 'tf_flowers', and noticed that a lot of images consist mostly of black canvas, like this:
flower1
flower2
Is there any easy way to remove/or filter it out? Preferably it should work on batches, and compile into a graph with @tf.function, as I plan to use it also for bigger datasets with dataset.map(...)

A: The black pixels are just because of padding. This is a simple operation that allows you to have network inputs having the same size (i.e. you have batches containing images with the of size: 223x221 because smaller images are padded with black pixels).
An alternative to padding that removes the need of adding black pixels to the image, is that of preprocessing the images by:

*

*removing padding via cropping operation

*resizing the cropped images to the same size (e.g. 223x221)

You can do all of these operations in simple python, thanks to tensorflow map function. First, define your python function
def py_preprocess_image(numpy_image):
    input_size = numpy_image.shape  # this is (223, 221)
    image_proc = crop_by_removing_padding(numpy_image)
    image_proc = resize(image_proc, size=input_size)
    return image_proc

Then, given your tensorflow dataset train_data, map the above python function on each input:
# train_data is your tensorflow dataset
train_data = train_data.map(
                 lambda x: tf.py_func(preprocess_image,
                                      inp = [x], Tout=[tf.float32]),
                 num_parallel_calls=num_threads
             )

Now, you only need to define crop_by_removing_padding and resize, which operate on ordinary numpy arrays and can thus be written in pure python code. For example:
def crop_by_removing_padding(img):
    xmax, ymax = np.max(np.argwhere(img), axis=0)
    img_crop = img[:xmax + 1, :ymax + 1]
    return img_crop

def resize(img, new_size):
    img_rs = cv2.resize(img, (new_size[1], new_size[0]), interpolation=cv2.INTER_CUBIC)
    return img_rs


Q: Hazelcast file persistence (MapStore implementation) I am using Hazelcast for clustered data distribution. I read in the documentation about data persistence, using the interfaces MapStore and MapLoader. I need to implement these interfaces and write the class name in the hazelcast.xml file.
Is there any example of implementation of these interfaces for file persistence with hazelcast? Does anyone know about any source code or jar file that I can download and work with?
Thanks

A: You can implement your own just using ObjectOutputStream  and ObjectInputStream.
You can create a directory with map's name.
store(key, value) operation creates a file with name key.dat, with content of serialized value.
load(key) method reads "key.dat" file into an object and returns.
Here usage examples of  ObjectOutputStream  and ObjectInputStream
http://www.mkyong.com/java/how-to-write-an-object-to-file-in-java/
http://www.mkyong.com/java/how-to-read-an-object-from-file-in-java/
Then you should add this implementation class to your class path and set it in your hazelcast.xml


Q: navLinkDayClick of FullCalendar Did anyone use navLinkDayClick of FullCalendar and call a custom event (by fetching data from database) based on the date selection?
I am using eventClick to populate the calendar data however I am unable to do so for individual dates after setting the navLinks to true.
Everything above navLinkDayClick works fine.

function FetchEventAndRenderCalendar() {method contains to fetch all event from database}

function FetchTotalAmount() { method calls a SP to get the total amount for that day of the calendar}. This also contains the method to generate the calendar which is given below.

function GenerateCalender(events) - events are the ones that are fetched in the first method.

function GenerateCalender(events) {
..................
..................
events: events,
eventClick: function (calEvent) {
var selectedCalendarEvent = calEvent;
$('#calendarModal #eventTitle').text(calEvent.title);
..................
..................
navLinks: true,
navLinkDayClick: function() {
how to use this to show the total amount for that day of the calendar when the date is selected?
}

A: navLinkDayClick in FullCalendar v3.8 -

navLinks: true,
navLinkDayClick: function (date) {
selectedDate = date.format("DD-MMM-YYYY");
selectedAmountEvent = amounts.find(item => item.paymentDate.format("DD-MMM-YYYY") === selectedDate);
var $AmountData = $('
');
$AmountData.append($('
').html('Payment Date: ' + selectedAmountEvent.paymentDate.format("DD-MMM-YYYY")));
if (selectedAmountEvent.totalAmount < 0) {
    $AmountData.append($('
').html('Total Amount: ' + selectedAmountEvent.totalAmount + ' $' + ''));
}
else {
    $AmountData.append($('
').html('Total Amount: ' + selectedAmountEvent.totalAmount + ' $' + ''));
}

$('#eventModal #AmountDetails').empty().html($AmountData);

$('#eventModal').modal();
}

amounts is an array holding the data.


Q: Ruby thread safe thread creation I came across this bit of code today:
@thread ||= Thread.new do
  # this thread should only spin up once
end

It is being called by multiple threads. I was worried that if multiple threads are calling this code that you could have multiple threads created since @thread access is not synchronized. However, I was told that this could not happen because of the Global Interpreter Lock. I did a little bit of reading about threads in Ruby and it seems like individual threads that are running Ruby code can get preempted by other threads. If this is the case, couldn't you have an interleaving like this:
Thread A             Thread B
========             ========
Read from @thread    .
Thread.New           .
[Thread A preempted] .
.                    Read from @thread
.                    Thread.New
.                    Write to @thread
Write to @thread

Additionally, since access to @thread is not synchronized are writes to @thread guaranteed to be visible to all other threads? The memory models of other languages I've used in the past do not guarantee visibility of writes to memory unless you synchronize access to that memory using atomics, mutexes, etc.
I'm still learning Ruby and realize I have a long way to go to understanding concurrency in Ruby. Any help on this would be super appreciated!

A: You need a mutex. Essentially the only thing the GIL protects you from is accessing uninitialized memory. If something in Ruby could be well-defined without being atomic, you should not assume it is atomic.
A simple example to show that your example ordering is possible. I get the "double set" message every time I run it:
$global = nil
$thread = nil

threads = []

threads = Array.new(1000) do
  Thread.new do
    sleep 1
    $thread ||= Thread.new do
      if $global
        warn "double set!"
      else
        $global = true
      end
    end
  end
end

threads.each(&:join)


Q: Spotify API device list empty after short inactivity period I'm trying to use the Spotify API for a personal project.
My problem is that the "devices" endpoint that normally returns a list of my available devices (my phone) returns an empty array if I swipe out of the Spotify app for a short while before requesting the device list.
For example:
I open the Spotify app in my phone. I send a Postman request to the "devices" endpoint of the Spotify API and confirm that my phone is listed as an available device for playback. I then swipe out of the Spotify app, into another app and click around there for 30 seconds or so. I then send the same Postman request to the "devices" endpoint and receive an empty array. My phone is immediately forgotten after a short period of inactivity in the Spotify app, and thus any requests to play a song etc. fail since no available device is found.
Has anyone managed to force their device to stay on the API's radar, or found a way to "wake" their device before sending a request that targets it to the API?
I am currently using iOS.
Thanks.


Q: Android Polyline - Adding point by point I'm currently having a map, and each 10 meters I use LocationListener to refresh my location and get the new Latitude and Longitude. Now I wish that the route the user is taking will be displayed with a red line. So everytime the OnLocationChange() from LocationListener class is called, I want to update the map with a line between the last location and the new location.
So far I've added the following:
private void initializeDraw() {
    lineOptions = new PolylineOptions().width(5).color(Color.RED);
    lineRoute = workoutMap.addPolyline(lineOptions);
}

during the OnLocationChanged I call this:
drawTrail();

now what should I insert into this function so that each time it adds the newly attained location as a point and draws a line from the last to the new point.
Thanks

A: First translate Location into LatLng:
LatLng newPoint = new LatLng(location.getLatitude(), location.getLongitude());

Then add a point to existing list of points:
List<LatLng> points = lineRoute.getPoints();
points.add(newPoint);
lineRoute.setPoints(points);


Q: How to get the current (working) directory in Scala? How can I get the current directory (working directory) of the executing program in Scala?

A: Use this:
import scala.reflect.io.File
File(".").toAbsolute

A: I use new java.io.File(".").getAbsolutePath, but all the other answers work too. You don't really gain anything by using Scala-specific API here over regular Java APIs

A: import scala.sys.process._
val cwd = "pwd".!!  //*nix OS

A: Use this
System.getProperty("user.dir")
Edit:
A list of other standard properties can be found here. https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

A: Use java.nio:
import java.nio.file.Paths
println(Paths.get(".").toAbsolutePath)

Remark on scala.reflect.io.File: I don't see any reason to look into scala.reflect packages for such mundane tasks. Getting the current working directory has usually nothing to do with Scala's reflection capabilities. Here are more reasons not to use scala.reflect.io.File: link.

A: os-lib makes it easy to get the current working directory and perform other filesystem operations.  Here's how to get the current directory:
os.pwd

It's easy to build other path objects from os.pwd, for example:
os.pwd/"src"/"test"/"resources"/"people.csv"

The syntax is intuitive and easy to remember, unlike the other options.  See here for more details on how to use the os-lib project.


Q: Colspan in Backendlayout not working (TYPO3 8.7 LTS) The 3 columns in my backendlayout should be equal size, independent of their content. In my case their width get determined by their content though. Glad about any hints!
Environment:

*

*TYPO3 8.7.0

*PHP 7.0.13

*MySQL 5.6.34
Installed Extensions:

*

*gridelements dev-master c5120b0e

*realurl 2.2.0

*slickcarousel 8.x-dev

*vhs 4.1.0
The TS was generated using the wizard. It is a 3 columns layout with 2 rows. The second row has 3 cols (colspan = 1) and the first one has 1 col (colspan = 3).
mod.web_layout.BackendLayouts {
MainTemplate {
    title = MainTemplate
    name = MainTemplate
    icon = EXT:amtemplate/ext_icon.png
    config {
        backend_layout {
            colCount = 6
            rowCount = 2
            rows {
                1 {
                    columns {
                        1 {
                            name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.sliderarea
                            colPos = 1
                            colspan = 6
                        }
                    }
                }
                2 {
                    columns {
                        1 {
                            name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.left
                            colPos = 2
                            colspan = 2
                        }
                        2 {
                            name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.main_content
                            colPos = 0
                            colspan = 2
                        }
                        3 {
                            name = LLL:EXT:amtemplate/Resources/Private/Language/locallang.xlf:amtemplate_be_layout_maintemplate.right
                            colPos = 3
                            colspan = 2
                        }
                    }
                }
            }
        }
    }
}
}

A: Worked here in 8.7.1 without any problems. Maybe you wann update to the latest release?

A: There are two different concepts you are mixing up here, namely colspan and width.
The colspan attribute is used to tell a cell of a table how many of the other cells of another row it should overlap. So this has nothing to do with fixed widths even though it might feel like that, when you got the same content in each cell or no content at all. As soon as you fill the table cells with different content, the width of each cell might differ even though some of these cells might use the same colspan value.
So colspan actually just defines the relation between the cells but not their width. Still the core somehow circumvents that behaviour by applying min and max width values to several parts of the page module via CSS, so the cells will stay within a certain width range.
Now that you have installed gridelements, there can not be such a range anymore, because there might be nested grid structures that have to consume way more space. So gridelements uses a CSS removing that range and thereby restores the default behaviour of HTML table cells.


Q: Android OpenGL ES app crashes logging back in I'm using OpenGL ES 2.0 on Android to make a basic game. I discovered that if I hit the home key on my device (emulator or real device) when the GLSurfaceView is present and then log back into the app from the Android home screen the app will crash. In contrast, if I I hit the back key while the GLSurfaceView is present which then takes me back to my MainActivity / MainView then everything is fine. I assume this has to do with how the GL Thread is managed, and when I close the app immediately the state is saved as opposed to being popped off the activity stack like when I hit the back button to go to my MainActivity.
My question is how should I best deal with destroying the GLSurfaceView state information? If the user hits the home key I want the information to reset and not be saved. Should I override onStop in the class that implements GLSurfaceView.Renderer and delete the GLSL program?
I can give a rough picture of how my activites are laid out below.
MainActivity class:
public MainActivity extends Activity
     GameView view;
     public onCreate ( ... ) { }
GameView class:
public GameView extends GLSurfaceView
  Renderer renderer;
  public onCreate (...) { // set EGL information and renderer };
Renderer class:
public Renderer implements GLSurfaceView.Renderer
    // implements the surface change, created, and draw methods

A: Make sure that your android version supports OpenGL ES 2.0 rendering on it's background state. Because whenever you press the home key app enters background state and gives background thread for your application, that may cause crashes. Mostly in iOS and android it is best to identify the app state and pause the rendering in background state.  Refer further in  this link Run Android OpenGL in Background as Rendering Resource for App?

A: I found out that I needed to override the 'onSurfaceDestroyed( SurfaceHandle handle) method in the class that extends GLSurfaceView and clean up my resources.
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
    super.surfaceDestroyed(holder);
    ResourceManager.getInstance().cleanUp();
}


Q: How to Update a MYSQL Column Based On Varying Conditions I need to update a MYSQL Table
Here is a very simple look at Table_A
ID  VALUE  RESULT
1   4      0
2   2      0
3   7      0

I want to update the RESULT Column based on conditions
So my query statement needs to look something like
UPDATE Tabel_A
SET RESULT = (if some condition) 1
             OR (if another condition) 2
             OR (if a different condition) 3

Or should I use something like
UPDATE Tabel_A
SET RESULT = (CASE 1) 1
             (CASE 2) 2
             (CASE 3) 3

I am not sure how to structure the query
Thanks

A: I'll prefer to use CASE here.
UPDATE TAble1
SET Result = CASE value
                WHEN 1 THEN x
                WHEN 2 THEN y
                ....
                ELSE z
            END

or
UPDATE TAble1
SET Result = CASE
                WHEN value = 1 THEN x
                WHEN value = 2 THEN y
                ....
                ELSE z
            END


Q: [Android - Kitkat ]Get/pick an image from Android's built-in Gallery app programmatically Try to pick only one particular image from the SD card.I am able to pick images from gallery and Photos app in kikat.But not getting file path when i pick image from recents am getting file path as null.
I tried https://stackoverflow.com/a/2636538/1140321.

A: This works for Kitkat
public class BrowsePictureActivity extends Activity{

private static final int SELECT_PICTURE = 1;

private String selectedImagePath;
private ImageView imageView;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.browsepicture);
    imageView = (ImageView)findViewById(R.id.imageView1);

    ((Button) findViewById(R.id.button1))
            .setOnClickListener(new OnClickListener() {

                public void onClick(View arg0) {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,
                            "Select Picture"), SELECT_PICTURE);
                }
            });
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            Uri selectedImageUri = data.getData();
            if (Build.VERSION.SDK_INT < 19) {
                selectedImagePath = getPath(selectedImageUri);
                Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
                imageView.setImageBitmap(bitmap);

            }
            else {
                ParcelFileDescriptor parcelFileDescriptor;
                try {
                    parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageUri, "r");
                    FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                    Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
                    parcelFileDescriptor.close();
                    imageView.setImageBitmap(image);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

/**
 * helper to retrieve the path of an image URI
 */
public String getPath(Uri uri) {
        if( uri == null ) {
            return null;
        }
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if( cursor != null ){
            int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        return uri.getPath();
}

}

You need to add permission
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


Q: only rotate button and not it's text on button click I rotate a button on click:
<button class="btn" type="button">Go</button>

css:
.btn:focus {
  transform: rotate(180deg);
}

now the problem is txt also rotates on btn click. How can I don't rotate the txt or rotate it 360 on button click?

A: Wrap the button text in a span, and rotate that on :focus of the button by another 180 degree:

.btn:focus {
  transform: rotate(180deg);
}

.btn:focus span {
  display: inline-block;
  transform: rotate(180deg);
}
<button class="btn" type="button">Go</button>

A: Wrap the text with a span and rotate it to the other direction:

.btn:focus {
  transform: rotate(180deg);
}

.btn:focus > span {
  display: block;
  transform: rotate(-180deg);
}
<button class="btn" type="button">
  Go
</button>


Q: SiteMapPath not working with route attribute in nodes I have this xml sitemap:
<?xml version="1.0" encoding="utf-8" ?>
<mvcSiteMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0"  xsi:schemaLocation="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-4.0 MvcSiteMapSchema.xsd">
  <mvcSiteMapNode title="Home" controller="Home" action="Index" key="home">
    <mvcSiteMapNode title="Access Control" route="AccessControl_default" controller="Home" action="Index" key="access-control">
      <mvcSiteMapNode title="My dashboard" route="AccessControl_default" controller="Dashboard" action="Index" key="dashboard"/>
       <mvcSiteMapNode title="Personnel" route="AccessControl_default" clickable="false" key="personnel">
        <mvcSiteMapNode title="Groups" route="AccessControl_default" controller="Personnel" action="Groups" key="groups"/>
        <mvcSiteMapNode title="Members" route="AccessControl_default" controller="Personnel" action="People" key="people"/>
      </mvcSiteMapNode>
    </mvcSiteMapNode>
  </mvcSiteMapNode>
</mvcSiteMap>

This is the targeted route defined in area route configuration:
context.MapRoute(
    "AccessControl_default",
    "accesscontrol/{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new[] { "UI.WebPortal.Areas.AccessControl.Controllers" }
);

Then navigation menu tree is shown with @Html.MvcSiteMap().SiteMap() but breadcrumb is not working when using @Html.MvcSiteMap().SiteMapPath(). Is it because I'm using routing explicitly? and what could be the solution?

A: While you use areas, just add area="...." to nodes under them.
...
<mvcSiteMapNode title="Groups" route="AccessControl_default" area="AccessControl" controller="Personnel" action="Groups" key="groups"/>
...


Q: iPhone -- [UITextField sizeToFit] does not always account for cursor When I call sizeToFit on a UITextfield that is being edited, the size reacts in an inconsistent way to the cursor.  Sometimes it accounts for it; sometimes it doesn't.  If it doesn't, part of the first letter is clipped.
Has anyone found a way around this?

A: I just ran into this problem (it's fixed in iOS 5). My solution was to add a 4-point padding to the width:
[textField_ sizeToFit];
textField_.frame = CGRectMake(textField_.frame.origin.x,
                              textField_.frame.origin.y,
                              CGRectGetWidth(textField_.frame) + 4,
                              CGRectGetHeight(textField_.frame));

A bit tedious but got the job done for me.


Q: Mismatch between the processor architecture I have an issue with these two famous warnings which are raised during compilation of our solution. There are many forums about these already and I read those, but they still don't solve my issue completely...
1. There was a mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "XXX", "AMD64". This mismatch may cause runtime failures. Please consider changing the targeted processor architecture of your project through the Configuration Manager so as to align the processor architectures between your project and references, or take a dependency on references with a processor architecture that matches the targeted processor architecture of your project.
2. Referenced assembly 'XXX' targets a different processor than the application.
The reason why these appear in our case is clear. Our solution is compiled as AnyCPU and we want to keep it this way, as we do not want to compile it twice (once as x86 and second as x64). However, we use external DLL which is either x86 or x64 (it is not delivered as AnyCPU).
We develop the application on 64bit windows, so we use the x64 DLL version as reference in the visual studio during development. When we deliver the application to end-users, the installer is customized to copy the proper DLL based on the platform of the target system, e.g. when it is installed on 64bit windows, it copies the x64 DLL version and when it is installed on 32bit windows, it copies the x86 DLL version. Therefore, we know that everything is finally ok, and we can ignore those messages. And therefore, I just want to make them disappear:-)
The first warning can be supressed by the following tag in the project file:
  <PropertyGroup>
    <ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>None</ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>
  </PropertyGroup>

But I did not find anywhere how to get rid of the other message? Is this possible as well?
I know that this is just small issue and I can live with that. However, there is something like "Warning Free Build Initiative" going on in my company, so I'd like to get rid of all warnings we have.
Thank you in advance for any hints,
Tomas


Q: Delete AWS Cloud formation stack with resources created by it Based on this page I can do:
aws cloudformation delete-stack \
    --stack-name my-stack

It says I can attach the command:
[--retain-resources <value>]
Does that mean that if I don't specify that line, all the resources created by the stack will be removed? I'm trying to delete everything generated by the stack, which is a lot.
How can I achieve this?
Thanks

A: Yes, those resources will be kept if you specify the [--retain-resources <value>], if you dont Cloudformation will delete all the resources in the stack name (including the nested stacks as well) you are providing given you have permissions to do. If any of the resources inside the cloudformation stack has retain policy set they won't be deleted.

During deletion, AWS CloudFormation deletes the stack but does not delete the retained resources.

From the same page aws cloudformation delete-stack
You might wanna read this too How do I retain some of my resources when I delete an AWS CloudFormation stack?
You can specify the retain policy as well in cloudformation template.


Q: What does this error "Thread 1: EXC_BAD_ACCESS (code=2, address=0x30d51fff8)" mean? How do I fix it import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var triviaLabel: UILabel!

    @IBOutlet weak var trueButton: UIButton!

    @IBOutlet weak var falseButton: UIButton!

    @IBOutlet weak var progressBar: UIProgressView!

    var quiz = [Question(text: "Blah blah", answer: "True"),
                Question(text: "Ha ha", answer: "True"),Question(text: "Bruh bruh", answer: "False")]

    var questionNumber = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        updateQuestion()
    }

    @IBAction func answerButtonPressed(_ sender: UIButton) {
        let userAnswer = sender.currentTitle
        let actualAnswer = quiz[questionNumber].answer
        if userAnswer == actualAnswer {

        } else {

        }

        if questionNumber < quiz.count-1 {
            questionNumber += 1
        }else {
            questionNumber = 0
        }
        updateQuestion()
    }

    func updateQuestion() {
        triviaLabel.text = quiz[questionNumber].text // Get the error here
        updateQuestion()
    }
}

The build succeeds and the app launches but there comes a blank screen and the error occurs. I tried mapping the label again with the storyboard. I speculate that there is some problem with the label declaration or connection.


Q: Should Context be injected with Dagger? I know it is possible to inject Context with Dagger. We can see examples here and here.
On the other end, there are numerous posts about not placing context on a static variable to avoid leaks.
Android Studio (lint) also warms about this:

Do not place Android context classes in static fields; this is a
  memory leak (and also breaks Instant Run)

I understand that by injecting a Context with Dagger, we are placing it on a singleton class, so context is somehow static. Doesn't this go against the lint warning?
Injecting the context seems to create cleaner code, since you don't have to pass it to several classes (that don't need it) so that they can further pass it to other classes that need it for some reason (getting a resource for instance).
I am just concerned that this may cause some undesired leak or breaks lint in some way.

A: You should never store/reference activity context (an activity is a context) for longer than the lifetime of the activity otherwise, as you rightly say, your app will leak memory. Application context has the lifetime of the app on the other hand so is safe to store/reference in singletons. Access application context via context.getApplicationContext().

A: If you are aware of Android lifecycles and are careful to distinguish the Application Context and the Context of Activities and Services then there is no fault injecting the Context using Dagger 2.
If you are worried about the possibility of a memory leak you can use assertions to prevent injection of the wrong Context:
public class MyActivityHelper {
     private final Context context;

     @Inject
     public MyActivityHelper (Context context) {
         if (context instanceof Application) {
              throw new IllegalArgumentExecption("MyActivityHelper requires an Activity context");
         }
     }
}

Alternatively you could use Dagger 2 Qualifiers to distinguish the two so you don't accidentally inject an app Context where an Activity Context is required. Then your constructor would look something like this:
@Inject
public class MyActivityHelper (@Named("activity") Context context) {

Note also, as per David's comment, a Dagger 2 @Singelton is not necessarily a static reference.


Q: Can a factory method pattern use different overloads I have a use case where I need to build a factory class that returns different concrete types based on an enum being passed. However, each of those types require different constructor parameters. So, in that case does it make sense to have multiple methods with different signatures, or is that not a factory pattern at all?
I'm thinking something like
class CarFactory
{
  public ModelS TeslaMaker (List<Battery> batteries){/*return ModelS*/}
  public Mustang FordMaker (Engine engine) {/*return a Mustang*/}
}

instead of say
    class CarFactory
    {
      public Car GetCar(CarType carType) //where CarType is an enum (Ford=0,Tesla=1)
      {
        switch(carType)
        {  case CarType.Ford: return new Mustang(); }//just an example
      }
    }

EDIT:
In my case I actually need to return a family of classes. So, if it's a Tesla, return a ModelS, a ModelSService, ModelSWarranty, etc. So I'm going to go with the Abstract Factory approach which will wrap the suggestions given here.

A:
So, in that case does it make sense to have multiple methods with different signatures, or is that not a factory pattern at all?

It doesn't make any sense to have a factory with specific methods. If your client code has to decide which specific method should it use, why wouldn't it call the specific car's constructor directly? In your example, factory methods would merely be wrappers over specific constructors.
On the other hand having a single factory method that is called with an enum gives your client a chance to decide dynamically which car should it create, the decision could for example be based on a database query.
There are some possible ways around your current approach.
One option would be to have a hierarchy of classes that represent constructor parameters. You don't even need the enum then because the parameter type is enough to infer which specific car should be created:
public abstract class CarCreationParams { }

public class FordCreationParams : CarCreationParams
{
    public Engine engine;
}

...

public class CarFactory
{
    public Car GetCar( CarCreationParams parms )
    {
        if ( parms is FordCreationParams )
            return new Ford( ((FordCreationParams)parms).engine );
        ...

Another option would be to think whether you really need your Fords to be created with external engines (aggregation) or rather they own their engines (composition). In the latter case, you would expose parameterless constructors to your specific car types:
public class Ford : Car
{
     public Engine engine;

     // car is composed of multiple parts, including the engine
     public Ford()
     {
          this.engine = new FordEngine();
     }

which makes the implementation of the factory much easier.

A: No that is not a good example of factor pattern. Rather if your Car class is dependent on different types of Components you can have factories for those too. E.G For Car and Engine you can have like:
    public interface ICar
    {
        IEngine Engine { get; set; }
    }

    public class Mustang : ICar
    {
        private IEngine _engine = EngineFactory.GetEngine(EngineType.Mustang);
        public IEngine Engine
        {
            get { return _engine; }
            set { _engine = value; }
        }
    }

    public class CarFactory
    {
        public ICar GetCar(CarType carType)
        {
            switch (carType)
            { case CarType.Ford: return new Mustang(); }
        }
    }

Similarly for Engine
    public interface IEngine { }

    public class MustangEngine : IEngine
    {

    }

    public class EngineFactory
    {

        public static IEngine GetEngine(EngineType engine)
        {
            switch (engine)
            { case EngineType.Mustang: return new MustangEngine(); }
        }
    }

A: In case you need different parameters for object creation(batteries for Tesla or Engine for Ford) you can choose between different solutions:
 - pass all of these parameters while creating a factory  - it will be specific factory for all types of car with such available details;
class SpecificCarFactory
{
  public SpecificCarFactory(IList<Battery> batteries, IList<Engine> engines)
  {
    //save batteries etc into local  properties
  }
  public Car GetCar(CarType carType)
  {
    switch(carType)
    {  case CarType.Ford: return new Mustang(_engines.First()); }
  }
}

*

*encapsulate parameters into class object and get them from factory method parameter;
class CarFactory
{
      public Car GetCar(CarDetail carDetail) //where CarDetails                  encapsulates all the possible car details
      {
             switch(carDetail.type)
             {  case CarType.Ford: return new Mustang(carDetail.Engine);//just an example
             }
      }
}

A: Yes, It is factory pattern.
factory pattern says to create factories of Object but let subclass decide the way to instantiate the object .
This is true in your case your deciding based on type of Enum


Q: How to set/remove attributes dynamically in c#? I am using from attribute validation in my project.
[Required(ErrorMessage = "DepartmentCode is Required")]
public string DepartmentCode { get; set; }

In some case DepartmentCode isn't required. How can I dynamically ignore Validation in my case?

A: Take a look at: Remove C# attribute of a property dynamically
Anyway I think the proper solution is to inherit an attribute from RequiredAttribute and override the Validate() method (so you can check when that field is required or not). You may check CompareAttribute implementation if you want to keep client side validation working.

A: Instead of dynamically adding and removing validation, you would be better served to create an attribute that better serves this purpose.
The following article demonstrates this (MVC3 with client-side validation too):
http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx

A: I would remove the RequiredAttribute from your model and check it once you've hit your controller and check it against whatever causes it to not be required.
If it falls into a case where it is required and the value is not filled in, add the error to the ModelState manually
ModelState.AddModelError("DepartmantCode", "DepartmantCode is Required");
You would just lose the validation on the client side this way

A: I've got round this issue in the model, in some cases it's not ideal but it's the cheapest and quickest way.
public string NonMandatoryDepartmentCode
{
    get
    {
        return DepartmentCode;
    }
    set
    {
        DepartmentCode = value;
    }
}

I used this approach for MVC when a base model I inherited contained attributes I wanted to override.


Q: Why do Spark jobs require so much memory? I am experiencing memory issues when running PySpark jobs on our cluster with YARN. YARN keeps killing my executors for running out of memory, no matter how much memory I give them, and I cannot understand the reason for that.
Example screenshot:
Screenshot from SparkUI
The amount of data that one task is processing is even slightly lower than the usually recommended 128 MB, and yet it gets killed for exceeding 10 GB (6 GB executor memory + 4 GB overhead). What is going on there?
The only answer that I keep bumping in everywhere I look is to increase the memory allocation even more, but, obviously, there is a physical limit to that at some point (and we do want to run other MapRed/Spark jobs simultaneously), so rather than increasing the memory allocation mindlessly, I would like to understand why so much memory is used.
Any help on that will be greatly appreciated! If you need any additional input from me, I'll be glad to provide it, if I can.
UPDATE: Found the culprit. By carefully restructuring and analyzing the code I managed to localize the code which is running out of memory. I use a rather complicated UDF there. I'll try and rework that bit of code, maybe it will solve the problem.


Q: Graphics rendering in thread game loop. Changing data on arrays I have two objects of 2D int arrays called:
originalMap and rendedMap which they contain numbers that correspond to the puzzle game map.
From the thread class i obtain the map array from the class call Puzzle.java and modifying the one.
   int [][] rendedMap = Puzzle.getRendedMap().getMap();
   int [][] originalMap = Puzzle.getMapObj().getMap();

This is my thread loop:
drawPuzzle(canvas, map); takes the canvas and the array and draws a map.
    while(running){
            if(!holder.getSurface().isValid())
                continue;

                    canvas = holder.lockCanvas();

                    if(runSolution && movements.size()>0){
                        executeSolution();
                        drawPuzzle(canvas, rendedMap);
                        if(finished){//checks if the execution finished
                            runSolution=false;
                        }
                    if(message.equals("No more actions") ||
                                    message.equals("Out of bounds, try again!")){
                            System.out.println(message);
                            drawPuzzle(canvas, originalMap);
                    }
                    }else{
                        drawPuzzle(canvas, originalMap);
                    }

                    drawMovements(canvas);
                    holder.unlockCanvasAndPost(canvas);
    }
}

And this is the method that i modify the array:
public void executeSolution(){

    numOfPlanets = 2;

    for(int x=0;x<rendedMap.length-1; x++){
        for(int y=0;y<rendedMap[x].length-1; y++){
            //Checks where the robot is and saves its initial position
            if(rendedMap[x][y]>=7 && rendedMap[x][y]<=9){
                initX=x; initY=y; initial=true;
                System.out.println("Initial X: "+initX +" Y: "+initY );
                direction = rendedMap[x][rendedMap[x].length-1];
                System.out.println("Direction: "+direction );
            }
        }//end inner for
    }//end for

    if(movements.size()>0){
        for(int i=0; i<movements.size();i++){

            if(movements.get(i).getColour().equals("none")){
                if(movements.get(i).getMotion().equals("straight")){
                    if(direction==RIGHT){
                        if(rendedMap[initX][initY+1]==0){
                            finished=true;
                            message = "Out of bounds, try again!";
                            return;
                        }else{
                            rendedMap[initX][initY+1]= rendedMap[initX][initY+1]+6;
                            rendedMap[initX][initY]=rendedMap[initX][initY]-6;
                        }
                    }
                }//action if
            }//color if
        }//movements for loop

        if(numOfPlanets > 0 ){
            finished = true;

            message ="No more actions";
        }
    }//movements if statement
}

My problem is when i render the renderMap array for some reason originalMap changes as well and when i am trying to draw back the originalMap it doesn't change back.
I have even print them out and checked line by line and they are the same.
Any tips what might cause this?
I spend like days to figure it out.

A: if(direction==RIGHT) {
    if(rendedMap[initX][initY+1]==0) {
        finished=true;
        message = "Out of bounds, try again!";
        return;
    } else {
        rendedMap[initX][initY+1]= rendedMap[initX][initY+1]+6;
        rendedMap[initX][initY]=rendedMap[initX][initY]-6;
    }
}

check your rendedMap array is been initialized because this can often lead to contextual errors, especially within the android IDE.

A: if(!holder.getSurface().isValid())
                continue;

                    canvas = holder.lockCanvas();

                    if(runSolution && movements.size()>0){
                        executeSolution();
                        drawPuzzle(canvas, rendedMap);
                        if(finished){//checks if the execution finished
                            runSolution=false;
                        }
                    if(message.equals("No more actions") ||
                                    message.equals("Out of bounds, try again!")){
                            System.out.println(message);
                            drawPuzzle(canvas, originalMap);
                    }
                    }else{
                        drawPuzzle(canvas, originalMap);
                    }

                    drawMovements(canvas);

recall your drawPuzzle beforte surface view is locked down as the else causes it may not be executed in that contextual loop, as I said befor it is a problem that is comon with our organization apps
hope this helps! do hesistate to ask for more assistence
sorry for english I am indian


Q: Django m2m_changed signal with additional model I have a model looking like this:
class Recipe(models.Model):
    name = models.CharField(_('Name'))
    components = models.ManyToManyField(RecipeComponent, through='alchemy.RecipeComposition')
    total_weight = models.FloatField(_('How much recipe will weight'))

class RecipeComponent(models.Model):
    name = models.CharField(_('Name'))

class RecipeComposition(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE)
    component = models.ForeignKey(RecipeComponent, on_delete=models.CASCADE)
    number = models.FloatField(_('Defines how much of the component you need'), default=1)

I have to do some calculations (for example total weight) of the recipe after any updates in RecipeComposition.
Trying to do like this unfortunately doesn't help:
@receiver(m2m_changed, sender=Recipe.components.through, weak=False)
def recipe_components_changed(sender, **kwargs):
    print("meow >^-_-^<")
    # some calculations for recipe.total_weight here

Found question with same problem but it's old (3 yrs ago) and has no correct answer. There is a link to ticket 17688 there which is opened 6 yrs ago but still not solved.
I do not want to use post_save like this:
@receiver(post_save, sender=RecipeComposition)

because in this case when new Recipe created total_weight will be recalculated after each component added.
Are there any other ideas how to make this work?


Q: Type 'List' is not a subtype of type 'Map' I'm developing a flutter application that depends on API REST calls.The Response from the API is a bit complex.
I can see the response from the log when calling my API (e.g : api/products) :
But i have this Error :  type 'List< dynamic >' is not a subtype of type 'Map< String, dynamic >'
I've seen all the questions/answers on the internet without any result.
I've tried with a simple RestAPI like : https://my-json-server.typicode.com/typicode/demo/posts and it works.
but it doesn't in my case
API Response Example :
[
   {
      "id":1,
      "tenant":{
         "id":1,
         "code":"company",
         "name":"company"
      },
      "type":{
         "code":"activity",
         "name":"Activité"
      },
      "subType":{
         "code":"ticket",
         "name":"Ticket"
      },
      "inventoryType":{
         "code":"external_source",
         "name":"Source externe"
      },
      "externalReference":"CAL6970",
      "externalSystem":{
         "code":"koedia",
         "name":"Koedia"
      },
      "active":true,
      "durationDays":12,
      "durationNights":14,
      "durationHours":9,
      "durationMinutes":10,
      "supplier":{
         "id":1,
         "tenant":{
            "id":1,
            "code":"company",
            "name":"company"
         },
         "name":"Jancarthier"
      },
      "group":null,
      "subGroup":null,
      "name":"Hôtel Koulnoué Village",
      "translations":[
         {
            "id":1,
            "name":"Hôtel Koulnoué Village",
            "locale":"fr"
         },
         {
            "id":24,
            "name":"Hôtel Koulnoué Village",
            "locale":"en"
         }
      ],
      "vatPercentage":"0.00",
      "longitude":null,
      "latitude":null,
      "departureTime":null,
      "arrivalTime":null,
      "arrivalDayPlus":1,
      "stars":4,
      "localities":[
         {
            "id":41,
            "locality":{
               "id":34,
               "code":"ARM",
               "name":"Armenia"
            },
            "role":{
               "code":"stop",
               "name":"Escale"
            }
         },
         {
            "id":49,
            "locality":{
               "id":55,
               "code":"hossegor",
               "name":"Hossegor"
            },
            "role":{
               "code":"drop_off",
               "name":"Retour"
            }
         },
         {
            "id":50,
            "locality":{
               "id":55,
               "code":"hossegor",
               "name":"Hossegor"
            },
            "role":{
               "code":"localisation",
               "name":"Localisation"
            }
         }
      ]
   }
]

StackTrace  :
I/flutter ( 2865): type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

[Updated] : return ProductsResponse.fromJson(response) instead of response
ProductsRespository :
import 'dart:async';
import 'package:day_experience/models/product/ProductResponse.dart';
import 'package:day_experience/networking/ApiProvider.dart';

class ProductRepository {
  ApiProvider _provider =  ApiProvider();

  Future<ProductsResponse> fetchProducts() async {

      final response = await _provider.getFromApi("products");
      // here line 11 where exception is thrown
      return ProductsResponse.fromJson(response);
  }

}

ProductsBloc :
import 'dart:async';

import 'package:day_experience/models/product/ProductResponse.dart';

import 'package:day_experience/networking/Response.dart';
import 'package:day_experience/repository/ProductRepository.dart';

class ProductBloc {
  ProductRepository _productRepository;
  StreamController _productListController;
  bool _isStreaming;
  StreamSink<Response<ProductsResponse>> get productListSink =>
      _productListController.sink;

  Stream<Response<ProductsResponse>> get productListStream =>
      _productListController.stream;

  ProductBloc() {
    _productListController = StreamController<Response<ProductsResponse>>();
    _productRepository = ProductRepository();
    _isStreaming = true;
    fetchProducts();

  }

  fetchProducts() async {
    productListSink.add(Response.loading('Getting Products.'));
    try {
     ProductsResponse productsResponse =
      await _productRepository.fetchProducts();
     if (_isStreaming) productListSink.add(Response.completed(productsResponse));
    } catch (e) {
      if (_isStreaming) productListSink.add(Response.error(e.toString()));
      print(e);
    }
  }

  dispose() {
    _isStreaming = false;
    _productListController?.close();
  }
}

Response :
class Response<T> {
  Status status;
  T data;
  String message;

  Response.loading(this.message) : status = Status.LOADING;
  Response.completed(this.data) : status = Status.COMPLETED;
  Response.error(this.message) : status = Status.ERROR;

  @override
  String toString() {
    return "Status : $status \n Message : $message \n Data : $data";
  }
}

enum Status { LOADING, COMPLETED, ERROR }

ApiProvider :
import 'package:day_experience/networking/CustomException.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
import 'dart:convert';
import 'dart:async';

class ApiProvider {

  final String _baseApiUrl = "URL_API/";

  Future<dynamic> getFromApi(String url) async {
    var responseJson;
    try {
      final response = await http.get(Uri.encodeFull(_baseApiUrl + url),headers:{"Accept":"application/json"} );
      print(response);
      responseJson = _response(response);
    } on SocketException {
      throw FetchDataException('No Internet connection');
    }
    return responseJson;
  }

  dynamic _response(http.Response response) {
    switch (response.statusCode) {
      case 200:
        var responseJson = json.decode(response.body);

        print(responseJson);
        return responseJson;
      case 400:
        throw BadRequestException(response.body.toString());
      case 401:

      case 403:
        throw UnauthorisedException(response.body.toString());
      case 500:

      default:
        throw FetchDataException(
            'Error occured while Communication with Server with StatusCode : ${response.statusCode}');
    }
  }
}

Model : ProductResponses
import 'ExternalSystem.dart';
import './InventoryType.dart';
import './Localities.dart';
import 'SubType.dart';
import 'Supplier.dart';
import 'Tenant.dart';
import './Translation.dart';
import './Type.dart';

class ProductsResponse {
    final int id;
    final Tenant tenant;
    final Type type;
    final SubType subType;
    final InventoryType inventoryType;
    final String externalReference;
    final ExternalSystem externalSystem;
    final bool active;
    final int durationDays;
    final int durationNights;
    final int durationHours;
    final int durationMinutes;
    final Supplier supplier;
    final String name;
    final List<Translation> translations;
    final String vatPercentage;
    final int arrivalDayPlus;
    final int stars;
    final List<Localities> localities;
    final String group;
    final String subGroup;
    final double longitude;
    final double latitude;
    final String departureTime;
    final String arrivalTime;

    ProductsResponse({this.id, this.tenant , this.type, this.subType, this.inventoryType, this.externalReference, this.externalSystem, this.active, this.durationDays, this.durationNights, this.durationHours, this.durationMinutes, this.supplier, this.name, this.translations, this.vatPercentage, this.arrivalDayPlus, this.stars, this.localities, this.group, this.subGroup, this.longitude, this.latitude, this.departureTime, this.arrivalTime});

    factory ProductsResponse.fromJson(Map<String, dynamic> json) {
        return ProductsResponse(
            id: json['id'],
            tenant: json['tenant'] != null ? Tenant.fromJson(json['tenant']) : null,
            type: json['type'] != null ? Type.fromJson(json['type']) : null,
            subType: json['subType'] != null ? SubType.fromJson(json['subType']) : null,
            inventoryType: json['inventoryType'] != null ? InventoryType.fromJson(json['inventoryType']) : null,
            externalReference: json['externalReference'],
            externalSystem: json['externalSystem'] != null ? ExternalSystem.fromJson(json['externalSystem']) : null,
            active: json['active']?json['active']:null,
            durationDays: json['durationDays']?json['durationDays']:null,
            durationNights: json['durationNights']?json['durationNights']:null,
            durationHours: json['durationHours']?json['durationHours']:null,
            durationMinutes: json['durationMinutes']?json['durationMinutes']:null,
            supplier: json['supplier'] != null ? Supplier.fromJson(json['supplier']) : null,
            name: json['name']?json['name']:null,
            translations: json['translations'] != null ? (json['translations'] as List).map((i) => Translation.fromJson(i)).toList() : null,
            vatPercentage: json['vatPercentage']?json['vatPercentage']:null,
            arrivalDayPlus: json['arrivalDayPlus']?json['arrivalDayPlus']:null,
            stars: json['stars']?json['stars']:null,
            localities: json['localities'] != null ? (json['localities'] as List).map((i) => Localities.fromJson(i)).toList() : null,
            group: json['group'] != null ? json['group'] : null,
            subGroup: json['subGroup'] != null ? json['subGroup'] : null,
            longitude: json['longitude'] != null ? json['longitude'] : null,
            latitude: json['latitude'] != null ? json['latitude'] : null,
            departureTime: json['departureTime'] != null ? json['departureTime'] : null,
            arrivalTime: json['arrivalTime'] != null ? json['arrivalTime'] : null,
        );
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['externalReference'] = this.externalReference;
        data['active'] = this.active;
        data['durationDays'] = this.durationDays;
        data['durationNights'] = this.durationNights;
        data['durationHours'] = this.durationHours;
        data['durationMinutes'] = this.durationMinutes;
        data['name'] = this.name;
        data['vatPercentage'] = this.vatPercentage;
        data['arrivalDayPlus'] = this.arrivalDayPlus;
        data['stars'] = this.stars;
        if (this.tenant != null) {
            data['tenant'] = this.tenant.toJson();
        }
       if (this.type != null) {
            data['type'] = this.type.toJson();
        }
        if (this.subType != null) {
            data['subType'] = this.subType.toJson();
        }
        if (this.inventoryType != null) {
            data['inventoryType'] = this.inventoryType.toJson();
        }
        if (this.externalSystem != null) {
            data['externalSystem'] = this.externalSystem.toJson();
        }
        if (this.supplier != null) {
            data['supplier'] = this.supplier.toJson();
        }
        if (this.translations != null) {
            data['translations'] = this.translations.map((v) => v.toJson()).toList();
        }
        if (this.localities != null) {
            data['localities'] = this.localities.map((v) => v.toJson()).toList();
        }
        if (this.group != null) {
            data['group'] = this.group;
        }
        if (this.subGroup != null) {
            data['subGroup'] = this.subGroup;
        }
        if (this.longitude != null) {
            data['longitude'] = this.longitude;
        }
        if (this.latitude != null) {
            data['latitude'] = this.latitude;
        }
        if (this.departureTime != null) {
            data['departureTime'] = this.departureTime;
        }
        if (this.arrivalTime != null) {
            data['arrivalTime'] = this.arrivalTime;
        }
      print(data);

        return data;
    }
}

[Updated] : removed ProductsRepository (should only access via bloc)
ProductView
import 'package:day_experience/blocs/ProductBloc.dart';
import 'package:day_experience/models/product/ProductResponse.dart';
import 'package:day_experience/networking/Response.dart';
import 'package:day_experience/repository/ProductRepository.dart';
import 'package:day_experience/view/widget/Loading.dart';
import 'package:day_experience/view/widget/ProductList.dart';
import 'package:flutter/material.dart';
import 'package:day_experience/view/widget/Error.dart';

class ProductView extends StatefulWidget {
 @override
 _ProductViewState createState() => _ProductViewState();
}

class _ProductViewState extends State<ProductView> {
 ProductBloc _bloc = new ProductBloc();

 @override
 void initState() {
   super.initState();
   _bloc.fetchProducts();
 }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       elevation: 0.0,
       automaticallyImplyLeading: false,
       title: Text('Products',
           style: TextStyle(color: Colors.white, fontSize: 20)),
       backgroundColor: Color(0xFF333333),
     ),
     backgroundColor: Color(0xFF333333),
     body: RefreshIndicator(
       onRefresh: () => _bloc.fetchProducts(),
       child: StreamBuilder<Response<ProductsResponse>>(
         stream: _bloc.productListStream,
         builder: (context, snapshot) {
           if (snapshot.hasData) {
             switch (snapshot.data.status) {
               case Status.LOADING:
                 return Loading(loadingMessage: snapshot.data.message);
                 break;
               case Status.COMPLETED:
                 return ProductList(productList:snapshot.data.data);
                 break;
               case Status.ERROR:
                 return Error(
                   errorMessage: snapshot.data.message,
                   onRetryPressed: () => _bloc.fetchProducts(),
                 );
                 break;
             }
           }
           return Container();
         },
       ),
     ),
   );
 }

}

Tenant Example same logic for others(Translation,Type,SubType..)
class Tenant {
   final int id;
   final String code;
   final String name;

   Tenant({this.id, this.code, this.name});

   factory Tenant.fromJson(Map<String, dynamic> json) {
       return Tenant(
           id: json['id'],
           code: json['code'],
           name: json['name'],
       );
   }

   Map<String, dynamic> toJson() {
       final Map<String, dynamic> data = new Map<String, dynamic>();
       data['id'] = this.id;
       data['code'] = this.code;
       data['name'] = this.name;
       return data;
   }
}

A: You can copy paste run full code below
Because your json string produce a List<ProductResponse> not ProductResponse
In your code you can directly return response.body as String and parse with productsResponseFromJson
code snippet
List<ProductsResponse> productsResponseFromJson(String str) =>
List<ProductsResponse>.from(
    json.decode(str).map((x) => ProductsResponse.fromJson(x)));

Future<List<ProductsResponse>> fetchProducts() async {
  ApiProvider _provider = ApiProvider();
  String response = await _provider.getFromApi("products");
  // here line 11 where exception is thrown
  return productsResponseFromJson(response);
  //return ProductsResponse.fromJson(response);
}

Future<String> getFromApi(String url) async {

String _response(http.Response response) {
    switch (response.statusCode) {
      case 200:
        print(response.body);
        //var responseJson = jsonDecode(response.body);

        //print(responseJson);
        return response.body;

working demo

full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
//     final productsResponse = productsResponseFromJson(jsonString);

import 'dart:convert';

List<ProductsResponse> productsResponseFromJson(String str) =>
    List<ProductsResponse>.from(
        json.decode(str).map((x) => ProductsResponse.fromJson(x)));

String productsResponseToJson(List<ProductsResponse> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class ProductsResponse {
  int id;
  Tenant tenant;
  ExternalSystem type;
  ExternalSystem subType;
  ExternalSystem inventoryType;
  String externalReference;
  ExternalSystem externalSystem;
  bool active;
  int durationDays;
  int durationNights;
  int durationHours;
  int durationMinutes;
  Supplier supplier;
  dynamic group;
  dynamic subGroup;
  String name;
  List<Translation> translations;
  String vatPercentage;
  dynamic longitude;
  dynamic latitude;
  dynamic departureTime;
  dynamic arrivalTime;
  int arrivalDayPlus;
  int stars;
  List<Locality> localities;

  ProductsResponse({
    this.id,
    this.tenant,
    this.type,
    this.subType,
    this.inventoryType,
    this.externalReference,
    this.externalSystem,
    this.active,
    this.durationDays,
    this.durationNights,
    this.durationHours,
    this.durationMinutes,
    this.supplier,
    this.group,
    this.subGroup,
    this.name,
    this.translations,
    this.vatPercentage,
    this.longitude,
    this.latitude,
    this.departureTime,
    this.arrivalTime,
    this.arrivalDayPlus,
    this.stars,
    this.localities,
  });

  factory ProductsResponse.fromJson(Map<String, dynamic> json) =>
      ProductsResponse(
        id: json["id"],
        tenant: Tenant.fromJson(json["tenant"]),
        type: ExternalSystem.fromJson(json["type"]),
        subType: ExternalSystem.fromJson(json["subType"]),
        inventoryType: ExternalSystem.fromJson(json["inventoryType"]),
        externalReference: json["externalReference"],
        externalSystem: ExternalSystem.fromJson(json["externalSystem"]),
        active: json["active"],
        durationDays: json["durationDays"],
        durationNights: json["durationNights"],
        durationHours: json["durationHours"],
        durationMinutes: json["durationMinutes"],
        supplier: Supplier.fromJson(json["supplier"]),
        group: json["group"],
        subGroup: json["subGroup"],
        name: json["name"],
        translations: List<Translation>.from(
            json["translations"].map((x) => Translation.fromJson(x))),
        vatPercentage: json["vatPercentage"],
        longitude: json["longitude"],
        latitude: json["latitude"],
        departureTime: json["departureTime"],
        arrivalTime: json["arrivalTime"],
        arrivalDayPlus: json["arrivalDayPlus"],
        stars: json["stars"],
        localities: List<Locality>.from(
            json["localities"].map((x) => Locality.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "tenant": tenant.toJson(),
        "type": type.toJson(),
        "subType": subType.toJson(),
        "inventoryType": inventoryType.toJson(),
        "externalReference": externalReference,
        "externalSystem": externalSystem.toJson(),
        "active": active,
        "durationDays": durationDays,
        "durationNights": durationNights,
        "durationHours": durationHours,
        "durationMinutes": durationMinutes,
        "supplier": supplier.toJson(),
        "group": group,
        "subGroup": subGroup,
        "name": name,
        "translations": List<dynamic>.from(translations.map((x) => x.toJson())),
        "vatPercentage": vatPercentage,
        "longitude": longitude,
        "latitude": latitude,
        "departureTime": departureTime,
        "arrivalTime": arrivalTime,
        "arrivalDayPlus": arrivalDayPlus,
        "stars": stars,
        "localities": List<dynamic>.from(localities.map((x) => x.toJson())),
      };
}

class ExternalSystem {
  String code;
  String name;

  ExternalSystem({
    this.code,
    this.name,
  });

  factory ExternalSystem.fromJson(Map<String, dynamic> json) => ExternalSystem(
        code: json["code"],
        name: json["name"],
      );

  Map<String, dynamic> toJson() => {
        "code": code,
        "name": name,
      };
}

class Locality {
  int id;
  Tenant locality;
  ExternalSystem role;

  Locality({
    this.id,
    this.locality,
    this.role,
  });

  factory Locality.fromJson(Map<String, dynamic> json) => Locality(
        id: json["id"],
        locality: Tenant.fromJson(json["locality"]),
        role: ExternalSystem.fromJson(json["role"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "locality": locality.toJson(),
        "role": role.toJson(),
      };
}

class Tenant {
  int id;
  String code;
  String name;

  Tenant({
    this.id,
    this.code,
    this.name,
  });

  factory Tenant.fromJson(Map<String, dynamic> json) => Tenant(
        id: json["id"],
        code: json["code"],
        name: json["name"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "code": code,
        "name": name,
      };
}

class Supplier {
  int id;
  Tenant tenant;
  String name;

  Supplier({
    this.id,
    this.tenant,
    this.name,
  });

  factory Supplier.fromJson(Map<String, dynamic> json) => Supplier(
        id: json["id"],
        tenant: Tenant.fromJson(json["tenant"]),
        name: json["name"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "tenant": tenant.toJson(),
        "name": name,
      };
}

class Translation {
  int id;
  String name;
  String locale;

  Translation({
    this.id,
    this.name,
    this.locale,
  });

  factory Translation.fromJson(Map<String, dynamic> json) => Translation(
        id: json["id"],
        name: json["name"],
        locale: json["locale"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "locale": locale,
      };
}

void main() {
  runApp(MyApp());
}

Future<List<ProductsResponse>> fetchProducts() async {
  ApiProvider _provider = ApiProvider();
  String response = await _provider.getFromApi("products");
  // here line 11 where exception is thrown
  return productsResponseFromJson(response);
  //return ProductsResponse.fromJson(response);
}

class ApiProvider {
  Future<String> getFromApi(String url) async {
    var responseJson;
    try {
      //final response = await http.get(Uri.encodeFull(_baseApiUrl + url),headers:{"Accept":"application/json"} );
      String jsonString = '''
      [
   {
      "id":1,
      "tenant":{
         "id":1,
         "code":"company",
         "name":"company"
      },
      "type":{
         "code":"activity",
         "name":"Activité"
      },
      "subType":{
         "code":"ticket",
         "name":"Ticket"
      },
      "inventoryType":{
         "code":"external_source",
         "name":"Source externe"
      },
      "externalReference":"CAL6970",
      "externalSystem":{
         "code":"koedia",
         "name":"Koedia"
      },
      "active":true,
      "durationDays":12,
      "durationNights":14,
      "durationHours":9,
      "durationMinutes":10,
      "supplier":{
         "id":1,
         "tenant":{
            "id":1,
            "code":"company",
            "name":"company"
         },
         "name":"Jancarthier"
      },
      "group":null,
      "subGroup":null,
      "name":"Hôtel Koulnoué Village",
      "translations":[
         {
            "id":1,
            "name":"Hôtel Koulnoué Village",
            "locale":"fr"
         },
         {
            "id":24,
            "name":"Hôtel Koulnoué Village",
            "locale":"en"
         }
      ],
      "vatPercentage":"0.00",
      "longitude":null,
      "latitude":null,
      "departureTime":null,
      "arrivalTime":null,
      "arrivalDayPlus":1,
      "stars":4,
      "localities":[
         {
            "id":41,
            "locality":{
               "id":34,
               "code":"ARM",
               "name":"Armenia"
            },
            "role":{
               "code":"stop",
               "name":"Escale"
            }
         },
         {
            "id":49,
            "locality":{
               "id":55,
               "code":"hossegor",
               "name":"Hossegor"
            },
            "role":{
               "code":"drop_off",
               "name":"Retour"
            }
         },
         {
            "id":50,
            "locality":{
               "id":55,
               "code":"hossegor",
               "name":"Hossegor"
            },
            "role":{
               "code":"localisation",
               "name":"Localisation"
            }
         }
      ]
   }
]
    ''';

      http.Response response = http.Response(jsonString, 200);
      print(response);
      responseJson = _response(response);
    } on Exception {
      //throw FetchDataException('No Internet connection');
    }
    return responseJson;
  }

  String _response(http.Response response) {
    switch (response.statusCode) {
      case 200:
        print(response.body);
        //var responseJson = jsonDecode(response.body);

        //print(responseJson);
        return response.body;
      /* case 400:
        throw BadRequestException(response.body.toString());
      case 401:

      case 403:
        throw UnauthorisedException(response.body.toString());
      case 500:

      default:
        throw FetchDataException(
            'Error occured while Communication with Server with StatusCode : ${response.statusCode}');*/
    }
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  List<ProductsResponse> productResponseList;

  void _incrementCounter() async {
    productResponseList = await fetchProducts();
    print('${productResponseList[0].inventoryType}');
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            productResponseList == null
                ? CircularProgressIndicator()
                : Text('${productResponseList[0].inventoryType.name}'),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


Q: Spring @Autowired(required = true) is null I have a webmodule with JSF 2 end Spring 4.3. In a backing bean I use @Autowired for DI of a service of a JAR. In EAR module there are WAR, JAR with @Service Spring and JAR with Spring configuration file.
Below a web.xml snippet:
    <context-param>
        <param-name>locatorFactorySelector</param-name>
        <param-value>classpath:beanRefContext.xml</param-value>
    </context-param>

    <context-param>
        <param-name>parentContextKey</param-name>
        <param-value>sharedContext</param-value>
    </context-param>
    <context-param>
    <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

applicationContext.xml:
    <context:annotation-config />
    <context:spring-configured />
<!-- package of @Service class in jar module in EAR-- >
    <context:component-scan base-package="com.ipdb.service" />

beanRefContext.xml:

<bean id="sharedContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">    <constructor-arg>
    <list>
        <value>spring-ctx.xml</value>
    </list>
</constructor-arg>    </bean>

When I Use @Autowired(required=null) in a Backing Bean the value is null (there is not any exception). My JSF bean
@Component
@ManagedBean
@ViewScoped
public class PortfolioController {

    @Autowired(required = true)
    private PortfolioService portfolioService;

...

Can you help me, please.

A: PortfolioController is considered a JSF context bean adding @Component to @ManagedBean is totally wrong you can't mark same class as bean in two different contexts (JSF and Spring ).
Two solutions either make PortfolioController a spring bean thus remove the @ManagedBean and @ViewScoped or inject PortfolioController via JSF injection annotation @ManagedProperty
@ManagedProperty("#{portfolioService}")
private PortfolioService portfolioService;

A: if the applicationContext.xml is in your jar dependency, then you need to add asterisk after classpath:
  <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext.xml</param-value>
    </context-param>

With the asterisk  spring search files applicationContext.xml anywhere in the classpath not only the current project.


Q: For excel VBA, using "for each...next" statement. How can you use all the iterated elements at once Here is a sample code that im testing
Sub Selek()

Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)

Dim item As Variant
With fd
    If .Show = -1 Then
        For Each item In .SelectedItems
            MsgBox item
        Next item
    Else
    End If
End With
Range("K1") = item

End Sub

This script shows selected items one by one in different message boxes but I want all selected ones in just a single msgbox.
Followup question. I also need to work with the file paths found for each selected item. I realize I couldn't assign them to a variable once I'm outside of the "With" section. My solution is when I'm still in the "With" block, then I assign the item to a cell and then once I'm out of the "With" block then thats when I assign it to a variable. Is there a way to use the element directly without doing this?


Q: Why `boost::bind()` can't be replaced with `std::bind()` here? In this part of code from the example:
int main()
{
  boost::asio::io_service io;
  printer p(io);
  boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
  io.run();
  t.join();

  return 0;
}

If I replace the boost::bind(&boost::asio::io_service::run, &io) to std::bind(&boost::asio::io_service::run, &io) I get the compilation error:
.../usr/lib/c++/v1/functional:1843:1: note: candidate template
  ignored: couldn't infer template argument '_Fp'
bind(_Fp&& __f, _BoundArgs&&... __bound_args)
^
/usr/lib/c++/v1/functional:1852:1: note: candidate template
  ignored: couldn't infer template argument '_Rp'
bind(_Fp&& __f, _BoundArgs&&... __bound_args)
^
1 error generated.

Why this error happen?
Why std::bind(&printer::print1, &p) works, but std::bind(&boost::asio::io_service::run, &io) doesn't work?

A: The compiler is telling you that it could not figure out the type of the first argument to std::bind.
If you look at io_service::run, you will see that it is overloaded. The compiler had a choice, and this is a possible reason for the compiler not figuring out the type. To test this, you can use a cast:
std::bind(static_cast<size_t (boost::asio::io_service::*)()>(&boost::asio::io_service::run), &io)

This way makes the choice explicit in the code.
With a modern compiler, you don't need to use bind at all. You can do something like this:
[&]() { io.run(); }

That avoids all the problems with the std::bind template. You need to consider variable lifetime and copies vs. references.


Q: how to convert date format range in php for ex below I am getting date range from input
22 Mar, 2021 - 22 Apr, 2021, so what my question is , in MySQL 2019-01-30 00:00:00 (created_at), how to set date range search laravel query

A: You can use php's native functiion to convert string to date format.
$startDate = date('Y-m-d', strtotime('22 Mar, 2021'));//2021-03-22
$endDate = date('Y-m-d', strtotime('22 Apr, 2021'));//2021-04-22

Now you can perform laravel search query. For example:
DB::table('yourTable')
    ->whereBetween('created_at', [$startDate, $endDate])
    ->get();

See Document: strtotime


Q: Rspec not accessing datas updated via capybara? I have a form containing a "name" regular input field and a "content" CKeditor textarea. As described here I can fill in the form and if I stop here I can see the "name" and "content" columns correctly updated in the Test DataBase. Fine.
Now, if I do :
template = ContractTemplate.all.last
puts "#{template.name}" # => "template_name"
puts "#{template.content}" # => "
template_content
"

And then problem begins, if I try to update those two attributes (still using Capybara), I now always fall back on values saved at the "create" action, although they ARE correctly updated into the database. It's just like there where no update of the values. I've tried to do ContractTemplate.reload , but it doesn't work.
Full spec is like this :
it 'should edit a contract template', :js => true do

  visit contract_templates_path
  click_link "Add"

  fill_in "contract_template_name", :with => "test_template_name"
  fill_in_ckeditor "contract_template_content", :with => "test_template_content"
  click_button "Save"

  template = ContractTemplate.all.last
  template.name.should eq("test_template_name") # pass, content created
  template.content.should eq("
\r\n\ttest_template_content
\r\n") # pass

  visit contract_template_path(template.id)

  fill_in "contract_template_name", :with => "edited_test_template_name"
  fill_in_ckeditor "contract_template_content", :with => "edited_test_template_content"
  click_button "Save"

  template.name.should eq("edited_test_template_name") # Fail, because == "test_template_name"
  template.content.should eq("
\r\n\tedited_test_template_content
\r\n") # Fail, not updated too

end

My approach may be wrong, but since the "content" attribute is filled using a wisiwig editor, I just can't see any other way to test if the save action really updates name and content... BTW there is no view in the app where I could display the result of the textarea, it's all going to be rendered as PDF.
Could someone help me ?

A: You need a template.reload after your second save. Otherwise, the template record will  contain the values from when it was first loaded.

A: I GOT IT ! I just had to turn transactionnal fixtures to false inside spec_helper.rb :
RSpec.configure do |config|
  ...
  config.use_transactional_fixtures = false # true by default
  ...
end

Now everything runs fine. Ho my... 4 hours on this, I was just getting mad.


Q: Efficient way to convert units from one system to another I'm having an hard time figuring an efficient way to converts differents types of unit to various other types.
Switch cases would work, but IMO that's not an efficient way has I will have 3 different Systems (SI, Imperial and US).
My converter (inside my app) will always convert from SI to something or from something to SI.  It kinds of lower the complexity, but yet I still need advice on how to make clean code.
I had defined that my input parameters for conversion would be Value(number) and Unit(string).
I would have 2 functions.   SIToSomething(value, unit) and SOmethingToSi(value, unit).
Unit is defined because I would be converting length, weight, qty etc..
What would you suggest ?

A: How about this:
var converters = {
    'SIToImperial' : {
        'cm' : function(val) {
            // implementation, return something
        },
        'kg' : function(val) {
            // implementation, return something
        } //, etc.
    },
    'SIToUS' : {
        'cm' : function(val) {
            // implementation, return something
        },
        'kg' : function(val) {
            // implementation, return something
        } //, etc.
    },
    'USToSI' : {
        'cm' : function(val) { /* ... */ } // etc
    } // , etc
}

SIToSomething(value, unit, system) {
    return converters["SITo" + system][unit](value);
}

var meterInImperial = SIToSomething(100, 'cm', 'Imperial');
var fiftyKilosInUS = SIToSomething(50, 'kg', 'US');

A: What you can do is have a base unit, and for each target unit, define conversion functions to/from this base unit. Then, to convert from A to B, for example, you'd have this:
A -> base -> B

This way, you only need two conversion functions per unit (not counting the base unit):
var units = {
    a: {
        toBase: function(value) { return value * 2; },
        fromBase: function(value) { return value / 2; }
    },
    b: {
        toBase: function(value) { return 1.734 * value + 48; },
        fromBase: function(value) { return (value / 1.734) - 48; }
    }
}

function convertFromTo(unitA, unitB, value) {
    return unitB.fromBase(unitA.toBase(value));
}

convertFromTo(units.a, units.b, 36489);

A: Do all conversions to/from SI. For example if converting Imperial->US, you'd go Imperial->SI->US.
This is minimal effort you can put in. It also gets you SI "for free".


Q: Writing UTF-8 fields from mysql in PHP to CSV format I am using a php class, where it writes and stores CSV files in the folder of my site. But am unable to write UTF-8 characters of different languages which is present in my database.
I am using the following class to write csv file. How can I add support to write utf-8 characters to this class. I have tried google and other places, but no finding any luck.
class b3rtCSVWriter
{
var $filename;
var $delimiter;

var $fileHandle;
var $fileBuffer;
var $fileBufferSize;

var $errorList;

/*function b3rtCSVWriter()
    {
    }*/

    function __construct()
    {
    $this->filename = '';
    $this->delimiter = ',';

    $this->fileHandle = NULL;
    $this->fileBuffer = '';
    $this->fileBufferSize = 4096;

    $this->errorList = array();
    }

    function __destruct()
    {
    $this->closeFile();
    }

    function setFilename($filename)
    {
    $this->filename = $filename;

    return $this->openFile();
    }

    function setDelimiter($delimiter)
    {
    if (strlen($delimiter) != 1)
        {
        $this->setError('Invalid delimiter');
        return FALSE;
        }

    $this->delimiter = $delimiter;
    return TRUE;
    }

    function getErrors()
    {
    return $this->errorList;
    }

    function putRecord($recordData)
    {
    if ($this->errorList)
        return ($this->fileHandle === NULL ? '' : FALSE);

    $rowBuffer = '';

    // Check if recordData is an array
    if (isset($recordData) && is_array($recordData))
        {
        $currentFieldIndex = -1;
        $lastFieldIndex = count($recordData) - 1;

        // Loop through every array item
        foreach($recordData as $recordValue)
            {
            $currentFieldIndex++;
            $isQuotedField = FALSE;

            // Set isQuotedField if a " is present and replace " with ""
            if (strpos($recordValue, '"') !== FALSE)
                {
                $isQuotedField = TRUE;
                $recordValue = str_replace('"', '""', $recordValue);
                }

            // Set isQuotedField if a delimiter or newline is present
            if ((strpos($recordValue, $this->delimiter) !== FALSE) ||
                (strpos($recordValue, "\n") !== FALSE))
                $isQuotedField = TRUE;

            // Put field inside " if isQuotedField is set
            if ($isQuotedField)
                $recordValue = '"'.$recordValue.'"';

            // Add recordValue to rowBuffer and, if not at last field, a delimiter
            $rowBuffer .= $recordValue .
                ($currentFieldIndex != $lastFieldIndex ? $this->delimiter : '');
            }
        }

    // Add EOL to rowBuffer, even when it's empty
    $rowBuffer .= "\r\n";

    // If no file is currently open, return rowBuffer as is
    if ($this->fileHandle === NULL)
        return $rowBuffer;
    else // Else write rowBuffer to file
        return $this->writeFile($rowBuffer);
    }

    function openFile()
    {
    $this->closeFile();

    if ($this->filename == '')
        $this->setError('Invalid filename');

    if ($this->errorList)
        return FALSE;

    $this->fileHandle = @fopen($this->filename, 'w');
    if (!$this->fileHandle)
        {
        $this->setError('Could not open file');
        $this->fileHandle = NULL;
        return FALSE;
        }

    if (!flock($this->fileHandle, LOCK_EX))
        {
        $this->setError('Could not lock file');
        $this->closeFile();
        return FALSE;
        }

    return TRUE;
    }

    function writeFile($toWrite, $forceWrite = FALSE)
    {
    if ($this->fileHandle === NULL)
        {
        $this->setError('No file specified');
        return FALSE;
        }

    $this->fileBuffer .= $toWrite;

    if ($forceWrite || (strlen($this->fileBuffer) > $this->fileBufferSize))
        {
        if (@fwrite($this->fileHandle, $this->fileBuffer, strlen($this->fileBuffer)) === FALSE)
            {
            $this->setError('Could not write to file');
            return FALSE;
            }

        $this->fileBuffer = '';
        }

    return TRUE;
    }

    function closeFile()
    {
    if (is_resource($this->fileHandle))
        {
        // Force buffer to be written
        $this->writeFile('', TRUE);

        if (!fflush($this->fileHandle))
            $this->setError('Could not flush output to file');
        if (!flock($this->fileHandle, LOCK_UN))
            $this->setError('Could not unlock file');
        if(!@fclose($this->fileHandle))
            $this->setError('Could not close file');
        }

    $this->fileHandle = NULL;
    }

    function setError($error)
    {
    $this->errorList[] = $error;
    }
    }

After browsing from so many days, I found that I would have to need to add BOM to fix UTF-8 in Excel, but was unseccessful in adding to this class.
    $fp = fopen('php://output', 'w');
    fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
    fclose($fp);

A: Add it here:
$this->fileHandle = @fopen($this->filename, 'w');
if (!$this->fileHandle)
    {
    $this->setError('Could not open file');
    $this->fileHandle = NULL;
    return FALSE;
    }
fputs($this->fileHandle, chr(0xEF) . chr(0xBB) . chr(0xBF));


Q: Ignore Rewrite Rule for images folder I have a .htaccess file on a website I'm working on which rewrites urls from mydomain.com/sub/folder/ to mydomain.com?index.php?controller=sub&view=folder
Unfortunately the way I've written it means I can't access images, stylesheets and other linked files anymore.  Could anyone tell me how best to exclude specific directories / URL requests from the rewrite rule?
Apologies if this is a bit of a newbie question, I'm still wrapping my head around this mod rewrite stuff!
The .htaccess file looks like this:
RewriteEngine on
RewriteRule ^([a-zA-Z0-9-]+)/?$ index.php?Controller=$1
RewriteRule ^([a-zA-Z0-9-]+)/([a-zA-Z0-9-_]+)/? index.php?Controller=$1&View=$2

A: If your images are in mydomain.com/images and you are linking to them using relative links on the page mydomain.com/sub/folder/ the browser is going to try to attempt to access the image via mydomain.com/sub/folder/images/i.gif. But if you change your links to absolute links, the browser will correctly attempt to load mydomain.com/images/i.gif. However, the RewriteRule will change it to: mydomain.com/index/php?Controller=images&View=i.gif. To avoid this you need to add a few RewriteConds:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9-_]+)\/?$ index.php?Controller=$1
RewriteRule ^([a-zA-Z0-9-_]+)/([a-zA-Z0-9-_]+)\/? index.php?Controller=$1&View=$2

So that when attempting at access an existing file/directory, don't rewrite to index.php.


Q: How can I save the array to a text file and import it back? Basically, I want to know how to get my array that gets data from peoples input saved to a text file and automatically imported back into the array when the program starts again.
Edit: Now after this, it seems saving and reopening adds data to the same subarrays
My code:
import json
import time

datastore=[]
datastore = json.load(open("file.json"))
menuon = 1

def add_user():
    userdata = input("How many users do you wish to input?")
    print("\n")

    if (userdata == 0):
        print("Thank you, have a nice day!")

    else:
        def add_data(users):
            for i in range(users):
                datastore.append([])
                datastore[i].append(input("Enter Name: "))
                datastore[i].append(input("Enter Email: "))
                datastore[i].append(input("Enter DOB: "))
        add_data(int(userdata))

def print_resource(array):
    for entry in datastore:
        print("Name:  "+entry[0])
        print("Email:  "+entry[1])
        print("DOB:  "+entry[2])
        print("\n")

def search_function(value):
  for eachperson in datastore:
      if value in eachperson:
          print_resource(eachperson)

while menuon == 1:
    print("Hello There. What would you like to do?")
    print("")
    print("Option 1: Add Users")
    print("Option 2: Search Users")
    print("Option 3: Replace Users")
    print("Option 4: End the program")
    menuChoice = input()

    if menuChoice == '1':
        add_user()

    if menuChoice == '2':
        searchflag = input("Do you wish to search the user data? y/n")
        if(searchflag == 'y'):
            criteria = input("Enter Search Term: ")
            search_function(criteria)

    if menuChoice == '3':
        break

    if menuChoice == '4':
        print("Ending in 3...")
        time.sleep(1)
        print("2")
        time.sleep(1)
        print("1")
        json.dump(datastore, open("file.json", "w"))
        menuon=0

A: This module would do what you want: http://docs.python.org/3/library/pickle.html
An example:
import pickle

array = ["uno", "dos", "tres"]

with open("test", "wb") as f:
    pickle.dump(array, f)

with open("test", "rb") as f:
    unpickled_array = pickle.load(f)
    print(repr(unpickled_array))

Pickle serializes your object. In essence this means it converts it to a storeable format that can be used to recreate a clone of the original.
Check out the wiki entry if you're interested in more info: http://en.wikipedia.org/wiki/Serialization

A: Python docs have a beautiful explanation on how to handle text files among other files to read/write. Here's the link:
http://docs.python.org/2/tutorial/inputoutput.html
Hope it helps!

A: You need to serialize the array somehow to store it in a file.  Serialize basically just means turn into a representation that is linear.  For our purposes that means a string.  There are several ways (csv, pickle, json). My current favorite way to do that is json.dump() and json.load() to read it back in.  See json docs
import json

def save_file():
    with open('datafile.json', 'w') as f:
        json.dump(datastore, f)

def load_file():
    with open('datafile.json', 'r') as f:
        datastore = json.load(f)

A: Use JSON; Python has a json module built-in :
import json

datastore = json.load(open("file.json")) // load the file

datastore["new"] = "new value" // do something with your data

json.dump(datastore, open("file.json", "w")) // save data back to your file

You could also use Pickle to serialize a dictionary, but JSON is better for small data and is human-readable and editable with a simple text editor, where as Pickle is a binary format.
I've updated your code to use JSON and dictionaries, and it works fine :
import json
import time

datastore = json.load(open("file.json"))
menuon = 1

def add_user():
    userdata = input("How many users do you wish to input?")
    print("\n")

    if (userdata == 0):
        print("Thank you, have a nice day!")
    else:
        def add_data(users):
            for i in range(users):
                datastore.append({"name":input("Enter Name: "), "mail":input("Enter Email: "), "dob":input("Enter DOB: ")})
        add_data(int(userdata))

def print_resource(array):
    for entry in datastore:
        print("Name:  "+entry["name"])
        print("Email:  "+entry["mail"])
        print("DOB:  "+entry["dob"])
        print("\n")

def search_function(value):
  for eachperson in datastore:
    for i in eachperson.keys():
        if value in eachperson[i]:
            print_resource(eachperson)

while menuon == 1:
    print("Hello There. What would you like to do?")
    print("")
    print("Option 1: Add Users")
    print("Option 2: Search Users")
    print("Option 3: Replace Users")
    print("Option 4: End the program")
    menuChoice = input()

    if menuChoice == '1':
        add_user()

    if menuChoice == '2':
        searchflag = input("Do you wish to search the user data? y/n")
        if(searchflag == 'y'):
            criteria = input("Enter Search Term: ")
            search_function(criteria)

    if menuChoice == '3':
        break

    if menuChoice == '4':
        print("Ending in 3...")
        time.sleep(1)
        print("2")
        time.sleep(1)
        print("1")
        json.dump(datastore, open("file.json", "w"))
        menuon=0