text:
Q: Why only one item showing outside of foreach loop? I want to get access to variable(arrays) outside of foreach loop.When i do echo inside foreach loop i'm getting this:
Reuslt inside foreach roop
$path='http://localhost:8000/api/devices';
try {
    $device= new Client();

    $answer= $device->request('GET', $path);
    $body = $answer->getBody();
    $status = 'true';
    $message = 'Data found!';
    $final= json_decode($body);

    foreach ($final as $res) {
        $id = $res->clientId;
        echo $id;
    }

And outside of loop i'm getting only last item of array:
Result outside foreachloop
$route='http://localhost:8000/api/devices';
try {
    $device= new Client();

    $answer= $client->request('GET', $answer);
    $body = $answer->getBody();
    $status = 'true';
    $message = 'Data found!';
    $final= json_decode($body);

    foreach ($finala $res) {
        $id = $res->clientId;
    }
    echo $id;

A: You are doing this :
foreach ($data as $item) {
    $id= $item->clientId;
}
echo $id;

So every time, your last $id value is erased and get the new current id value.
If you want ALL id, try this :
// Create an array
$id_array = array();
foreach ($data as $item) {
    // Add each id value in your array
    $id_array[]= $item->clientId;
}
// Here you can display your array and see that you have all value
var_dump($id_array);

Now if you want to echo (or use) each id AFTER the foreach loop, you can do :
foreach($id_array as $my_id) {
    echo $my_id;
}


text:
Q: Converting a base R loop into R data.table I have a dataframe with records for every 15min values.
I'm using a loop to compute the number of records in a 15 min range.
But its very slow. I feel converting it into a data.table functionality will speed up the process considerably.
i have written the following loop:
Input$Freq  <-  array()

for(i in 1:nrow(Input))
{
  Input[i,"Freq"]<-0
}

for(i in 1:nrow(Input))
{
  for(j in 1:nrow(Input))
  {
    if(Input[i,"Cur_DateTime"]  > Input[j,"Cur_DateTime"] & Input[i,"Cur_DateTime"] < Input[j,"Window_15"])
      Input[i,"Freq"] <- Input[i,"Freq"]+1
  }
}

A: I am not sure if this exactly answers your question.  One can bin the data directly using base R's cut command.
Here is an example:
#create a dummy sequence
s<-seq(from =as.POSIXct("2015-02-15 09:46:43.17"), by="5 min", length.out = 50)
df<-data.frame(s)

#bin the sequence by 15 minute intervals:
df$bins<-cut(df$s, "15 min")

Use the dplyr library to summarize:
library(dplyr)
summarise(group_by(df,bins), n())

or as Frank suggested:
count(df, bins)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to support stopPropagation in delegated event listeners I've looked at the source code from jQuery to find out how they implemented support for event.stopPropagation() in delegated event listeners, i.e. document.on(event, element...), but can't seem to get my own vanilla JS implementation to fully work.
I tried overriding the native event.stopPropagation() in my method to simply set an event.propagationStopped on the event itself, and looking for this when deciding if the event should propagate up to its parents.
This works when the event listener that stops propagation is attached before other ones, however it does not when it's attached in reverse order, something that does work as expected in jQuery's implementation.
function delegate(type, selector, callback) {
    document.addEventListener(type, function(event) {
        event.stopPropagation = function() {
            event.propagationStopped = true;
        };

        var element = event.target, found;

        while (element && element.parentNode) {
            if (element.matches(selector)) {
                callback.call(element, event);
            }

            if (!event.propagationStopped) {
                element = element.parentNode;
            } else {
                break;
            }
        }
    });
}

delegate('click', '.overlay', function() {
    console.log('Close overlay');
});

delegate('click', '.modal', function(e) {
    e.stopPropagation();

    console.log('Clicked inside modal, stopping propagation...');
});

I want the event to stop its further propagation in all event listeners regardless of the order in which they were attached, instead of the current behaviour.

A: I think this is only possible by doing the delegated event propagation yourself in a single event listener. In your current implementation, the second listener attached to the document always fires second, regardless of its selector - but when it selects a descendant of the other selector, you need it to fire first.
Here I'm collecting a list of delegated event listeners, and then iterate that for each element in your parent traversal. You could keep the list on the element itself (e.g. with symbols or a WeakMap), but since you only delegate on document I'll simply store them globally.
const delegatedListeners = {};

function delegate(type, selector, callback) {
    if (!delegatedListeners[type]) {
        const listeners = delegatedListeners[type] = [];
        document.addEventListener(type, function(event) {
            for (let element = event.target; element && element.parentNode; element = element.parentNode) {
                // unfortunately, event.currentTarget cannot be overwritten with element
                for (const {selector, callback} of listeners) {
                    if (element.matches(selector)) {
                        callback.call(element, event);
                    }
                }
                if (event.cancelBubble) { // a getter for the propagation stopped flag :-)
                    break;
                }
            }
        });
    }
    delegatedListeners[type].push({selector, callback});
}


text:
Q: Sqlite thread modes and sqlite misuse paradox I have a project where i should use multiple tables to avoid keeping dublicated data in my sqlite file(Even though i knew usage of several tables was nightmare).
In my application i am reading data from one table in some method and inserting data into another table in some other method. When i do this i am getting from sqlite step function, error code 21 which is sqlite misuse.
Accoding to my researches that was because i was not able to reach tables from multi threads.
Up to now, i read the sqlite website and learned that there are 3 modes to configurate sqlite database:
1) singlethread: you have no chances to call several threads.
2) multithread: yeah multi thread; but there are some obstacles.
3) serialized: this is the best match with multithread database applications.
if sqlite3_threadsafe() == 2  returns true then yes your sqlite database is serialized and this returned true, so i proved it for myself.
then i have a code to configurate my sqlite database for serialized to take it under guarantee.
sqlite3_config(SQLITE_CONFIG_SERIALIZED);

when i use above codes in class where i read and insert data from 1 table works perfectly :). But if i try to use it in class where i read and insert data from 2 tables (actually where i really need it) problem sqlite misuse comes up.
I checked my code where i open and close database, there is no problem with them. they work unless i delete the other.
I am using ios5  and this is really a big problem for my project. i heard that instagram uses postgresql may be this was the reason ha? Would you suggest postgresql or sqlite at first?

A: It seems to me like you've got two things mixed up.
Single vs. multi-threaded
Single threaded builds are only ever safe to use from one thread of your code because they lack the mechanisms (mutexes, critical sections, etc.) internally that permit safe use from several. If you are using multiple threads, use a multi-threaded build (or expect "interesting" trouble; you have been warned).
SQLite's thread support is pretty simple. With a multi-threaded build, particular connections should only be used from a single thread (except that they can be initially opened in another).
All recent (last few years?) SQLite builds are happy with access to a single database from multiple processes, but the degree of parallelism depends on the…
Transaction type
SQL in general supports multiple types of transaction. SQLite supports only a subset of them, and its default is SERIALIZABLE. This is the safest mode of access; it simulates what you would see if only one thing could happen at a time. (Internally, it's implemented using a scheme that lets many readers in at once, but only one writer; there's some cleverness to prevent anyone from starving anyone else.)
SQLite also supports read-uncommitted transactions. This increases the amount of parallelism available to code, but at the risk of readers seeing information that's not yet been guaranteed to persist. Whether this matters to you depends on your application.


text:
Q: Failed to prepare app package(s) because it is being used by another process I can successfully process Revit models with now linked documents on Forge Design Automation, but when I try to process models with linked documents I get this error:
 Error: Failed to prepare app package(s). The process cannot access the file 'T:\Aces\Applications\Revit2ProtoExporter.zip' because it is being used by another process.
[11/06/2020 01:23:22] Error: Unable to download file https://developer.api.autodesk.com/oss/v2/signedresources/5b476183-5bfb-4e98-8276-505dec9cc972?region=US: System.InvalidOperationException: DasZip failed with exit code = 1
   at CoreEngineRunner.DasZip.RunDasZipAsync()
   at CoreEngineRunner.DasZip.ExtractToDirectoryAsync(String sourceArchiveFileName, String destinationDirectoryName, String encoding, CancellationToken ct, Boolean isFaultTolerantOn)
   at CoreEngineRunner.DownloadItem.DownloadAsync(TraceSource logger).
[11/06/2020 01:23:22] Error: An unexpected error happened during phase Downloading of job.
[11/06/2020 01:23:22] Job finished with result FailedEnvironmentSetup

From what I can tell from the logs all the linked documents were successfully downloaded, so I am not sure what's going on. Below is the full log:

[11/06/2020 01:23:20] Job information:
"CommandLine":[
  "\"$(engine.path)/revitcoreconsole.exe /i $(args[rvtFile].path) /al $(appbundles[Revit2ProtoExporter].path)\""
]
"Settings":{
  "dasreportfaileduploadoptional": {
    "value": "true",
    "isEnvironmentVariable": true
  }
}
"Id":"8dff5a5fd1144e9e9302505e30987bdd"
"ActivityId":"WDQIfAV8PqNa9XSKPmv6MDu3xAtLGfXI.Revit2ProtoExporterActivity+AppliedVR50"
"Engine.Id":"Autodesk.Revit!39"
"Apps": [
"App.Id":"WDQIfAV8PqNa9XSKPmv6MDu3xAtLGfXI.Revit2ProtoExporter!55"
]
"BoundArguments":{
  "rvtFile": {
    "zip": true,
    "localName": "",
    "pathInZip": "root.rvt",
    "references": [
      {
        "url": "https://developer.api.autodesk.com/Masked:Sae2ipw7szdulRannCn5DzwBuhM="
      },
      {
        "url": "https://developer.api.autodesk.com/Masked:NPqlMsVOXAFdIg5sx5eIR2Y26HI="
      }
    ],
    "url": "https://developer.api.autodesk.com/Masked:M+AnWc5OiowsRTaJvH8nPzTA9ao="
  },
  "params": {
    "localName": "params.json",
    "url": "data:application/json,{\"ViewId\": 7759865}"
  },
  "result": {
    "localName": "result.avr",
    "url": "https://developer.api.autodesk.com/Masked:TFOCpwjedup6t/kPU2xq3JvGyfo=",
    "verb": "put"
  },
  "onProgress": {
    "ondemand": true,
    "url": "https://wlnr5sjl3a.execute-api.us-east-1.amazonaws.com/Masked:UK/Z3b5X3xUWxXiH6C9r9i9UlRU=",
    "headers": {
      "Content-Type": "application/json",
      "x-das-authorize": "awssigv4(us-east-1)",
      "x-ads-token-data": "{\"access_token\":{\"client_id\":\"WDQIfAV8PqNa9XSKPmv6MDu3xAtLGfXI\"},\"scope\":\"code:all data:write data:read bucket:create bucket:delete\",\"expires_in\":3569,\"client_id\":\"WDQIfAV8PqNa9XSKPmv6MDu3xAtLGfXI\"}"
    },
    "verb": "put"
  }
}
"Quotas":{
  "limitProcessingTimeSec": 10800,
  "limitTotalUncompressedAppsSizeInMB": 5000
}
[11/06/2020 01:23:20] Starting work item 8dff5a5fd1144e9e9302505e30987bdd
[11/06/2020 01:23:20] Start download phase.
[11/06/2020 01:23:20] Start downloading input: verb - 'GET', url - 'https://developer.api.autodesk.com/oss/v2/signedresources/5b476183-5bfb-4e98-8276-505dec9cc972?region=US'
[11/06/2020 01:23:20] Start downloading input: verb - 'GET', url - 'https://developer.api.autodesk.com/oss/v2/signedresources/c286f6d4-d6ac-45b8-84b7-7bd804d6cf35?region=US'
[11/06/2020 01:23:20] Start downloading input: verb - 'GET', url - 'https://developer.api.autodesk.com/oss/v2/signedresources/66b668df-a639-4ba4-bb3b-2e2f35049365?region=US'
[11/06/2020 01:23:20] Embedded resource [{"ViewId": 7759865}] is saved as file: T:\Aces\Jobs\8dff5a5fd1144e9e9302505e30987bdd\params.json.
[11/06/2020 01:23:20] '4681728' bytes have been written to T:\Aces\Jobs\8dff5a5fd1144e9e9302505e30987bdd\9821ccb1a0bac5ffe69e46ca6d4ddde9.
[11/06/2020 01:23:20] End downloading file 'https://developer.api.autodesk.com/oss/v2/signedresources/c286f6d4-d6ac-45b8-84b7-7bd804d6cf35?region=US'.
[11/06/2020 01:23:20] '4685824' bytes have been written to T:\Aces\Jobs\8dff5a5fd1144e9e9302505e30987bdd\d6b0fa35b9c5a76b8868f754562fbc09.
[11/06/2020 01:23:20] End downloading file 'https://developer.api.autodesk.com/oss/v2/signedresources/66b668df-a639-4ba4-bb3b-2e2f35049365?region=US'.
[11/06/2020 01:23:21] '13568850' bytes have been written to T:\Aces\Jobs\8dff5a5fd1144e9e9302505e30987bdd\zip_21.zip.
[11/06/2020 01:23:21] End downloading file 'https://developer.api.autodesk.com/oss/v2/signedresources/5b476183-5bfb-4e98-8276-505dec9cc972?region=US'.
[11/06/2020 01:23:22] Error: Failed to prepare app package(s). The process cannot access the file 'T:\Aces\Applications\Revit2ProtoExporter.zip' because it is being used by another process.
[11/06/2020 01:23:22] Error: Unable to download file https://developer.api.autodesk.com/oss/v2/signedresources/5b476183-5bfb-4e98-8276-505dec9cc972?region=US: System.InvalidOperationException: DasZip failed with exit code = 1
   at CoreEngineRunner.DasZip.RunDasZipAsync()
   at CoreEngineRunner.DasZip.ExtractToDirectoryAsync(String sourceArchiveFileName, String destinationDirectoryName, String encoding, CancellationToken ct, Boolean isFaultTolerantOn)
   at CoreEngineRunner.DownloadItem.DownloadAsync(TraceSource logger).
