text:
Q: Terminal and software update do not open anymore ubuntu 20.04 My terminal does not open anymore. I'm using PyCharm terminal to run the commands.
I have tried so many solutions but still getting this error after running sudo apt upgrade:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
4 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] y
Setting up update-notifier-common (3.192.30.5) ...

Progress: [  0%] [...........................................................................................................................................................................................................]
/var/lib/dpkg/info/update-notifier-common.postinst: 29: /usr/lib/update-notifier/package-data-downloader: not found..........................................................................................................]
dpkg: error processing package update-notifier-common (--configure):
 installed update-notifier-common package post-installation script subprocess returned error exit status 127
dpkg: dependency problems prevent configuration of update-notifier:
 update-notifier depends on update-notifier-common (= 3.192.30.5); however:
  Package update-notifier-common is not configured yet.

dpkg: error processing package update-notifier (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of update-manager:
 update-manager depends on update-notifier; however:
  Package update-notifier is not configured yet.

dpkg: error processing package update-manager (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of ubuntu-release-upgrader-gtk:
 ubuntu-release-upgrader-gtk depends on update-manager; however:
  Package update-manager is not configured yet.

dpkg: error processing package ubuntu-release-upgrader-gtk (--configure):
 dependency problems - leaving unconfigured
No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                No apport report written because the error message indicates its a followup error from a previous failure.
                                                                                No apport report written because MaxReports is reached already
                                                 Errors were encountered while processing:
 update-notifier-common
 update-notifier
 update-manager
 ubuntu-release-upgrader-gtk
E: Sub-process /usr/bin/dpkg returned an error code (1)

Any ideas on how can I fix this, please?


text:
Q: Constraining column values using trigger I am trying to use trigger (as suggested here by Bohemian) to constrain how many yes/no will occur in my table. I want at most one yes in the isTeamLead column per unique item in the project column but can have as many no as necessary. For no, it seems the best I can do is use a workaround where I can have something like no1, no2, no3, etc. My code successfully inserts the yes rows but throws errors on the no rows.
DROP TABLE team CASCADE CONSTRAINTS PURGE ;
create table team (
  name varchar2(10) NOT NULL UNIQUE,
  project varchar2(10),
  isTeamLead char(10) check (isTeamLead IN ('No', 'Yes'))
);

create unique index only_one_yes_per_project on team(project, isTeamLead);

DROP SEQUENCE test1_seq;
create SEQUENCE test1_seq
START WITH 1
INCREMENT BY 1;

set define off;
set serveroutput on format wrapped;
CREATE OR REPLACE TRIGGER insert_yesno
  BEFORE INSERT ON team
  FOR EACH ROW
BEGIN
  IF (:new.isTeamLead = 'No') THEN
    DBMS_OUTPUT.put_line(:new.isTeamLead);
    :new.isTeamLead := CONCAT('No', test1_seq.nextval);
    DBMS_OUTPUT.put_line(:new.isTeamLead);
    INSERT INTO team VALUES
      (:new.name, :new.project, :new.isTeamLead);
  END IF;
END insert_yesno;
/

insert into team values ('member1', 'project1', 'Yes');
insert into team values ('member2', 'project1', 'No');
insert into team values ('member3', 'project1', 'No');
insert into team values ('member4', 'project2', 'No');
insert into team values ('member5', 'project2', 'Yes');
insert into team values ('member6', 'project2', 'No');

select * from team;

Here's a snapshot of the error report:
Error starting at line : 244 in command -
insert into team values ('member6', 'project2', 'No')
Error report -
SQL Error: ORA-02290: check constraint (SEDEH.SYS_C0012563) violated
ORA-06512: at "SEDEH.INSERT_YESNO", line 6
ORA-04088: error during execution of trigger 'SEDEH.INSERT_YESNO'
02290. 00000 -  "check constraint (%s.%s) violated"
*Cause:    The values being inserted do not satisfy the named check

Please let me know if any thoughts. Thanks.
Running Oracle Database 11g Enterprise Edition Release 11.2.0.1.0

A: Why not just add a unique function-based index?  The following should constrain the column to have only one team lead per project:
create unique index idx_team_isTeamLead_yes on
    team(case when isTeamLead = 'yes' then project else NULL end);

This takes advantage of Oracle's ignoring rows where all the index columns are NULL.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to add objects to Class and save info to Firebase database I want to save new objects via a view controller in my app. However, I want these new objects to load when the app is logged into. I am using firebase to save data into a database, but how can I save an object and have it return when the app is logged into again? I am new-ish to programming, sorry for any potential confusion.
Here is where the goal information is read when the app has been logged into.
for i in 0 ... clientList.count - 1 {

screenHandle = ref?.child(organizationCode).child(clientList[i].name).observe(.value, with: { (snapshot) in
    let clientStuffLoad = snapshot.value as! [String:Any]

    if clientStuffLoad["Goal 1 Description"] != nil {
        clientList[i].goal1 = clientStuffLoad["Goal 1"] as! String
    } else {
        clientList[i].goal1 = ""
    }

This is essentially what I have regarding adding a new member to the class Client:
@IBAction func addingClientSaveButton(_ sender: Any) {

        var client7 = Client(name: addingClientName.text!,
                      goal1: addingClientGoal1.text!, goal2:
                      addingClientGoal2.text!,
                      goal3: addingClientGoal3.text!,
                      isSelected: false, s: 1,
                      ind: 1, targetBehavior1 : addingClientTB1.text!,
                      targetBehavior2 : addingClientTB2.text!,
                      targetBehavior3 : addingClientTB3.text!,
                      targetBehavior1Info : addingClientTB1Info.text!,
                      targetBehavior2Info : addingClientTB2Info.text!,
                      targetBehavior3Info : addingClientTB3Info.text!)

but I would like the object name to read the client name input as opposed to client7
The second part to this is that I want a way to write this to the database, and be able to read it at log in so that I can use the properties of the class and add to it when adding a new client.

A: This is a super broad question because it covers a lot of different aspects of working with Firebase; writing, reading, handling DataSnapshots etc. Also, I don't know what your data represents so I picked something for me to cover some of the aspects of working with Firebase.
There's no error checking but it works as is. I've commented along the way.
Firebase has no objects; just parent and child nodes. Everything can be thought of as key: value pairs like a dictionary. You cannot write an object or read an object. Only NSString, NSNumber, NSDictionary and the dreaded NSArray (or their Swift counterparts)
Let's start with a class - there's 100 ways to do this but I like classes to be responsible for their properties as well as accepting them and presenting them
class WineClass {
    var wine_key = ""
    var name = ""
    var varietal = ""

    //this is used when creating a new wine object before storing in firebase
    init(withName: String, andVarietal: String) {
        self.name = withName
        self.varietal = andVarietal
    }

    //this is used when we are loading data from firebase to create the wineclass object
    init(withSnapshot: DataSnapshot) {
        let wineName = withSnapshot.childSnapshot(forPath: "wine_name").value as? String ?? "No Wine Name"

        let wineDict = withSnapshot.value as! [String: Any]
        let wineVarietal = wineDict["wine_varietal"] as? String ?? "No Wine Varietal"

        self.wine_key = withSnapshot.key //when we read a wine, this will be it's reference in case we want to update or delete it
        self.name = wineName
        self.varietal = wineVarietal
    }

    //this is use to create a dictionary of key:value pairs to be written to firebase
    func getWineDictForFirebase() -> [String: Any] {
        let d = [
            "wine_name": self.name,
            "wine_varietal": self.varietal
        ]

        return d
    }
}

Then, we need a class var to store the WineClass's. This would be for example a dataSource for a tableView
var wineArray = [WineClass]() //a class var array to store my wines

Then I will give you two buttons, one that populates and writes some wine to Firebase and then a second that read them in and prints to console
func button0() {
    self.writeWine(withName: "Scarecrow", andVarietal: "Red Blend")
    self.writeWine(withName: "Ghost Horse", andVarietal: "Cabernet Sauvignon")
    self.writeWine(withName: "Screaming Eagle", andVarietal: "Cabernet Sauvignon, Merlot, Cabernet Franc")
}

func button1() {
    self.readWines()
}

And then the function that accepts some strings as properites for each wine and writes them to Firebase
func writeWine(withName: String, andVarietal: String) {
   let newWine = WineClass(withName: withName, andVarietal: andVarietal) //create a new wine object

   let wineListRef = self.ref.child("wine_list") //get a reference to my firebase wine_list
   let thisWineRef = wineListRef.childByAutoId() //a new node for this wine
   let d = newWine.getWineDictForFirebase() //get the wine properties as a dictionary
   thisWineRef.setValue(d) //save it in firebase
}

and finally a function that reads in those wines, and prints their properties in console
func readWines() {
   let wineRef = self.ref.child("wine_list")
   wineRef.observeSingleEvent(of: .value, with: { snapshot in //we are reading in the entire wine node which will contain many child nodes
       let allWines = snapshot.children.allObjects as! [DataSnapshot] //cast each child node as a DataSnapshot & store in array
       for wineSnap in allWines { //iterate over each child node in the array
           let wine = WineClass(withSnapshot: wineSnap) //create a new wine, ensuring we also keep track of it's key
           self.wineArray.append(wine) //add to the array
       }

       for wine in self.wineArray  {
           print(wine.wine_key, wine.name, wine.varietal)
       }
   })
}

lastly, when button0 is clicked, our Firebase looks like this
wine_list
   -LhbjhkEC8o9TUISCjdw
      wine_name: "Scarecrow"
      wine_varietal: "Red Blend"
   -LhbjhkEC8o9TUISCjdx
      wine_name: "Ghost Horse"
      wine_varietal: "Cabernet Sauvignon"
   -LhbjhkEC8o9TUISCjdy
      wine_name: "Screaming Eagle"
      wine_varietal: "Cabernet Sauvignon, Merlot, Cabernet Franc"

and then the output when button1 is clicked
-LhbjhkEC8o9TUISCjdw Scarecrow Red Blend
-LhbjhkEC8o9TUISCjdx Ghost Horse Cabernet Sauvignon
-LhbjhkEC8o9TUISCjdy Screaming Eagle Cabernet Sauvignon, Merlot, Cabernet Franc

Note that self.ref is a reference to the root node of my firebase yours will need to reference your firebase.


text:
Q: Getting first item in Julia SortedSet Is there any way of directly accessing the first element in a SortedSet? I'm currently iterating over the SortedSet and immediately calling break, but this seems inelegant.

A: You can use first. first gives you the first element of an iterable collection.
a = SortedSet([3,5,2,4,1])
first(a)
# or you can use piping syntax
a |> first


text:
Q: Angular 2 передача данными между компонентами через router-outlet Задача такая: есть главный компонент, у него через router-outlet отрисован дочерний. Мне нужно передать в дочерний компонент данные (если быть точным, массив), при этом, чтобы компонент мог изменять его и эти изменения синхронно приходили к главному компоненту. Не могу точно понять, как это нужно делать: через queryParams, или же через службы/провайдеры, или же через inputs/outputs (как тогда через router-outlet тег передавать данные в инпуты?) Если нужен код, могу прикрепить, но, как мне кажется, суть вопроса понятна и без кода.

A: Обновление 1
С моей точки зрения это должно выглядеть примерно так:
chat.service.ts
public fetchMessages(user1Id, user2Id) - возвращает сообщения между user1Id и user2Id
и такой роут: chat/:userId , userId - urlParams, например, при переходе в chat/3 будут загружаться сообщения с пользователем с id 3, это user2id. user1Id - Это авторизованный пользователь.
chat.component.ts
activeUserId: number;
userId: number;
messages: any;
userService.activeUserChanges.subscribe(activeUserId => this.activeUserId = activeUserId);
urlParams.subscribe(userId => {
    this.messages = chatService.fetchMessages(this.activeUserId, userId);
    this.userId = userId;

}
Оригинал
Т.к. нужно отлавливать изменения в родительском компоненте из router-outlet, то через сервис
parent.component.ts
sharedDataService.data.subcribe(data => this.arr = data);

child.component.ts
sharedDataService.data.emit(data);

shared-data.service.ts
private arr: any[];
public data: EventEmitter<any[]>


text:
Q: How to delete all posts from a custom post type? I want to delete all posts from a custom post type "TV-Serie". The number of all posts in this post type are 150,000.
Moreover, when I try to delete them all manually while selecting more than 500 posts at once this provides "timeout error".
Any idea on how to delete them all?


text:
Q: next.js fetch request gives error TypeError: fetch failed I'm setting up a next.js website with strapi but running into an issue with my fetch request. When I make the request in postman I can see the data is returned so the endpoint is correct.
The error I get is TypeError: fetch failed in my console I get
TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11118:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  cause: Error: connect ECONNREFUSED 127.0.0.1:1337
      at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
    errno: -111,
    code: 'ECONNREFUSED',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 1337
  }
}

In my page template, I have
import React from "react";

import Layout from "@/components/Layout/Layout";
import { fetcher } from "@/lib/api";

const Insights = () => {
  return (
    <Layout>

Insights

    </Layout>
  );
};

export default Insights;

export async function getServerSideProps() {
  const insightsResponse = await fetcher(
    "http://localhost:1337/api/insights"
  );
  return {
    props: {
      insights: insightsResponse,
    },
  };
}

My fetcher function is
export async function fetcher(url: string, options = {}) {
  let response;

  if (!options) {
    response = await fetch(url);
  } else {
    response = await fetch(url, options);
  }

  const data = await response.json();

  return data;
}

A: reference with video in codegrepperThis error occur because you are  using node version 18 or above where fetch is given by node.
So you have to use node which is below 18 to make fetch work inside
getServerSideProps.you can use nvm to control node version you want to use.

A: Could you open the Developement tools and check the response code?
I've seen ECONNREFUSED meaning the server is refused this request.
Make sure you are requesting correct data (you can also check it in Network Tab)
Please reference this document
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
The fetch have more options, such as method, headers (headers field is very important), ... Add these request options and try again.


text:
Q: Question about a proof in Lang's undergraduate analysis
This is from page 580 of Lang's undergraduate analysis (2nd edition).
I have difficulty in understanding the proof, hope that someone here can enlighten me.
My questions are:
i)  On line 5 of the proof, why is it true that the boundary of $A$ equals the boundary of the closure of $A$?
ii) Why do we need this fact in this proof?
Thank you in advance for taking time to answer my question.
PS: According to Lang, a set is said to be admissible if it is bounded and its boundary is a negligible set.
A set $S$ is said to be negligible if for all $\epsilon>0$, there exists a finite number of rectangles the sum of whose volumes are less that $\epsilon$ and their union covers $S$. This is usually called Jordan content 0.


text:
Q: Integrate phpgrid with codeigniter Im trying to integrate phpgrid  with my codeigniter program.
I need a few clarifications on how to use the library function.
I have added the phpgrid files to the application/libraries path and I have loaded the libray using $this->load->library('phpGrid');
Below is the code in the phpgrid conf.php file.
<?php
// mysql example
define('DB_HOSTNAME','localhost'); // database host name
define('DB_USERNAME', 'admin');     // database user name
define('DB_PASSWORD', 'pop3'); // database password
define('DB_NAME', xtra); // database name
define('DB_TYPE', 'mysql');  // database type
define('DB_CHARSET','utf8'); // ex: utf8(for mysql),AL32UTF8 (for oracle), leave blank to use the default charset

define('SERVER_ROOT', '/grid');

/******** DO NOT MODIFY ***********/
require_once('phpGrid.php');
/**********************************/
?>

Can someone please help me how can I reference the define and require_once files to my library path?
Or is there any other way that I can include the phpgrid files to my CI project?

A: I've just looked at the PHPgrid source files and it appears that they are encrypted so you are limited as to how much you can fully "integrate" with Codeigniters MVC framework.
To work with an external library like this, here's what I would generally do:
Store a separate config.php file (that looks like the PHPgrid one) that defines the db connection constants in the root directory.
Then require this in your Codeigniter config/database.php file and use the constants to set the Codeigniter settings as well. So your Codeigniter database.php would look like:
require_once('config.php');

$db['default']['hostname'] = DB_HOSTNAME;

$db['default']['username'] = DB_USERNAME;

$db['default']['password'] = DB_PASSWORD;

$db['default']['database'] = DB_NAME;

You don't want to be storing database connection details all over the place.
Then include config.php at the top of your phpgrid/conf.php file, and use the constants to fill the details the same way, obviously fill out the other phpgrid constants as well.
Put all the PHPgrid files in a subdir of application/libraries. Now create a new file in your application/libraries file that is called something like ci_phpgrid.php and in it create a new class like below:
<?php
require_once('phpgrid/conf.php');

class CI_phpgrid {

    public function example_method($val = '')
    {
        $dg = new C_DataGrid("SELECT * FROM Orders", $val, "Orders");
        return $dg;
    }
}

You can now use this to communicate with php grid, leaving the original files intact.
In you controller you would just do something like:
$this->load->library('ci_phpgrid');
$data['phpgrid'] = $this->ci_phpgrid->example_method(3)

$this->load->view('home_page',$data);

And then in the view you can display the table using:
$phpgrid->display()

As I mentioned, I've not used PHPgrid and you'll need to include all the relevant JS for sorting etc but this is generally the way you want to approach external libraries in CI.


text:
Q: Sending livetail output to an http endpoint I am using livetail-cli provided by sumologic.
I am trying send the livetail output to an http endpoint. But it shows connection time out error after some time.
The command which i am using is
while IFS= read -r newline; do echo $newline |  curl -XPOST --data-binary $0 http://localhost:9090 -H Content-Type:application/json  ; done < <(./livetail _sourceCategory="x")

What is the best way to achieve this so that the connection persists?Although the sumologic api mentions about the session timeout after 30min of inactivity. But i am sure that the logs would be continuously coming from the source.

A: Sumo Logic's live tail/live tail CLI wasn't intended to stream logs to be forwarded on to other systems.
For this you should either forward it directly from the collector or forward it to an S3 bucket and set up a Lambda function to then forward it on to your other HTTP source.


text:
Q: Azure DevOps Principal is not Showing Up in Key Vault following this document, im trying to consume secrets in my key vault when i design my YAML template on my CI pipeline, but when i go to key vault, add access policies, select principal, i cannot find my principal, it simply says "No result found."
This is the step where I'm stuck at

my project name is PoC-One
my devops account name is Home-PoC
subscription id is XXXXX
so my principal should have been Home-PoC-PoC-One-XXXXX right?
Is this a bug or am I missing something?

A: go to project settings -> service connection -> select ur service connection -> edit -> copy the WHOLE subscription ID -> paste the whole subscription ID in the select a principal search box in key vault when adding access policies -> you should find it then click add


text:
Q: Svn working copy to git working copy I recently converted our SVN repositories to GIT repositories.
Now we want to link our working copies to our git remote repositories.
Do we need to delete our working copies and git clone our repositories?
This would be inconvinient because we would lose uncommitted changes.

A: For any uncommitted change at the svn working directory, you have two options:

*

*copy changed files over to a git working directory and treat as normal git change.

*create a new svn "wip" branch for every remaining change, commit changes from working directory there. Sync those changes into git. Checkout those wip branches at git working directories.


text:
Q: postgres datetime field "x00008F4900000000" I have generate a table data in MS SQL Server to insert it into Postgresql.
The script has this format of insert
INSERT INTO Bank_Draft_Information (Bank_Code, Draft_Type, Transaction_Type, Institution_Code, Serial_Number, Bank_Draft_Date, Total_Amount, Balance_Amount, Created_By, Created_On, Amended_By, Amended_On)
VALUES

 (6, 'C', 'I', NULL, NULL, 0x00008F4900000000 AS DateTime, 1500.0000, 1000.0000, 1, 0x0000950400000000 AS DateTime, 19, 0x0000A32400000000 AS DateTime));

Got error this error,

syntax error at or near "x00008F4900000000"

More, have no access to the MS SQL Server db anymore. How can I convert this into postgres date time object?

A: From this article:

So how does SQL Server internally store the dates? It uses 8 bytes to store a datetime value—the first 4 for the date and the second 4 for the time. SQL Server can interpret both sets of 4 bytes as integers. For the date portion, the value SQL Server stores is the number of days before or after a base date of January 1, 1900. (...)
SQL Server stores the second integer for the time as the number of clock ticks after midnight. A second contains 300 ticks, so a tick equals 3.3 milliseconds (ms). You can see the values for days and clock ticks by converting a datetime value to a binary(8) value and using the substring function to extract each set of 4 bytes. The code in Figure 3 then converts each set of 4 bytes into an integer.

Considering that I'm guessing that x00008F49 probably represents the number of days past since January 1, 1900, And the rest of the strings is probably time representation. Since it's all 0 it represents midnight.


text:
Q: Error while validating and publishing windows 8.1 universal project built with MobileFirst Foundation In MobileFirst Foundation, adding the JSONStore to the Windows 8.1 Universal environment will add the following files to the project:
Msvcr110.dll
Sqllite3.dll
JSONStoreWin8Lib.dll
To create a package and validate it for publishing, I open the .sln file in windows 8 native using Visual Studio, click on the project publish
(project->store-create application package) to start the process.
The validation process failed with the error:
'msvcr110.dll  is not supported'
The error will occur only when taken through MS store validation.
How can I resolve this error?

A: MobileFirst bundles the VC++ runtime for JSON Store along with Windows 8 project.
This is necessary for some devices (tablets) which have an OS without the runtime (usually old Win RT 8.1 operating system)
The issue arises due to the msvcr110.dll referenced in the project.
This is a OS runtime library  that is referenced in the MFP project with JSONStore enabled.
To solve this issue please perform the following:

*

*Delete the msvcr110.dll reference from visual studio project

*Delete the msvcr110.dll from the following locations
a. {ProjectName}/windows8/native/buildtarget/ARM/msvcr110.dll
b. {ProjectName}/windows8/native/buildtarget/x86/msvcr110.dll
c. {ProjectName}/windows8/native/buildtarget/x64/msvcr110.dll

*Add Microsoft Visual C++ Runtime Package (11.0 version) as a
reference in the project. In the Visual Studio project, right click on
references , add new reference , click Windows 8.1 -> extensions. Ensure
Microsoft Visual C++ Runtime Package V11.0 is selected. If other
versions are selected as well ,it's ok.
Ensure 11.0 is selected and checked.
4.Rebuild and deploy.


text:
Q: Filter an existing itemgroup so it only includes files that match some condition How do you filter an existing ItemGroup based on a specific condition, such as file extension or the item's metadata?
For this example, I'll use the file extension. I'm trying to filter the 'None' ItemGroup defined by VS so that my target can operate on all files of a given extension.
For example, the following may be defined:
<ItemGroup>
    <None Include="..\file1.ext" />
    <None Include="..\file2.ext" />
    <None Include="..\file.ext2" />
    <None Include="..\file.ext3" />
    <None Include="..\file.ext4" />
</ItemGroup>

I want to filter the 'None' ItemGroup above so it only includes the ext extension. Note that I do not want to specify all the extensions to exclude, as they'll vary per project and I'm trying to make my target reusable without modification.
I've tried adding a Condition within a target:
<Target Name="Test">
    <ItemGroup>
        <Filtered
            Include="@(None)"
            Condition="'%(Extension)' == 'ext'"
            />
    </ItemGroup>
    <Message Text="None: '%(None.Identity)'"/>
    <Message Text="Filtered: '%(Filtered.Identity)'"/>
</Target>

But sadly, it doesn't work. I get the following for output:
Test:
  None: '..\file1.ext'
  None: '..\file2.ext'
  None: '..\file.ext2'
  None: '..\file.ext3'
  None: '..\file.ext4'
  Filtered: ''

A: <ItemGroup>
  <Filtered Include="@(None)" Condition="'%(Extension)' == '.ext'" />
</ItemGroup>

A: For advanced filtering I suggest using the RegexMatch from MSBuild Community Tasks.
In this Example we will Filter for Versionnumbers
    <RegexMatch Input="@(Items)" Expression="\d+\.\d+\.\d+.\d+">
        <Output ItemName ="ItemsContainingVersion" TaskParameter="Output" />
    </RegexMatch>

Install MSBuild Community Tasks via Nuget: PM> Install-Package MSBuildTasks or download it here

Then Import it in your MSBuild Script:
<PropertyGroup>
    <MSBuildCommunityTasksPath>..\.build\</MSBuildCommunityTasksPath>
</PropertyGroup>
<Import Project="$(MSBuildCommunityTasksPath)MsBuild.Community.Tasks.Targets" />


text:
Q: Mysql error in Jira "Illegal mix of collations (latin1_swedish_ci,I MPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='" I am trying to setup jira and I am using mysql database. I keep receiving this error all the time:
Caused by: java.sql.SQLException: Illegal mix of collations (latin1_swedish_ci,I                                                                              MPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='
What could cause this and how to solve it?

A: Please follow the JIRA Setup guide. It's pretty obvious that you are using the wrong collation. JIRA uses utf8_bin as a collation. I would recommend you to take a look at this document and follow the steps.


text:
Q: file_get_contents failed to open stream: HTTP request failed! HTTP/1.1 463 I am trying to get RSS from other sites. They all work fine using file_get_contents except one link give me this error:

Warning: file_get_contents(http://alwatan.kuwait.tt/rss.ashx): failed to open stream: HTTP request failed! HTTP/1.1 463

I download all files and all have:
<rss version="2.0">

but the link with error have:
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">

this is the only difference between them.

A: Looks to me that that feed is not allowing you to grab it.

463 Restricted Client: This resource is not available for access by your
  client software. This request has been blocked. Please retry your
  request from a different client.
DOSarrest Internet Security is a cloud based fully managed DDoS
  protection service. This request has been blocked by DOSarrest due to
  the above violation. If you believe you are getting blocked in error
  please contact the administrator of scripts.local to resolve this issue.

You can test this by trying to use a curl instead of file_get_contents
<?php

$ch = curl_init("http://alwatan.kuwait.tt/rss.ashx");

curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm");
curl_setopt($ch, CURLOPT_USERAGENT, "spider");

curl_exec($ch);
curl_close($ch);

?>

As Aziz mentioned, if you set the agent and the referred, you can get through.


text:
Q: mvn clean package, I want to copy the created jar to the current directory I want to update my pom.xml so that when someone uses: mvn clean package, the generated jar file is copied to the current directory. I'm looking at the maven plugin copy-resources, but i'm not sure how to specify the current directory, is there an operating system agnostic way to do this? Would like it to also work on windows, if possible
<plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>2.4.3</version>
                    <executions>
                        <execution>
                            <id>copy-resources</id>
                            <!-- here the phase you need -->
                            <phase>validate</phase>
                            <goals>
                                <goal>copy-resources</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${basedir}</outputDirectory>
                                <resources>
                                    <resource>
                                        <directory>target/Test-0.0.1-SNAPSHOT.jar</directory>
                                        <filtering>true</filtering>
                                    </resource>
                                </resources>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

Thanks

A: If by current directory you mean ${project.basedir} then yes you can do this easily. Just make sure you use ${build.finalName}.jar as the file name part as it will properly get the main artifact of a project with <packaging> set to jar (the default).
    <execution>
      <id>copy-resources</id>
         <!-- here the phase you need -->
      <phase>validate</phase>
      <goals>
        <goal>copy-resources</goal>
      </goals>
      <configuration>
      <outputDirectory>${project.basedir}</outputDirectory>
      <resources>
        <resource>
          <!-- Get main artifact -->
          <directory>target/${build.finalName}.jar</directory>
          <!-- Don't filter binary files -->
          <filtering>false</filtering>
        </resource>
      </resources>
      </configuration>
    </execution>

If you wanted to do the current working directory instead you should be able to do it using ${user.dir} as the outputDirectory


text:
Q: hartl rails tutorial chapter 9 error with email method? I'm working on Michael Hartl's Ruby on Rails tutorial and I ran into an error in chapter 9.
Error:
  1) Error:
UsersIndexTest#test_index_as_admin_including_pagination_and_delete_links:
NoMethodError: undefined method `email' for nil:NilClass
    test/test_helper.rb:18:in `log_in_as'
    test/integration/users_index_test.rb:11:in `block in <class:UsersIndexTest>'

36 runs, 79 assertions, 0 failures, 1 errors, 0 skips

FILE: test/integration/users_index_test.rb
require 'test_helper'

class UsersIndexTest < ActionDispatch::IntegrationTest

  def setup
    @user =      users(:michael)
    @non_admin = users(:archer)
  end

  test "index as admin including pagination and delete links" do
    log_in_as(@admin)
    get users_path
    assert_template 'users/index'
    assert_select 'div.pagination'
    first_page_of_users = User.paginate(page: 1)
    first_page_of_users.each do |user|
      assert_select 'a[href=?]', user_path(user), text: user.name
      unless user == @admin
        assert_select 'a[href=?]', user_path(user), text: 'delete',
                                                    method: :delete
      end
    end
    assert_difference 'User.count', -1 do
      delete user_path(@non_admin)
    end
  end

  test "index as non-admin" do
    log_in_as(@non_admin)
    get users_path
    assert_select 'a', text: 'delete', count: 0
  end
end

FILE: test/test_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
require 'rails/test_help'

class ActiveSupport::TestCase
  fixtures :all

  # Returns true if a test user is logged in.
  def is_logged_in?
    !session[:user_id].nil?
  end

  # Logs in a test user.
  def log_in_as(user, options = {})
    password    = options[:password]    || 'password'
    remember_me = options[:remember_me] || '1'
    if integration_test?
      post login_path, session: { email:       user.email,
                                  password:    password,
                                  remember_me: remember_me }
    else
      session[:user_id] = user.id
    end
  end

  private

    # Returns true inside an integration test.
    def integration_test?
      defined?(post_via_redirect)
    end
end

I can't figure out how to fix this error... Any help is much appreciated!
EDIT:
FILE: app/controllers/user_controller.rb
class UsersController < ApplicationController
  before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
  before_action :correct_user,   only: [:edit, :update]
  before_action :admin_user,     only: :destroy

  def index
    @users = User.paginate(page: params[:page])
  end

  def show
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
      log_in @user
      flash[:success] = "Welcome to the Sample App!"
      redirect_to @user
    else
      render 'new'
    end
  end

  def edit
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      flash[:success] = "Profile updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted"
    redirect_to users_url
  end

  private

    def user_params
      params.require(:user).permit(:name, :email, :password,
                                 :password_confirmation)
    end

    # Before filters

    # Confirms a logged-in user.
    def logged_in_user
      unless logged_in?
        store_location
        flash[:danger] = "Please log in."
        redirect_to login_url
      end
    end

    # Confirms the correct user.
    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_url) unless current_user?(@user)
    end

    # Confirms an admin user.
    def admin_user
      redirect_to(root_url) unless current_user.admin?
    end
end

FILE: db/schema.rb
ActiveRecord::Schema.define(version: 20150418002759) do

  create_table "users", force: :cascade do |t|
    t.string   "name"
    t.string   "email"
    t.datetime "created_at",                      null: false
    t.datetime "updated_at",                      null: false
    t.string   "password_digest"
    t.string   "remember_digest"
    t.boolean  "admin",           default: false
  end

  add_index "users", ["email"], name: "index_users_on_email", unique: true

end

A: In the setup of your test, you need to change @user to @admin:
  def setup
    @admin = users(:michael)
    @non_admin = users(:archer)
  end

That is the instance variable name that is referenced in the rest of the test.  Since you did not set it up correctly, @admin is nil, causing the error


text:
Q: Hadoop 3.1.2: jps output lists only jps after executing start-all.sh I am new to Hadoop and have installed hadoop 3.1.2 on Ubuntu 16.04 in standalone mode. When I try to start daemons using start-all.sh, the command says that it is starting different daemons. However, when I check with jps, there is nothing other than jps
(sparkVenv) applied@nadeem-Inspiron-5558:~$ start-all.sh
WARNING: Attempting to start all Apache Hadoop daemons as applied in 10 seconds.
WARNING: This is not a recommended production deployment configuration.
WARNING: Use CTRL-C to abort.
Starting namenodes on [nadeem-Inspiron-5558]
Starting datanodes
Starting secondary namenodes [nadeem-Inspiron-5558]
Starting resourcemanager
Starting nodemanagers
(sparkVenv) applied@nadeem-Inspiron-5558:~$ jps
21729 Jps
(sparkVenv) applied@nadeem-Inspiron-5558:~$

Here is a portion of log of namenode
************************************************************/
2019-05-06 15:36:43,116 INFO org.apache.hadoop.hdfs.server.namenode.NameNode: registered UNIX signal handlers for [TERM, HUP, INT]
2019-05-06 15:36:43,252 INFO org.apache.hadoop.hdfs.server.namenode.NameNode: createNameNode []
2019-05-06 15:36:43,515 INFO org.apache.hadoop.metrics2.impl.MetricsConfig: loaded properties from hadoop-metrics2.properties
2019-05-06 15:36:43,635 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: Scheduled Metric snapshot period at 10 second(s).
2019-05-06 15:36:43,636 INFO org.apache.hadoop.metrics2.impl.MetricsSystemImpl: NameNode metrics system started
2019-05-06 15:36:43,671 INFO org.apache.hadoop.hdfs.server.namenode.NameNodeUtils: fs.defaultFS is file:///
2019-05-06 15:36:43,816 ERROR org.apache.hadoop.hdfs.server.namenode.NameNode: Failed to start namenode.
java.lang.IllegalArgumentException: Invalid URI for NameNode address (check fs.defaultFS): file:/// has no authority.
        at org.apache.hadoop.hdfs.DFSUtilClient.getNNAddress(DFSUtilClient.java:697)
        at org.apache.hadoop.hdfs.DFSUtilClient.getNNAddressCheckLogical(DFSUtilClient.java:726)
        at org.apache.hadoop.hdfs.DFSUtilClient.getNNAddress(DFSUtilClient.java:688)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.getRpcServerAddress(NameNode.java:529)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.loginAsNameNodeUser(NameNode.java:660)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.initialize(NameNode.java:680)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.(NameNode.java:937)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.(NameNode.java:910)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.createNameNode(NameNode.java:1643)
        at org.apache.hadoop.hdfs.server.namenode.NameNode.main(NameNode.java:1710)
2019-05-06 15:36:43,819 INFO org.apache.hadoop.util.ExitUtil: Exiting with status 1: java.lang.IllegalArgumentException: Invalid URI for NameNode address (check fs.defaultFS): file:/// has no authority.
2019-05-06 15:36:43,821 INFO org.apache.hadoop.hdfs.server.namenode.NameNode: SHUTDOWN_MSG:
/************************************************************
SHUTDOWN_MSG: Shutting down NameNode at nadeem-Inspiron-5558/127.0.1.1
************************************************************/

A: You have already got the issue in log, your NameNode fails to start because of issue in core-site.xml "fs.defaultFS" configuration.
Hope this helps.

A: Found that core-site.xml and hdfs-site.xml were empty.
Added configuration mentioned at https://hadoop.apache.org/docs/r3.2.0/hadoop-project-dist/hadoop-common/SingleCluster.html under pseudo distributed mode and formatted namenode.
After that the daemons started on executing start-all.sh


text:
Q: Key-Value based databases, can someone explain to me how to use them practically? There seems to be a big push for key/value based databases, which I believe memcache to be.
Is the value usually some sort of collection or xml file that would hold more meaningfull data?
If yes, is it generally faster to deserialize data then to do traditinally JOINS and selects on tables that return a row based result set?

A: What has happened is that some really, really, REALLY big web sites like Google and Amazon occupy a teeny, tiny niche where their data storage and retrieval requirements are so different to anyone else's that a new way of storing/retrieving data is called for.  I'm sure these guys know what they are doing, they are very good at what they do.
However, then this gets picked up and reported on and distorted into "relational databases aren't up to handling data for the web".  Also, readers start to think "hey, if relational databases aren't good enough for Amazon and Google, they aren't good enough for me."
These inferences are both wrong: 99.9% of all databases (including those behind web sites) are not in the same ball park as Amazon and Google - not within several orders of magnitude.  For this 99.9%, nothing has changed, relational databases still work just fine.

A: As with most things, "it depends". If the joins are relatively inconsequential (that is, a small number of joins on well-keyed data), and you are storing especially complex data, it may be better just to stick with the more complex query.
It's also a matter of freshness. In many cases the purpose of many joins is to bring together very disparate data; that is, data which varies widely in its relative freshness. It can add considerable complexity and overhead to keep a key-value pair table synchronized when a small slice of the data across a large number of pairs is updated. System complexity can often be considered a form of performance cost; the time, risk and cost to make a change to a complex system without impacting performance is often far greater than a simple one.
The best solution is always to code what works as simply as you can. In most cases I'd say this means create a fully normalized database design and join the crap out of it. Only revisit your design after performance becomes an obvious problem. When you analyze the issue, it will also be obvious where the problems lie and what needs to be done to fix them. If it's reducing joins, then so be it. You'll know when you need to know.

A: I don't have a lot of experience with key/value dbs, so take what I say with a grain of salt.
With that said, the first thing I should point out is that memcached isn't a key/value database.  A database implies some kind of persistent store, which memcached isn't.  Memcached is intended to be a temporary store to save a query to the actual database.
Other than that, my understanding is that you're not going to be able to replace your RDBMS with a key/value database.  They tend to be best for unstructured data or other data where you may not know all the attributes that need to be stored.  If you need to store highly-structured data, you can't do much better than a traditional RDBMS.

A: They can be complex structured data that needs deserialization.  They can also be simple fixed-size records, just like your RDBMS.  Part of the benefit is that you get to make that decision yourself.  When you're optimizing your database, you're not limited to what SQL can do.
The way you ask makes it sound like the join or the deserialization will always be the bottleneck.  But in any database, things are never that simple.  You can put denormalized data in your RDBMS, too, or write an RDBMS interface on top of a key-value database, if you really want.


text:
Q: Power query order of queries I would like to know if it is possible to control the execution order of queries in PQ.
Let me explain, i run:

*

*A procedure that I named "executer_procedure"

*I display a table that has been modified by the previous procedure that I named "Requete 1"

So, it is essential for me that "executer_procedure" is executed before "Requete 1".
Is it possible to create a new query with "executer_procedure" and then "Requete 1" ?
I tried to encapsulate the procedure in my second request but it doesn't work. The procedure does not run (I did the test by clearing the data from the table to see if the procedure updates it well).
I show you a screenshot of the dependencies of my queries.
Screenshot
I searched the internet for resources but couldn't find an answer ...
On Excel, using VBA I can update the queries in the order I want but I don't want to use VBA in my projects ...
Is this possible under PQ?
Thank you.
Saigon

A: I integrated my procedure into my 2nd query so it runs well before displaying my table.
This is the solution (and I have searched in different forums) that I have found to not include vba code in my project, without complicating my file
If it can help anyone ...
Thank you for your time :)


text:
Q: Can IIS serve my .NET app over the QUIC protocol? We have a super chatty (ajax) html 5 app (gmail-like in its construction, tons of js).
The reading of QUIC sounds interesting.  https://en.wikipedia.org/wiki/QUIC
Can IIS (or any .NET hosting engine) support QUIC?
If IIS/Win can't do it, can I do it in an haproxy instance (on CentOS) in front of IIS?

A: As of August 2020, the version of IIS present in Windows 10 Version 2004 (2020-04) and Windows Server 2019 (version 19041) does support QUIC, and QUIC seems to be enabled by default:

Some caveats from my own observations:

*

*It only seems to be present in the full-fat IIS, and not IIS Express (but you wouldn't be using IIS Express in production anyway).

*HTTP/3 (QUIC) and HTTP/2 (SPDY) only seem to be enabled in a HTTPS binding and not in a plaintext HTTP binding.

*

*I might be wrong - I'm not familiar with QUIC's details.

*Note that QUIC is actually a rather low-level protocol, and that "HTTP/3" can be thought-of as "HTTP/2-over-QUIC".

*Other than the single checkbox to disable QUIC in the Binding settings page, I can't see any other way to configure QUIC in IIS.

Regarding the common scenario of using IIS as a front-end reverse-proxy (using IIS' URL Rewrite extension and Application Request Routing):

*

*I cannot find any information regarding support for QUIC in ARR.

*Note that the URL Rewrite Extension (which is required to use ARR) has been recently updated to version 2.1 in 2017 after being stuck at version 2.0 for almost a decade. You need to install it manually from the IIS Downloads page.

*The ARR extension is still stuck on version 3.0 which was released in 2013.

*

*This makes me think that ARR 3.0 won't support HTTP/2 (SPDY) or HTTP/3 (QUIC) - but at the same time, ARR makes use of the existing HTTP.sys stack in Windows, so it's actually possible that ARR may use HTTP/3 or HTTP/2 if available. But without an official word or tip from an insider at Microsoft it's impossible to say.

Additionally, in May 2020, Microsoft announced their implementation of QUIC was open-source on GitHub: https://github.com/microsoft/msquic - if you have any further questions you may get answers to them there rather than through MS' official support channels or their never-updated IIS blog.

I did post an Issue to the MSQuic GitHub repo seeking more information and documentation for the QUIC feature, but the issue was closed as off-topic, but they did assure me that they've forwarded the question to the internal documentation team, but doing a date-range Google search shows that no new documentation for QUIC has been published by Microsoft.


text:
Q: How to parse data from array of object I have an array of object $data in my code. I want to collect some of the object attribute to print in my web page. That's why I printed dump($data)
so that I can see the pattern how the object and their attributes distributed in the array of object $data.
But I could not parse anything from that after seeing $data through the dump() function.
After using dump($data) I found something like...
array:1 [▼
  0 => {#238 ▼
    +"data_": 8
  }
]

I need "data_": 8 so that I can collect 8 from here. Why there is #238 ?
What's the significance of it ?

A: The 238 should be the object id.
Try the following code:
foreach($data as $obj)
{
    echo $obj->data_;
}

A: do u ever try using dd method
dd($dump);
laravel helpers


text:
Q: An exercise about p-solvable I'm dealing with a problem about p-solvable in Isaac's finite group theory book. Question is the following: "Let $G$ be $p-$solvable and $P \in Sy{l_p}\left( G \right)$ and $K \le G$ such that $p$ doesn't divide $\left| K \right|$. Suppose that $P \le {N_G}\left( K \right)$. Show that $K \le {O_{p'}}\left( G \right)$." There is a hint.
Hint: Firstly, consider the case ${O_{p'}}\left( G \right) = 1$. For general case, consider the quotient group $G$/${O_{p'}}\left( G \right) $. I hope some of you can answer me.

A: It's probably easiest to work by induction on $|G|$. As in the hint, if $O_{p'}(G) \ne 1$, then the result for $G$ follows immediately from the result for $G/O_{p'}(G)$, so we can assume that $O_{p'}(G)=1$.
So $O_p(G) \ne 1$, and then $O_p(G) \le P \le N_G(K)$ implies that $[K,O_{p
}(G)] \le K \cap O_{p}(G) = 1$, so $K \le C_G(O_{p}(G))$. Now, since $O_{p}(N) \le O_{p}(G)$ for any normal subgroup $N$ of $G$, we can assume that $G = C_G(O_{p}(G))$ - that is $O_{p}(G) \le Z(G)$.
We can clearly assume that $K$ is nontrivial, so $G$ is not a $p$-group, and hence $O_p(G) < O_{p,p'}(G)$, and $O_{p,p'}(G)$ must decompose as a direct product of $O_p(G)$ and a nontrivial $p'$-group, where the latter lies in $O_{p'}(G)$, contradicting $O_{p'}(G)=1$.
That seems a bit contorted, and there may well be a slicker way of doing it!


text:
Q: (Python) Best way to remove non alphanumeric characters: converting text file into list of strings def getCandidates(f):
try:
    candidates = []
    flist = open(f,"r")
    for line in flist:
        line = line.strip()
        if (line==""):
            continue
        candidates.append(line)
    return candidates

except IOError:
     print("Filename not found")
     return candidates

Need to remove any non alphanumeric characters coming from a text file into a list of strings, should I use a another loop or is there a way to implement it into my existing code.
Cheers.

A: F=open("file")
Data=(i.strip() for I in F)


text:
Q: Android: How to enable button when service complete its task? I have two buttons StartButton and StopButton on MainActivity.java . When I press StartButton a Service is created and StartButton get disable. On pressing StopButton Service get destroyed and StartButton get enable.
What I wanted to do is to enable my Start Button as Service completed its task; it returns any notification or trigger type event or message value on my MainActivity.java so my Start Button get enable.
Please give me any idea, concept or code to make it easy for me to understand.

A: Have you tried,
MyButton.setClickable(false);

It will make the button disabled.
and
MyButton.setClickable(true);

It will enable the button.
However, if you want to hide or show the button, you can use,
MyButton.setVisibiity(VIEW.VISIBLE); and MyButton.setVisibiity(VIEW.INVISIBLE);
Edit- As you want to enable the button, once its task is completed, you could open the mainActivity with a flag value true, something like this,
Intent i= new Intent(getBaseContext(), myActivity.class);
i.putExtra("flag", true);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(i);

and in the mainActivity, check the value of flag,
Boolean flag;
flag = this.getIntent().getBooleanExtra("flag", false);
if(flag == true) {
MyButton.setClickable(true);
}

But for it, you should keep the value of flag initially to false.
and once you click the button, you could then set it as not clickable.

A: To understand the communication between service and application take a look at the examples in the android developer docs.
You can enable and disable your buttons in the onServiceDisconnected() and onServiceConnected() methods.
Keep in mind that the service runs in the same thread as your app by default.

A: There can be many ways to achieve this. Let me tell you one with Broadcast Receiver. I hope you are aware of BroadcastReceiver Concepts.
Changes requires in your activity
1) Create a Broadcast receiver as inner class in your activity.
2) Register it with some action, suppose "MY_ACTION".(remember to unregister this receiver on onPause/onDestroy methods)
3) Suppose service completed its task, and you are into onReceive method of Broadcast receiver, now write your code to enable/disable button(i hope you know how to do it)
Changes requires in your Service
1) find out code where you think its task has completed.
2) Create an intent with same action ("MY_ACTION").
3) Broadcast message with sendBroadcast , intent as param. and you are done. :)
let me know if in any point you feel you are stuck ,


text: Q: What does the make target 'nonint_oldconfig' mean in the linux kernel Makefile? Recent versions of the kernel don't seem to support this target. I'm playing around with a 2.6.32 kernel and one of the targets is nonint_oldconfig. I'm not sure what this target actually does.


text:
Q: JavaScript image loading in percents Is there any way to show "percentage-load-bar" while loading an image in js?
In other words I want to use this:
var img = new Image();
img.onload = function() {
  document.querySelector('#percents').innerHTML = 'all done';
};

img.onreadystatechange = function(e) {
  document.querySelector('#percents').innerHTML = e.percentsLoaded;
};

img.src = 'http://example.com/image.png';

A: Javascript has no intermediate events for loading resources. You can however show a loading bar if you are loading more than one image but I'm guessing that's not the case.
If you do really want this I think the only solution is to use Flash, which can do a number of fancy things but .. well .. it's Flash :/
Look at some of the big album-image hosting sites and see if they have a solution.


text:
Q: Generation of polynomial features in C++98 I am trying to generate polynomial features of an array of 27 floats to obtain an array of 405 floats as output. I am working on an old version of C++98 (no upgrade possible). I used to use this piece of code in C++11 to generate those features:
#include <vector>
#include <iostream>
//#include <numeric>

using namespace std;

template <class T>
std::vector<T> polynomialFeatures( const std::vector<T>& input, unsigned int
degree, bool interaction_only, bool include_bias )
{
    std::vector<T> new_chunk; // declare new_chunk here
    std::vector<T> features = input;
    std::vector<T> prev_chunk = input;
    std::vector<size_t> indices( input.size() );

   for ( int d = 1 ; d < degree ; ++d )
    {
       for ( size_t i = 0 ; i < input.size() - ( interaction_only ? d : 0 ) ; ++i )
        {
            // Store the index where to start multiplying with the current component at the next degree up:
            size_t next_index = new_chunk.size();
           for ( auto coef_it = prev_chunk.begin() + indices[i + ( interaction_only ? 1 : 0 )] ; coef_it != prev_chunk.end() ; ++coef_it )
            {
                new_chunk.push_back( input[i]**coef_it );
            }
            indices[i] = next_index;
        }
        // Extend the feature vector with the new chunk of features:
        features.reserve( features.size() + std::distance( new_chunk.begin(),
new_chunk.end() ) );
        features.insert( features.end(), new_chunk.begin(), new_chunk.end() );

        prev_chunk = new_chunk;
    }
    if ( include_bias )
        features.insert( features.begin(), 1 );

    return features;
}

And due to my limited Knowledge in C++, I am having difficulties to adapt this function in C++98. I tried the following by removing the vectors which I don't need:
float polynomialFeatures( float input[27], unsigned int
degree, bool interaction_only, bool include_bias )
{
    float new_chunk; // declare new_chunk here
    float  features = input;
    float  prev_chunk = input;
    float  indices( input.size() );

   for ( int d = 1 ; d < degree ; ++d )
    {
       for ( size_t i = 0 ; i < input.size() - ( interaction_only ? d : 0 ) ; ++i )
        {
            // Store the index where to start multiplying with the current component at the next degree up:
            size_t next_index = new_chunk.size();
           for ( auto coef_it = prev_chunk.begin() + indices[i + ( interaction_only ? 1 : 0 )] ; coef_it != prev_chunk.end() ; ++coef_it )
            {
                new_chunk.push_back( input[i]**coef_it );
            }
            indices[i] = next_index;
        }
        // Extend the feature vector with the new chunk of features:
        features.reserve( features.size() + std::distance( new_chunk.begin(),
new_chunk.end() ) );
        features.insert( features.end(), new_chunk.begin(), new_chunk.end() );

        prev_chunk = new_chunk;
    }
    if ( include_bias )
        features.insert( features.begin(), 1 );

    return features;
}

And I get those errors:
 In function 'float polynomialFeatures(float*, unsigned int, bool, bool)':
 error: cannot convert 'float*' to 'float' in initialization
     float  features = input;
                       ^
 error: cannot convert 'float*' to 'float' in initialization
     float  prev_chunk = input;
                         ^
 error: request for member 'size' in 'input', which is of non-class type 'float*'
     float  indices( input.size() );
 warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
    for ( int d = 1 ; d < degree ; ++d )
 error: request for member 'size' in 'input', which is of non-class type 'float*'
        for ( size_t i = 0 ; i < input.size() - ( interaction_only ? d : 0 ) ; ++i )
 error: request for member 'size' in 'new_chunk', which is of non-class type 'float'
             size_t next_index = new_chunk.size();
 warning: 'auto' changes meaning in C++11; please remove it [-Wc++0x-compat]
            for ( auto coef_it = prev_chunk.begin() + indices[i + ( interaction_only ? 1 : 0 )] ; coef_it != prev_chunk.end() ; ++coef_it )
 error: 'coef_it' does not name a type
            for ( auto coef_it = prev_chunk.begin() + indices[i + ( interaction_only ? 1 : 0 )] ; coef_it != prev_chunk.end() ; ++coef_it )
 error: expected ';' before 'coef_it'
            for ( auto coef_it = prev_chunk.begin() + indices[i + ( interaction_only ? 1 : 0 )] ; coef_it != prev_chunk.end() ; ++coef_it )
 error: 'coef_it' was not declared in this scope
 error: request for member 'end' in 'prev_chunk', which is of non-class type 'float'
            for ( auto coef_it = prev_chunk.begin() + indices[i + ( interaction_only ? 1 : 0 )] ; coef_it != prev_chunk.end() ; ++coef_it )
 error: request for member 'push_back' in 'new_chunk', which is of non-class type 'float'
                 new_chunk.push_back( input[i]**coef_it );
 error: invalid types 'float[size_t {aka long unsigned int}]' for array subscript
             indices[i] = next_index;
 error: request for member 'reserve' in 'features', which is of non-class type 'float'
         features.reserve( features.size() + std::distance( new_chunk.begin(),
 error: request for member 'size' in 'features', which is of non-class type 'float'
         features.reserve( features.size() + std::distance( new_chunk.begin(),
 error: 'distance' is not a member of 'std'
         features.reserve( features.size() + std::distance( new_chunk.begin(),
 error: request for member 'begin' in 'new_chunk', which is of non-class type 'float'
         features.reserve( features.size() + std::distance( new_chunk.begin(),
 error: request for member 'end' in 'new_chunk', which is of non-class type 'float'
 new_chunk.end() ) );
 error: request for member 'insert' in 'features', which is of non-class type 'float'
         features.insert( features.end(), new_chunk.begin(), new_chunk.end() );
 error: request for member 'end' in 'features', which is of non-class type 'float'
         features.insert( features.end(), new_chunk.begin(), new_chunk.end() );
 error: request for member 'begin' in 'new_chunk', which is of non-class type 'float'
         features.insert( features.end(), new_chunk.begin(), new_chunk.end() );
 error: request for member 'end' in 'new_chunk', which is of non-class type 'float'
         features.insert( features.end(), new_chunk.begin(), new_chunk.end() );
 error: request for member 'insert' in 'features', which is of non-class type 'float'
         features.insert( features.begin(), 1 );
 error: request for member 'begin' in 'features', which is of non-class type 'float'
         features.insert( features.begin(), 1 );

I also would like to multiply each of the generated features during the features generation procedure with a coefficient of another array of floats with 405 values and add all of those multiplications to obtain at the end the scalar product of both arrays ( the polynomial features array 'features[405]' and the already known array 'abc[405]'


text:
Q: Is there a hotkey to select all the text I've typed in a unix command? In some shell such as terminal on Mac OS X, I want to select all the text I've typed in the command line. For example, I've typed this in the command line and have yet to hit enter. I want to do a select all (such as ctrl A or apple A) so that I can cut or copy this command (ctrl X/C or apple X/C).
$ grep -r "test" .

Is there a way to do this without having to use the mouse and actually selecting all of the command? This would make life easier for when I need to copy a unix command to send to someone else.

A: Here's how it works on my OSX laptop.
bash$ echo "this is a command I haven't run yet"             # press Ctrl-u here
bash$                                                        # blank line
bash$ pbcopy <<<                                             # now I press Ctrl-y
bash$ pbcopy <<< echo "this is a command I haven't run yet"  # press Enter
bash$

From here, the command is in the clipboard and I haven't used the mouse or set up any keyboard shortcuts.  This will work with the standard bash, so you don't need to set up MacPorts either.

A: Your terminal might provide something like that. Applications like screen and tmux also sometimes provide things like that (though generally only for use in the shell session I think and not into the system clipboard). There's a layering problem with just about anything else doing it.

A: I don't believe there is a terminal shortcut to select all of the text. One alternative may be to use the pbcopy command to copy the last command into the system pasteboard.
fc -ln -1 | pbcopy

You can then use Command-V to paste anywhere else on your computer. It's probably not faster than using your mouse, but if you need to do it a lot, you could create an alias.

A: Not with the OS X default bash. (It is only 3.2).
But if you install bash 4.0+ (i'm recommendind using MacPorts) you can use the next feature:

bind
-x keyseq:shell-command
Cause shell-command to be executed whenever keyseq is entered.
When shell-command is executed, the shell sets the READLINE_LINE
variable to the contents of the Readline line buffer and the
READLINE_POINT variable to the current location of the insertion
point. If the executed command changes the value of READLINE_LINE or
READLINE_POINT, those new values will be reflected in the editing
state.

So, for example you can bind the CTRL-X c sequence, (press CTRL-X and after an simple "c") to the pbcopy with the next bind command:
bind -x '"\C-xc":pbcopy <<<"$READLINE_LINE"'

Now, anything you typed into bash, after pressing "CTRL-X c" will be copied into the clipboard.
If you're not like the sequence, you can also set the sequince in the Terminal.app -> Preferences -> Settings -> Keyboard as in the next screeenshot

where I binded the "CTRL-X c" \030c to the CTRL-ALT-LEFT_ARROW, so now i have both binding.

A: You can use history file to do that. Make your bash to write all commands to history file immediately, as described here
Then make a keybinding to run script tail ~/.bash_history -n 1 | pbcopy. Or you can integrate this script directly to PROMPT_COMMAND variable as described in link.
Not tested:
PROMPT_COMMAND="history -a; history -c; history -r; tail ~/.bash_history -n 1 | pbcopy; $PROMPT_COMMAND"


text:
Q: Loading text file in Jupyter notebook enter image description here
enter image description here
I tried loading a notepad textfile in my jupyter notebook but it has not been successful. I tried including the file path but all to no avail. Please can someone help me out. Thank you


text: Q: How we can add combine with feature in react-beautiful-dnd without re-ordering the items? I am new to react-beautiful-dnd libary , We are implementing the combine with feature in our project , Suppose we have files and folders in the list , and we want when we drag files over the folders and combine them , We get that functionality , but We need to stop re-ordering , I have added the custom styles to stop this , but then combine only work at certain angle ,not on whole files only works at if we drag over right end , So is there any way , I can drag files over the folder anywhere and get the result when drag ends.


text:
Q: How to restore original MailItem of an Inspector? I'm changing the body of a MailItem object associated with an Inspector, and I would like to restore the original state.  Currently I'm saving the original content (i.e., email body, subject, etc) and setting it back again, but whenever a user closes the Inspector he is presented with a dialog asking if he wants to save changes.  Does anyone know if there's a way to restore the original MailItemwithout having to present the user with a dialog asking if he wants to save it?

A: Don't do that. If you need to display data different from what is stored in Outlook, create a form region, task pane, or a custom message form. Resetting/restoring is a hack that will break at the worst possible moment.


text:
Q: Adding a QGLWidget to a QMainWindow I have a MainWindow class with a QGraphicsView which I'd like to add to a MainWindow, so that I'm able to see what's actually going on. All I'm trying to do right now is render a cube.
Main Function
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

MainWindow Ctor
MainWindow::MainWindow( QWidget *parent )
    : QMainWindow( parent ),
      mUi( new Ui::MainWindow ),
      mDisplay( new GLWidget ),
      mScene( new QGraphicsScene )
{
    mUi->setupUi( this );
    //mScene->addWidget( mDisplay );
    QGraphicsView *graphicsView = new QGraphicsView;
    //QGraphicsView::setupViewport( this );
    graphicsView->setViewport( mDisplay );
    graphicsView->show();
}

GLWidget::initializeGL
void GLWidget::initializeGL( void )
{
    glMatrixMode( GL_COLOR );

    glClearColor( 0.0, 0.0, 0.0, 1.0 );

    glMatrixMode( GL_MODELVIEW );

    glClearDepth( 1.0f );

    glEnable( GL_VERTEX_ARRAY );
    glEnable( GL_NORMAL_ARRAY );
    glEnable( GL_DEPTH_TEST );
    glEnable( GL_CULL_FACE );
    glShadeModel( GL_SMOOTH );
    glEnable( GL_LIGHTING );
    glEnable( GL_LIGHT0 );
    glEnable( GL_MULTISAMPLE );
    static GLfloat lightPosition[ 4 ] = { 0.5, 5.0, 7.0, 1.0 };
    glLightfv( GL_LIGHT0, GL_POSITION, lightPosition );

    qDebug() << "GL Initialized" << '\n';
}

As you can see, glClearColor is supposed to set the background to a black screen. The problem is that when I render it, I see two windows which pop up and not one. While the MainWindow class has a window frame which is supposed to render the GLWidget, it appears that, rather than adding it to the window frame, it simply generates both of the frame as well as the window using the QGraphicsView. Both windows only show a white screen; one of them is at least supposed to show a black background, as the glClearColor states.
What am I doing wrong here?

A: glClearColor only sets the color that will be used to clear the screen.
To actually clear the screen you must call glCear function:
glClear(GL_COLOR_BUFFER_BIT);

Same thing with glClearDepth - it only sets value of depth to clear with. To actually clear it use the same glCler function. You can clear color buffer and depth buffer with one glClear call like this:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


text:
Q: Click tracking with sendGrids @sendgrid/mail npm library I'm using the @sendgrid/mail library and am trying to enable click tracking inside of my msg config object but the only documentation I have been able to find is to set trackingSettings: {}. What additional properties need to be set in order to turn click tracking on within the trackingSettings object?

A: It's a bit late I know, but I've come across your question while searching for the same topic.
Here's how you do it:
trackingSettings: {
  clickTracking: {
    enable: true
  },
  openTracking: {
    enable: true
  },
  subscriptionTracking: {
    enable: true
  }
}

You can check out more advanced use cases of the library here:
https://github.com/sendgrid/sendgrid-nodejs/blob/master/packages/mail/USE_CASES.md


text:
Q: Eclipse Luna IDE projects won't run Today I upgraded to Eclipse Luna, on my Linux machine. Everything seemed to work until I ran a "Hello World" program.
It gave me this error:
Exception in thread "main" java.lang.UnsupportedClassVersionError: test/test : Unsupported major.minor version 52.0
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:643)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:277)
at java.net.URLClassLoader.access$000(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:212)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:323)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:268)

Could not find the main class: test.test. Program will exit.
Obviously, I have the main method and everything correct, but it's not working.
Also for some reason I am using JRE System Library [jkd-6-openjdk-amd64], when I believe I need to be using JRE System Library [1.8], but I couldn't find it installed.
Checking java -version in the terminal confirms that 1.8 is installed.
Any help fixing this?
Thanks.

A: Major Minor version 52.0 which means you have JDK and JRE version mismatch.
Suppose that you are using jre8 for your environment settings, then you have to define JDK8 path for Eclipse as well.
 You can do it as following:
-vm
..\path-to-jre\bin\javaw.exe


text:
Q: Flex Code Generator based on XML or Database Structure I don't know if it exists some code generation method for Flex based on XML or Database Structure.
For example, we want to manipulate a table in the DB, the most common task is (View/Insert/Update/Delete). And when we have more than 100 fields on the interface, it's rather boring to type them manually in Flex. Is there some ways to generate the Flex Code and the ActionScript functions for managing that. Which is the best way to do such a thing?
Thanks for replying

A: You can use RestfulX if you have Ruby and Rails installed.
Define the table-fields/model-properties in a yaml file like this:

project:
 - name: string
 - notes: text
 - start_date: date
 - end_date: date
 - completed: boolean
 - belongs_to: [user]
 - has_many: [tasks]

And then run
ruby script/generate rx_yaml_scaffold
All the details are on the Getting Started with RestfulX Page.
It creates an MXML Datagrid for viewing lists of your data, and a basic CMS/form view for CRUD operations.  It's a great generator.  The generated code renders into this:

(source: github.com)


text:
Q: How to run .cc extension file in linux? I have main.cc file and i would like to run this file in linux. May i know what would be the correct way of executing this file ? Is it

gcc -o x main.cc

? Any help or feedback is appreciated.

A: In your case it would be gcc main.cc -o main.ou where main.cc is your main-file and main.ou your output file.
You can also read more about executing c/c++ files here:
http://www.cyberciti.biz/faq/compiling-c-program-and-creating-executable-file/

A: The command you gave will compile the file. The resulting executable is put in x. To run it, you do:
./x


text:
Q: How to install Python wand on Windows? I installed wand with pip install wand, and the ImageMagick DLL (coming from ImageMagick-7.1.0-46-Q16-HDRI-x64-dll package) is in the PATH.
Doing this:
import wand.image

with wand.image.Image(filename='test.pdf', resolution=300) as pic:
    with wand.image.Image(pic.sequence[0]) as first_page:
        first_page.save(filename='test.jpg')

produces this error:

wand.exceptions.MissingDelegateError: NoDecodeDelegateForThisImageFormat `PDF' @ error/constitute.c/ReadImage/741

How to solve this wand problem?
Ghostscript is installed on my system (and in the PATH too). I tried with gs64 and gs32 versions (according to this answer: PythonMagick can't find my pdf files).
I have also read the Wand Windows installation doc.
The question install wand on a windows machine, How to install python imagemagick at windows 7. I followed these instruction and Imagemagick Convert PDF to JPEG: FailedToExecuteCommand `"gswin32c.exe" / PDFDelegateFailed are linked but did not help. (I remember I already struggled with this years ago, I don't remember if I finally found a solution)

A: I finally solved it by uninstalling ImageMagick portable version (all directories were in the PATH though), and reinstalling the standard ImageMagick from https://imagemagick.org/script/download.php#windows:
ImageMagick-7.1.0-46-Q16-HDRI-x64-dll.exe

I checked all the checkboxes (except Perl related).
Then it worked.


text:
Q: Hierarchical custom setting I would like to know about some real world examples of hierarchical custom setting.

A: We have used them to record approval levels for payments. The org default can have very low levels set (or zero), specific profiles (categories of users) higher levels and specific users (e.g. department manager) the highest levels.

A: It is usually used to store values that are not a list but applicable across the organization. For example integration end points that will change across sandboxes.
It can also be used to set a specific value specific to organization and then further specific values for profiles/users etc. For example user preferences can be saved in this. getInstance() method gives the most specific result. Check
https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_custom_settings.htm


text:
Q: Error tying to run the command "npm install angular-in-memory-web-api --save" Am new to Angular so am trying to follow tutorial on https://angular.io/tutorial/toh-pt6
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.7 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.7: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

*

*angular-in-memory-web-api@0.8.0
updated 1 package and audited 42609 packages in 21.447s
found 5 high severity vulnerabilities
run npm audit fix to fix them, or npm audit for details

A: This is an optional dependency so you can just ignore it.
If you really want this message to disappear - try to update npm
npm i -g npm@latest

it can help.

A: According to this issue. You can ignore this warning since fsevents is required on macOS so it's skipped on windows.


text:
Q: Eclipse shortcut to change panel size I was wondering if there was a shortcut in Eclipse to change the view height/width.
Normally you have to find the line where your cursor change to a vertical/horizontal two-sided arrow, click and then drag to change the panel height/width.
Is there a shortcut where you just press, for example Ctrl+P or the mouse wheel, and just move the cursor around and the current panel (the one under your mouse) change size accordingly ? Or a plugin for this ? This would be a lot faster (even though it's not that terrible).
Either I didn't find the way to put it clearly or nobody asked this because I didn't find anything, only stuff about switching views/panels from one to another or changing font size.

A: There is no such shortcut. Providing a plug-in therefore seems difficult as there is no API to query or set the size of a view stack.
The only shortcut related to changing the size of a view stack is Ctrl+M. It maximizes/minimizes the view stack of the currently active view.


text:
Q: Making a specific Graph with the use of R With the help of the Monte Carlo method I need to determine the value of Pi.
For so far I have a code that gives me Pi by a random value of the radius of the circle between 0.1 and 1. Next thing that I have to do is to plot the variable radius against the number that is found for Pi, as i tried to describe below
     |
   Pi|~~~~~~~~~~~~    <- values
     |
     |______________
     0.1     R      1

library("plotrix")
n = 400
z = runif(1, 0.1, 1)
R= z
x = runif(n, -R, R)
y = runif(n, -R, R)
plot(x, y, asp = 1, xlim = c(-1, 1))
#draw a square
rect( -R, -R, R, R)
#draw a circle
draw.circle(0, 0, R, nv = 1000, border = NULL, col = NA, lty = 1, lwd = 1)
#
#test if points are in the circle (Pin=points in circle)
pin = sum(ifelse(sqrt(x^2 + y^2 <= R^2), 1, 0))
#pi is given by (4*n in circle/n total)
  4 * pin/n
plot(z, 4 * pin/n)

With this code, I can make 1 point in the whole graph. What I'm looking for is to have like 100 points on the graph. So 'easily' said, let the code determine 100 pi values by different R's and plot these in one graph.
Is this possible? I've been looking for the answer for two days, but I'm not making any progress so far.. Thanks!

A: How about making the calculation into a function, and running it a hundred times? Once you have the values, you can then plot them all together. The same thing can be done using a for-loop.
Here's an example. Let's create a function ppi first:
ppi<-function(N=1000) {
    n = N
    z = runif(1, 0.1, 1)
    R= z
    x = runif(n, -R, R)
    y = runif(n, -R, R)
    pin = sum(ifelse(sqrt(x^2 + y^2 <= R^2), 1, 0))
    return(c(z, n, pin))
}

You can then run that 100 times (see replicate()), and then plot the results using some plotting function.


text:
Q: If 0 is a point of Lebesgue density of $E\in\mathbb{R}$ and B a ball center in 0, why $B\bigcap E\bigcap -E$ has positive measure? From definition of Lebesgue density and invariance of measure, I can get $m(B\bigcap-E)=m(B\bigcap E)\geq(1-\epsilon)m(B)>0$, $\forall 0<\epsilon<1$, But I don't see how to conclude $m(B\bigcap E\bigcap-E)>0$. Isn't that possible to be the case that $E\bigcap-E=\emptyset$?

A: Hint Try to use
$$m(X\cap Y) = m(X) + m(Y) - m(X \cup Y)$$


text:
Q: cmake OUTPUT_VARIABLE is not working with docker build Here comes a strange issue when run docker build with cmake.
If run cmake . directly, it works perfect that the message shows the version get from get_version.sh like !!!! Warning !!!! build version <1.6.3>.
But if trying to build a image from docker build . -t test it only shows !!!! Warning !!!! build version <>.
That's quite strange! Anyone has any idea about this issue?
Dockerfile
FROM alpine:3.10

RUN mkdir build
WORKDIR /build

RUN apk add --update build-base cmake

COPY CMakeLists.txt CMakeLists.txt
COPY get_version.sh get_version.sh
RUN cmake .

CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project("testcmake")

execute_process(COMMAND chmod 777 ./get_version.sh)

execute_process(COMMAND ./get_version.sh
    OUTPUT_VARIABLE
    VERSION_INFO)
MESSAGE(STATUS "!!!! Warning !!!! build version <${VERSION_INFO}>")

get_version.sh
#!/bin/bash
set -x
retval=$(echo -ne "1.6.3")
echo -ne $retval


text:
Q: Rails 4 : Can't verify CSRF token authenticity but data still insert into database I apply the CSRF in Controller by adding this:
  class ApplicationController < ActionController::Base
     protect_from_forgery
  end

and I do a post request to my API using Postman.
The funny result is I can't verify CSRF, but the data I send still be inserted into DB.
Here is the server log.
 Processing by Api::ListingsController
   Parameters: {"listing"=>{...}}
 Can't verify CSRF token authenticity
   (0.2ms)  BEGIN
 SQL (0.6ms)  INSERT INTO "listings" ...
   (0.4ms)  COMMIT
 Completed 201 Created in 54ms (Views: 0.2ms | ActiveRecord: 6.3ms)

Seems everything is fine, and data is in DB now!
Why is CSRF not working?
Anyone can give any explains?

A: There are 3 behaviours that a csrf token mismatch can trigger:

*

*raise an exception (:exception)

*reset the session to a new, empty session (:reset_session)

*use an empty session for the request, but don't reset it completely (:null_session)

The rationale for the last 2 is that the point of a CSRF attack is usually to abuse the fact that the user is already logged in and thus the browser will send session cookies with the request. Therefore reseting or ignoring the session (assuming that is where credentials are stored) will make the request proceed as an unauthenticated request.
If the application doesn't require the user to be logged in then :null_session and :reset_session will allow the request to proceed.
The default behaviour has changed over the years, but as of rails 4.2 is is :null_session. You can change it by specifying a with option to protect_from_forgery

A: In ApplicationController you can add
class ApplicationController < ActionController::Base
    protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format      == 'application/json' }
    # Or
    # skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }
end


text:
Q: namespaces from header files in c++ I have created a noname namespace with some variables inside in header, want to initialize them in .cpp and see in main.cpp. A noname namespace i am expecting to work just fine without mentioning this namespace in .cpp. However I get error as if in .cpp I had totally new a and b. Anyone has idea how to resolve it?
xx.h
namespace
{
    int a;
    int b;
}

.cpp
#include "xx.h"
a = 5;
b = 10;

main.cpp
#include <iostream>
#include "xx.h"
int main()
{
       std::cout << "values" << a << b << std::endl;
}

A: You may not use assignment statements outside functions. You may only declare or/and define objects . So the valid code will be
namespace
{
    int a = 5;
    int b = 10;
}

main.cpp
#include <iostream>
#include "xx.h"
int main()
{
       std::cout << "values" << a << b << std::endl;
}

Take into account that objects declared in unnamed namespaces have internal linkage. It means that if this header is included in more than one module then in each module it declares a separate namespace.
Consder the following example
unnamed.h
namespace
{
    int a = 5;
    int b = 10;
}

void f();

second.cpp
#include <iostream>
#include "unnamed.h"

void f()
{
    a = 10; b = 5;
    std::cout << "a = " << a << ", b = " << b << std::endl;
}

main.cpp
    #include
    #include "unnamed.h"
int main()
{
    f();
    std::cout << "a = " << a << ", b = " << b << std::endl;

    return 0;
}

The output is
a = 10, b = 5
a = 5, b = 10

A: The problem is not with the anonymous namespace. Variables cannot be assigned at global scope.
// At global scope
int num;

num = 10;  // Error. You are doing something similar.

Either initialize the variables in the namespace itself or assign them values in a function.

A: your header has to declare them as extern and in cpp you have to define them. (otherwise any including file will create their own a and b)
this may work (quite not sure because of anonymous namespace):
xx.h
namespace
{
    extern int a;
    extern int b;
}

.cpp
#include "xx.h"
int a = 5;
int b = 10;

main.cpp
#include <iostream>
#include "xx.h"
int main()
{
       std::cout << "values" << a << b << std::endl;
}


text:
Q: Is it possible to set self.var123 as var123 in rest of class definition? Right now i'm doing:
class Block:
    def __init__(self, lenght, height, width, position=(0,0)):

        self.lenght = lenght
        self.height= height
        self.width = width
        self.corner = tuple(position)

My code is about blocks, indeed.
And I also define methods for calculating the volume, surface area, etc. for that block.
My question is, when i'm writing those other methods, couldn't i shorten my code and make it easier to understand if i have length as the variable for self.length?
Is it possible to name the lenght once, and not at the beginning of every method?

A: You can always create a local reference in a method for variables you are using a lot:
def some_method(self):
    length = self.length
    # code that uses length

You can't otherwise make attributes on self locals, no.


text:
Q: How to Fix 'There has been a critical error on your website' for Wordpress I currently update my WordPress to 5.3 and the below error shows up. I encounter the below problem then I change wp-config.php settings to TRUE, to be able to see the below error, pls help me so many errors shows up
Fatal error: Uncaught Error: Call to undefined function electro_get_home_v1_meta() in /home/cjabiaxx/public_html/wp-content/themes/electro/template-homepage-v1.php:19 Stack trace: #0 /home/cjabiaxx/public_html/wp-includes/template-loader.php(98): include() #1 /home/cjabiaxx/public_html/wp-blog-header.php(19): require_once('/home/cjabiaxx/...') #2 /home/cjabiaxx/public_html/index.php(17): require('/home/cjabiaxx/...') #3 {main} thrown in /home/cjabiaxx/public_html/wp-content/themes/electro/template-homepage-v1.php on line 19


text:
Q: python: changing from print to return does not process items right I created a program that reads a couchDB to list followers and friends ids of a single twitter user. Friends are identified under the group "friend_edges" and followers under "follower_edges".
I use the intersection operation between sets -set1.intersection(set.2)- in order to obtain the list of those who are both friends and followers.
When I use print to see the outputs, the results are correct. But when I change to return to process the results, it only processes friends, not followers.
Can somebody give me a clue of what I'm doing wrong and how to improve the code?.... thanks in advance.
from twitter_login import oauth_login
from twitter_DB import load_from_DB
from sets import Set

def friends_and_followers(doc):
    if 'friend_edges' in doc.keys():
        flist = []
        for x in doc['friend_edges']:
            flist.append(x)
        #print "Number of friends: ", len(flist) <-- shows the right number of items
        return flist
    else:
        return []

    if 'follower_edges' in doc.keys():
        followlist = []
        for x in doc['follower_edges']:
            followlist.append(x)
        #print "Number of followers: ", len(followlist) <-- shows the right number of items
        return followlist
    else:
        return []

    flist = Set(flist)
    followlist = Set(followlist)
    return flist.intersection(followlist)

if __name__ == '__main__':
    twitter_api = oauth_login()
    DBname = 'users-aguy-+-only'
    ff_results = load_from_DB(DBname)
    print 'number loaded', len(ff_results)

    for doc in ff_results:
        together = friends_and_followers(doc)
        print "Friends and followers of a guy: ", together

A: A return statement stops execution of that method and returns to the calling method, so by adding a return statement you are saying, "Stop here and go back to where you came from"
You need to store both the values you want returned in variables and return them at the same time at the end of your method:
return value1, value2

You will call this with something like this:
val1, val2 = get_value1_and_value2(input)

It might make more sense to just break that up into two separate methods that each return the correct value though.


text:
Q: trying to find the fixed points, stability, and then trying to see what it converges to. In the following question I am trying to find the fixed points, stability, and then trying to see what it converges to.
To find the stability of this we must find $|f'(x^*)|$ to see whether it is $>1$ which would make it unstable or $<1$ which would make it stable.
$x_{n+1}=lnx_n$
So setting $f(x)=lnx$ and $f(x)=x$ to find the fixed point then $x=lnx$
But how do I find the value of this $x$ that makes $x=lnx$ work. You cant use $x=1$ because $1\ne 0$. I am not trying to use a graphical method either, trying to work it out numerically.
Once I have the fixed points, I could then use $|f'(x^*)|$ to find out whether $|f'(x^*)|<1$ to make it stable or whether $|f'(x^*)|>1$ which makes it unstable.
Are there any intersection points?

A: Let us rewrite the equation $x = \ln x$ satisfied by the stationnary points as
$$ {-1} = {-\ln x}\, \text{e}^{-\ln x} \, , $$
which is of the form $X \text{e}^{X}= Y$ with $X={-\ln x}$ and $Y={-1}$. The solutions are $X=W (Y)$, where $W$ is the Lambert W-function. Hence,
$$ x = \text{e}^{-W (-1)} = -W (-1) \, . $$
This value is not real, since the natural logarithm $x\mapsto \ln x$ and the identity $x\mapsto x$ don't cross on the real line.
When studying the present dynamical system, one can observe that $x_{n+1} = \ln x_n \leq x_n -1$. The sequence $x_{n+1}= x_n -1$ is strictly decreasing with no limit, and so does $x_{n+1} = \ln x_n$ (until $x_n \leq 0$ for some $n$, where $x_{n+1}$ becomes complex).


text:
Q: ActionScript 3.0 textInput and Display I am new at flash, the below is my script, i have 3 textinput boxes, name1, name2, name3 and 3 dynamic texts, output1, output2, output3. Once the user, enters the text in the box, it should appear exactly the same in the dynamic output text. It works for the first one, but does not work for the second and third one. I renamed changehandlers differently to remove compile errors, but now only the first one works. Is there a better way of doing this, if i want to have multiple textbox entrees?
name1.addEventListener(Event.CHANGE, changeHandler);

function changeHandler(e:Event):void
{
    output1.text = name1.text

}
name2.addEventListener(Event.CHANGE, changeHandler);

function changeHandler1(e:Event):void
{
    output2.text = name2.text;
}

name3.addEventListener(Event.CHANGE, changeHandler);

function changeHandler2(e:Event):void
{
    output3.text = name3.text;
}

A: You forgot to change the name of the listener functions in the latter two addEventListener() calls. It currently calls changeHandler() on all three events.
You should have:
name2.addEventListener(Event.CHANGE, changeHandler1);
name3.addEventListener(Event.CHANGE, changeHandler2);

You can create a class that manages joining the input text field with the output text field:
package
{
    import flash.text.TextField;
    import flash.events.Event;

    public class TextBinder extends Object
    {
        // vars
        private var _input:TextField;
        private var _output:TextField;

        /**
         * Joins input with output
         * @param inp The input text field
         * @param outp The output text field
         */
        public function join(inp:TextField, outp:TextField):void
        {
            _input = inp;
            _output = outp;

            _input.addEventListener(Event.CHANGE, _change);
        }

        /**
         * Event.CHANGE
         */
        private function _change(e:Event):void
        {
            _output.text = _input.text;
        }
    }
}

And now you can loop through your text fields and join them using this:
var tb:TextBinder = new TextBinder();
tb.join(name1, output1);


text:
Q: Convert dictionary in Helm chart template I want to convert dictionary to dictionary (Variable) in Helm chart, not related to the Template rendering
# Values.yaml
proxy:
  public:
    alias: proxy-public.somedomain.com
    address: 123.123.123.123
  private:
    alias: proxy-private.somedomain.com
    address: 172.25.8.16

I want to convert to another dictionary, dict comprehension/jq/Terraform style:
{{- $aliases := ... ???? -}}

So structure is,
{public: proxy-"public.somedomain.com", private: "proxy-private.somedomain.com"}

Having hard time making proper syntax
Purpose is, to have this dictionary converted to Json down the line
data:
  aliases: {{ $aliases | toJson | quote }}

Which is different from looping and rendering it to the template, like in this SO anwer, for example:


text:
Q: Getting all users mentioned in a tweet text and their user ID's When I search for a tweet containing certain words, I want to check for users mentioned in those tweets that say specifically 'follow @someoneSo' so I could keep track of them and check out their profiles if they seem like relevant accounts, and hopefully, follow some accounts that I like at the end of it.
Is there something similar to Discord's message.mentions.users where it returns a list of users mentioned in a tweet text?
For example, if a tweet text = 'dvffegregre rg ADQEW follow @chad @lee efkneknen' or tweet text = 'dvffegregre rg ADQEW follow these guys @chad @lee efkneknen', my script would be able to follow @chad and @lee

A: text = 'dvffegregre rg ADQEW follow @chad @lee efkneknen'
textlist = text.split(' ')
users = []
if 'follow' in textlist:
    for subtext in textlist:
        if subtext.startswith('@'):
            API.create_friendship(subtext.strip('@'))

I think this should work for your purpose.


text:
Q: How to call netsuite restlet externally? I have Tried from google script but getting error:

'USER_ERROR
  error message:No Authorization header'

var url = 'https://debugger.na1.netsuite.com/app/site/hosting/restlet.nl?script=107&deploy=1';

var header = {
    contentType: 'application/json',
    Authorization: 'NLAuth nlauth_account=TSTDRVXXXXX,    nlauth_email=xxx@xxx.com, nlauth_signature=XXXXXXX, nlauth_role=3',
    method: 'GET',
    muteHttpExceptions: true
  };

  var response = UrlFetchApp.fetch(url, header);

A: You should review the docs for UrlFetchApp. You've collapsed headers and optional params. The setup should be more like:
var params = {
    contentType: 'application/json',
    headers:{Authorization: 'NLAuth nlauth_account=TSTDRVXXXXX, nlauth_email=xxx@xxx.com, nlauth_signature=XXXXXXX,     nlauth_role=3'},
    method: 'GET',
    muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, params);


text:
Q: Problem with friction Consider a block on a table which is placed on a frictionless surface (friction exists between table and block). When we push the block, why does the table move? What are the forces on the table?

A: The table exerts a horizontal force on the block (friction).  By Newton's third law, the block exerts an equal and opposite horizontal force on the table.  This is the only horizontal force on table (the table is on frictionless surface), so the table moves horizontally in the direction in which you push on the block.
For the sake of completeness, there are also vertical forces on the table (gravity, normal force) but they balance out so the table doesn't move up or down.


text:
Q: Running Polymer demos in NodeJS on windows 7 I finally got NodeJS, Git and Polymer all configured on my windows 7 machine, how do I get NodeJS to run it? When I try node polymer it throws an error saying module.js is missing. I am a complete newbie with Node...
Thanks,
Sam

A: Polymer is a client side library. It builds a set of abstractions on top of the HTML DOM and is intended to be run inside of a browser, not on the server side.
To use Polymer with a node.js server use something like node-static to serve the polymer assets down to the browser.


text:
Q: Are parameters considered automatic variables?
An automatic variable is a local variable which is allocated and
  deallocated automatically when program flow enters and leaves the
  variable's scope.

So if I have a function with a parameter, does that mean the parameter's scope is the entire function, and therefore it fits the above definition? Or does it not quite fit this?
(I am unsure what category to put this question in, sorry)

A: Yes, parameters are objects with automatic storage duration.
N1570 6.9.1p9:

Each parameter has automatic storage duration; its identifier is an lvalue.

You asked about scope, which isn't directly relevant.  Scope and lifetime are two different things. An identifier has a scope, the region of program text in which that identifier is visible. An object has storage duration (lifetime), which is the period during program execution in which the object logically exists. An object with automatic storage duration exists during the execution of the enclosing block; for a function parameter, it ceases to exist when the function returns. Its name is visible only within the body of the function, but the object itself can be accessed from outside its scope (for example if its address is passed to another function).

A: Yes.Parameter works within the function till the function ends.