Q:

How can I setup the mockRepository return method to return an IEnumerable?

I'm new to MOQ and I already done some coding before but this time I need to return 2 objects on a List of Tasks that I created. I tried using mockRepository.SetReturnsDefault() command but somehow it just don't work as the way I programmed to. I'm using this test that create two different Tasks and I just need to Update the first Tasks that I created (taskPrev).
I created a Handler to make the exceptions so that i can't create tasks that overlap others, and others business rules, and that Test i'm trying to Update a previous task and should return Sucess but when I run test it return all tasks that i added to the List tasks even when i'm using a function to filter those tasks.
The part that i'm using to filter is var tasks = await _repository.FindBy(x => x.Id != command.Id); but it just return all the two tasks without filtering it.
I'd like to know if i'm using the moq on the wrong way or is other thing because i already search for many foruns and didn't find anything that could help me.
Here is the way i'm configuring moq to return the list:
//Criar 1ª Task
Task taskPrev = new Task(taskTypeId, projectId, costCenterId, Convert.ToDateTime(date),
        startHour, startMinute, endHour, endMinute, workItem, timeSheetId, description);
taskPrev.Id = taskId;
//Criar 2ª Task
Task taskCurr = new Task(taskTypeId, projectId, costCenterId, Convert.ToDateTime(date),
        endHour, startMinute, Convert.ToByte(endHour + 1), endMinute, workItem, timeSheetId, description);
taskCurr.Id = taskId + 1;

List<Task> tasks = new List<Task>();
tasks.Add(taskPrev);
tasks.Add(taskCurr);
// mockRepository.SetReturnsDefault(System.Threading.Tasks.Task.FromResult((IEnumerable<Task>)tasks));
mockRepository.Setup(x => x.FindBy(x => It.IsAny<IAsyncRepository<Task>>())).Returns(System.Threading.Tasks.Task.FromResult((IEnumerable<Task>)tasks.Where(x => x.Id == taskCurr.Id)));

Using mockRepository.SetReturnsDefault() return both tasks and dont filter;
Using mockRepository.SetReturnsDefault() and mockRepository.Setup() makes the same as using only SetReturnsDefault();
And using only mockRepository.Setup() return empty.
The Test code that i'm using:
[Theory]
[InlineData(1,1,1,"2020-03-25",9,0,10,0,"",1,"valor",1,5)]
[InlineData(2,2,2,"2020-03-28",11,0,12,0,"Valor",2,"valor",3,6)]
[InlineData(3,4,5,"2020-03-04",13,0,14,0,"",6,"valor",7,7)]
//Deve permitir editar uma task criada anteriormente a nova task
//EX: 1ª task finaliza as 10:00 e a nova inicia as 10:00, deve permitir uma alteração da 1ª task
public async void Update_PreviousTask_Return_Success_When_CurrentTask_HasStartHour_Equals_PreviousTask_EndHour(
    int taskTypeId, int projectId, int costCenterId, string date, byte startHour, byte startMinute,
    byte endHour, byte endMinute, string workItem, int timeSheetId, string description, int employeeId, int taskId)
    {
        //São necessários apenas para criação do handler
        var mockRepository = new  Mock<IAsyncRepository<Task>>();
        var mockRepositoryTimeSheet = new  Mock<IAsyncRepository<TimeSheet>>();
        var mockRepositoryProject = new  Mock<IAsyncRepository<Project>>();

        //Cria handler
        TaskHandler handler = new TaskHandler(mockRepository.Object,
        mockRepositoryTimeSheet.Object, mockRepositoryProject.Object);

        //Cria Project
        Project project = new Project("nameProject", 1, true, 1);
        project.Id = projectId;

        // List<Project> projects =new List<Project>();
        // projects.Add(project);
        mockRepositoryProject.SetReturnsDefault(System.Threading.Tasks.Task.FromResult(project));

        //Cria timeSheet
        TimeSheet timeSheet = new TimeSheet(1, Convert.ToDateTime(date).AddDays(-30), Convert.ToDateTime(date).AddDays(30), employeeId);
        timeSheet.Id = timeSheetId;

        List<TimeSheet> timeSheets = new List<TimeSheet>();
        timeSheets.Add(timeSheet);
        mockRepositoryTimeSheet.SetReturnsDefault(System.Threading.Tasks.Task.FromResult((IEnumerable<TimeSheet>)timeSheets));

        //Criar 1ª Task
        Task taskPrev = new Task(taskTypeId, projectId, costCenterId, Convert.ToDateTime(date),
                startHour, startMinute, endHour, endMinute, workItem, timeSheetId, description);
        taskPrev.Id = taskId;
        //Criar 2ª Task
        Task taskCurr = new Task(taskTypeId, projectId, costCenterId, Convert.ToDateTime(date),
                endHour, startMinute, Convert.ToByte(endHour + 1), endMinute, workItem, timeSheetId, description);
        taskCurr.Id = taskId + 1;

        List<Task> tasks = new List<Task>();
        tasks.Add(taskPrev);
        tasks.Add(taskCurr);
        // mockRepository.SetReturnsDefault(System.Threading.Tasks.Task.FromResult((IEnumerable<Task>)tasks));
        mockRepository.Setup(x => x.FindBy(x => It.IsAny<IAsyncRepository<Task>>())).Returns(System.Threading.Tasks.Task.FromResult((IEnumerable<Task>)tasks.Where(x => x.Id == taskCurr.Id)));

        //Command para criar a task
        UpdateTaskCommand command = new UpdateTaskCommand(taskTypeId, projectId, costCenterId, Convert.ToDateTime(date),
        startHour, startMinute, endHour, endMinute, workItem, "descrição Teste", taskId, employeeId);

        //Act
        var retorno = (CommandResult)await handler.Handle(command);

        //Assert
        Assert.True(retorno.Sucess);
        }

And the Handler part that is not working as it should be:
var tasks = await _repository.FindBy(x => x.Id != command.Id);
var retorno = tasks.FirstOrDefault(x => (x.TimeSheetId == command.TimeSheetId && x.Date.Date == command.Date.Date)
                                         &&
                                         (
                                             (
                                                 (new TimeSpan(x.StartHour, x.StartMinute, 0) <= new TimeSpan(command.StartHour, command.StartMinute, 0))
                                              && (new TimeSpan(x.EndHour, x.EndMinute, 0) > new TimeSpan(command.StartHour, command.StartMinute, 0))
                                              )
                                              ||
                                              (
                                                 (new TimeSpan(x.EndHour, x.EndMinute, 0) >= new TimeSpan(command.EndHour, command.EndMinute, 0))
                                              && (new TimeSpan(x.StartHour, x.StartMinute, 0) < new TimeSpan(command.EndHour, command.EndMinute, 0))
                                              )
                                              ||
                                              (
                                                 (new TimeSpan(x.StartHour, x.StartMinute, 0) >= new TimeSpan(command.StartHour, command.StartMinute, 0))
                                              && (new TimeSpan(x.EndHour, x.EndMinute, 0) <= new TimeSpan(command.EndHour, command.EndMinute, 0))
                                              )

                                         ));

if (retorno != null)
    throw new BusinessException("Não é permitido criar novos registros que se sobreponham a outros existentes",
                                nameof(command.StartHour) + ", " + nameof(command.StartMinute) + ", " +
                                nameof(command.EndHour) + ", " + nameof(command.EndMinute), ErrorsEnum.ResourceInvalidField);

A:

I think you have some confusion in how you're defining the expected parameter in your Setup method.
To illustrate the issue, let's look at a setup that doesn't involve lambdas:
var myMock = new Mock<IMyThing>();
myMock.Setup(m => m.GetById(7)).Returns(new Thing());

This is a setup for a call to GetById where the parameter is exactly 7.  If the code you are testing calls GetById(7), it will get a Thing object.  If the calling code passes anything other than 7, then the setup will not be matched, and the return will be null.
You can make your setup more flexible by using It.IsAny():
var myMock = new Mock<IMyThing>();
myMock.Setup(m => m.GetById(It.IsAny<int>())).Returns(new Thing());