[11/06/2020 01:23:22] Error: An unexpected error happened during phase Downloading of job.
[11/06/2020 01:23:22] Job finished with result FailedEnvironmentSetup
[11/06/2020 01:23:22] Job Status:
{
  "status": "failedDownload",
  "reportUrl": "https://dasprod-store.s3.amazonaws.com/workItem/WDQIfAV8PqNa9XSKPmv6MDu3xAtLGfXI/8dff5a5fd1144e9e9302505e30987bdd/report.txt?AWSAccessKeyId=ASIATGVJZKM3DKXULYFE&Expires=1604640200&x-amz-security-token=IQoJb3JpZ2luX2VjEKH%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMSJIMEYCIQD30WUuRtM0iuIWxkOah9t90%2B96TOt0DkqqAjHwzTuSKwIhAOm8LiqpZlwCDr6Ah4YWCzhSZ8xq0zzP4KRBHY2L0uMPKt4BCPr%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEQAhoMMjIwNDczMTUyMzEwIgyxm%2BA7M7tzSCXAOAQqsgGayvqco1UE6lJY%2Fzm6Q%2BFcoeJvpYXKN%2Fbx8o6B2DqoExa14uAjmS9GkYaAr1GXX%2B1YUgHJqU1EhJK9A1IUe41I0VnrujiHpMF8h3zlQEJ3q%2Fhrxg7%2BPND7RaBmy9dLYrS4giEwcmw0LvLNhGQcX56DDbsrqn94fgseSnGXa8VzikJVRHJcW3QU2%2BTD95fED8Ti6FJlHr1cwnXrKXK%2FUpsa8sbXCl1AW8prMb3kwhQQBC5XMPS9kv0FOt8BYzfwE32Tqa95uBxIX4yKHW3r2VHUr7ERl6vbP%2BSbCL2%2BFjRWeBUnKhwvyhvu6qyRmncho5VMdtxZv%2FyRK3l3%2BYykUO%2BKOVWxuku1nD1gxdqrcq4Kydz4DDluNPxsgNr3Vm9ewRAdzYS9ANmHysWWVRFFB81rOmWUPgrpbTKiX8dCqvZKSjkoLXNKXGaYkYmnDHS0qymqF353mLw42D9%2FoRgLbqQBI0EJDrielO1L%2Fxh%2BsN7vRsch3XA2YywIIc1ZnQnfbsWaH7DvmgK43DC5RFRffsVtMek9%2FyGlzsgYhg%3D%3D&Signature=eXSYaQ493438TS381AOIZ6rFfBY%3D",
  "stats": {
    "timeQueued": "2020-11-06T01:23:20.2861629Z",
    "timeDownloadStarted": "2020-11-06T01:23:20.6030353Z"
  },
  "id": "8dff5a5fd1144e9e9302505e30987bdd"
}


text:
Q: How to solve Laravel Ajax dropdown?
Here is my output. When user select the site, the list of controller will display. My problems is when user select the site, the list of controller does not displayed.
Controller:
public function index()
{
    $sites = Sites :: pluck ('sites_id' ,'site_code' , 'site_name');
    return view ('query.index',compact('sites'));
}

public function getController($sites_id){

    $controllerData['data'] = device_profile::orderby("dvc_name","asc")
                            ->select('id','dvc_name')
                            ->where('sites',$sites_id)
                            ->get();

    return response()->json($controllerData);

}

View:

                        Site:
                        <select name="sites_id" class="form-control" required="">
                            @foreach ($sites as $site_code => $sites_id)
                                <option value="{{$sites_id}}"
                                    {{ old('sites_id') == $sites_id ? 'selected' : '' }}>
                                    {{ $site_code }}
                                </option>
                            @endforeach
                        </select>

                        @error('sites_id')

                                {{ $message }}

                        @enderror

                        Select Controller:
                        <select name="dvc_name" class="form-control" required="">
                        <option>--Controller List--</option>
                        </select>

Web:
Route::get('query-index', 'QueryDataController@index')->name('query.index');
Route::get ('query-controller/getcontrollers/{sites_id}', 'QueryDataController@getControllers')->name('profile.getControllers');

Below is my database for sites and device profile:
Sites:

Device Profile:

I hope someone can help me to solve this problem. Thank you.

A: your URL in your ajax method is:
url: 'getController/'+sites_id,

And your route is :
Route::get ('query-controller/getcontrollers/{sites_id}', 'QueryDataController@getControllers')->name('profile.getControllers');

So you should change your ajax URL to this:
url: 'query-controller/getControllers/'+sites_id,

A: In this you have to call that url in ajax, url should be same as that you mention in Routes,
    $('#sites_id').change(function(){
    var site_id=this.value;
    $.ajax({
    siteid:site_id,
    url : 'query-controller/getcontrollers/'+siteid,
    })
    })


text:
Q: Fetch sum of variables in component controller I have a list of question with answers on scale from -1 to +2 displayed in a button group (SLDS).
Component
<aura:component access="global" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes" controller="getChartData" >

        <ui:outputText value="{!v.firstName}"/>
        actively supports and guides me in the current sales campaign.

      <lightning:button aura:id="Q1btn" class="slds-button slds-button_icon slds-button_icon-border slds-is-selected"
     title="Dont know yet." label="?" />
      <lightning:button aura:id="Q1btn" class="slds-button slds-button_icon slds-button_icon-border" label="-1"
     title="Little awareness and involvement" value="-1" onclick="{!c.buttonScore}" />
      <lightning:button aura:id="Q1btn" class="slds-button slds-button_icon slds-button_icon-border" label="0"
     title="Some organizational awareness" value="0" onclick="{!c.buttonScore}"/>
      <lightning:button aura:id="Q1btn" class="slds-button slds-button_icon slds-button_icon-border" label="1"
     title="Limited involvement" value="1" onclick="{!c.buttonScore}" />
      <lightning:button aura:id="Q1btn" class="slds-button slds-button_icon slds-button_icon-border" label="2"
       title="Strong involvement" value="2" onclick="{!c.buttonScore}"/>

    </aura:component>

Controller
buttonScore : function(component,event,helper){
   var btnClicked = event.getSource();
   var btnId = btnClicked.getLocalId();
   var btnValue = btnClicked.get("v.value");
   //console.log('btnID-->'+btnId+'  '+btnValue);
   var a,b,c,d,e,f;

   if(btnId == "Q1btn"){
       a = parseInt(btnValue);

   }
    if(btnId == "Q2btn"){
       b = parseInt(btnValue);
       console.log('a-->'+a);
       console.log(a+b);
   }
     if(btnId == "Q3btn"){
       c = parseInt(btnValue);
   }
     if(btnId == "Q4btn"){
       d = parseInt(btnValue);
   }
      if(btnId == "Q5btn"){
       e = parseInt(btnValue);
   }
      if(btnId == "Q6btn"){
       f = parseInt(btnValue);

   }
  },

Similiarly I have many question and I want the sum of all the scales added dynamicall in the client side controller itself. Since onclick of the scale option is a button event, the values get refreshed everytime I click and gives incorrect value. What approach should I take ?

A: you can save value in an attribute on every button click. And then on click of next button get that value and add new value in it.
buttonScore : function(component,event,helper){
   var btnClicked = event.getSource();
   var score = component.get("v.score");
   var btnId = btnClicked.getLocalId();
   var btnValue = btnClicked.get("v.value");
   //console.log('btnID-->'+btnId+'  '+btnValue);
   var a,b,c,d,e,f;

   if(btnId == "Q1btn"){
       a = parseInt(btnValue);
      component.set("v.score",score+a);
   }
    if(btnId == "Q2btn"){
       b = parseInt(btnValue);
       console.log('a-->'+a);
       console.log(a+b);
      component.set("v.score",score+b);
   }
     if(btnId == "Q3btn"){
       c = parseInt(btnValue);
       component.set("v.score",score+c);
   }
     if(btnId == "Q4btn"){
       d = parseInt(btnValue);
component.set("v.score",score+d);
   }
      if(btnId == "Q5btn"){
       e = parseInt(btnValue);
component.set("v.score",score+e);
   }
      if(btnId == "Q6btn"){
       f = parseInt(btnValue);
component.set("v.score",score+f);
   }
  },


text:
Q: How to fix WordPress Website showing Unknown results in Google? I was exploring my WordPress powered website and I found some unknown results in Google Search which I had never seen before and isn't related to my website.
See the image here
I have also installed and configured the WordFence Security plugin. I also checked the Sucuri Site check tool but none of the tools showed any type of virus alerts.
The site I need help with is : [Link Deleted by User]
Any help would be appreciated and thanks in advance.

A: You need to check the Google Search Console. Some of the URL indexed by Google is a 404 URL, so manually check for the URL from Google Search Console, remove the indexed URL which are a 404 URL.
https://search.google.com/search-console/about

A: *

*Install Yoast SEO plugin

*Add metadata with Yoast.

*Create a XML site map

*Submit your site map at google console

A: Have you uploaded/submitted a valid sitemap.xml to your google search console?


text:
Q: 'texture2D' : function is removed in Forward Compatibile context I am trying to implement 5x5 convolution filter (Find Edges) using GLSL here is my code of .glsl source:
#version 150
#define SIZE 25

// A texture is expected
uniform sampler2D Texture;

// The vertex shader fill feed this input
in vec2 FragTexCoord;

// The final color
out vec4 FragmentColor;

float matr[25];
float matg[25];
float matb[25];

vec4 get_pixel(in vec2 coords, in float x, in float y) {
   return texture2D(Texture, coords + vec2(x, y));
}

float convolve(in float[SIZE] kernel, in float[SIZE] matrix) {
   float res = 0.0;
   for (int i = 0; i < 25; i++)
      res += kernel[i] * matrix[i];
   return clamp(res, 0.0, 1.0);
}

void fill_matrix() {
   float dxtex = 1.0 / float(textureSize(Texture, 0));
   float dytex = 1.0 / float(textureSize(Texture, 0));
   float[25] mat;
   for (int i = 0; i < 5; i++)
      for(int j = 0; j < 5; j++) {
        vec4 pixel = get_pixel(FragTexCoord,float(i - 2) * dxtex, float(j - 2) * dytex);
         matr[i * 5 + j] = pixel[0];
         matg[i * 5 + j] = pixel[1];
         matb[i * 5 + j] = pixel[2];
      }
}

void main() {

  float[SIZE] ker_edge_detection = float[SIZE] (
    .0,.0, -1., .0, .0,
    .0, .0,-1., .0, .0,
    .0, .0, 4., .0, .0,
    .0, .0, -1., .0,.0,
    .0, .0, -1., .0, .0
  );

  fill_matrix();

  FragmentColor = vec4(convolve(ker_edge_detection,matr), convolve(ker_edge_detection,matg), convolve(ker_edge_detection,matb), 1.0);
}

When I run my code it gives me errors:
Error Compiling Fragment Shader ...
ERROR: 0:17: 'texture2D' : function is removed in Forward Compatibile context
ERROR: 0:17: 'texture2D' : no matching overloaded function found (using implicit conversion)

Error Linking Shader Program ...
Attached fragment shader is not compiled.

Function is removed in Forward Compatibile context

Weird thing is, when I've tried to run code on other linux and then windows machines it just worked fine. Also when I changed texture2D in get_pixel() function to return texture only it worked like a charm. Could someone explain where is a problem?

A: The error says everything you need to know. texture2D is an old function from the GLSL 1.00 days. It was removed and replaced with texture, which uses function overloading to work on most sampler types, rather than being restricted to sampler2D. So in a core profile or forward compatibility context, you cannot call texture2D.


text:
Q: Print with key and value from array of objects I have an array of objects. I want to get the key and value and print the data. eg. I have id, username and password and I want the username and password.
[
  {"id":1,"name":"admin","password":"admin","role":"Admin"},
  {"id":2,"name":"user","password":"user","role":"User"},
  {"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
]

The output should be
name : admin
password : admin,
name : user
password : user,
name : superadmin
password : superadmin

A: To iterate key values dynamically, you have to iterate object.

    let arr = [
      {"id":1,"name":"admin","password":"admin","role":"Admin"},
      {"id":2,"name":"user","password":"user","role":"User"},
      {"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
    ];

    arr.forEach((item, i) => {
       for(let key in item) {
           console.log(`${key}: ${item[key]}`);
       }
    });

If you would like to display only name and password, then you can add a condition.

arr.forEach((item, i) => {
   for(let key in item) {
      if (key === 'name' || key === "password") {
          console.log(`${key}: ${item[key]}`);
      }
   }
});

A: Given the array you have, you simply need to loop through it:

var arr = [
  {"id":1,"name":"admin","password":"admin","role":"Admin"},
  {"id":2,"name":"user","password":"user","role":"User"},
  {"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
]

arr.forEach(function(obj) {
  console.log('name: ' + obj.name);
  console.log('password: ' + obj.password);
})

A: let data = [
  {"id":1,"name":"admin","password":"admin","role":"Admin"},
  {"id":2,"name":"user","password":"user","role":"User"},
  {"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
];

var out_data = data.reduce((a, b) => a + 'name: ' + b.name + ', password: ' + b.password + ' ', '');
console.log(out_data);

A: var arr = [
  {"id":1,"name":"admin","password":"admin","role":"Admin"},
  {"id":2,"name":"user","password":"user","role":"User"},
  {"id":3,"name":"superadmin","password":"superadmin","role":"superadmin"}
]
[![enter image description here][1]][1]
Loop through the array
arr.forEach(function(data) {
  console.log('name', data.name);
  console.log('password', data.password);
})

  [1]: https://i.stack.imgur.com/uYA9i.png


text:
Q: How to find the sessions time from a stream of user login events in python? Given User Login Events continuously appearing in a stream processing system similar to this, where each line is 1 event (you can assume the pipeline is external to this program, this is a line-by-line function call):
1532926994 User01 LogOutSuccessful
1532926981 User02 LogInSuccessful
1532926982 User04 LogInFailed
1532926992 User01 LogInSuccessful
1532926986 User02 LogOutSuccessful
1532927003 User03 LogOutSuccessful
Implement a module with standard libraries (e.g. no Spark) that continuously processes these events and outputs user session durations as soon as a successful logout occurs in a structured format similar to:
{ "username": "User02", "session_duration": 5 }
{ "username": "User05", "session_duration": 10 }
I was asked this question in an interview and I could parse and extract the data but I was not able to store the user events and use it to compute the session time. Any guidance would be appreciated.
We have to write a python function which takes one line at a time and takes some action when we receive LogInSuccessful or LogOutSuccessful. I think we can ignore LogInFailed for the moment.
def get_user_session_time(stream_text):

    user_info = stream_text.split()

    if user_info[2] == 'LogInSuccessful':
       #store the data somewhere
    elif user_info[2] == 'LogOutSuccessful':
       #get the data stored in the above step
       #compute the session time
       #print the key value pair { "username": "User02",
       #"session_duration": 5 }

A: Code without using any python library

dict={}
def event(input):
    (cur_time,user,status) = input.split()
    if status=="LogOutSuccessful" and user in dict.keys():
            for logintime,login_status in dict[user].items():
                pass

            logout_time =int(cur_time)-int(logintime)
            print("{username: '" + user + "' , session duration: " + str(logout_time)+"}")
            del dict[user]
    else:
        dict[user]={cur_time:status}

event('1532926981 User01 LogInSuccessful')
event('1532926981 User02 LogInSuccessful')
event('1532926994 User01 LogOutSuccessful')
event('1532926982 User04 LogInFailed')
event('1532927003 User02 LogOutSuccessful')

O/P {username: 'User01' , session duration: 13}
{username: 'User02' , session duration: 22}


text:
Q: TeamCity Agent Push Failure when Checking Platform When attempting to install an agent using the Agent Push feature I get the following error:
[12:05:15]: AgentPush v32407 - Install Agent on remote host
[12:05:15]: Looking for Target Host...
[12:05:15]: Validating TeamCity Server Root URL 'http://####' ...
[12:05:19]: Starting agent push to '###'(IP: ###) using preset 'Packer Baker' (Username 'administrator'. Target platform: 'Windows')
[12:05:19]: Checking Platform...
[12:05:24]: 'ssw0rd'' is not recognized as an internal or external command,
[12:05:24]: operable program or batch file.
[12:05:24]: Executing command: 'C:\Tomcat\temp\___1655843086080428423\cli-wrapper.exe D:\TMC-Data\system\pluginData\psexec\psexec.exe /accepteula \\### -e -h -u administrator -p ********** cmd.exe /C ver'
[12:05:24]: Remote agent installation failed: Command 'C:\Tomcat\temp\___1655843086080428423\cli-wrapper.exe D:\TMC-Data\system\pluginData\psexec\psexec.exe /accepteula \\### -e -h -u administrator -p ********** cmd.exe /C ver' was executed with error message(s): Execution error. Return code=1

Any ideas what might cause this?

A: This was caused by not escaping the ampersand character in the "Credentials to push agent" password.
In the above case I used the password P&ssw0rd. When the command
C:\Tomcat\temp\___1655843086080428423\cli-wrapper.exe D:\TMC-Data\system\pluginData\psexec\psexec.exe /accepteula \\### -e -h -u administrator -p ********** cmd.exe /C ver

is executed & is used to run multiple commands on the same line and requires escaping.
After escaping the & with ^ and changing the password to P^&ssw0rd the agent push ran successfully.


text:
Q: React JS on submit remove input fields and display "Thank You" only My code has got 3 input fields i.e first name, last name, email and 1 useState to hold its value, I want to remove the div part containing all the input fields after i hit Sign up and display only Thank You
My code has got 3 input fields i.e first name, last name, email and 1 useState to hold its value, I want to remove the div part containing all the input fields after i hit Sign up and display only Thank You
Before signing up

AFter signing up

const Home = () => {
  const [saveInput, setInput] = useState({
    fname: '',
    lname: '',
    email: '',
  });
  const [message, setMessage] = useState('enter email');

  const inputFields = (event) => {
    const { value, name } = event.target;
    setInput((preValue) => ({
      ...preValue,
      [name]: value,
    }));
  };

  const onSubmits = (event) => {
    setMessage('thanks');
  };
  return (

Maryam's Restaurant

        <Link
          style={{
            color: 'white',
            textDecoration: 'inherit',
            textAlign: 'center',
          }}
          to="/Restaurant"
          className="home_button"
        >
          View Menu
        </Link>

          Binging with Babish is a cooking show dedicated to discovering what
          the delectable (and occasionally horrible) foods from fiction actually
          taste like.

        {receipeList.map((curElem) => (

{curElem.h1}

{curElem.date}

        ))}

      <homeMainDetails />

          <bold>Subscribe</bold>

            Sign up with your email address to receive news and updates.

        <input
          className="home4MainInput"
          name="fname"
          onChange={inputFields}
          value={saveInput.fname}
          type="text"
          placeholder="First Name"
        />
        <input
          className="home4MainInput"
          name="lname"
          onChange={inputFields}
          value={saveInput.lname}
          type="text"
          placeholder="Last Name"
        />
        <input
          className="home4MainInput"
          name="email"
          onChange={inputFields}
          value={saveInput.email}
          type="text"
          placeholder="Email Address"
        />
        <button onClick={onSubmits}>Sign Up</button>

          {message}

  );
};
export default Home;

A: You can do it with a basic condition message !== "Thank you" like this:

  {message !== "Thank you" && (
    <>

        <bold>Subscribe</bold>

        Sign up with your email address to receive news and updates.

      <input
        className="home4MainInput"
        name="fname"
        onChange={inputFields}
        value={saveInput.fname}
        type="text"
        placeholder="First Name"
      />
      <input
        className="home4MainInput"
        name="lname"
        onChange={inputFields}
        value={saveInput.lname}
        type="text"
        placeholder="Last Name"
      />
      <input
        className="home4MainInput"
        name="email"
        onChange={inputFields}
        value={saveInput.email}
        type="text"
        placeholder="Email Address"
      />
      <button onClick={onSubmits}>Sign Up</button>
    </>
  )}

    {message}

And update message
  const onSubmits = (event) => {
    setMessage('Thank you');
  };

A: You could use another state to indicate your submit state.
This way you can hold state value without affecting to the message state:

*

*Use another state:

const [isSubmited, setIsSubmited] = useState(false);

*

*Change that state when you submit:

const onSubmits = (event) => {
    setMessage('thanks');
    setIsSubmited(true);
  };

*

*Then render it conditionally:

{isSubmited ? (

          ...

      ) : message}

A: Create a useState that contains the value on the state of the form.
const [isSubmited, setIsSubmited] = useState(false);
Then use this value in the JSX to conditional render the elements you want to display.
isSubmitted ?
 Thank You!
 :
 your form....

You can call setIsSubmited(true) when you submit the form.


text:
Q: Exploratory factor analysis for clustered data in R I am new to both R and factor analysis, and I need to run EFA for a dataset that used cluster survey design. Is there any package for FA in R that can handle cluster data?

A: Accounting for survey clustering doesn't alter your parameter estimates, only the standard errors. EFA is a descriptive technique, which doesn't care about standard errors.
For the purpose of EFA, you can ignore the clusters.


text:
Q: Google script code not working in other sheets this is the code that i am currently running in mainWsName sheet. It is basically a dependent dropdown list.
I also want this same script/code to work in another sheet. I tried to change all the variables in to the new sheet. But then the script does only work in one of the sheets. I want it to work in both the sheets.

var mainWsName = "Inkoop";
var sittardWsName = "Sittard";
var merkColumn = 4;
var modelColumn = 5;
var categorieColumn = 6;

var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mainWsName);
var wsSittard = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sittardWsName);
var arraySittard = wsSittard.getRange(2,1,wsSittard.getLastRow()-1,3).getValues();

function categorie(){
}

function onEdit(e){
  var activeCell = e.range;
  var val = activeCell.getValue();
  var r = activeCell.getRow();
  var c = activeCell.getColumn();
  var wsName = activeCell.getSheet().getSheetName()

  if(wsName == mainWsName && c == merkColumn && r > 1){
      if(val === ""){
      ws.getRange(r ,modelColumn).clearContent();
      ws.getRange(r ,modelColumn).clearDataValidations();
      ws.getRange(r ,categorieColumn).clearContent();
    } else{
      ws.getRange(r ,modelColumn).clearContent();
      var filterarraySittard = arraySittard.filter(function(o){return o[0] === val});
      var listToApply = filterarraySittard.map(function(o){ return o[1]});
      var cell = ws.getRange(r ,modelColumn);
      applyValidationToCell(listToApply, cell);
    }
  }
} // end onEdit

function applyValidationToCell(list,cell){
  var rule = SpreadsheetApp.newDataValidation()
  .requireValueInList(list)
  .setAllowInvalid(false)
  .build();
  cell.setDataValidation(rule);
}

A: The reason why it's only working in one sheet is because you are telling the program to only work in a single sheet.
If you look on your onEdit(e) function there is only one sheet that you are modifying, ws. Therefore you need to change the variable naming to be able to modify both sheets:
Modified Script
Basically instead of statically getting the sheet to be modify (ws) retrieve it from the onEdit event:
var mainWsNames = ["Inkoop", "Verkoop"]; // Changed to an array of names to modify
var sittardWsName = "Sittard";
var merkColumn = 4;
var modelColumn = 5;
var categorieColumn = 6;

var wsSittard = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sittardWsName);
var arraySittard = wsSittard.getRange(2,1,wsSittard.getLastRow()-1,3).getValues();

function categorie(){
}

function onEdit(e){
  var activeCell = e.range;
  var val = activeCell.getValue();
  var r = activeCell.getRow();
  var c = activeCell.getColumn();
  var ws = activeCell.getSheet();
  var wsName = ws.getSheetName();

// Check if the name of the worksheet is in the array previously defined with indexOf
  if(mainWsName.indexOf(wsName) != -1 && c == merkColumn && r > 1){
      if(val === ""){
      ws.getRange(r ,modelColumn).clearContent();
      ws.getRange(r ,modelColumn).clearDataValidations();
      ws.getRange(r ,categorieColumn).clearContent();
    } else{
      ws.getRange(r ,modelColumn).clearContent();
      var filterarraySittard = arraySittard.filter(function(o){return o[0] === val});
      var listToApply = filterarraySittard.map(function(o){ return o[1]});
      var cell = ws.getRange(r ,modelColumn);
      applyValidationToCell(listToApply, cell);
    }
  }
} // end onEdit

function applyValidationToCell(list,cell){
  var rule = SpreadsheetApp.newDataValidation()
  .requireValueInList(list)
  .setAllowInvalid(false)
  .build();
  cell.setDataValidation(rule);
}

A: This is how I solved it
var mainWsName = "Inkoop";
var wsVerkoop = "Verkoop"
var sittardWsName = "Sittard";
var merkColumn = 4;
var modelColumn = 5;
var categorieColumn = 6;

var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mainWsName);
var wVerkoop = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(wsVerkoop);
var wsSittard = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sittardWsName);
var arraySittard = wsSittard.getRange(2,1,wsSittard.getLastRow()-1,3).getValues();