Now it doesn't matter what integer your calling code passes to GetById() - the setup will always be matched, and you'll always get a non-null Thing.
With that understanding in place, let's look at your setup:
mockRepository.Setup(x => x.FindBy(x => It.IsAny<IAsyncRepository<Task>>())).Returns(//stuff);

The FindBy method takes a predicate of type Func<Task,bool>, and here you have provided a specific predicate: x => It.IsAny<IAsyncRepository<Task>>().  Because you provided a specific parameter value, then the calling code must either exactly match that specific parameter, or the setup won't be matched.  The predicate your calling code is passing to FindBy does not match because (x => x.Id != command.Id) != (x => It.IsAny<IAsyncRepository<Task>>()), and since the setup is not matched, you return null (or if SetReturnsDefault has been called, it will return whatever the default return is).
If you want your setup to match any lambda your calling code might send in, it should look like this:
mockRepository.Setup(x => x.FindBy(It.IsAny<Func<Task,bool>>())).Returns(//stuff);


Q:

Sometimes Informatica gets successful runs, sometimes it gets error "Data source name not found and no default driver specified"

We have some workflows that work in our development and test environments, using the same ODBC credentials to pull data from the same sql server source. When we run jobs over and over, they're always successful in dev and test. When we run jobs in our prod server, they succeed or fail at around 50-50 chance with no changes to anything. When the jobs fail, they get the error below.
How are these jobs sometimes succeeding and sometimes failing when no changes are occurring? If it can find the data source sometimes, I am baffled by why it can't find the data source other times.
READER_1_1_1> RR_4036 Error connecting to database [
[DataDirect][ODBC lib] Data source name not found and no default driver specified
Database driver error...
Function Name : Connect
Database driver error...
Function Name : Connect
Database Error: Failed to connect to database using user [user_name] and connection string [connect_string].].
READER_1_1_1> CMN_1761 Timestamp Event: [Wed Jul 05 15:21:49 2017]
READER_1_1_1> BLKR_16001 Error connecting to database...

A:

The issue persists if the user has no permission to access odbc.ini or you might have missing/additional entries in odbc.ini.  This will fail your workflows always. Not sure, you say it is successful some times and fails some times. May be database would temporary gone down at that moment. Pleas check with your dba to get the stats for the database, so that you can identify the issue clearly
Thank you


Q:

Set ViewData outside the controller

I'm trying to create a logger that will write the queries LINQ executes to the page formatted with the great javascript library SyntaxHighlighter.
For that, I've set the DataContext's Log property to my custom logger, which is working well.
Now I just need to get the current Controller object (outside the controller execution context) so I can set some ViewData with what needs to be outputted.
Any suggestions?

A:

If you want to perform operations outside of the controller, then action-filters (etc) are a good bet; just inherit from ActionFilterAttribute, override OnActionExecuting (etc) to inject data into the view, and mark your controller with [YourCustomFilter].
Like this

(original; I may have misunderstood)
It would be better to use dependency injection here, by passing the log-writer into the repository as a constructor argument (ideally via something like StructureMap, which works very well with MVC via StructureMapControllerFactory, or similar).


Q:

Error when trying to test Craft Pro on .dev

I have a fresh Craft install set up locally at mysite.craft.dev. I would like to start building out the features offered by the pro license, but when I click the "Show me" link in the footer, I get "An unknown error occurred."
I am seeing this error in craft.log:
015/04/03 17:13:55 [error] [php] Cannot modify header information - headers already sent (/Users/aaron/Sites/mysite/craft/app/framework/web/CHttpRequest.php:1392)
In potentially related news, tasks do not seem to be behaving correctly.
Anyone ever experience this before? Any help is appreciated :)

A:

I found a solution! I had my local environment setup with homebrew following this article's instructions. After looking at the php error logs, I uncommented always_populate_raw_post_data = -1 in the php.ini file found in /usr/local/etc/php/5.6.
I then restarted the brew services with brew services restart php56 (install brew services by tapping gapple/services with brew tap gapple/services) and restarted apache with apachectl restart.
That did the trick!


Q:

Prohibition to wear black for mourning?

I've heard a rumor floating around to the effect that Jews should not wear all black as an expression of mourning. Is there anything to that? If so, is there anything inherently wrong with it, is it a way to not copy "the way of the gentiles" ("chukat hagoyim"), or something else?
Answers that cite authoritative sources only, please.

A:

The Ramma in Even Ha'ezer siman 17 siff 5 brings from earlier sources a custom to wear black for mourning. No-one seemed to have a problem with it.


Q:

Make ListBox items have a different value than item text

I want a ListBox full of items. Although, each item should have a different value.
So when the user selects an item and presses a button, a method will be called which will use the value the select item has.
I don't want to reveal the item values to the user.
EDIT: This is not for ASP.NET, it's for a Windows Forms application. I just thought the HTML example would be easy to read.
I have the inspiration from HTML:
<form>
<input type="radio" name="sex" value="Value1" /> Male
<br />
<input type="radio" name="sex" value="Value2" /> Female
</form>

This also allows me to use different values than what the user sees.

A:

You can choose what do display using the DisplayMember of the ListBox.
List<SomeData> data = new List<SomeData>();
data.Add(new SomeData() { Value = 1, Text= "Some Text"});
data.Add(new SomeData() { Value = 2, Text = "Some Other Text"});
listBox1.DisplayMember = "Text";
listBox1.DataSource = data;

When the user selects an item, you can read the value (or any other property) from the selected object:
int value = (listBox1.SelectedItem as SomeData).Value;

Update: note that DisplayMember works only with properties, not with fields, so you need to alter your class a bit:
public class SomeData
{
    public string Value { get; set; };
    public string Text { get; set; };
}


Q:

Add-in Express RTD refresh issue

Excel AddIn using Add-In express, VS2010, cometd.net talks to cometd server and Tom cat
In RTDInitialize event handler, I log in Tom Cat and connect to cometd server, I use an instance of class credential to remember it is loggedOn(set IsLoggedOn to true) and sessionID.
In RefreshData handler of topic, I will register to cometd server if not register yet.  Then I will subscribe topic to Tom Cat. Now when users delete the RTD function from Excel,
DisconnectData handler is called, in it I disconnect from cometd server, logout from Tom Cat, clear out sessionID.
Next time, when users enter RTD function again, it will call RTDInitialize event handler, login and connect where IsLoggoned set to true and sessionID is updated. The strange thing is after 2nd time login, in refreshData, I check the credentials, IsLogged becomes false and sessionID is empty just like what it was at first logout.  Anyone know why? not sure if I make it clear.  Thanks

A:

I suppose you have just one topic in your tests. I suppose that you store a reference to the "instance of class credential" on the class level of the RTD server module. And when you delete the topic, the RTD server module is destroyed; this kills the information about previous connection. If you think that I misunderstood the problem, please clarify.


Q:

Checking the nature of the sequence ${x_{n}}=\frac{\left\lfloor xn \right\rfloor}{n}$ **[TIFR GS-2011]**

[TIFR GS-2011, Q1.]

Consider the sequence ${x_{n}}$ defined by $\frac{\left\lfloor xn
\right\rfloor}{n}$ for $x \in \mathbb{R}$. Then
(A) Converges to $x$.
(B) Converges not to $x$.
(C) doesn't converge.
(D) oscillate.

When I take $x=1$ sequence converges to $1$. similarly I had given particular values to $x$, I am not able to judge the answer. Can any one help me to figure out the solution? Thanks in advance.

A:

$$x_n=\frac{\lfloor xn\rfloor}{n}=\frac{xn-\{xn\}}{n}=x-\frac{\{xn\}}{n}\to x\text{ as }n\to\infty,$$
where $\{y\}\in[0,1)$ is the fractional part of $y$. Therefore, the answer is (A).


Q:

Android can not get ListView on second tab

I have Activity that got TabHost. XML file is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TabHost
    android:id="@android:id/tabhost"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="70sp"
            android:layout_alignParentBottom="true" >

        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@android:id/tabs" >

            <LinearLayout
                android:id="@+id/tab1"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

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

                </ListView>

            </LinearLayout>

            <LinearLayout
                android:id="@+id/tab2"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <ListView
                    android:id="@+id/listFavourites"
                    android:layout_width="match_parent"
                    android:layout_height="356dp"
                    android:layout_weight="1" >
                </ListView>

            </LinearLayout>

            <LinearLayout
                android:id="@+id/tab3"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <ScrollView
                    android:id="@+id/scrollView1"
                    android:layout_width="wrap_content"
                    android:layout_height="match_parent" >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:orientation="vertical" >

                        <ImageView
                            android:id="@+id/imageView1"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:src="@drawable/wikibilim" />

                        <TextView
                            android:id="@+id/textFavourite"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="@string/wiki" />

                    </LinearLayout>
                </ScrollView>

            </LinearLayout>
        </FrameLayout>

    </RelativeLayout>
</TabHost>

In my MainActivity at the begining onCreate method, I wrote:
tabHost = (TabHost) findViewById(android.R.id.tabhost);

    tabHost.setup();

    // TabHost.TabSpec tabSpec;

    View indicator1 = getLayoutInflater().inflate(R.layout.tab1, null);
    im1 = (ImageView) indicator1.findViewById(R.id.imageView1);

    View indicator2 = getLayoutInflater().inflate(R.layout.tab2, null);
    im2 = (ImageView) indicator2.findViewById(R.id.imageView1);

    View indicator3 = getLayoutInflater().inflate(R.layout.tab3, null);
    im3 = (ImageView) indicator3.findViewById(R.id.imageView1);

    TabHost.TabSpec tabSpec;
    tabSpec = tabHost.newTabSpec("tag1");
    tabSpec.setIndicator(indicator1);
    tabSpec.setContent(R.id.tab1);
    tabHost.addTab(tabSpec);

    tabSpec = tabHost.newTabSpec("tag2");
    tabSpec.setIndicator(indicator2);
    tabSpec.setContent(R.id.tab2);
    tabHost.addTab(tabSpec);

    tabSpec = tabHost.newTabSpec("tag3");
    tabSpec.setIndicator(indicator3);
    tabSpec.setContent(R.id.tab3);
    tabHost.addTab(tabSpec);

    dialog = new ProgressDialog(this);
    dialog.setMessage(getString(R.string.loading));
    dialog.setCanceledOnTouchOutside(false);

    dictionaryList = (ListView) this.findViewById(R.id.listDictionary);

I'm easily uploaded data to dictionaryList using async task. After that I have added listener to TabHost:
tabHost.setOnTabChangedListener(new OnTabChangeListener() {

        @Override
        public void onTabChanged(String tabId) {
            // TODO Auto-generated method stub
            if (tabId.equals("tag2")) {
                View view = tabHost.getChildAt(tabHost.getCurrentTab());
                favouritesList = (ListView) view.findViewById(R.id.listFavourites);
                Toast.makeText(getApplicationContext(), favouritesList.toString(), Toast.LENGTH_LONG).show();
            }
        }
    });

When It tries to get favouritesList there appears an NullPointerException. What did I do wrong ?
LogCat:
      02-19 21:40:52.360: E/AndroidRuntime(25828): FATAL EXCEPTION: main
      02-19 21:40:52.360: E/AndroidRuntime(25828): java.lang.NullPointerException
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at                                          kz.wikibilim.sozdik.MainActivity$1.onTabChanged(MainActivity.java:117)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at            android.widget.TabHost.invokeOnTabChangeListener(TabHost.java:402)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at android.widget.TabHost.setCurrentTab(TabHost.java:387)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:150)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:560)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at android.view.View.performClick(View.java:4223)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at android.view.View$PerformClick.run(View.java:17275)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at android.os.Handler.handleCallback(Handler.java:615)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at android.os.Handler.dispatchMessage(Handler.java:92)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at android.os.Looper.loop(Looper.java:137)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at android.app.ActivityThread.main(ActivityThread.java:4898)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at java.lang.reflect.Method.invokeNative(Native Method)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at java.lang.reflect.Method.invoke(Method.java:511)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1008)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:775)
      02-19 21:40:52.360: E/AndroidRuntime(25828):  at dalvik.system.NativeStart.main(Native Method)

I have found how to get this listFavourites and setted adapter. When I start application, it starts well, there is no mistakes. However, when I click on the second tab, where this ListView is located, it gives me again NullPointerException

A:

I have found my mistake. It was in my adapter that will be setted in my ListView. There in getView() method I forgot to write return view, there still was return null. Anyway, Thank you for attention.


Q:

Paypal API Express Checkout in PHP Payment error code 13113

We have tried and tested our site with Paypal sandbox and it works fully deducting the amount.
We switched the API details to Paypal and the links. We have tried with several paypal accounts to see if it works (all of them have enough funds for the transaction).
We recieve this back through the API on our returnUrl page -
The API Call Failed
Array ( [TIMESTAMP] => 2012%2d07%2d15T19%3a31%3a43Z [CORRELATIONID] => 927a89205e54a
[ACK] => Failure [VERSION] => 65%2e1 [BUILD] => 3300093 [L_ERRORCODE0] => 13113
[L_SHORTMESSAGE0] => Buyer%20Cannot%20Pay%2e [L_LONGMESSAGE0] =>
The%20Buyer%20cannot%20pay%20with%20PayPal%20for%20this%20Transaction%2e [L_SEVERITYCODE0] => Error )

Php to make the final API call -
$APIUSERNAME="*****";
$APIPASSWORD="***";
$APISIGNATURE="*****";
$ENDPOINT = "https://api-3t.paypal.com/nvp";
//$ENDPOINT     = "https://api-3t.sandbox.paypal.com/nvp";
$VERSION      = "64";

//Build the Credential String:
$cred_str = "USER=" . $APIUSERNAME . "&PWD=" . $APIPASSWORD . "&SIGNATURE=" .
$APISIGNATURE . "&VERSION=" . $VERSION;

//Build NVP String for GetExpressCheckoutDetails
$nvp_str = "&METHOD=GetExpressCheckoutDetails&TOKEN=" . urldecode($token);

//Lets combine both strings then make the API call
$req_str = $cred_str . $nvp_str; $response = PPHttpPost($ENDPOINT, $req_str);

The above array comes from when i recieve my final acknowledgment from paypal.
//check Response
if($doresponse['ACK'] == "Success" || $doresponse['ACK'] == "SuccessWithWarning") {
echo "completed"; //just put to test
include "finishtransaction.php"; //cancels my cart sessions
} else{
    echo "The API Call Failed"; print_r($doresponse);
}

There is not much on google about this error, not even in the API error codes. Has anyone come accross this before?

A:

The PayPal API Error Codes are admittedly not very helpful.
Error code 13113, or "The Buyer cannot pay with PayPal for this Transaction" means that PayPal has taken a security measure by refusing to process the transaction.  This can happen for one of the following reasons (there are more, but here are a few):

The buyer does not have enough money in their account
The buyer does not have enough money in their account, and there is a problem charging their credit card (if they have that set in their settings)
The buyer has asked for a refund on another item from the seller, and PayPal has therefore blocked the buyer's account from transferring money to the seller until the situation has been resolved.
The buyer is suspected of fraudulent activity, so there is a freeze on their accounts.
The buyer's account is restricted to sending money to the specific seller for some other reason
The buyer's account is entirely frozen for some specific reason

Unfortunately, there isn't much anyone can tell you without thoroughly looking through your code.  I would check my code and make sure all appropriate flags and what-not are set.  If you wait a few hours and are still getting the error (especially on multiple/new accounts), then you will need to contact PayPal.
I know it sucks, but only PayPal will be able to tell you why exactly the transaction is failing.


Q:

K&R Exercise 1-18 Almost done... Why am i getting strange characters at the end of some lines?

This is my code.
exercise 1-18 says: Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.
this is the post i made like an hour ago for this exercise
when i deleted the commented lines that eclipse adds it compiled...
#include <stdio.h>

#define MAXLINE 1000
#define BLANK 1
#define NOT_BLANK 0

int getlinea (char s [], int lim);
void copy (char to [], char from []);
int erasewhites (char s[], int len);

int main (void){
    char palabra [MAXLINE];
    int len;
    while ( (len = getlinea (palabra, MAXLINE) ) >= 0)
        if (len > 0)
            printf ("%s\n",palabra);
    return 0;
}

int getlinea (char s[], int lim){
    int i, c, len;
    char aux[MAXLINE];
    for ( i=0; ( c = getchar () )!= EOF && c != '\n' && i < lim-1 ; ++i)
        aux[i] = c ;
    if (c == EOF)
        return -1;
    if ( ( len = erasewhites ( aux, i) ) > 0 )
        copy ( s , aux );
    else
        return 0;
    return len;
}

int erasewhites (char s[], int len){
    int state = BLANK;
    while (len >= 0 && state == BLANK){
        if ( s[len] != 32 && s[len] != '\t' )
            state = NOT_BLANK;
        else
            --len;
    }
    if ( len >= 0 )
        s[len+1] = '\0';
    else
        return 0;
    return len;
}

void copy ( char to[], char from [] ){
    int i;
    for ( i = 0 ; from [i] != '\0' ; ++i)
        to [i] = from [i] ;
    to [i+1] = '\0';
}

and this is the output i get when in terminal i write
./myprogram < main.c
#include <stdio.h>t
#define MAXLINE 1000
#define BLANK 1
#define NOT_BLANK 00
int getlinea (char s [], int lim);
void copy (char to [], char from []);
int erasewhites (char s[], int len);;
int main (void){(c
    char palabra [MAXLINE];],
    int len;ab
    while ( (len = getlinea (palabra, MAXLINE) ) >= 0)d
        if (len > 0)=
            printf ("%s\n",palabra);al
    return 0;("
}re
int getlinea (char s[], int lim){,
    int i, c, len;ha
    char aux[MAXLINE];s[
    for ( i=0; ( c = getchar () )!= EOF && c != '\n' && i < lim-1 ; ++i)
        aux[i] = c ;c
    if (c == EOF)c
        return -1;F)
    if ( ( len = erasewhites ( aux, i) ) > 0 )=
        copy ( s , aux );wh
    elsey
        return 0;,
    return len;
}re
int erasewhites (char s[], int len){)
    int state = BLANK;ar
    while (len >= 0 && state == BLANK){)
        if ( s[len] != 32 && s[len] != '\t' )
            state = NOT_BLANK;&
        elsete
            --len;=
    }
    if ( len >= 0 )LA
        s[len+1] = '\0';NK
    elseen
        return 0;=
    return len;
}re
void copy ( char to[], char from [] ){)
    int i;py
    for ( i = 0 ; from [i] != '\0' ; ++i))
        to [i] = from [i] ;i]
    to [i+1] = '\0';i]
}to

This is my final code for this exercise...
#include <stdio.h>

#define MAXLINE 1000
#define BLANK 1
#define NOT_BLANK 0

int getlinea (char s [], int lim);
void copy (char to [], char from []);
int erasewhites (char s[], int len);

int main (void){
    char palabra [MAXLINE];
    int len;
    while ( (len = getlinea (palabra, MAXLINE) ) >= 0)
        if (len > 0)
            printf ("%s\n",palabra);
    return 0;
}

int getlinea (char s[], int lim){
    int i, c, len;
    char aux[MAXLINE];
    for ( i=0; ( c = getchar () )!= EOF && c != '\n' && i < lim-1 ; ++i)
        aux[i] = c ;
    if (c == EOF)
        return -1;
    if ( ( len = erasewhites ( aux, i) ) > 0 )
        copy ( s , aux );
    else
        return 0;
    return len;
}

int erasewhites (char s[], int len){
    int state = BLANK;
    while (len >= 0 && state == BLANK){
        if ( s[len] != 32 && s[len] != '\t' )
            state = NOT_BLANK;
        else
            --len;
    }
    if ( len >= 0 )
        s[len] = '\0';
    else
        return 0;
    return len;
}

void copy ( char to[], char from [] ){
    int i;
    for ( i = 0 ; from [i] != '\0' ; ++i)
        to [i] = from [i] ;
    to [i] = '\0';
}

Works like a charm. Thx @vaughn cato and @R sahu you were both right and that was my mistake in some lines.

A:

copy() is wrong:
void copy ( char to[], char from [] ){
    int i;
    for ( i = 0 ; from [i] != '\0' ; ++i)
        to [i] = from [i] ;
    to [i+1] = '\0'; // should be to [i] = '\0';
}

For example, let's say that from is "abc".  The loop will end when i is equal to 3, because the statement from[i] != '\0' will be false. In that case, you want to put the nul terminator at to[3] not to[4].


Q:

How to fix specific div's position in CSS

I want to fix position of my divs like this:

so I did this code (note that div's order in HTML is reverse)

bottom

middle

top

and css code (colors aren't important)
#area{
    position:fixed;
    right: 10px;
    bottom: 10px;
    border: 2px solid green;
    padding: 10px;
}
#bottom{
    padding: 5px;
    border: 1px solid yellow;
    bottom: 0;
    position: relative;
}
#middle{
    padding: 5px;
    border: 1px solid blue;
    bottom: 30px;
    position: relative;
}
#top{
    padding: 5px;
    border: 1px solid red;
    bottom: 60px;
    position: relative;
}

Why all divs inside #area are on top of #area?
Code example

A:

position:relative refers to relative to the object's own visual position, since each element is (apparently) 30px tall, the top and bottom items need to move 60px in a respective direction.
If the elements' sizes are not known an alternative solution is recommended.

#area {
  position: fixed;
  right: 10px;
  bottom: 10px;
  border: 2px solid green;
  padding: 10px;
}
#bottom {
  padding: 5px;
  border: 1px solid yellow;
  top: 60px;
  /* up 60px from where it is */
  position: relative;
}
#middle {
  padding: 5px;
  border: 1px solid blue;
  /* no need to move*/
}
#top {
  padding: 5px;
  border: 1px solid red;
  top: -60px;
  /* down 60px from where it is */
  position: relative;
}

bottom

middle

top

Alternative Solution with Flexbox : No need for any positioning.
#area{
    position:fixed;
    display:flex;
    flex-direction:column-reverse;
    right: 10px;
    bottom: 10px;
    border: 2px solid green;
    padding: 10px;
}

#area{
    position:fixed;
    display:flex;
    flex-direction:column-reverse;
    right: 10px;
    bottom: 10px;
    border: 2px solid green;
    padding: 10px;
}
#bottom{
    padding: 5px;
    border: 1px solid yellow;
}
#middle{
    padding: 5px;
    border: 1px solid blue;
 }
#top{
    padding: 5px;
    border: 1px solid red;

}

bottom

middle

top


Q:

WP Cron: Save third party data as user meta

Editors note: Twitter ID and Google Analytics only serve as examples and are exchangeable.
TL;DR
I want to save external data in a user profile once or twice a day.
I added two custom fields in my user profiles:

Twitter_ID (I manually put it from the dashboard)
test1 (external data got with php function)

I would like to be able to do something like :
Save once a day in test1 for each user profile the external data I get from Twitter_ID.
The main goal : I am working on a panel which will display statistics of my user websites (external website). For that, I use the Google Analytics API. I save the Google Analytics profile number in a custom profile field. For the moment, I run the script (statistics) each time my users want to see them (in front end). And it takes few seconds to generate them. My statistics change approx once a day (It's not hourly stats, but daily stats). So, the idea was to save once a day the statistics to the user profiles. So, like that, it won't take time to generate them each time the user will load a stats page.
The solutions : So, I started to think about different solutions. But the best would be to save the data without any action from the users. Or maybe when someone visits the website, it would save the data for everyone once the day with wp_cron. For the moment, the only thing I succeed was to save the data when a user update his profile. But it will save only his data, and not for everyone, so it's not what I want.
EDIT
I tried this :
add_filter('cron_schedules', 'new_interval');

function new_interval($interval) {

    $interval['minutes_1'] = array('interval' => 10*60, 'display' => 'Once 1 minute');

    return $interval;
}

function InitiateMyCron() {
    if (!wp_next_scheduled('MyCronAction')) {
        wp_schedule_event(time(), 'minutes_1', 'MyCronAction');
    }
}

function MyCronAction( $user_id ) {
    $twitter_id = $_POST['twitter_id'];
    $result = $twitter_id;
    if ( !current_user_can( 'edit_user', $user_id ) )
    return false;
    update_usermeta( $user_id, 'test1', $result );
}

add_action( 'personal_options_update', 'MyCronAction' );
add_action( 'edit_user_profile_update', 'MyCronAction' );

But, the field "test1" is updated when I save the "Twitter_id". I don't know if it is updated every minute
EDIT 2
if ( ! wp_next_scheduled( 'my_save_statistiques' ) ) {
  wp_schedule_event( strtotime('tomorrow'), 'daily', 'my_save_statistiques' );
}

function my_save_statistiques( $user_id ) {

"blabla php"  =
$ga->requestReportData($num_analytics,array('pagePath'),array('visits'), null, null, $fromDate, $toDate);
$visites_totales = $ga->getVisits();

if ( !current_user_can( 'edit_user', $user_id ) )
return false;
update_usermeta( $user_id, 'visites_totales', $visites_totales );
add_action( 'personal_options_update', 'my_save_statistiques' );
add_action( 'edit_user_profile_update', 'my_save_statistiques' );
}

EDIT 3
I finally ended up with this but it's not working : (I changed 1 week to 30 seconds but the name are still the same)
add_filter( 'cron_schedules', 'myprefix_add_weekly_cron_schedule' );
function myprefix_add_weekly_cron_schedule( $schedules ) {
    $schedules['weekly'] = array(
        'interval' => 30, // 30 seconds
        'display'  => __( 'Once Weekly' ),
    );

    return $schedules;
}

// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'myprefix_my_cron_action' ) ) {
    wp_schedule_event( time(), 'weekly', 'myprefix_my_cron_action' );
}