function categorie(){
}

function onEdit(e){
  var activeCell = e.range;
  var val = activeCell.getValue();
  var r = activeCell.getRow();
  var c = activeCell.getColumn();
  var wsName = activeCell.getSheet().getSheetName()

  if(wsName == mainWsName && c == merkColumn && r > 1){
      if(val === ""){
      ws.getRange(r ,modelColumn).clearContent();
      ws.getRange(r ,modelColumn).clearDataValidations();
      ws.getRange(r ,categorieColumn).clearContent();
    } else{
      ws.getRange(r ,modelColumn).clearContent();
      var filterarraySittard = arraySittard.filter(function(o){return o[0] === val});
      var listToApply = filterarraySittard.map(function(o){ return o[1]});
      var cell = ws.getRange(r ,modelColumn);
      applyValidationToCell(listToApply, cell);
    }
  }
  if(wsName == wsVerkoop && c == merkColumn && r > 1){
      if(val === ""){
      wVerkoop.getRange(r ,modelColumn).clearContent();
      wVerkoop.getRange(r ,modelColumn).clearDataValidations();
      wVerkoop.getRange(r ,categorieColumn).clearContent();
    } else{
      wVerkoop.getRange(r ,modelColumn).clearContent();
      var filterarraySittard = arraySittard.filter(function(o){return o[0] === val});
      var listToApply = filterarraySittard.map(function(o){ return o[1]});
      var cell = wVerkoop.getRange(r ,modelColumn);
      applyValidationToCell(listToApply, cell);
    }
  }
} // end onEdit

function applyValidationToCell(list,cell){
  var rule = SpreadsheetApp.newDataValidation()
  .requireValueInList(list)
  .setAllowInvalid(false)
  .build();
  cell.setDataValidation(rule);
}


text:
Q: How do I fix name service for Vagrant client? I am new to Ubuntu (having just installed Ubuntu 12.10) and want to start developing with it. So I have installed Vagrant, downloaded lucid64.box, initialized, started it up and accessed it via ssh.
To the test the Internet connection on my client I've done ping google.com
and received unknown host: google.com. (Host got ping of course.)
Searching the web only got me to this solution which suggested to remove Vagrant and Virtual box, and re-install them, just make sure Vagrant installed first. I've tried this solution and I am still getting the same results.
What else can I try to get it to work?

A: For Vagrant 1.1+ you will need
config.vm.provider "virtualbox" do |v|
  v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end

Tested on Vagrant 1.2.2
Found on Lyte's Blog http://lyte.id.au/tag/vagrant/

A: You can make the modifyvm trick work across all Vagrant VMs in one hit by putting a snippet in ~/.vagrant.d/Vagrantfile, e.g.:
Vagrant::Config.run do |config|
    config.vm.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end

A: I had the same issue with Ubuntu 12.10 and found a solution. Just add those lines to your Vagrantfile:
config.vm.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
config.vm.customize ["modifyvm", :id, "--natdnsproxy1", "on"]

For Vagrant 1.1+ you will need (thanks to farooqsadiq)
config.vm.provider "virtualbox" do |v|
  v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end

It seems to be a known bug in VirtualBox on Ubuntu 12.10:
https://bugs.launchpad.net/ubuntu/+source/virtualbox/+bug/1048783
https://www.virtualbox.org/ticket/10864

A: The (new) default Vagrantfile* contains a bunch of commented-out examples, one of which is as follows:
  # Assign this VM to a bridged network, allowing you to connect directly to a
  # network using the host's network device. This makes the VM appear as another
  # physical device on your network.
  # config.vm.network :bridged

Make sure you un-comment this line:
conig.vm.network :bridged

That will give your virtual machine access to the network/Internet.
* As of version 1.0.6.  As of the time of this answer, the latest version in the repository is 1.0.3, it may not have all of the extra examples; in which case, you'll need to add that line of code.


text:
Q: Rails Tutorial Unable to find field "Name" at spec run after 10.34 I am going through the Rails tutorial and I have an issue that seems to be causing a lot of other tests to fail. There are 23 errors and most of them explain that there is a missing field called "Name". When I run the command
bundle exec rspec spec/requests/user_pages_spec.rb

I get the following errors (that seem to change order every time I run it):

1) User pages edit with valid information
       Failure/Error: fill_in "Name",             with: new_name
       Capybara::ElementNotFound:
         Unable to find field "Name"
       # ./spec/requests/user_pages_spec.rb:136:in `block (4 levels) in '

As a result, many other cases seem to fail. What app file would cause this issue? sessions_helper.rb?

Here is my spec/requests/user_pages_spec.rb: require 'spec_helper'
describe "User pages" do

  subject { page }

  describe "index" do
    let(:user) { FactoryGirl.create(:user) }

    before do
      sign_in user
      visit users_path
    end

    it { should have_title('All users') }
    it { should have_content('All users') }

    describe "pagination" do

      before(:all) { 30.times { FactoryGirl.create(:user) } }
      after(:all)  { User.delete_all }

      it { should have_selector('div.pagination') }

      it "should list each user" do
        User.paginate(page: 1).each do |user|
          expect(page).to have_selector('li', text: user.name)
        end
      end
    end

    describe "delete links" do

      it { should_not have_link('delete') }

      describe "as an admin user" do
        let(:admin) { FactoryGirl.create(:admin) }
        before do
          sign_in admin
          visit users_path
        end

        it { should have_link('delete', href: user_path(User.first)) }
        it "should be able to delete another user" do
          expect do
            click_link('delete', match: :first)
          end.to change(User, :count).by(-1)
        end
        it { should_not have_link('delete', href: user_path(admin)) }
      end
    end
  end

  describe "profile page" do
    let(:user) { FactoryGirl.create(:user) }
    let!(:m1) { FactoryGirl.create(:micropost, user: user, content: "Foo") }
    let!(:m2) { FactoryGirl.create(:micropost, user: user, content: "Bar") }

    before { visit user_path(user) }

    it { should have_content(user.name) }
    it { should have_title(user.name) }

    describe "microposts" do
      it { should have_content(m1.content) }
      it { should have_content(m2.content) }
      it { should have_content(user.microposts.count) }
    end
  end

  describe "signup page" do
    before { visit signup_path }

    it { should have_content('Sign up') }
    it { should have_title(full_title('Sign up')) }
  end

  describe "signup" do

    before { visit signup_path }

    let(:submit) { "Create my account" }

    describe "with invalid information" do
      it "should not create a user" do
        expect { click_button submit }.not_to change(User, :count)
      end

      describe "after submission" do
        before { click_button submit }
        signup_errors
      end
    end

    describe "with valid information" do

      before { valid_signup }

      it "should create a user" do
        expect { click_button submit }.to change(User, :count).by(1)
      end

      describe "after saving the user" do
        before { click_button submit }
        let(:user) { User.find_by(email: 'user@example.com') }

        it { should have_link('Sign out') }
        it { should have_title(user.name) }
        it { should have_welcome_message( 'Welcome')}

        describe "followed by signout" do
          before { click_link "Sign out" }
          it { should have_link('Sign in') }
        end
      end
    end
  end

  describe "edit" do
    let(:user) { FactoryGirl.create(:user) }
    before do
      sign_in user
      visit edit_user_path(user)
    end

    describe "page" do
      it { should have_content("Update your profile") }
      it { should have_title("Edit user") }
      it { should have_link('change', href: 'http://gravatar.com/emails') }
    end

    describe "with valid information" do
      let(:new_name)  { "New Name" }
      let(:new_email) { "new@example.com" }
      before do
        fill_in "Name",             with: new_name
        fill_in "Email",            with: new_email
        fill_in "Password",         with: user.password
        fill_in "Confirm Password", with: user.password
        click_button "Save changes"
      end

      it { should have_title(new_name) }
      it { should have_selector('div.alert.alert-success') }
      it { should have_link('Sign out', href: signout_path) }
      specify { expect(user.reload.name).to  eq new_name }
      specify { expect(user.reload.email).to eq new_email }
    end
  end
end

A: The error you receive when running your spec suggests that Capybara expects a field called "Name" to fill (because you ask it to at line fill_in "Name", with: new_name).
If for some reason, after sign-in you don't get to the user form, or the user form is missing the "Name" field - that would explain your failures.
In your comment you say that you get no form after sign-up, so that would definitely explain that.
To verify that, you can add a test to describe "page" like this:
it { should have_field("Name") }

If that fails - you can't expect any of the tests counting on that field to pass...


text:
Q: React native tabview configure sliding speed I'm using react native tab view https://github.com/react-native-community/react-native-tab-view  to have something like a carousel. It seems to work fine, but the sliding transition is too fast for me. How can I configure it? Docs say that there's a configureTransition callback which should return the transition configuration, but doesn't say what's that configuration and how should it look like:
 configureTransition - optional callback which returns a configuration for
 the transition, return null to disable animation

Please, help me to find out how to configure transition speed.

A: Transition spec is defined in this file.
  import { Animated } from 'react-native';

  _configureTransition = () => {
    return {
      timing: Animated.spring,
      tension: 300,
      friction: 100,
    };
  }

  render() {
    return (
      <TabViewAnimated
        ....
        configureTransition={this._configureTransition}
      />
    );
  }


text:
Q: Test failure when mocking nil result When trying to run a test that mocks a nil return value, I'm getting the following error.
Any idea?
function f1() returns string?|error {
    return f2();
}

function f2() returns string?|error {
    return "done";
}

// --tests
import ballerina/test;

@test:Mock {
    functionName: "f2"
}
test:MockFunction mockF2 = new;

@test:Config
function shouldReturnNil() {
    // arrange
    test:when(mockF2).thenReturn(());

    // act
    string?|error result = f1();

    // assert
    if result is error {
        test:assertFail(string `Expected nil, got error ${result.message()}`);
    } else if result is string {
        test:assertFail(string `Expected nil, got string ${result}`);
    }
}

Error:
Running Tests
        hello
                [fail] shouldReturnNil:
                    {ballerina}TypeCastError {"message":"incompatible types: 'error' cannot be cast to '(any|ballerina/test:0.8.0:Error)'"}
                        at ballerina.test.0_8_0:mockHandler(mock.bal:378)
                        ppp.hello.0_1_0:f1(main.bal:2)
                        ppp.hello.0_1_0.tests.main_test:shouldReturnNil(tests/main_test.bal:14)
0 passing
1 failing
0 skipped

A: test:when(mockF2).thenReturn(());

doesn't work with '()' values. If you need to return a nil value, you need to use the following approach.
test:when(mockF2).call("mockNilReturn");

You need to have 'mockNilReturn' function defined as follows.
function mockNilReturn() returns string?|error {
    return ();
}


text:
Q: Use UnsafeProjection to convert row to Person Row I write a simple test case that want to convert InternalRow(UTF8String.fromString("tom"), 1) to an UnsafeRow that has only one field(type is ObjectType(classOf[Person]))
  test("SparkTest UnsafeProjection") {
    val row = InternalRow(UTF8String.fromString("tom"), 1)
    val encoder = ExpressionEncoder[Person].resolveAndBind()
    val proj = UnsafeProjection.create(Seq(encoder.deserializer))
    val proj_row = proj(row)
    val p = proj_row.get(0, ObjectType(classOf[Person])).asInstanceOf[Person]
    println(p.name)
    println(p.age)
  }

When I run it, an exception throws,but I don't know how to fix to make
Unsupported data type ObjectType(class org.apache.spark.sql.Person)
org.apache.spark.SparkException: Unsupported data type ObjectType(class org.apache.spark.sql.Person)
    at org.apache.spark.sql.catalyst.expressions.InterpretedUnsafeProjection$.generateFieldWriter(InterpretedUnsafeProjection.scala:244)
    at org.apache.spark.sql.catalyst.expressions.InterpretedUnsafeProjection$.$anonfun$generateStructWriter$1(InterpretedUnsafeProjection.scala:114)
    at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:238)


text:
Q: Chart.js Second chart won't load I am having an issue with Chart.js. I have made it so that the chart can change its type based off of what selector is chosen (I have got this to work). I am now trying to get a second chart to load on the same page and also have the option of changing the chart type, but when I put the new chart within js and html it loads an empty canvas. If anyone has any ideas of how to fix please let me know.
HTML
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewpoint" content="width=device-width, initial-scale=1.0">
  <title></title>

  <link rel="stylesheet" href="LeadsDash.css">

Here's a quick overview for you.

        <button id="nextChart" onClick= "updateChartType()"></button>

Date From

            <input type="date" required style="width: 150px;">

Date To

            <input type="date" required style="width: 150px;">

Campaign

            <input type="text" required style="width: 150px;">

User

          <input type="text" required style="width: 150px;">

Lead Status

          <input type="text" required style="width: 150px;">

          <button class="updateBtn" style="float: right;">Update</button>

        <select name="chartType" id="chartType" onchange="updateChartType()">
          <option value="line">Line</option>
          <option value="bar">Bar</option>
          <option value="pie">Doughnut</option>
        </select>

        <canvas id="myChart"></canvas>

        <canvas id="myChart1"></canvas>

JS
// functionality for the "next" button to switch between selectors
$("#nextChart").click(function() {
    let isLastElementSelected = $('#chartType > option:selected').index() == $('#chartType > option').length -1;

    if (!isLastElementSelected) {
        $('#chartType > option:selected').removeAttr('selected').next('option').attr('selected', 'selected'); } else {
           $('#chartType > option:selected').removeAttr('selected');
           $('#chartType> option').first().attr('selected', 'selected');
        }
});

// hiding the HTML selectors
$("#chartType").hide();

// the leads everyone has in order of labels
let leads = [1, 10, 10, 40, 20, 30, 45];
let people = ["Jeff", "Jannice", "Steve", "Jenna", "Fred", "Jeoff", "Brad"];

myData = {
        labels: people,
        // properties of the data
        datasets: [
          {
            label: "Total Leads",
            fill: false,
            data: leads,
            borderWidth: 1,
            backgroundColor: [
                'rgba(45, 170, 214, 0.6)',
                'rgba(255, 159, 64, 0.6)',
                'rgba(255, 205, 86, 0.6)',
                'rgba(75, 192, 192, 0.6)',
                'rgba(255, 130, 130, 0.6)',
                'rgba(153, 102, 255, 0.6)',
                'rgba(122, 227, 114, 0.6)'
              ],
              borderColor: [
                'rgb(45, 170, 214)',
                'rgb(255, 159, 64)',
                'rgb(255, 205, 86)',
                'rgb(75, 192, 192)',
                'rgb(255, 130, 130)',
                'rgb(153, 102, 255)',
                'rgb(122, 227, 114)'
              ],
          }
        ]
    };

// Default chart defined with type: 'bar'
// building the onload chart
let ctx = document.getElementById('myChart').getContext('2d');
let myChart = new Chart(ctx, {
    type: 'bar',
    data: myData,
    options: {
        plugins: {
            legend: {
                labels: {
                    // This more specific font property overrides the global property
                    font: {
                        size: 16,
                        family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"
                    }
                }
            }
        }
    }
});

let ctl = document.getElementById('myChart1').getContext('2d');
let myChart1 = new Chart(ctl, {
    type: 'line',
    data: myData,
    options: {
        plugins: {
            legend: {
                labels: {
                    // This more specific font property overrides the global property
                    font: {
                        size: 16,
                        family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"
                    }
                }
            }
        }
    }
});

// Function runs on chart type select update
function updateChartType() {
  // Rebuilding chart with changed chart type
   myChart.destroy();
   myChart = new Chart(ctx, {
     type: document.getElementById("chartType").value,
     data: myData,
   });

   myChart1.destroy();
   myChart1 = new Chart(ctl, {
     type: document.getElementById("chartType").value,
     data: myData,
   });
};


text:
Q: Reordering array of objects into nested objects How do I reorder an array of objects
[ {"2007": rank, "2008": rank, "Class": "label 1"},
  {"2007": rank, "2008": rank, "Class": "label 2"}, ... ]

into a nested object such as:
 {"2007":
      {"label 1": rank, "label 2": rank},
 "2008":
      {"label 1": rank, "label 2": rank}, ...}

A: It seems that your requirement is to transpose the table and index by Class:

*

*call the input "table"

*call every element of the array "row"

*for every year that is a key in at least one row, except the key Class

*

*make year a key in output, mapping to the object:

*

*each key in output[year] is the value class of Class in some row, mapping to the value:

*

*output[year][class] = input.find("Class",class)[year]
This is one possible implementation:
 var input = [ {"2007": rank, "2008": rank, "Class": "label 1"},
               {"2007": rank, "2008": rank, "Class": "label 2"} ]
 //////////
 var yr, i;
 var output = {};
 for(i=0; i<input.length; i++){
   var row = input[i];
   for(yr in row){
     output[yr] = output[yr] || {};
     output[yr][row.Class] = row[yr];
   }
 }
 //////////////
 return output;

test: http://jsfiddle.net/aT5YG/1
If multiple rows have the same Class, the later rows overwrite the previous rows. If the nput was jagged, the output will be jagged.


text:
Q: Wordpress generates some weird links for images Hy.
After uploading an image to Wordpress it shows some weird link instead of "link-to-project/wp-content/uploads/2019/04/IMG_20171129_125745.jpg"
I noticed it shows some info from the database. For example the ID and the date, the size etc. But idk why wordpress is doing this.
When I inspect the source I get this weird link:

Here is the PHP code
<a class = "logo" href="<?php echo get_home_url(); ?>/"><img src="<?php the_field('website_logo','options');  ?>" alt="logo" />

Note I'm using advanced custom fields here.

A: Just to add to your answer for people having issues in the future, the problem was the ACF Image field you was calling was set to image object and you was expecting it to return just the url. There are 2 ways to fix this:
Option 1: Edit the image field to only return the Image URL
Pros

*

*Easy and simple to do, fastest solution

*Good for inline background css

Cons

*

*Unable to control the image size that is returned

*Unable to display the image alt tag which can impact SEO

Option 2: Use the correct ACF Image code to display what you're looking for
The better way to display the image will be to use the Image object field as it allows a much better approach as you have access to all image attributes not just the URL. In order to display these see below:
$image = get_field('website_logo','options');

<a class="logo" href="<?php echo get_home_url(); ?>/">
    <img src="<?php echo $image['url'];?>" alt="<?php echo $image['alt'];?>" />

More information on using the image object when using ACF Image fields can be found by clicking here.
Pros

*

*Equally as easy and simple to do

*Allows you to make use of the alt, sizes, title, caption etc. of the image

*Allows you to use the same image with easy further down in the code by not needing to type out the field function again

Cons

*

*Not the ideal solution when inlining background image css, use image url for this reason instead

A: *Fixed
I just had to use Image url as Return Value here, I accidentally used array for the return value.
Thanks.


text:
Q: error 403 when requesting to activate the kun code, I think it's in the data but I can't understand import requests
from hashlib import sha384
import time
import json
import hmac