// Hook into that action that'll fire weekly
add_action( 'myprefix_my_cron_action', 'myprefix_function_to_run' );
function myprefix_function_to_run() {
    function my_save_statistiques( $user_id ) {
            [...]
        $visites_totales = $ga->getVisits();

        if ( !current_user_can( 'edit_user', $user_id ) )
        return false;
        update_usermeta( $user_id, 'visites_totales', $visites_totales );
    }
    add_action( 'personal_options_update', 'my_save_statistiques' );
    add_action( 'edit_user_profile_update', 'my_save_statistiques' );
}

Edit 4:
I discovered that
add_action( 'personal_options_update', 'my_save_statistiques' );
is the action when a user updates his own profile but it's not what I want... Because I want to save the data for all users once a day. So that's why (I guess), I thought that my previous code wasn't working.
Edit 5:
FIRST STEP : 1/2 SUCCESS
The user will save his data each time he visits the website. The main goal was to update the data for everyone but it can work like that.
Next step : Cron
function my_save_statistiques( $user_id ) {
    $visites_totales = [myscript];
    if ( !current_user_can( 'edit_user', $user_id ) )
    return false;
    update_usermeta( $user_id, 'visites_totales', $visites_totales );
}
add_action( 'wp_head', 'my_save_statistiques' );

EDIT 6:
Is it correct ?
// Schedule an action if it's not already scheduled
if ( ! wp_next_scheduled( 'wp_head' ) ) {
wp_schedule_event( time(), 'hourly', 'wp_head' );
}
// Hook into that action that'll fire weekly
function my_save_statistiques( $user_id ) {
$visites_totales = [myscript];
update_usermeta( $user_id, 'visites_totales', $visites_totales );
}
add_action( 'wp_head', 'my_save_statistiques' );

I found a different solution
The solution :
Save the time when the action has been ran and check the difference with actual time :
function my_save_statistiques( $user_id ) {
    $user_id = get_current_user_id();
    $current_time = time();

    if (empty($current_time)) {
    update_usermeta( $user_id, 'last_analytics',  $current_time );
    }

    $last_analytics = get_user_meta( $user_id, 'last_analytics', true );
    $diff = $current_time - $last_analytics;
    $one_day = 86400;

    if ($diff > $one_day) {

    $visites_totales = [myscript]

    update_usermeta( $user_id, 'last_analytics',  $current_time );
    update_usermeta( $user_id, 'visites_totales',  $visites_totales );
    }
}

add_action( 'wp_head', 'my_save_statistiques' );

A:

An alternative way to do what I wanted :
Save the time when the action has been ran and check the difference with actual time :
function my_save_statistiques( $user_id ) {
    $user_id = get_current_user_id();
    $current_time = time();

    if (empty($current_time)) {
    update_usermeta( $user_id, 'last_analytics',  $current_time );
    }

    $last_analytics = get_user_meta( $user_id, 'last_analytics', true );
    $diff = $current_time - $last_analytics;
    $one_day = 86400;

    if ($diff > $one_day) {

    $visites_totales = [myscript]

    update_usermeta( $user_id, 'last_analytics',  $current_time );
    update_usermeta( $user_id, 'visites_totales',  $visites_totales );
    }
}

add_action( 'wp_head', 'my_save_statistiques' );

So, the script will run for a logged user if the time between the last "run" and now is more than 24h, knowing that my website is only accessible to a logged user


Q:

what will be type where result get stored when expressions are passed as parameters in c

If i am passing an mathematical expression like func(a*b/c) where type of a may be double, b might be long int etc.
Is there any problem in passing parameters like that? What happens if the resultant value is too long? Any issues in using expressions as function parameters?

A:

Don't mix the definiion of a function with the calling of the function. The definition says what the type of the argumens are; in the calling, the compiler faithfully executes (compiles) the expression, casting it to the appropriate type of the function's argument as it has been defined.
void func1(double a);
void func2(int a);
...
func1( 2 * 3/3);
func2( 2.0 * 3/3);

In the first call to func1(), the expression is evaluated as integers and then the result is pushed onto the stack as a double. In the second cal to func2() the expression is evaluated as doubles and then the result is cast to integer and pushed onto the stack. In the second case the compiler might give a warning about possible loss of precission in the conversion; in the first case it will not issue such a warning as all integer results fit a double.


Q:

Tools for upper/lower case consistency in CMake source

CMake commands are valid in lower, upper, and mixed case. Mixing all of those together in one file however reduces the readability of the CMake code.
Is there a tool for automatically correcting this kind of stylistic inconsistencies?

A:

The answer by steveire links to the right resources, but let me explain explicitly in case those links vanish.
CMake command are case insensitive but lower case is recommended according to CMake developer Brad King in 2012:

Ancient CMake versions required upper-case commands.  Later command
  names became case-insensitive.  Now the preferred style is lower-case.

The shell code that allowed to convert my project CMakeLists.txt file to lower case was inspired by the code behind the links of steveire's answer:
cmake --help-command-list \
    | while read c; do
        echo 's/\([^a-zA-Z_]\|^\)'"$c"'\(\s*\)(/\1'"$c"'\2(/gI'
    done > convert.sed
git ls-files -z -- '*CMakeLists.txt' | xargs -0 sed -i -f convert.sed

It has the following improvements:

grep -v "cmake version" is not required anymore because it seems that the --help-command-list output does not contain that anymore
the original regex contained a \b which made it not match any thing with GNU sed 4.2.2
instead, the cmake command must be preceded by a non-letter/underscore or the start of the line
instead of converting the cmake command to all upper case, make the regex case insensitive. This will also find and convert mixed-case occurrences like Find_Package.
there are no parts specific to the cmake codebase. Modify to fit yours. This simple construct was enough for mine.

A:

Adapt this to your needs:
http://cmake.org/gitweb?p=cmake.git;a=commitdiff;h=77543bd
See also:
http://cmake.org/gitweb?p=cmake.git;a=commitdiff;h=9db31162


Q:

Extracting keys-values from dictionary

import random

dictionary = {'dog': 1,'cat': 2,'animal': 3,'horse': 4}
keys = random.shuffle(list(dictionary.keys())*3)
values = list(dictionary.values())*3
random_key = []
random_key_value = []

random_key.append(keys.pop())
random_key_value.append(???)

For random_key_values.append, I need to add the value that corresponds to the key that was popped. How can I achieve this? I need to make use of multiples of the list and I can't multiply a dictionary directly, either.

A:

I'm going on python (you should specify the language in your question).
If I understand, you want to multiply the elements in the dictionary. So
list(dictionary.keys()) * 3

is not your solution: [1,2] * 3 results in [1,2,1,2,1,2]
Try instead list comprehension:
[i * 3 for i in dictionary.keys()]

To take into account the order (because you shuffle it) shuffle the keys before the multiplication, then create the values list (in the same order that the shuffled keys) and finally multiply the keys:
keys = dictionary.keys()
random.shuffle(keys)
values = [dictionary[i]*3 for i in keys]
keys = [i * 3 for i in keys]

And finally:
random_key.append(keys.pop())
random_key_value.append(values.pop())

Also take care about the random function, it doesn't work as you are using it. See the documentation.


Q:

c# need help working with arrays

is there a way to put these into either a 1 D array or a 2 D array. ? i have produced code and it looks a bit untidy as well as long can this be shortened?
    double worstPrice = 6.47;
    double bestPrice = 0.99;
    double CivetCatPrice =29.14;
    double whenPrice = 10.50;
    double everythingPrice = 319.56;
    int bestStock = 3238;
    int worstStock = 8;
    int civetCatstock = 3;
    int whenStock = 37;
    int everythingStock = 2;

A:

You can make an array for each doubles and ints like this
double[] priceData = new double[]{ 6.47, 0.99, 29.14, 10.50, 319.56 };
int[] stockData = new int[]{ 3238, 8, 3, 37, 2 };

Alternatively you can use a dictionary if you wish for them to keep their names
Dictionary<string, double> priceDict = new Dictionary<string, double>();
priceDict.Add("worstPrice", 6.47);
//And so on for each double

Dictionary<string, int> stockDict = new Dictionary<string, int>();
priceDict.Add("bestStock", 3238);
//And so on for each int

The values in these can be called like so
double worstMinusBestPrices = priceData[0] - priceData[1]; //For arrays
double worstMinusBestPrices = priceDict["worstPrice"] - priceDict["bestPrice"] //For dictionaries


Q:

Yii active record- how to relate a model to another third model

in real words..
i have restaurant model, restaurant model have many foods, and each food have one category,
so m question is how to get all used categories through restaurant model
Really Thanks.

A:

Look at http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-through
Something like:
public function relations()
{
  return array(
    'foods' => array(self::HAS_MANY, 'Food', 'restaurant_id'),
    'categories' => array(self::HAS_MANY, 'Category', array('category_id'=>'id'),
                       'through' => 'foods'),
  );
}

Should be in your Restaurant model.


Q:

If $P(A) = 0$, then can we conclude that $Q(A) = 0 $ ??

Suppose $( \Omega, \mathscr{A}, P ) $ is probability space. $X$ is r.v. such that $X \geq 0 $ almost surely and $\mathbb{E} \{ X \}  = 1 $. Suppose $\exists A \in \mathscr{A}$ s.t. $P(A) = 0$, is it true that $Q(A) = 0 $ as well??
$Q(A) = \mathbb{E}_{\mathbb P} \{ X 1_A \} $

A:

If $P(A)=0$, then $X\mathbf{1}_A=0$ almost surely with respect to $P$. Thus $Q(A)=\mathbb{E}_P[X\mathbf{1}_A]=0$.


Q:

On what basis are block sizes chosen?

Sha1/0 (160 bits output), md5(128 bits output) has block size of 512 bits.
Gost has 256 bits.
What is the reason behind having it specifically  512/256/1024 bits?
What are the various factors which are considered while choosing a specific block size for an algorithm ?
Sorry for the naive question !! :-)

A:

There are really two considerations: fulfilling the security requirements, and doing so efficiently.
Security Considerations
Typically you would select the minimum secure block size depending on the type of algorithm in question, and the target operating environment. A block size that is too small can lead to attacks of time/space complexity that can be performed in practice. For an example, see the sweet32 attack.
Your question mentions hashes, but also mentions algorithm design in general, and the core of a hash function is often times a type of psueodrandom permutation (PRPs are arguably the workhorses of symmetric cryptography).
The block size will need to take into account the type of hashing construction, i.e. a Merkle–Damgård construction versus a sponge construction. For example, the full Keccak uses a larger state than many other designs, which may be related to the fact that much of the state is truncated before being output.
Using a block size smaller than 128 bits is almost guaranteed to enable attacks against your design (which may or may not be applicable, depending your use case). Larger block sizes tend to offer greater security.
Hardware considerations and performance play an integral role.
Using too small of a block size will not make effective use of the available registers on the machine. Using too large of a block size will also not make effective use of the available registers on the machine.
In an otherwise solidly designed psuedorandom permutation, memory accesses in the main loop can/will become the dominant cost, especially in the case of SIMD registers. If you have a bunch of MOV operations into an SIMD register in the main loop of your PRP, you will quickly eat into the advantage provided by SIMD.
SIMD operations are important. In order to compete on the throughput front, it is effectively a requirement to utilize SIMD operations. These instructions allow the application of an instruction to a larger number of registers in parallel. This will effectively multiply your block size while processing it in more or less the same amount of time.
Typically, you would initially target one of: constrained hardware, 8-bit platforms, 32-bit platforms, 64-bit platforms, then use the available SIMD instructions (if any) to increase the throughput of the design. Not all platforms offer SIMD operations - clearly, if you are designing for constrained hardware, this advice about SIMD does not really apply anymore.
Using a block size larger than 1024 bits is likely to be too big on almost any normal platform. To use a 1024-bit permutation effectively, you would need 64-bit registers, with 1 SIMD register spanning the length of 4 normal registers (256-bits), and 4 SIMD registers dedicated to your data (constants and other information that will also put pressure on the registers), then you can operate efficiently on 1024-bits at a time.
Modern desktop CPU's offer 64-bit registers. However, there are still many places where 32-bit platforms are used, as well as 8-bit platforms; Performance on these platforms will suffer if your design does not cater to them.
Similarly, if you design an algorithm that operates on 8 bits at a time, performance may suffer on a platform with wider registers.
Designing an algorithm that is friendly on all platforms is a topic of current research
In general, it will probably tend to yield a more balanced algorithm to design for an 8-bit or 32-bit platform, then run multiple instances in parallel via SIMD. This way you can ensure that performance is acceptable on all platforms, rather than excellent at one end of the spectrum, and horrible at the other.
Gimli opts for a 384-bit block size, so that is probably the sweet spot for balanced performance on all platforms. You may be able to squeeze slightly more performance out of a 512-bit block size, depending the nature of your design.
Why is the performance section larger than the security one?
If efficiency is not a concern, then the game becomes too easy. Just make everything huge. Don't expect your design to see use in the real world if you can't hash more then 20MB/s on a desktop CPU...


Q:

ChartJS time axis not plotting correctly | getting an hour instead of date

I have a time series that is a CSV file (pastebin link).  I am trying to plot the cumulative time (one of the columns) on the Y axis with the date on the X axis and the tooltip as the task completed.  The Y axis and the tooltip work fine but the X-axis date does not.  Instead of getting a date on the X-axis, I get a time.  I am not sure why that is.  Can someone help, please?
If I can better share these files with you, please let me know and I can try and do that for your convenience.
Outcome:

HTML (Paste bin):
<!DOCTYPE html>
<html lang="en">

  <head>
    <title>Task progress scatter chart</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8">
    <!-- Load jQuery -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <!-- Load Chart.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
    <!-- Load D3.js to read csv files -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.9.7/d3.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
  </head>

  <body>
    <canvas id="container" style="width:100%; height:400px;"></canvas>
    <script src="./script_ed5101.js"></script>
  </body>

</html>

Java script (Paste bin) with Chart:
$(document).ready(function() {

  var TITLE = 'Task progress';

  var POINT_X = 'date'; // column name for x values in data csv
  var POINT_X_PREFIX = ''; // prefix for x values, eg '$'
  var POINT_X_POSTFIX = ''; // postfix for x values, eg '%'

  var POINT_Y = 'cumulative'; // column name for y values in data.csv
  var POINT_Y_PREFIX = ''; // prefix for x values, eg 'USD '
  var POINT_Y_POSTFIX = ''; // postfix for x values, eg ' kg'

  var POINT_NAME = 'task'; // point names that appear in tooltip
  var POINT_COLOR = 'rgba(0,0,255,0.7)'; // point color, eg `black` or `rgba(10, 100, 44, 0.8)`
  var POINT_RADIUS = 3; // radius of each data point

  var X_AXIS = 'Date';  // x-axis label and label in tooltip
  var Y_AXIS = 'Cumulative time on tasks'; // y-axis label and label in tooltip

  var SHOW_GRID = true; // `true` to show the grid, `false` to hide

  // Read data file and create a chart
  d3.csv('./time_series.csv').then(function(rows) {

    var data = rows.map(function(row) {
      return {
        x: row[POINT_X],
        y: row[POINT_Y],
        name: row[POINT_NAME]
      }
    })

        var scatterChartData = {
            datasets: [{
                label: 'task progress',
                backgroundColor: POINT_COLOR,
        data: data,
        pointRadius: POINT_RADIUS,
        pointHoverRadius:  POINT_RADIUS + 2,
            }]
    };

    var ctx = document.getElementById('container').getContext('2d');

    Chart.Scatter(ctx, {
      data: scatterChartData,
      options: {
        title: {
          display: true,
          text: TITLE,
          fontSize: 14,
        },
        legend: {
          display: false,
        },
        scales: {
          xAxes: [{
            type: 'time',
        distribution: 'series',
            scaleLabel: {
              display: true,
              labelString: X_AXIS
            },
            gridLines: {
              display: SHOW_GRID,
            },
            ticks: {
              callback: function(value, index, values) {
                return POINT_X_PREFIX + value.toLocaleString() + POINT_X_POSTFIX;
              }
            }
          }],
          yAxes: [{
            scaleLabel: {
              display: true,
              labelString: Y_AXIS
            },
            gridLines: {
              display: SHOW_GRID,
            },
            ticks: {
              callback: function(value, index, values) {
                return POINT_Y_PREFIX + value.toLocaleString() + POINT_Y_POSTFIX;
              }
            }
          }]
        },
        tooltips: {
          displayColors: false,
          callbacks: {
            title: function(tooltipItem, all) {
              return [
                all.datasets[tooltipItem[0].datasetIndex].data[tooltipItem[0].index].name,
              ]
            },
            label: function(tooltipItem, all) {
              return [
                X_AXIS + ': ' + POINT_X_PREFIX + tooltipItem.xLabel.toLocaleString() + POINT_X_POSTFIX,
                Y_AXIS + ': ' + POINT_Y_PREFIX + tooltipItem.yLabel.toLocaleString() + POINT_Y_POSTFIX
              ]
            }
          }
        }
      }
    });

  });
});

A:

You could define time.unit option 'day' on your xAxis as explained here. This will display the xAxis tick mark in the default display format defined for 'day'.
xAxes: [{
  type: 'time',
  time: {
    unit: 'day'
  }
  ...

In case you want the date to be displayed in a different format, the definition could look as follows.
xAxes: [{
  type: 'time',
  time: {
    unit: 'day',
    displayFormats: {
      day: 'YYYY-MM-DD'
    },
    tooltipFormat: 'YYYY-MM-DD'
  }

See Moment.js for the allowable format strings.


Q:

Angular2 date range picker format date string

I am using this calendar on my Angular2/Spring web application:
https://www.npmjs.com/package/ng2-daterangepicker
http : // www. daterangepicker . com/
I am facing the problem of formatting the date output. From the official documentation this is the object that is responsible for formatting the date:

locale.format: "MM/DD/YY" // which returns 05/13/2017

However, I am interested in more user-friendly output. Something like: May 2017.
How am I suppose to do this? Where can I found letters that can format my date in Javascript (like this in PHP: http://php.net/manual/en/function.date.php).
Thank you very much for the replies.

A:

If I were you I'd save myself the hassle of working with Dates in Javascript and download Moment.js. If you're using npm you can install it with
npm install moment --save

Dates are a pain to work with in vanilla JS so moment is a really powerful library that lets you "parse, validate, manipulate, and display dates and times" super easily. To use it in your Angular2 Component you just need to import it in your component after downloading it.
import * as moment from 'moment';

Then you can format your output date using the format() function.
let rangePickerValue = new Date(); // example date
moment(rangePickerValue).format('MMMM YYYY'); // May 2017

You can see what sort of time and date output options there are in moment's documentation: here. For examlpe, MMMM outputs the full month's name (January, February, March...) while MMM prints (Jan, Feb, Mar...).


Q:

Event OnLoad on Telerik's grid (client selection)

I'm using Grid with "Client Selection" (http://demos.telerik.com/aspnet-mvc-beta/grid/selectionclientside) of Telerik, and my page loads with one of the lines already marked. I wonder how it could activate the event OnRowSelected (on the marked line) when the page loads.
Thanks everyone!

A:

You can check this forum thread.


Q:

Cut issue in prolog

I'm trying to do an exercise in prolog. I put a lot of cut (I know. Too much and some of them are useful and I will discuss in future to remove some of them), otherwise the program doesn't stop itself. Here is my code:
as_monomial(X, m(X, 0, [])) :- number(X), !.
as_monomial(^(Y, Z), m(1, Z, [v(Z, Y)])) :- !.
as_monomial(*(X, ^(Y, Z)), m(G, K, Q)) :- as_monomial(X, m(G, TD, Vars)), K is (TD + Z), ordina_m([v(Z, Y)| Vars], Q), !.
as_monomial(*(X, Y), m(G, K, Q)) :- as_monomial(X, m(G, TD, Vars)), K is (TD + 1), ordina_m([v(1, Y)| Vars], Q), !.
as_monomial(-(X), m(-A, Y, L)) :- as_monomial(X, m(A, Y, L)).
as_monomial(X, m(1, 1, [v(1, X)])).

ordina_m(List, Sorted) :- sort(2, @=<, List,  Sorted).

ordina_poly1(List, Sorted) :- sort(2, @>=, List,  Sorted).
ordina_poly2(List, Sorted) :- sort(3, @=<, List,  Sorted).

is_monomial(m(_C, TD, VPs)) :- integer(TD), TD >= 0, is_list(VPs).

is_polynomial(poly(M)) :- is_list(M), foreach(member(Monomio, M), is_monomial(Monomio)).

as_polynomial(+(X, Y), poly(C)) :- as_monomial(Y, G), as_polynomial(X, poly(Gs)), inverti(G, H), inverti2(Gs, Hs), ordina_poly2([H| Hs], D), inverti2(D, F), ordina_poly1(F, C), !.
as_polynomial(-(X, Y), poly(C)) :- as_monomial(-Y, G), as_polynomial(X, poly(Gs)), inverti(G, H), inverti2(Gs, Hs), ordina_poly2([H| Hs], D), inverti2(D, F), ordina_poly1(F, C), !.
as_polynomial(X, poly([X])) :- is_monomial(X), !.
as_polynomial(X, poly([Q])) :- as_monomial(X, Q), is_monomial(Q).

/* coefficienti */
coefficients(Poly1, Result) :- is_polynomial(Poly1), coefficienti(Poly1, Result), !.
coefficients(Poly1, Result) :- as_polynomial(Poly1, Result1), coefficienti(Result1, Result), !.

coefficienti(poly([]), []) :- !.
coefficienti(poly([m(X, _, _)|Xs]), [X|Ys]) :- coefficienti(poly(Xs), Ys), !.

/* variabili */
variables(Poly1, Result) :- is_polynomial(Poly1), variabili(Poly1, Result), !.
variables(Poly1, Result) :- as_polynomial(Poly1, Result1), variabili(Result1, Result), !.

variabili(poly([]), []) :- !.
variabili(poly([m(_, _, X)|Xs]), [X|Ys]) :- variabili(poly(Xs), Ys), !.

/* monomi */
monomials(Poly1, Result) :- is_polynomial(Poly1), monomi(Poly1, Result), !.
monomials(Poly1, Result) :- as_polynomial(Poly1, Result1), monomi(Result1, Result), !.

monomi(poly([]), []) :- !.
monomi(poly([X|Xs]), [X|Ys]) :- monomi(poly(Xs), Ys), !.

/* somma */
polyplus(Poly1, Poly2, Result) :- is_polynomial(Poly1), is_polynomial(Poly2), poly_plus(Poly1, Poly2, Result), !.
polyplus(Poly1, Poly2, Result) :- is_polynomial(Poly1), as_polynomial(Poly2, Q), poly_plus(Poly1, Q, Result), !.
polyplus(Poly1, Poly2, Result) :- as_polynomial(Poly1, Q), is_polynomial(Poly2), poly_plus(Q, Poly2, Result), !.
polyplus(Poly1, Poly2, Result) :- as_polynomial(Poly1, Q1), as_polynomial(Poly2, Q2), poly_plus(Q1, Q2, Result).

poly_plus(poly([]), poly(Q), poly(Q)) :- !.
poly_plus(poly([X|Xs]), poly(Q), poly([X|Z])) :- poly_plus(poly(Xs), poly(Q), poly(Ys)), compress_somma(X, Ys, Z), compara(Ys, Z).
poly_plus(poly([X|Xs]), poly(Q), poly(Z)) :- poly_plus(poly(Xs), poly(Q), poly(Ys)), compress_somma(X, Ys, Z).

compress_somma(_X, [], []) :- !.
compress_somma(m(X,Y,Z), [m(R,Y,Z)| List1], [m(K,Y,Z)| List2]) :- compress_somma(m(X,Y,Z), List1, List2), K is (R + X), !.
compress_somma(X, [Y| List], [Y| List]) :- compress_somma(X, List, List).

/* differenza */
polyminus(Poly1, Poly2, Result) :- is_polynomial(Poly1), is_polynomial(Poly2), poly_minus(Poly1, Poly2, Result), !.
polyminus(Poly1, Poly2, Result) :- is_polynomial(Poly1), as_polynomial(Poly2, X), poly_minus(Poly1, X, Result), !.
polyminus(Poly1, Poly2, Result) :- as_polynomial(Poly1, X), is_polynomial(Poly2), poly_minus(X, Poly2, Result), !.
polyminus(Poly1, Poly2, Result) :- as_polynomial(Poly1, Y), as_polynomial(Poly2, Z), poly_minus(Y, Z, Result).

poly_minus(poly([]), poly(X), poly(X)) :- !.
poly_minus(poly([X|Xs]), poly(Q), poly([X|Z])) :- poly_minus(poly(Xs), poly(Q), poly(Ys)), compress_differenza(X, Ys, Z), compara(Ys, Z).
poly_minus(poly([X|Xs]), poly(Q), poly(Z)) :- poly_minus(poly(Xs), poly(Q), poly(Ys)), compress_differenza(X, Ys, Z).

compress_differenza(_X, [], []) :- !.
compress_differenza(m(X,Y,Z), [m(R,Y,Z)| List1], [m(K,Y,Z)| List2]) :- compress_differenza(m(X,Y,Z), List1, List2), K is (X - R), !.
compress_differenza(X, [Y| List], [Y| List]) :- compress_differenza(X, List, List).

/*moltiplicazione */

compara([], []) :- !.
compara([X|Xs], [X|Ys]) :- compara(Xs, Ys).

inverti(m(_, _, []), m(_, _, [])) :- !.
inverti(m(X, Y, [v(W, Z)| Xs]), m(X, Y, [v(Z, W)| Ys])) :- inverti(m(X, Y, Xs), m(X, Y, Ys)), !.

inverti2([], []) :- !.
inverti2([m(X, Y, [])| Zs], [m(X, Y, [])| Ss]) :- inverti2(Zs, Ss), !.
inverti2([m(X, Y, [v(W, Z)| Xs])| Zs], [m(X, Y, [v(Z, W)| Ys])| Ss]) :- inverti2([m(X, Y, Xs)| Zs], [m(X, Y, Ys)| Ss]), !.

The program gives me as output the right one but, instead of give me the end of the procedure it looks like it's waiting for something and I have to "force" the end with "enter". Is there some problem or it should be normal? Are you able to help me in someway? Thanks everyone

A:

Okay. I solve my problem thanks to @coder. To solve it I put another cut (maybe the good one) in a single line of the closure "as_polynomial":
as_polynomial(+(X, Y), poly(C)) :- as_monomial(Y, G), as_polynomial(X, poly(Gs)), inverti(G, H), inverti2(Gs, Hs), ordina_poly2([H| Hs], D), inverti2(D, F), ordina_poly1(F, C), !.
as_polynomial(-(X, Y), poly(C)) :- as_monomial(-Y, G), as_polynomial(X, poly(Gs)), inverti(G, H), inverti2(Gs, Hs), ordina_poly2([H| Hs], D), inverti2(D, F), ordina_poly1(F, C), !.
as_polynomial(X, poly([X])) :- is_monomial(X), **!**.
as_polynomial(X, poly([Q])) :- as_monomial(X, Q), is_monomial(Q).
Then I also remove is_monomial(Q) because it was not useful


Q:

SqLite in memory database : CREATE TABLE does not work?

When using this code on a SqLite file database, it works fine.
using (var ctx = new Test2010Entities())
{
    string s = "CREATE TABLE 'Company' ([Id] integer PRIMARY KEY AUTOINCREMENT NOT NULL, varchar(50) NOT NULL);";

    ctx.ExecuteStoreCommand(s);

    ctx.Companies.AddObject(new Company { Code = "_1" });
    ctx.Companies.AddObject(new Company { Code = "_2" });

    ctx.SaveChanges();

    foreach (var c in ctx.Companies.ToList())
    {
        Console.WriteLine(c.Code);
    }
}

But when runnning this code on a SqLite 'In Memory' database (Data Source=:memory:;Version=3;New=True;) , I get this exception:

Unhandled Exception: System.Data.UpdateException: An error occurred
  while updating the entries. See the inner exception for details. --->
  System.Data.SQLite.SQLiteException: SQL logic error or missing
  database no such table: Company

Note this is tested with VS 2010, EF 4.4.0.0 and sqlite-netFx40-setup-bundle-x86-2010-1.0.84.0

::: UPDATE :::

As Simon Svensson suggested, opening the connection before any other commands does do the trick:
ctx.Connection.Open();

A:

This happens when your ORM closes your connection, and reopens it. That will reset the sqlite in-memory database to its default state; i.e. empty.
The same thing happens with NHibernate unless you set connection.release_mode = close (the default is after_transaction.
I'm not familiar with Entity Framework, but I expect a similar setting or using the DataContext(IDbConnection) constructor which is documented as "If you provide an open connection, the DataContext will not close it."
The same documentation also states "In a System.Transactions transaction, a DataContext will not open or close a connection to avoid promotion." which may be a cleaner solution.
Using some Reflector magic shows that it's SQLiteConnection.Open that calls (via SQLite3.Open) sqlite3_open_interop (if you're using the NuGet sqlite package). This shows that you get a new empty in-memory database everytime you call SQLiteConnection.Open.


Q:

How can i update checkbox checked rows when i click on save amt button in php

I want to update checkbox checked rows when i click on save amt button. Please help me i getting error.
<?php
include_once("config.php");
if(isset($_POST['submit']))
{
  $paitAmt = $_POST['paidamt'];
  $uid = $_POST['uid'];
  $array = array($paitAmt, $uid);
  foreach ($array as list($paitAmt, $uid)) {
  $sql = "UPDATE tbldemo SET paidAmt = '$paitAmt' WHERE id = '$uid'";
  echo $sql;
  $result = mysql_query($sql);
  echo 'Updated Successfully';
  }
}
?>

A:

Try this:
<?php
include_once("config.php");
if(isset($_POST['submit']))
{
  $paitAmt = $_POST['paidamt'];
  $uid = $_POST['uid'];
  foreach ($paitAmt as $key=>$value) {
  $sql = "UPDATE tbldemo SET paidAmt = '$value' WHERE id = '{$uid[$key]}'";
  //echo $sql;
  $result = mysql_query($sql);
  echo 'Updated Successfully';
  }
}
?>


Q:

Very simple Hangman game

Does this code follow standard conventions, not redundant? How I can make it more comprehensible for other people?
It's an exercise from the Java introductory book:

Write a hangman game that randomly generates a word and
  prompts the user to guess one letter at a time. Each letter in the word is displayed as an asterisk. When the user makes a correct guess, the actual letter is then displayed. When the user finishes a word, display the number of misses.

My program:
import java.util.Arrays;
import java.util.Scanner;

public class Hangman{
    public static void main(String[] args) {
        String[] words = {"writer", "that", "program"};
        // Pick random index of words array
        int randomWordNumber = (int) (Math.random() * words.length);
        // Create an array to store already entered letters
        char[] enteredLetters = new char[words[randomWordNumber].length()];
        int triesCount = 0;
        boolean wordIsGuessed = false;
        do {
        // infinitely iterate through cycle as long as enterLetter returns true
        // if enterLetter returns false that means user guessed all the letters
        // in the word e. g. no asterisks were printed by printWord
        switch (enterLetter(words[randomWordNumber], enteredLetters)) {
            case 0:
                triesCount++;
                break;
            case 1:
                triesCount++;
                break;
            case 2:
                break;
            case 3:
                wordIsGuessed = true;
                break;
        }
        } while (! wordIsGuessed);
        System.out.println("\nThe word is " + words[randomWordNumber] +
            " You missed " + (triesCount -findEmptyPosition(enteredLetters)) +
            " time(s)");
    }

    /* Hint user to enter a guess letter,
    returns 0 if letter entered is not in the word (counts as try),
    returns 1 if letter were entered 1st time (counts as try),
    returns 2 if already guessed letter was REentered,
    returns 3 if all letters were guessed */
    public static int enterLetter(String word, char[] enteredLetters)    {
        System.out.print("(Guess) Enter a letter in word ");
        // If-clause is true if no asterisks were printed so
        // word is successfully guessed
        if (! printWord(word, enteredLetters))
            return 3;
        System.out.print(" > ");
        Scanner input = new Scanner(System.in);
        int emptyPosition = findEmptyPosition(enteredLetters);
        char userInput = input.nextLine().charAt(0);
        if (inEnteredLetters(userInput, enteredLetters)) {
            System.out.println(userInput + " is already in the word");
            return 2;
        }
        else if (word.contains(String.valueOf(userInput))) {
            enteredLetters[emptyPosition] = userInput;
            return 1;
        }
        else {
            System.out.println(userInput + " is not in the word");
            return 0;
            }
    }

    /* Print word with asterisks for hidden letters, returns true if
    asterisks were printed, otherwise return false */
    public static boolean printWord(String word, char[] enteredLetters) {
        // Iterate through all letters in word
        boolean asteriskPrinted = false;
        for (int i = 0; i < word.length(); i++) {
            char letter = word.charAt(i);
            // Check if letter already have been entered bu user before
            if (inEnteredLetters(letter, enteredLetters))
                System.out.print(letter); // If yes - print it
            else {
                System.out.print('*');
                asteriskPrinted = true;
            }
        }
        return asteriskPrinted;
    }

    /* Check if letter is in enteredLetters array */
    public static boolean inEnteredLetters(char letter, char[] enteredLetters) {
        return new String(enteredLetters).contains(String.valueOf(letter));
    }

    /* Find first empty position in array of entered letters (one with code \u0000) */
    public static int findEmptyPosition(char[] enteredLetters) {
        int i = 0;
        while (enteredLetters[i] != '\u0000') i++;
        return i;
    }
}

Log of its work:

(Guess) Enter a letter in word **** > a
(Guess) Enter a letter in word **a* > t
(Guess) Enter a letter in word t*at > q
q is not in the word
(Guess) Enter a letter in word t*at > t
t is already in the word
(Guess) Enter a letter in word t*at > b
b is not in the word
(Guess) Enter a letter in word t*at > h
(Guess) Enter a letter in word that
The word is that You missed 2 time(s)

A:

Magic Numbers: It would be better to move your definitions for 0,1,2,3 into an enum or final fields so that you can reference them with a meaningful name. For example final int LETTER_NOT_IN_WORD = 0 or enum HangmanGuess { LETTER_NOT_IN_WORD }
Redundancy: The core logic between findEmptyLetters and inEmptyLetters is the same, you are looking for a char in a char[]. You could refactor like this:
/* Check if letter is in enteredLetters array */
public static boolean inEnteredLetters(char letter, char[] enteredLetters) {
    return indexOf(letter, enteredLetters) >= 0;
}

/* Find first empty position in array of entered letters (one with code \u0000) */
public static int findEmptyPosition(char[] enteredLetters) {
    return indexOf('\u0000', enteredLetters)
}

/* Determine the index in {@code vals} where {@code ch} exists. Returns -1 if {@code ch} is not in {@code vals}. */
public static int indexOf(char ch, char[] vals) {
    return Arrays.asList(vals).indexOf(Character.valueOf(ch));
}

One thing to point out also is that in the current implementation, findEmptyPosition will return n where n is the enteredLetters.length + 1 if there are no empty positions. I'm not sure if this is the desired functionality.

A:

First (small) thing: it seems more common to use Random than Math.random(). See this best practices post.
The comments and switch first thing inside the do{ }while() is very confusing for me personally.  enterLetter() never returns true or false, and even most new programmers know a do / while iterates until the condition is met. It would be more helpful to describe what 0-3 represent (and if this were production code or more complex, an Enum would make it considerably more understandable).
Inside of enterLetter(), it would be helpful to move the int emptyPosition = findEmptyPosition(enteredLetters); call to the else if where it's used. Not only does it prevent allocating the memory until it's used, but it's also more readable (and you could remove the emptyPosition variable if you wanted and call the function inside the reference, but that's semantic).


Q:

Password validator with 8 characters and 2 digits don't work

Hey i'm trying to make this password validator working with 8 characters and 2 digits  but.. it doesn't.
I don't see how there's something wrong about my code .My console doesn't say that there's an error

                        Password:
                        <input type="text" name="pass-one" id="pass-one" />
                        Not Ok

A:

In order to make your code work you need to wrap it into an event handler. For instance you may use the change event and the addEventListener() to set the handler:

document.getElementById('pass-one').addEventListener('change', function(e) {
    let regex = new RegExp("^(?=(.*[a-zA-Z]){1,})(?=(.*[0-9]){2,}).{8}$");

    if ( !regex.test(this.value)) {
        document.getElementById("validity").innerHTML = "Not Ok";
        //return false;
    } else {
        document.getElementById("validity").innerHTML = "Ok";
    }
})

    Password:
    <input type="text" name="pass-one" id="pass-one" />
    Not Ok


Q:

How to store special characters in Hive?

I've been playing around with Spark, Hive and Parquet, I have some data in my Hive table and here is how it looks like ( warning french language ahead ) :
Bloqu� � l'arriv�e      NULL
Probl�me de connexion   Bloqu� en hub

Obviously there's something wrong here.
What I do is : I read a teradata table as a dataframe with spark, I store it as a parquet file and then I use this file to store it to hive, here's my create table script :
CREATE TABLE `table`(
   `lib` VARCHAR(255),
   `libelle_sous_cause` VARCHAR(255),
   )
 STORED AS PARQUET
 LOCATION
   'hdfs://location';

I don't really know what cause this, it might be caused by some special encoding between Teradata > parquet or Parquet > Hive, I'm not sure.
Any help will be appreciated, thanks.

A:

I figured that out, the solution was to simply use STRING instead of VARCHAR
CREATE TABLE `table`(
   `lib` STRING,
   `libelle_sous_cause` STRING,
   )
 STORED AS PARQUET
 LOCATION
   'hdfs://location';


Q:

Not Able to start Deployer Service after Sdl Web 8.5 CME installation

I have installed SDL web 8.5 on a single machine as mentioned here https://docs.sdl.com/LiveContent/web/pub.xql?action=home&pub=SDL%20Web-v5&lang=en-US#docid=GUID-8789A353-267D-4466-9A6D-4CF6709E4E88&addHistory=true&query=&scope=&tid=&filename=GUID-26992293-7D88-46D7-937F-5EBBA1DA3ABF.xml&resource=&inner_id=&toc=false&eventType=lcContent.loadDocGUID-8789A353-267D-4466-9A6D-4CF6709E4E88
But the Deployer service is not getting started.  When I try to start it manually, it says "SOME SERVICES STOP AUTOMATICALLY IF THEY ARE NOT IN USE BY OTHER SERVICES OR PROGRAMS". I can see Web Capabilities are added as roles in Cd_Storage file of Discovery Service :
<Role Name="TokenServiceCapability" Url="http://10.0.1.5:8082/token.svc"/>
      <Role Name="WebCapability"/>
</Roles>

I can See Deployer Service set as Local System Account for logon, which should be correct.

Note: I have ran .\quickinstall.ps1 -enable-discovery -enable-context -enable-deployer-combined -enable-preview -enable-session -auto-register -discovery-url http://localhost:8082/discovery.svc
-auto-register switch is on, also java -jar discovery-registration.jar update command executed
Only thing I noticed that after running quick install PowerShell with auto-register on, I didn't see Web Capabilities added in Cd_Storage file, I added it manually as mentioned in the doc as well.
Is it a correct sequence, or do I need to run the quick install again as web capabilities are added later?

A:

I don't think you should expect there to be any dependency between the CME and the deployer service. In normal circumstances, you would be expecting them to run on entirely separate servers, with the only connection being that the transport service talks to the deployer endpoint.
If you encounter a problem when running them on the same server, then a possible cause for problems is contention over some resource or other. So you could check whether you've configured the two services on the same port, for example.
In your comment you mention that publishing is stuck in Waiting for Publisher. Assuming that your items are the only items in the queue, the usual cause for this is that the publisher service isn't running.
In general with this kind of work, the most helpful source of information is logging. So make sure the appropriate logging level is set (presumably DEBUG in this situation) and read the logs.


Q:

Calculated Column with Item ID not working for new Items

My calculated column is using the Item Name and Item ID

="list-name/"&Title&"/"&ID

This works for all existing items but when I create a new item the item ID is not being appended. Is this because the column is calculating before the item is created? If so, Is there a way to recalculate the column after the item is created?
If I can't use Item ID, is there another unique identifier i could use?

A:

It is not supported by Microsoft to use ID in a calculated column. That is the reason why does not appear in the options to build the formula.

A:

jpussacq is correct as to why it doesn't work.
You can workaround this by populating the field using a workflow. If the Title could be changed, the workflow should run when the item is created and when it is changed.


Q:

Cannot add items to an NSMutableArray ivar

My goal is to add a string to array, and I do that in a method which I call.
In this method, I get a null value in the array, and don't know why. I have this at the start of my class:
NSMutableArray *listOfEvents;

and a method which I call on each event:
-(void)EventList
{
    [listOfEvents addObject:@"ran"];
    NSLog(@"%@", listOfEvents);
}

I get (null) in the log.
If I put the array definition  NSMutableArray *listOfEvents; in the function body, I get the string value @"ran", each time, so the array always has only one value, instead of having many strings named @"ran".
What's wrong with this? It seems that I can't understand something about arrays, even though I have read the documents a number of times.

A:

I'm assuming you haven't initialized listOfEvents.
Make sure you do listOfEvents = [[NSMutableArray alloc] init]; in your class's init method. Also make sure you release it in your class's dealloc method.

A:

If you're getting nil in your log message, you need to make sure listOfEvents is non-nil before adding your object. IE:
-(void)EventList
{
    if (listOfEvents == nil) {
        listOfEvents = [[NSMutableArray alloc] init];
    }
    [listOfEvents addObject:@"ran"];
    NSLog(@"%@",listOfEvents);
}

In Objective-C, messages with void return types sent to nil go to absolutely-silent nowhere-land.
Also, for the sake of balance, be sure you have a [listOfEvents release] call in your dealloc implementation.


Q:

In Java, can I consolidate two similar functions where uses JspWriter and the other PrintWriter?

I have the following class, which as you will see has rather a rather redundant formatNameAndAddress method:
package hu.flux.helper;
import java.io.PrintWriter;

import javax.servlet.jsp.JspWriter;

// A holder for formatting data
public class NameAndAddress
{
 public String firstName;
 public String middleName;
 public String lastName;
 public String address1;
 public String address2;
 public String city;
 public String state;
 public String zip;

 // Print out the name and address.
 public void formatNameAndAddress(JspWriter out)
  throws java.io.IOException
  {
   out.println("
");
    out.print(firstName);

    // Print the middle name only if it contains data.
    if ((middleName != null) && (middleName.length() > 0))
     {out.print(" " + middleName);}

    out.println(" " + lastName);

    out.println(" " + address1);

    if ((address2 != null) && (address2.length() > 0))
     out.println(" " + address2);

    out.println(city + ", " + state + " " + zip);
   out.println("
");
  }

 public void formatName(PrintWriter out)
 {
  out.println("
");
  out.print(firstName);

  // Print the middle name only if it contains data.
  if ((middleName != null) && (middleName.length() > 0))
   {out.print(" " + middleName);}

  out.println(" " + lastName);

  out.println(" " + address1);

  if ((address2 != null) && (address2.length() > 0))
   out.println(" " + address2);

  out.println(city + ", " + state + " " + zip);
  out.println("
");
 }
}

I'd like to rewrite the class to use a generic method like:
     // Print out the name and address.
 private void genericFormatNameAndAddress(Object out)
 {
  out.println("
");
   out.print(firstName);

   // Print the middle name only if it contains data.
   if ((middleName != null) && (middleName.length() > 0))
    {out.print(" " + middleName);}

   out.println(" " + lastName);

   out.println(" " + address1);

   if ((address2 != null) && (address2.length() > 0))
    out.println(" " + address2);

   out.println(city + ", " + state + " " + zip);
  out.println("
");
 }

But, I can't do this exactly like this because Object doesn't have print() and println() methods.  If I cast the output to either JspWriter or PrintWriter, I'd be casting it the wrong way sometimes.
I imagine what I need to do is somehow pass the object type as a variable and then use the variable to determine how to cast.  Is this possible?  If so, how?  If not, what would be a good solution?

A:

This will probably work:
public void formatNameAndAddress(JspWriter out) throws java.io.IOException {
    formatNameAndAddress(new PrintWriter(out));
}


Q:

Gremlin find all vertices that have "any" property with a given value

The properties in my graph are dynamic. That means, there can be any number of properties on the vertices. This also means that, when I do a search, I will not know what property value to look for. Is it possible in gremlin to query the graph to find all vertices that have any property with a given value.
e.g., with name and desc as properties. If the incoming search request is 'test', the query would be g.V().has('name', 'test').or().has('desc', 'test'). How can I achieve similar functionality when I do not know what properties exist? I need to be able to search on all the properties and check if any of those properties' value is 'test'

A:

You can do this using the following syntax:
g.V().properties().hasValue('test')

However, with any size dataset I would expect this to be a very slow traversal to perform as it is the equivalent of asking an RDBMS "Find me any cell in any column in any table where the value equals 'test'".  If this is a high frequency request I would suggest looking at refactoring your graph model or using a database optimized for searches such as Elasticsearch.


Q:

Configuring Content for Editable Email Notification Jenkins

I am using Editable E-mail notification to send email after a slave job is finished with the console output and test results as the email body.
I also need to add to the email direct link to the folder where build was actually built, is there an easy way to do this? maybe some kind of token? I didn't find any clues on how to get direct link to the build folder to display it location in the email.

A:

First, click the question mark ? next to Content Token Reference, this will tell you all you need.
What "folder where build was actually built" are you referring to? The Workspace, or the build Archive?
For Workspace: ${PROJECT_URL}/ws/
For Archive: ${BUILD_URL}/artifact/

A:

Build output:
${BUILD_LOG, maxLines=1000}
For tests you can use the tokens as below:
There are ${TEST_COUNTS, var="total"} total tests of which ${TEST_COUNTS, var="fail"} test(s) failed.
${FAILED_TESTS} - Displays failing unit test information, if any tests failed.
For complete reference to Content token and arguments, click on help icon.


Q:

See the creator of an image file

I hope this question fits on this stack exchange, if not I am sorry.
I was wondering whether it is possible to see who the creator of a certain image file is.
As an example lets say I have created an image(PNG,JPG etc...) through Photoshop or GIMP, would another person of whom I have sent the image file, then be able to check that I am the creator? Like if they check certain data of the image by "taking it apart" and then get information regarding the creator of the image, maybe the name of the PC or alike.

A:

JPEG and PNG have a "Comment" header and JPEG (and perhaps PNG) support EXIF/ICMP metadata. If you create the image from scratch (this can mean creating an empty image, and pasting another image over it) there won't be anything to identify the author in it (unless you have set a default image comment)(this is true for Gimp, I don't know what PS does by default).
In the general case it is hard to prove that you are (or are not) the author of an image because all the metadata can be very simply forged/cleaned.


Q:

What happened to the Lassiter?

In Trash, the crew steals a very valuable, antique laser pistol known as the Lassiter.
In The Message, Mal mentions that he's having difficulty selling it.

MAL:
  It's like something out of a fable!
  I've got this priceless artifact, the
  biggest score of my unseemly career,
  and no one will touch it.
INARA:
  The Lassiter's universally known.
  Fencing it is like...
  fencing the Mona Lisa.

In Serenity, which takes place pretty soon after, Mal is so desperate for money that he goes into straight-up armed robbery.
So what happened to the Lassiter? Were they not able to sell it? If so, what did they do with it?

A:

This is addressed in the film's official novelisation. In short, they sold it and used the funds to upgrade the Serenity.

This [The Serenity] was Mal's pride and joy. A while back, they got their hands on
  one of the few remaining Lassiters, one of the early laser pistols.
  Expensive as hell, they'd lifted it from right under the nose of a
  rich gent name of Durran from his estate on Belerophon. Took a spell
  to find a buyer for so major an item, but a buyer they did find, and
  the funds went to purchase a fancy new mule.

Inara seemed to think that she knew people who could afford it, so it's possible that one of her contacts ended up taking it off them for a fat fee.

MAL: It's like something out of a fable! I've got this priceless artifact, the biggest score of my unseemly career, and no one will
  touch it.
INARA: The Lassiter's universally known. Fencing it is like... fencing the Mona Lisa.
MAL: Well... Mona Who?
INARA: You're out of your league. You should consider my offer --
MAL: I done thinking about that, and you ought to stay clear.
INARA: I know people in the highest ranks of --
MAL: Jabber jabber jabber. I ain't listening. Just 'cause you helped out on the job don't make you a crook. I will not have you
  jeopardizing your career over this.

As to the proceeds of the sale, by the time of the film Serenity (supposedly set several months later) we see that the ship has been radically overhauled with a much larger dining area, a dedicated ship's kitchen, a medical bay with a fancy new medi-bed and all sorts of scanners and gizmos, not to mention that the exterior seems to be sporting a new wing design and the flashy new hover-mule.
It seems reasonably likely that that sort of work would require a lot of money, the kind of cash you'd get from selling a priceless artifact, even at a whomping discount.

A:

The show was cancelled. The Lassiter was featured in the third to last last episode of the series, with the last two episodes completely ignoring that plot thread.
However, we don't know what happened to it, in-universe. Suffice to say, it was too hard to fence; Mal had voiced such in The Message and the crew is later seen to still be quite destitute, later, in the film. This would not be possible had it been fenced, as it was a

priceless artifact


Q:

What is the difference among "Sign up", "Sign in" and "Log in"?

As I said in the title, I am wondering what is the meaning of the following expressions, and what are the differences between them ?

"Sign up"
"Sign in"
"Log in"

A:

While Hellion describes those terms in general, I am writing here in the context of the cyberworld that also includes the gadgets. You mentioned log-in and that's what makes me think that you probably want to know the difference in the context of Internet.
Well, sign up simply means to register. It could be portal, newsletter or things the like. So when you visit and access anything for the first time, you need to sign up. Often, this is referred to as register. For instance, if you are new to Twitter, you need to sign up first.
What is interesting is sign in and log in. Well, both mean same that you enter somewhere where you are already registered. The web portals use both the terms. Facebook, ELL and COCA calls it Log in, whereas Google, Twitter, Bank of America and LinkedIn uses Sign in.
Note that all these portals uses sign up for the process of first time registration and not log up.
A subtle difference
I'm acquainted with webmastership as well and it's interesting to know that during our audit, we check the log. The 'Log' includes the number of sessions per user. The session is a complete cycle of the user logging in and then after the work is done, logging out..
This means that if you are signing in for one session, the correct word is log in. So, for the user, it could be sign in but for the system, it's log in.
It is for this reason, content management software/portal like WordPress uses log in because it maintains the log each time you sign in and sign out which will complete the cycle of one session. It is for this reason again, the computer asks to log in and not sign in. After all, you enter and come out completing one cycle i.e. session.
What I prefer is asking the user to log in if you are strictly maintaining the record (--say WordPress or Bank portal) and in other case where maintaining log is not so important (say a subscription for the newsletter, jokes, pranks or the like) sign in.
While using these words, it's important that you stick to one style. If you ask the user to log in, give them an option of log out and not sign out and vice versa.

Not exactly the answer but important to mention.
Log on or Log in - You log on to the URL/Website and it'll take you on the webpage as a guest or non-registered member. You log in and the site is personalized for you. For instance, log on to Amazon.com and you see all the products listed. You are just a visitor. Log in to Amazon.com and you see all the products listed along with your personalized Amazon that may have the history of your purchase, favorite items and other services that Amazon provides to its registered user.
Good question BTW. +1

A:

To Sign up (for something) is essentially to enroll in it: you formally register your intent to participate.  Generally this happens well in advance of the actual start date.
You sign in to a place to officially record your presence there.  At a school, for instance, all visitors might be required to sign in at the office (generally by writing their name, purpose, and time of arrival in a designated book) and later sign out (by putting their time of departure on the same line) so that the school officials know at all times who is on the premises besides the teachers and students.
In modern usage, you log in to a computing system so that the system can present you with the options and information that you are entitled to use and view.  As with "signing in", it is primarily a security measure, but it is always referring to an electronic system.
(In older usage, logging in was basically the same as signing in.)


Q:

Python to Java code: String.encode() in java

I'm trying to emulate a keyboard using a Raspberry Pi, and found some code online that achieves that. On a python base it functions, but now I want to convert it to Java (my main language) to play around with it more.
This is the important part of the python code:
def write_report(report):
    print(report.encode())
    # with open('/dev/hidg0', 'rb+') as fd:
        # fd.write(report.encode())

# Press a
write_report(NULL_CHAR*2+chr(4)+NULL_CHAR*5)

So the output is the following:
b'\x00\x00\x04\x00\x00\x00\x00\x00'
How do I achieve it that the same output is written to the file in java?

A:

I found a way to write the same bytes to the file. Here is the code:
    byte[] bytes = new byte[] {0,0,4,0,0,0,0,0};
    FileOutputStream fWriter;
    try {
        fWriter = new FileOutputStream(new File("D:\\testJava.txt"));
        fWriter.write(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }

Thanks!


Q:

Which answer should I mark as correct - the first comments or the first answer?

After asking Player disappears when it collides with a tagged object, one user, in the comments section, asked one question and, with my answer, he asked another question and added a consideration that solved my problem.
I thanked him and told him to create an answer for the question.
Immediately after doing that, an answer pops-up, from another user, that apart from solving the problem, made some considerations on performance (that are helpful but not required to solve my problem).
The user that helped me solve the problem in the comment section then shared his answer.
I ended up marking the answer of the user that helped me solve the problem in the comment section as correct and adding a comment to upvote the other answer as it has an extra considerations related with performance, however, as I am having doubts if my approach was the right one, I decided to share it here to hear your feedback.

A:

The Help Center says:

Choose one answer that you believe is the best solution to your problem.

So it's entirely up to you.
Stack Exchange is not about who gives the fastest answer, it's a library of detailed answers to every question about certain topics. It's fine to accept a later, more complete answer, even though it may have drawn inspiration from previous answers (we have to trust the author here that they didn't copy it, they probably know they'd have to attribute it).
If you feel accepting the detailed answer doesn't reward the other (now-accepted) answer enough, consider posting a bounty and award it to the 'simple' answer.


Q:

Should I embed a view controller's view within a new view?

When adding an external view controller to an existing one in the Storyboard you would use a "container view". When adding one programatically you are presented with the option of creating a new UIView to embed the external VC's view within (replicating a container view) or simply just adding the external VC's .view directly into the existing one.
Which is considered the better practise here when doing this programatically? Does one have a different effect than the other on performance or reliability?

A:

Using a container view in Storyboard automates the process of:

instantiate view controller
add as childViewController
add its view as a subview of the container view (which is a subview of the main view)

Adding a child view controller via code is the same process:

instantiate view controller
add as childViewController
add its view as a subview of the current view, or as a subview of another subview of the current view

The other benefit of using a container view in Storyboard is that you get a visual design interface.
Of course, some people don't like Storyboard / IB, and prefer code-only approaches.
So really, whichever method best suits your needs and development style.


Q:

APT method bzip2 doesn't exist

I tried to update my system on Xubuntu  : sudo apt-get update && sudo apt-get upgrade.
I got this error message :
E: Le pilote pour la méthode /usr/lib/apt/methods/bzip2 n'a pu être trouvé.

In english the driver for the method /usr/lib/apt/methods/bzip2 can't be found.
I checked the folder :
$ ls /usr/lib/apt/methods/
cdrom  copy  file  ftp  gpgv  gzip  http  https  mirror  rred  rsh  ssh  xz

Actually for the moment, APT can't install anything cause it can't unzip with bzip2 : the method doesn't exist inside the proper folder.

A:

apt does not depend on bzip2 - bzip2 is only a symbolic link to gzip.
Create the link
sudo ln -s /usr/lib/apt/methods/gzip /usr/lib/apt/methods/bzip2

Install bzip2
sudo apt-get install bzip2

Alternative
apt-get download bzip2
sudo dpkg -i bzip2*.deb