class Wrapper:
    def __init__(self,
        public_key: str = None,
        private_key: str = None):
        self.public_key = public_key
        self.private_key = private_key
        self.DEFAULT_HEADERS = {
        "Accept": "application/json",
        "Content-Type": "application/json",
    }

    def _request(self, uri: str, path: str, body: dict):
        round(time.time() * 1000)
        nonce = round(time.time() * 1000)
        str_nonce = str(nonce)
        print(str_nonce, nonce)
        body = json.dumps(body)
        headers = self.DEFAULT_HEADERS.copy()
        headers["kun-nonce"] = str_nonce
        headers["kun-apikey"] = self.public_key
        headers["kun-signature"] = self._sign(
            path, str_nonce, body
        )
        response = requests.put(uri, json=body, headers=headers)
        json_response = response.json()
        return json_response

    def load(self, code):
        body = {"code": code}
        return self._request("https://api.kuna.io:443/v3/auth/kuna_codes/redeem", "/v3/auth/kuna_codes/redeem", body)
    def _sign(self, path: str, nonce: str, body: str) -> str:
        payload = "{}{}{}".format(path, nonce, body)
        print(nonce)
        payload_bin = payload.encode("ascii")
        private_key_bin = self.private_key.encode("ascii")
        sign = hmac.new(private_key_bin, payload_bin, sha384)
        return sign.hexdigest()

Please help I don't understand why it doesn't work.
Expecting value: line 1 column 1 (char 0)
<Response [403]> Forbidden
maybe I'm not passing the code correctly or something else is wrong


text:
Q: matching a number pattern between special characters I am trying to write a regular expression to extract only the number 120068018
!false!|!!|!!|!!|!!|!120068018!|!!|!false!

I am rather new to regular expressions and am finding this a daunting task.
I have tried using the pattern as the numbers always start with 1200
'/^1200+!\$/'

but that does not seem to work.

A: This is the regular expression you need:
/[0-9]+/

[0-9] Matches any number from 0 to 9
The + sign means 1 or more times.
If you want to get any number starting with 1200, then it would be
/1200[0-9]*/

Here I am using * because it allows zero or more. Otherwise, the number 1200 wouldn't be captured.
If you want to capture (extract) the String, surround it with parenthesis:
/(1200[0-9]*)/

A: Use this:
/1200\d+/

\d is a meta-character that will match any digits.
Your regular expression didn't work because:

*

*^ matches start of a string. You didn't have your number there.

*$ matches end of the string. Again, your number is in the middle of the string.

*
*

*applies to the immediately preceding character, meta-character or group. So 1200+ means 120 followed by 1 or more zeroes.

A: If your number always starts with 1200, you can do
/1200\d*/

This matches a string that starts with 1200 plus "however many digits follow". Depending on the 'dialect' of regex that you use, you might find
/1200[0-9]*/

more robust; or
/1200[[:digit:]]*/

which is more "readable"
Any of these can be "captured" with parentheses. Again, depending on the dialect, you may or may not need to escape these (add \ in front). Example
echo '||!!||!!||!!120012345||##!!@@!!||' | sed 's/^.*\(1200[0-9]*\).*$/\1/'

produces
120012345

just as you wanted. Explanation:
sed              stream editor command
s                substitute
^.*              everything from start of string until
\(               start capture group
1200             the number 1200
[0-9]*           followed by any number of digits
\)               end capture
.*$              everything from here to end of line
/\1/             and replace with the contents of the first capture group


text:
Q: How to Route to specific pages based on id? In one of my React projects, I have two components PhotoComp and VideoComp. I call both components based on following API -> /content/list/abc123ghi for VideoComp and /content/list/pqr456yui for PhotoComp. Now my Routing in App.js is as follows
<Route path="/content/list/:videoId" component={VideoComp} />
<Route path="/content/list/:photoId" component={PhotoComp} />

Now in Video and Photo components, I extract the parameter using useParams(), and then it's expected to route based on parameter. When I click on the Video section on the Main page it redirects to VideoComp perfectly showing video id 'abc123ghi' above in URL whereas when clicked on the Photo section it doesn't redirect to PhotoComp it moves to VideoComp, but, URL shown above is with photo id 'pqr456yui'.
What could be the appropriate solution?

A: If they are in a switch this is because your two routes are exactly the same /content/list/pqr456yui could refer to both Video and Photo. The only difference would be the property of useParams to get the id. const {videoId} = useParams() vs const {photoId} = useParams() being used.
You need some way to differentiante between them.
e.g. changing the url path
<Switch>
    <Route path="/videos/list/:videoId" component={VideoComp} />
    <Route path="/photos/list/:photoId" component={PhotoComp} />
</Switch>

A: React Router doesn't actually know whether you are passing a videoId or a photoId as your parameters. It tries to match the URL and returns the first match that it found which is VideoComp.
You need some way to differentiate between your video and photo ids. One thing that I would suggest is to wrap your VideoComp and PhotoComp in another component and conditionally render in that component.
Here is an example:
<Route path="/content/list/:videoId" component={PhotoVideoComp} />

PhotoVideoComp would look like this:
    function PhotoVideoComp(){
    return(
       props.match.params.videoId === 'video' ? VideoComp:PhotoComp
    )

    }
  export default PhotoVideoComp


text:
Q: Detach is not found in ef I am following a video on MVVM.
There I have written a simple method by following the steps in video as follows :
[OperationContract]
public IEnumerable<Patient> GetPatients()
{
    using (Lab_Lite_Entities db = new Lab_Lite_Entities())
    {
        var result = db.Patients.ToList();
        result.ForEach(p => db.Detach(p)); //I get an error here.
        return result;
    }
}

But I get an error as follows:
Lab_Lite_Data.Lab_Lite_Entities does not contain a definition for 'Detach' and no
extension method 'Detach' accepting a first argument of type
'Lab_Lite_Data.Lab_Lite_Entities' could be found
(are you missing a using directive or an assembly reference?)

I have added a reference to System.Data.Entity and EntityFramework.
I am using Entity Framework 6.0.

A: As the error shows DbContext doesn't contain Detach method but there is an alternative way
Entity Framework Code First - No Detach() method on DbContext


text:
Q: How To Fix 'No mapping exists from object type System.Data.SqlClient.SqlParameter to a known managed provider native type.' error in ASP.Net I am trying to call stored procedure from a controller. It's values come from ajax to controller. How can I resolve this error I'm getting?
Here is my stored procedure
ALTER PROCEDURE [dbo].[sp_Get_OADetails_By_Customer]
    @CustCode NVARCHAR(15),
    @Status INT,
    @Sdate NVARCHAR(20),
    @Edate NVARCHAR(20)
AS
BEGIN
    SELECT
        O.OANO, O.OADate, O.PONO, O.PODATE,
        SO.POLI, SO.ID, SO.MOULDCODE, SO.DESCRIPTION,
        SO.Drg, SO.Rev, M.METALNAME,
        SO.QTY, U.UNITName, SO.DELIVERYDT
    FROM
        OADetails AS O
    LEFT OUTER JOIN
        CustomerDetails AS C ON O.PCODE = C.PCODE
    LEFT OUTER JOIN
        SubOADetail AS SO ON O.OANO = SO.OANO
    LEFT OUTER JOIN
        MetalDetails AS M ON SO.METALCODE = M.METALCODE
    LEFT OUTER JOIN
        UNITMaster AS U ON SO.UNIT = U.UNITID
    WHERE
        C.CUSTCODE = @CustCode
        AND O.Status = @Status
        AND o.OADATE BETWEEN @Sdate AND @Edate
END

Here is my controller
[HttpPost]
public ActionResult GetOADetailByCustomer(string custcode, int status, string yr)
{
        var CST = new SqlParameter
        {
            ParameterName = "CUSTCODE",
            Value = custcode
        };

        var ST = new SqlParameter
        {
            ParameterName = "Status",
            Value = status
        };

        var yearval = Db.Years.Where(x => x.YEAR1 == yr).FirstOrDefault();

        var courseList = Db.Database.SqlQuery<OADetail>("exec sp_OADetails_Get @CustCode, @Status, @Sdate, @Edate",
            new SqlParameter("@CustCode", CST),
            new SqlParameter("@Status", ST),
            new SqlParameter("@Sdate", yearval.SDATE),
            new SqlParameter("@Edate", yearval.EDATE)).FirstOrDefault<OADetail>();
        return View();
}

Can anyone help me?
Thank you in advance..

A: Exactly as the person user2864740 said, you are doubling up the SqlParameters
Thus change to the following below are that will fix it.
[HttpPost]
public ActionResult GetOADetailByCustomer(string custcode, int status, string yr)
{
        var CST = custcode;
        var ST = status;

        var yearval = Db.Years.Where(x => x.YEAR1 == yr).FirstOrDefault();

        var courseList = Db.Database.SqlQuery<OADetail>("exec sp_OADetails_Get @CustCode, @Status, @Sdate, @Edate",
            new SqlParameter("@CustCode", CST),
            new SqlParameter("@Status", ST),
            new SqlParameter("@Sdate", yearval.SDATE),
            new SqlParameter("@Edate", yearval.EDATE)).FirstOrDefault<OADetail>();
        return View();
}


text:
Q: Reading Files: One single function works, but both don't Here is my code:
import re

def get_email_answers(path):
    for line in path:
        clear = line.strip()
        if re.match(r".*\s.*\t(Antw.+)\t.*Uhr", clear):
            subject = re.findall(r".*\s.*\t(Antw.+)\t.*Uhr", clear)
            print(subject)

def get_sizes(path):
    for line in path:
        clear = line.strip()
        if re.match(r".*\s([0-9][0-9]\s[MKG]B)", clear):
            size = re.findall(r".*([0-9][0-9]\s[MKG]B)", clear)
            print(size)
        elif re.match(r".*\s([0-9][0-9][0-9]\s[MKG]B)", clear):
            size = re.findall(r".*([0-9][0-9][0-9]\s[MKG]B)", clear)
            print(size)
        elif re.match(r".*\s([0-9]\s[MKG]B)", clear):
            size = re.findall(r".*([0-9]\s[MKG]B)", clear)
            print(size)
        elif re.match(r".*(.\.[0-9][0-9]\s[MKG]B)", clear):
            size = re.findall(r".*(.\.[0-9][0-9]\s[MKG]B)", clear)
            print(size)

file_opener = open(r"C:\Users\julia\Documents\RegEX-Test.txt", "r")
get_sizes(file_opener)
get_email_answers(file_opener)

The function get_sizes works, but the function get_email_answers doesn't.
If you comment the function get_sizes out, then get_email_answers works perfectly. If you put get_email_answers before get_sizes, then get_sizes doesn't work and get_email_answers does.
I have done this:
def get_email_answers(path):
    print(path) #modified here
    for line in path:
        print("line") #and here
        clear = line.strip()
        if re.match(r".*\s.*\t(Antw.+)\t.*Uhr", clear):
            subject = re.findall(r".*\s.*\t(Antw.+)\t.*Uhr", clear)
            print(subject)

The printed path is the same as in get_sizes.
But, the for-loop didn't run!
Why? And why does it, when you comment the other function get_sizes out?

A: Reading files is a sequential process. When you open a file, an internal "pointer" is created, rembering where in the file you are - at first it points to the beginning of file, and each time you read a chunk of it, the "pointer"moves past this chunk and points to the first byte that hasn't been read yet. So, after one of your functions reads the file, this pointer is set to the end of it, and when second function tries to read it, it seems empty. You need to reset this pointer between readings, invoking file_opener.seek(0).
Btw. file_opener is a slightly confusing name - this variable holds the file object itself, not some object offering functionality to open a file.

A: You can only read a file-object once. I have to stored the file data in a variable: data = file_opener.read() and iterate over that or you need to return the file pointer at the end of a function.
Try this:
get_sizes(file_opener)
file_opener.seek(0)
get_email_answers(file_opener)

To clarify: the issue isn't in the functions, it's in the way your handle the input file.


text:
Q: Undefined index: expiry_date in laravel I'm trying to get the user the expiry date from created_at in laravel I'm using carbon but when I submit the form it gives this message "Undefined index: expiry_date** why??? How I calculate 1-day expiry date from the current date(create_at)
my register controller  code is
<?php

 namespace App\Http\Controllers\Auth;

 use App\User;
 use App\Http\Controllers\Controller;
 use Illuminate\Support\Facades\Hash;
 use Illuminate\Support\Facades\Validator;
 use Illuminate\Foundation\Auth\RegistersUsers;
 use Carbon\Carbon;

 class RegisterController extends Controller
{
use RegistersUsers;

protected $redirectTo = '/dashboard';

public function __construct()
{
    $this->middleware('guest');
}

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:8', 'confirmed'],
        'phone' => ['required', 'string'],
        'country' => ['required', 'string'],
        'state' => ['required', 'string'],
        'purpose' => ['required', 'string'],
        'package' => ['required', 'string'],
        'months' => ['required', 'string'],
        'quantity' => ['required', 'string'],
        'amount' => ['required', 'string'],
    ]);
}

protected function create(array $data)
{

    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'phone' => $data['phone'],
        'country' => $data['country'],
        'state' => $data['state'],
        'purpose' => $data['purpose'],
        'expiry_date' => Carbon::now()->addHours($data['expiry_date']),

        //'package' => $data['package'],
       // 'months' => $data['months'],
        //'quantity' => $data['quantity'],
        //'amount' => $data['amount'],
    ]);
}
}

please help me. to solve this and how I calculate user expiry from the current date for one data

Thanks in advance.

A: You don't have expiry_date from request(), because it's not defined in Validator.
You need to add expiry_date :
Solution #1
return Validator::make($data, [
    'name'        => ['required', 'string', 'max:255'],
    'email'       => ['required', 'string', 'email', 'max:255', 'unique:users'],
    'password'    => ['required', 'string', 'min:8', 'confirmed'],
    'phone'       => ['required', 'string'],
    'country'     => ['required', 'string'],
    'state'       => ['required', 'string'],
    'purpose'     => ['required', 'string'],
    'package'     => ['required', 'string'],
    'months'      => ['required', 'string'],
    'quantity'    => ['required', 'string'],
    'amount'      => ['required', 'string'],
    'expire_date' => ['YOUR RULES'],         // <----------
]);

Solution #2
Or if you want to define expire_date 1-day expiry from now(), you should :
return User::create([
    'name'        => $data['name'],
    'email'       => $data['email'],
    'password'    => Hash::make($data['password']),
    'phone'       => $data['phone'],
    'country'     => $data['country'],
    'state'       => $data['state'],
    'purpose'     => $data['purpose'],
    'expiry_date' => Carbon::now()->addDay(),
]);

A: Seems you dont have the expiry_date in your request. So first try to print the value of expiry_date.
If it doesn't exist then check your request.
You can also use current date such as
'expiry_date' => Carbon\Carbon::now()

Or in PHP you can do it like
'expiry_date' => date('Y-m-d H:i:s');


text:
Q: Display IDataErrorInfo Error in Textblock instead of Tooltip I've seen lots of examples of how to display an error in a tooltip of a textbox. Can someone give me an example of how to display an error in a separate TextBlock instead of in a tooltip of the TextBox?
I'm particularly interested in knowing how to do this if the textbox and textblock are in different views. The view with the textblock has access to the data that has IDataErrorInfo implemented on it though.

A: you wrote

The view with the textblock has access to the data that has
  IDataErrorInfo implemented on it though.

so one way could be to just bind the textblock to the same property like your textbox do. then create a validationtemplate for your textblock wich cover the whole textblock.
EDIT: maybe something like this?
<ControlTemplate x:Key="ValidationTemplate">
    <Grid>
        <AdornedElementPlaceholder Name="MyAdornedElement" />
        <TextBlock Text="{Binding ElementName=MyAdornedElement,Path=AdornedElement.(Validation.Errors).CurrentItem.ErrorContent}" />
    </Grid>
</ControlTemplate>

you have to add this to the textblock style of course

A: So what I ended up doing is adding a property that I set with the Error text. Anytime my Name property is updated, if it has an error, I update the NameError property. I was then able to bind to that property. It seems a little dirty but it did the trick for me.


text:
Q: С чем может быть связана проблема? Отваливаются зависимости
Пробовал сносить проект несколько раз, в нугете обновлений нет, переодически возникает само по себе, через пару дней исправляется, опять же само. В этот раз попытался создать UnitTest, опять отвалились.


text:
Q: How do I pass a char(*)([long unsigned int]) as a parameter in C? I have a variable type:
char (*p)[12] = calloc(n, sizeof(*p));

I need the variable to stay this way, but I am having trouble passing it as a parameter due to the function type giving me errors:
void myMethod(char *p) { ... }

What can I use in myMethod as the parameter to make this work?

A:
What can I use in myMethod as the parameter to make this work

Possibly this:
void myMethod(char (*p)[12])

A: Use the same type for the parameter as you did for the variable:
void myMethod(char (*p)[12])
{
  // do something with p
}
...
char (*p)[12] = calloc(n, sizeof *p);
myMethod(p);

Remember that p is a pointer to a 12-element array of char, not a simple pointer to char.  Thus, the type of p[i] will be char [12] (which in most cases will decay to char *).

A: The typical C idiom is to pass a char* and a size_t (or unsigned int or whatever equivalent) parameter. Then the contract of the function is that it will respect the size_t argument as the length of the array/buffer.
If you must insist that the pointer be not changed, you use the const qualifier.

A: char (*p)[12] = ...

With the previous you have NOT defined an array of 12 elements, each one being a pointer to char BUT a pointer to an array with 12 char elements.
As explained in the following lines:
int *a[3];

Start at a . Look right, say array of size 3. Look left and say pointer. Look right and see nothing. Look left and say int. All together you say a is an array of size 3 pointers to int.
Adding parentheses is when it gets weird:
int (*a)[3];

The parentheses change the order just like in an expression. When you look right after a , you see the right parenthesis, which you cannot jump over until you look left. Hence, you would say a is a pointer to an array of 3 ints.
Check these links for better explanation:

*

*http://www.antlr.org/wiki/display/CS652/How+To+Read+C+Declarations

*http://www.ericgiguere.com/articles/reading-c-declarations.html

Still if you want to pass the array to a function you can either copy it, or since it is an array pass a pointer to the first element (you can simply do it by using the name of the array):
myMethod( p ) <- how you call the function

I personally would prefer the latter case, since you're passing to the function a simple pointer and not an array by copy of all of its elements


text:
Q: Magento 2: Change compare icon in product detailed page I want to change compare icon in product detailed page
for more info please find the attached image

A: Please check with below path :
/app/design/frontend/Magento/blank/web/css/source/styles-m.css // that is default theme css path. if you are using theme than check with theme path.

to find below class
.product-social-links .action.tocompare:before {
    content: '\e61e'; // to replace with your icon.
}


text:
Q: SYBASE cursor declare as for read only become infinitive There is a simple cursor, which has 260 records. Inside the loop not only print but update some tables. There is not only code, but explanation
/*Declare cursor for read only*/
DECLARE crsr_one CURSOR FOR
    SELECT a,b,c,d
    FROM table_name
    WHERE a>=100
    for read only

    OPEN crsr_one          /*open cursor*/
    DECLARE @a,@b,@c,@d    /*declare loop variables*/

    while (1=1)            /*start while loop*/
    BEGIN
        FETCH crsr_one into @a,@b,@c,@d    /*fetch into  variable */

        IF (@@sqlstatus = 2)               /*Break if no more records*/
            break
        /*some other code with select and update table*/
        print "%1! %2! %3! %4!", @a,@b,@c,@d   /*Print variables*/
    END

The problem is:
In the while loop it became infinitive and brings the same data.
Any idea why and how to correct it?

A: Your code looks good (except that the syntax for the DECLARE is invalid).
If the loop doesn't break on @@sqlstatus = 2, then the obvious question is: what value does it have? It can also be '1', indicating an error. To find out, print the value.
To be fully correct you should therefor also test for @@sqlstatus = 1. The easiest way to do this is to test for @@sqlstatus != 0 which covers both values 1 and 2.


text:
Q: Microsoft Office Professional Plus 2019 - Outlook - notificationMessages.replaceAsync not working Since updating to the latest version of Windows Outlook I can no longer see the message created by Office.context.mailbox.item.notificationMessages.replaceAsync. In a previous version (can't recall which) it was visible:

In the latest version of Outlook I can see a busy indicator and the text "... Add-in is working on your ... request" but then that disappears but the notification message does not appear.
Edit: This is for Version 1908 (Build 11929.20254 Click-to-Run)


text:
Q: Sorting and paging GridView issues i'm using a GridView and trying to sort and page it.
I have more than 20 rows on my DataBase, but the GridView just shows 10.
I set AllowPaging=true but noting happened.
Also I'm using AllowSorting = true and OnSorting="GridView_Sorting". But when I click on the header to sort the the content of that column, it does not enters on my OnSorting="GridView_Sorting" it goes right to the GridView1_RowCommand why ?
Sometimes it just give me this error:
Object reference not set to an instance of an object error
Here's my Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" style="font-family: Verdana, Arial, Sans-Serif;"

    CssClass="gridview" OnSorting="GridView_Sorting"
    AllowSorting ="True" AllowPaging="True" BackColor="#CCCCCC"
    BorderStyle="Inset" BorderWidth="2px" BorderColor="GrayText"
    CellPadding="1"
    CellSpacing="5"
    HeaderStyle-HorizontalAlign="Center"
    OnRowDataBound="GridView1_RowDataBound"
    ForeColor = "Black" RowStyle-CssClass="gridview"
    OnRowCommand="GridView1_RowCommand">
    <AlternatingRowStyle BackColor="#CCCCCC" />
       <columns>
          <asp:BoundField HeaderText="ID" DataField="id" SortExpression="id"  />
          <asp:BoundField HeaderText="PRIORIDADE" DataField="prioridade" ItemStyle-HorizontalAlign="Center" SortExpression="prioridade" SortExpression="prioridade" />
          <asp:BoundField  HeaderText="SITUAÇÃO"  DataField="situacao" ItemStyle-HorizontalAlign="Center" >
          <ItemStyle HorizontalAlign="Center" />
          </asp:BoundField>
          <asp:BoundField HeaderText="RESPONSAVEL" DataField="responsavel" HeaderStyle-Width="65px" ItemStyle-HorizontalAlign="Center">
          <HeaderStyle Width="65px" />
          <ItemStyle HorizontalAlign="Center" />
          </asp:BoundField>
          <asp:BoundField HeaderText="DATA DE CADASTRO" DataField="dt_cadastro" SortExpression="dt_cadastro" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"ItemStyleHorizontalAlign="Center" >
          <HeaderStyle Width="60px" />
          <ItemStyle HorizontalAlign="Center" />
          </asp:BoundField>
          <asp:BoundField HeaderText="PREVISÃO DE TÉRMINO" DataField="previsao_termino" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"
          ItemStyle-HorizontalAlign="Center">
          <HeaderStyle Width="60px" />
          <ItemStyle HorizontalAlign="Center" />
          </asp:BoundField>
          <asp:BoundField HeaderText="PROJETO" DataField="projeto"  ItemStyle-HorizontalAlign="Center"></asp:BoundField>
          <asp:BoundField HeaderText="FUNCIONALIDADE" DataField="funcionalidade" ItemStyle-HorizontalAlign="Center" />
          <asp:BoundField HeaderText="CLUBE" DataField="clube"  ItemStyle-HorizontalAlign="Center" />
          <asp:TemplateField HeaderStyle-Width="70px" HeaderText="VISUALIZAR" >
          <ItemTemplate>
          <asp:Button ID="Btn_Visualizar" runat="server" Text="VISUALIZAR" CssClass="Btn_Grid"  Font-Size="7pt" Font-Names="Verdana, Arial"  OnClick="Btn_Visualizar_Click"CommandName="visualizar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
          </ItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField HeaderStyle-Width="66px" HeaderText="ALTERAR">
          <ItemTemplate>
          <asp:Button ID="Btn_Alterar" runat="server" Text="ALTERAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial"CommandName="editar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
          </ItemTemplate>
       </asp:TemplateField>
       <asp:TemplateField HeaderStyle-Width="66px" HeaderText="FEEDBACK">
       <ItemTemplate>
       <asp:Button ID="Btn_Feedback" runat="server" Text="ADICIONAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana,Arial"CommandName="feedback" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
       </ItemTemplate>
       </asp:TemplateField>
       </columns>

My CodeBehind:
protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            string[] strSortExpression = ViewState["SortExpression"].ToString().Split(' ');

            // If the sorting column is the same as the previous one,
            // then change the sort order.
            if (strSortExpression[0] == e.SortExpression)
                {
                if (strSortExpression[1] == "ASC")
                {
                    ViewState["SortExpression"] = e.SortExpression + " " + "DESC";
                }
                else
                {
                    ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
                }
            }
                // If sorting column is another column,
                // then specify the sort order to "Ascending".
            else
            {
                ViewState["SortExpression"] = e.SortExpression + " " + "ASC";
            }
            // Rebind the GridView control to show sorted data.
            GridView1.DataSource = ch.BuscaTodosChamados();
            GridView1.DataBind();
        }

A: Add SortExpression attribute for each sortable column, informing its DataField.


text:
Q: insert title of articles in guillemets in ConTeXt bibliographies What shall I do to have articles title within french guillemets in a structural way? I have tryied this so far, but without success, whatever style I choose (APA, APS, Chicago). Compiled under LMTX, for the records. Playing with the style setups did not help very much neither.
\setuppapersize[A4]
\mainlanguage[fr]
\language[fr]

\startbuffer [bib]
@article{IslamIran,
   author = "Sétareh Gaffari",
   title = "Islam et politique en Iran",
   journal = "CEMOTI",
   number = "39--40",
   year = "2005",
   pages = {125--136},
   doi = "https://doi.org/10.3406/cemot.2005.1769",
   url = "https://www.persee.fr/doc/cemot_0764-9878_2005_num_39_1_1769"
}

\stopbuffer

\usebtxdataset[bib.buffer]

\usebtxdefinitions [apa]

%\setupbtx [apa:list:title:article]
%    [left={«},
%     right={»}]

%does not work neither
\setupbtx [apa:list:title:article]
    [left={\btxlabeltext{«}},
     right={\btxlabeltext{»}}]

\starttext

\nocite[IslamIran]

\placelistofpublications
\stoptext

A: Use the \quotation command.
\setupbtx
    [apa:list:title:article]
    [command=\quotation]

Full example (tested with MkIV and LMTX):
\setuppapersize[A4]
\mainlanguage[fr]
\language[fr]

\startbuffer [bib]
@article{IslamIran,
   author = "Sétareh Gaffari",
   title = "Islam et politique en Iran",
   journal = "CEMOTI",
   number = "39--40",
   year = "2005",
   pages = {125--136},
   doi = "https://doi.org/10.3406/cemot.2005.1769",
   url = "https://www.persee.fr/doc/cemot_0764-9878_2005_num_39_1_1769"
}

\stopbuffer

\usebtxdataset[bib.buffer]

\usebtxdefinitions [apa]

\setupbtx
    [apa:list:title:article]
    [command=\quotation]

\starttext

\nocite[IslamIran]

\placelistofpublications
\stoptext


text:
Q: Create a vector with multiple expressions In the following ggplot barchart. How can I generate a vector with multiple expressions automatically?
data <- data.frame(x = LETTERS[1:11], y = 10^(0:10))
z <- 0:10
y.labels <- sprintf(paste0("10^", z))
ggplot(data, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_y_log10(breaks = 10^(z), labels = y.labels)

I've tried with bquote(.(10^c(z))), but is not the desired result .
My only alternative is to do it manually, but it is not automatic:
y.labels <- expression("10"^0, "10"^1, "10"^2, "10"^3, "10"^4, "10"^5, "10"^6, "10"^7, "10"^8, "10"^9, "10"^10)

A: Try parse(text =, which will convert the character vector y.labels into the expected expression:
ggplot(data, aes(x, y)) +
    geom_bar(stat = "identity") +
    scale_y_log10(breaks = 10^(z), labels = parse(text = y.labels))

A: We can use bquote with expression
y.labels <-  sapply(z, function(u) as.expression(bquote(10^.(u))))
ggplot(data, aes(x, y)) +
   geom_bar(stat = "identity") +
   scale_y_log10(breaks = 10^(z), labels =y.labels)

A: If you don't need to store both z and y.labels, you can use:
library(scales)
data <- data.frame(x = LETTERS[1:11], y = 10^(0:10))
ggplot(data, aes(x, y)) +
  geom_bar(stat = "identity") +
  scale_y_log10(breaks = trans_breaks(log10, function(x) 10^x, 10),
                labels = trans_format(log10, math_format(10^.x)))


text:
Q: How to use graphviz draw a TCP/IP data encapsulation diagram? I am trying to use Graphviz to draw a TCP/IP data encapsulation diagram in Stevens' classical TCP/IP book.

The diagram seems not a standard computer graph. My questions are:

*

*how to align to right?

*how to mark the size below each record(i.e. 14 in IP header, 20 in TCP)?

*how to draw a edge like |<----------- 46 to 1500 bytes ---------->| and put it below some node?

Can graphviz draw it? If so, how? Thanks in advance.

A: *

*For alignment, I used straight edges (splines=false) and an indication of which corner of the node they come from and which corner of the other node they enter (compass points).

*To create labels under the words, I used a HTML-label with a two-row table, in the second row I made the bottom borders and the borders on the left and right sides invisible by setting the attribute sides="T" (T meaning top border).

*For drawing edge like |<----------- 46 to 1500 bytes ---------->|, I used node's width reduction (width=.01) and invisible nodes and edges, you can find them in the script below by attribute style=invis. Here is a small example with red tinted elements that are invisible in the final image:

Graphviz can draw it (see below for a example), but as answered in the comments above, it will be faster to use graphics editor.
Script:
digraph TCP_IP_diagram {
    label=<Figure 1.7  Encapsulation of data as it goes down the protocol stack.>
    nodesep=0
    ranksep=.1
    splines=false

    edge[style=dashed]
    node[shape=box height=.6]

    // NODES ------------------------------------

    table_0 [margin=0 shape=none label=<

user data

>]

    inv_0 [shape=point style=invis]

    table_1 [margin=0 shape=none label=<

        Appl
header
        user data

>]

    inv_00 [shape=point style=invis]

    table_2 [margin=0 shape=none label=<

        TCP
header
         application data

>]

    {
        rank=same;
        "TCP segment" [shape=plaintext]
        inv_1 [shape=point height=.01]
        inv_2 [shape=point height=.01]
    }

    table_3 [margin=0 shape=none label=<

        IP
header
        TCP
header
         application data

>]

    {
        rank=same;
        "IP datagram" [shape=plaintext]
        inv_3 [shape=point height=.01]
        inv_4 [shape=point height=.01]
    }

    table_4 [margin=0 shape=none label=<

        Ethernet
header
        IP
header
        TCP
header
         application data
        Ethernet
trailer

        14
        20
        20

        4

>]

    {
        rank=same;
        "Ethernet frame" [shape=plaintext]
        inv_5 [shape=box height=.4 width=.01 label=""]
        inv_6 [shape=box height=.4 width=.01 label=""]
    }

    {
        rank=same;
        "46 to 1500 bytes" [shape=plaintext]
        inv_7 [shape=box height=.4 width=.01 label=""]
        inv_8 [shape=box height=.4 width=.01 label=""]
    }

    table_5 [margin=0 shape=none label=<

Ethernet

>]

    morespace [style=invis shape=plain]

    // EDGES ------------------------------------

    table_0:f0:se -> table_1:f1:ne
    table_0:f0:sw -> table_1:f1:nw
    table_0 -> inv_0 [style=invis]
    inv_0 -> table_1 [style=invis]

    table_1:f0:sw -> table_2:f0:ne
    table_1:f1:se -> table_2:f1:ne

    table_1 -> inv_00 [style=invis]
    inv_00 -> table_2 [style=invis]

    table_2 -> "TCP segment" [style=invis]
    table_2:f0:sw -> inv_1 [arrowhead=none]
    table_2:f1:se -> inv_2 [arrowhead=none]

    inv_1 -> table_3:f0:ne
    inv_2 -> table_3:f1:ne

    "TCP segment" -> inv_1 [weight=0 style=solid]
    "TCP segment" -> inv_2 [weight=0 style=solid]

    table_3 -> "IP datagram" [style=invis]
    table_3:f0:sw -> inv_3 [arrowhead=none]
    table_3:f1:se -> inv_4 [arrowhead=none]

    "IP datagram" -> inv_3 [weight=0 style=solid]
    "IP datagram" -> inv_4 [weight=0 style=solid]

    inv_3 -> table_4:f0:ne [style=dashed]
    inv_4 -> table_4:f1:nw

    table_4 -> "Ethernet frame" [style=invis]
    table_4:f0:sw -> inv_5 [style=invis]
    table_4:f1:se -> inv_6 [style=invis]
    "Ethernet frame" -> inv_5 [weight=0 style=solid]
    "Ethernet frame" -> inv_6 [weight=0 style=solid]

    "Ethernet frame" -> "46 to 1500 bytes" [style=invis]
    table_4:f0:se -> inv_7 [style=invis]
    table_4:f1:sw -> inv_8 [style=invis]
    "46 to 1500 bytes" -> inv_7 [weight=0 style=solid]
    "46 to 1500 bytes" -> inv_8 [weight=0 style=solid]

    "46 to 1500 bytes" -> morespace [style=invis]

    {
        edge [minlen=2]
        "application" -> "TCP" -> "IP" -> "Ethernet\ndriver"
    }
    "Ethernet\ndriver" -> table_5:f0 [style=solid arrowhead=none]

    // OTHER RANKS ------------------------------------

    {rank=same;"application";inv_0}
    {rank=same;table_4;table_5}
}

Result:


text:
Q: How to upload on Dropbox Camera Capture image with Watermark without Compress (Keep Orignal Quality) in Android
*

*I am using this code right now but its destroy image quality.

*I have issue regarding blur image

if (requestCode == IMAGE_REQUEST_CODE) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {

        //    kkkk(data.getData());
            picture = (Bitmap) data.getExtras().get("data");//this

// I pass bitmap to function to get watermark

   result = mark(picture , sh.getString("BARCODE", null), 10, 50,R.color.colorPrimaryDark,              200, 30, false);

// now i need a file to upload image on dropbox
file = storeImage(result);

}

// here is my function

private File storeImage(Bitmap image) {

    File pictureFile = getOutputMediaFile();

    if (pictureFile == null) {
        Log.d("",
                "Error creating media file, check storage permissions: ");//    e.getMessage());
        return null;

    }

    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);

        image.compress(Bitmap.CompressFormat.PNG,55, fos);
            fos.flush();

        fos.close();

    } catch (FileNotFoundException e) {
        Log.d("", "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d("", "Error accessing file: " + e.getMessage());
    }

    return pictureFile;
    }

   private File getOutputMediaFile() {
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this.
    File mediaStorageDir = new    File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files");

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
    File mediaFile;
    increase++;
    String mImageName = sh.getString("BARCODE", null) + "_" + timeStamp +  ".jpg";
    mediaFile = new File(mediaStorageDir.getPath() + File.separator +  mImageName);
    return mediaFile;

}

</i>
 }