text: Q: How do I remove directory references from chm file generated by the Doxygen I want to generate documentation in Windows Help format (chm) free of any directory references. In all my attempts, Doxygen always generated set of dir_.html files containing information about ?source files? directories. This information is not visible in the chm document unless you start searching for keyword ?name of source file?; this search command seems to find reference to respective dir_.html file and by clicking on it you see full directory path. Can you please advise how to suppress either generating those dir_*.html files completely or just displaying references to those files in the search result window of the chm documentation?


text:
Q: Is it possible to change your voice? Ok so I have been playing Star Wars the Old Republic for at least a year now. But right now I need the help of a seasoned SWTOR veteran. Is there any way to change your character's voice without changing their gender?

A: Shadow's comment is exactly correct.  There is no way to change an existing character's voice other than the slight modulation provided by some helmets.  Voice is determined by gender and base class.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Analytics API V3 - Authorization API KEY (JAVA) I need to retrieve data from Google Analytics programatically in order to generate some reports, so OAuth 2.0 is not an option since it asks for user authorization..
Is there a way to retrieve data from GA API v3, using the API KEY ?
thanks!

A: The user must be authenticated to grant your application access to his data. This applies to any use case.
You can certainly use OAuth 2.0. Google offers the possibility to obtain an access token, which can be used by your application to access user data. In this case, the user only needs to be authorized once.
See https://developers.google.com/accounts/docs/OAuth2WebServer#callinganapi for more info about accessing Google API's with an application using OAuth 2.0.


text:
Q: How to prevent CasperJS navigating iframes? CasperJS will auto detect iframes and navigate to its url then sometimes crash.
Is there any config or method I can prevent casperjs navigate to iframe ?

A: You can abort any network request from the "resource.requested" event. If you know the iframe URL, then this can be applied.


text:
Q: Служба работает в интерактивном режиме, а при запуске "Как служба" перестает получать информацию из сети Сабж, у службы пробовал права и local system и network system ставить. Ноль эмоций. В интерактивном режиме инфу получает, когда запускаю как службу - запускается и работает, но инфу из сети не получает.
Кто-нибудь сталкивался?
Возможно это из-за стороннего драйвера (используется открытие сервера из dll).

A: Дай бог красноречия объяснить эту несусветную чушь))
В общем, в настройках драйвера можно менять tcp порт, тобишь он куда-то это записывает и видимо под пользователя, поэтому запускается интерактивный режим и берет правильный порт и прайс чекер достукивается до приложения, а когда запускается от службы, то порт берется по стандартной настройке(не тот, что указан для пользователя) и прайс чекеры стучаться не в тот порт.
Выход - поставил все устройства на стандартный порт.
Второй выход - поставить настройки для того же пользователя( в ту же ветку реестра) от которой запускается служба.


text:
Q: × Error: Invalid hook call. Hooks can only be called inside of the body of a function component.[ReactJS] am trying to build an Application using ReactJS but am getting this "Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

*

*You might have mismatching versions of React and the renderer (such as React DOM)

*You might be breaking the Rules of Hooks

*You might have more than one copy of React in the same app"

I tried many method from Google but i won't worked still getting this error.
Please help me!
CODE
import React from 'react'
import { useHistory, useParams } from 'react-router-dom'

function ProductDetails() {
  const { id } = useParams()
  // const { setText } = props;
  console.log(id)

  return (

{id}

  )
}

export default ProductDetails

App.js

import './App.css';
import {
  BrowserRouter,
  Switch,
  Route,
  Link
} from "react-router-dom";
import Header from './Components/Header';
import Homepage from './Components/HomePage';
import CartDetails from './Components/CartDetails';
import ProductDetails from './Components/ProductDetails';
import Error404 from './Components/Error404';
import { useState } from 'react';

function App() {
  const [text, setText] = useState(0);

  return (
    <>
      <BrowserRouter>

        <Switch>
          <Route exact path="/" component={Homepage} />
          <Route exact path="/cart-details" component={()=> <CartDetails val={text} />} />
          <Route exact path="/products-details/:id" component={ProductDetails} />
          <Route
            exact
            path="/products-details/:id"
            component={() => <ProductDetails setText={setText} />}
          />

        </Switch>
      </BrowserRouter>

    </>
  );
}
export default App;

package.json
  "peerDependencies": {
    "react": ">=16.8.0",
    "react-dom": ">=16.8.0"
 },

 "react-dom": "^17.0.2",

A: you should put a parameter called props in the ProductDetails() component then only you can access the props from the parent component.
put like this
function ProductDetails(props) {
   const { setText } = props;
   ....
}

Now you can use setText function inside the ProductDetails component.


text:
Q: Firebase Database Billing Usage I've just used Firebase & I have 2 questions that hopefully can be answered here.
I was wondering, is the quota for reading 50,000?
And if I exceed that limit, will I have to pay even though I haven't added a credit card or anything to my account.
I want to know this because I don't want to have to pay because I haven't even added a credit card.
If I exceed the quota, will the feature be disabled or will I have to pay?

A: If you're asking about quotas on the Spark free tier, the daily quota is 50,000 document reads per day, as described in the documentation.  If you exceed that quota, queries will fail until the quota is reset the next day.
If you have further question about billing, you should ask Firebase support directly rather than posting to Stack Overflow.


text:
Q: prevent multiple instances of same php script I am executing the following bash script on ubuntu 16.04 virtua machine startup with rc.local.
#!/bin/bash
# Loop forever (until break is issued)
(while true; do

   sudo php /var/www/has/index.php external communication

done ) &

As you can see, the bash executes a php script continuously. Over time, the script might take longer time to execute. Sometime scripts like the one above keep starting even though another instance of that same script is running. So, i want to know how can I prevent a new instance of the php script to execute, if there is an existing instance?

A: You can use file locking to acquire an exclusive lock.  If the lock exists, you can end the script or wait until the lock is released.
I suggest you read up on http://php.net/manual/en/function.flock.php
$fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
    // Execute logic
} else {
    echo "Couldn't get the lock!";
}


text:
Q: Unable to initialize object of type Animation I get the following warnings when I initialize an object of type animation.
(The warnings are added as comments)
Animation bottomUp = AnimationUtils.loadAnimation(
     android.content.Context, // warning: Expression expected
     R.animator.bottom_up     // warning: Expected resource of type anim
);

Here is a picture

Here is the code summary:
   public class MainActivity extends AppCompatActivity {

        // Class variables go here

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

                // Set onclick listener

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

                    // Animation Code

                    Animation bottomUp = AnimationUtils.loadAnimation(
                            android.content.Context, // warning: Expression expected
                            R.animator.bottom_up // warning: Expected resource of type
                    );

                    ViewGroup hiddenPanel = (ViewGroup)findViewById(R.id.hidden_panel);
                    hiddenPanel.startAnimation(bottomUp);
                    hiddenPanel.setVisibility(View.VISIBLE);

                }
            });

        }

        // Other stuff
    }

This is log cat after I try to compile

Here is where I use the erroneous code
  public class MainActivity extends AppCompatActivity {

listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

            Animation bottomUp = AnimationUtils.loadAnimation(
                    android.content.Context,
                    R.animator.bottom_up
            );

            ViewGroup hiddenPanel = (ViewGroup)findViewById(R.id.hidden_panel);
            hiddenPanel.startAnimation(bottomUp);
            hiddenPanel.setVisibility(View.VISIBLE);

I cannot find the bug.
I created the correct folder and files. Here they are.

Here is where I got the animation code I am using.
bottom_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:fromYDelta="75%p"
        android:toYDelta="0%p"
        android:fillAfter="true"
        android:duration="500"/>
</set>

bottom_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:fromYDelta="0%p"
        android:toYDelta="100%p"
        android:fillAfter="true"
        android:interpolator="@android:anim/linear_interpolator"
        android:duration="500" />
</set>

Java
Animation bottomUp = AnimationUtils.loadAnimation(getContext(),
            R.anim.bottom_up);
ViewGroup hiddenPanel = (ViewGroup)findViewById(R.id.hidden_panel);
hiddenPanel.startAnimation(bottomUp);
hiddenPanel.setVisibility(View.VISIBLE);

Tried to create an anim folder. Got this message.

A: First argument should be Context object. Try "this" if You are using it in Activity.
Second warning is because You have Your animation in animator folder (so it is recognized as animator resource) and the second parameter in AnimationUtils.loadAnimation is annotated with  @AnimRes annotation so this is just warning/suggestion that Your parameter should be resource of type anim. This is just lint warning not compilator.
This You can compile:
Animation bottomUp = AnimationUtils.loadAnimation(
 this, // if You are in Activity
 R.animator.bottom_up
);

To load Animator try:
Animator animator = AnimatorInflater.loadAnimator(this, R.animator.bottom_up );

but this is not what You want here. Just move files to anim folder.
Full sample code:
package com.example.user.exampleapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

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

        Animation bottomUp = AnimationUtils.loadAnimation(this,
            R.anim.bottom_up);
        TextView hiddenPanel = (TextView) findViewById(R.id.textView);
        hiddenPanel.startAnimation(bottomUp);
    }
}

A: First of all do you use this inside an activity or not?
I only know how to handle the first warning, sorry for that but I'm an amateur myself.
If you are inside an activity you can get the context using:
this

or
getApplicationContext()

If you are outside your activity you will have to pass down your context to the class using it:
public class MainActivity extends Activity(){

     ThisClassNeedsContext test;

     public MainActivity(Context context){
          // other code
          test = new ThisClassNeedsContext(context);
     }
}

public class ThisClassNeedsContext {
     public ThisClassNeedsContext(Context context){
          // now you have acces to the context
     }
}

I hope this helps! Good luck
EDIT: Typo in explanation


text:
Q: Multiple generics with Into I'm working on an asset manager for my game engine.
Here is a simplified version of the code:
trait Animal {
    fn create<P>(name: P) -> Self
    where
        P: Into<PathBuf>;
}

struct Dog;

impl Animal for Dog {
    fn create<P>(name: P) -> Self
    where
        P: Into<PathBuf>
    {
        Self {}
    }
}

fn create_animal<A, P>(name: P) -> A
where
    P: Into<PathBuf>,
    A: Animal,
{
    A::create(name)
}

When I'm trying to call create_animal like this, I'm getting the following error:
let dog = create_animal::<Dog>("Spike"); // Error: wrong number of type arguments: expected 2, found 1

The only way this function can be called right now is by passing both types explicitly:
let dog = create_animal::<Dog, &str>("Spike"); // This code is correct

I was wondering if there is any way to use Into with any other trait bound without explicitly passing its type (like in the first example).

A: You can use _ to leave the second type unspecified:
let dog = create_animal::<Dog, _>("Spike");

Or specify the variable's type:
let dog: Dog = create_animal("Spike");


text:
Q: Add column in Rails 5.1 migration not rolling back properly this is my first question here so please be kind.
I recently ran into this issue.
A migration for adding a column is not rolling back properly.
I can always do this with SQL statements, but I really wanted to figure out why this was not working.
My migration code looks like this.
class ChangeTypeForColumnStatusForInvoices < ActiveRecord::Migration[5.1]
  add_column :invoices, :tutor_pay, :integer
  remove_column :invoices, :status, :integer
  add_column :invoices, :status, :string
end

Here is the migration and the rollback when executed.
jameshong ~/Projects/tad_is_my_boss/toptutoring $ rails db:migrate
W, [2017-08-01T23:43:38.664232 #5782]  WARN -- : [SKYLIGHT] [1.3.1] Running Skylight in development mode. No data will be reported until you deploy your app.
(To disable this message for all local apps, run `skylight disable_dev_warning`.)
-- add_column(:invoices, :tutor_pay, :integer)
   -> 0.0030s
-- remove_column(:invoices, :status, :integer)
   -> 0.0015s
-- add_column(:invoices, :status, :string)
   -> 0.0011s
== 20170801015229 ChangeTypeForColumnStatusForInvoices: migrating =============
== 20170801015229 ChangeTypeForColumnStatusForInvoices: migrated (0.0000s) ====

jameshong ~/Projects/tad_is_my_boss/toptutoring $ rails db:rollback
W, [2017-08-01T23:44:00.076660 #5821]  WARN -- : [SKYLIGHT] [1.3.1] Running Skylight in development mode. No data will be reported until you deploy your app.
(To disable this message for all local apps, run `skylight disable_dev_warning`.)
-- add_column(:invoices, :tutor_pay, :integer)
-- add_column(:invoices, :tutor_pay, :integer)
rails aborted!
ActiveRecord::StatementInvalid: PG::DuplicateColumn: ERROR:  column "tutor_pay" of relation "invoices" already exists
: ALTER TABLE "invoices" ADD "tutor_pay" integer
/Users/jameshong/Projects/tad_is_my_boss/toptutoring/db/migrate/20170801015229_change_type_for_column_status_for_invoices.rb:2:in `<class:ChangeTypeForColumnStatusForInvoices>'
/Users/jameshong/Projects/tad_is_my_boss/toptutoring/db/migrate/20170801015229_change_type_for_column_status_for_invoices.rb:1:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
PG::DuplicateColumn: ERROR:  column "tutor_pay" of relation "invoices" already exists
/Users/jameshong/Projects/tad_is_my_boss/toptutoring/db/migrate/20170801015229_change_type_for_column_status_for_invoices.rb:2:in `<class:ChangeTypeForColumnStatusForInvoices>'
/Users/jameshong/Projects/tad_is_my_boss/toptutoring/db/migrate/20170801015229_change_type_for_column_status_for_invoices.rb:1:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
ActiveRecord::StatementInvalid: PG::DuplicateColumn: ERROR:  column "tutor_pay" of relation "invoices" already exists
: ALTER TABLE "invoices" ADD "tutor_pay" integer
/Users/jameshong/Projects/tad_is_my_boss/toptutoring/db/migrate/20170801015229_change_type_for_column_status_for_invoices.rb:2:in `<class:ChangeTypeForColumnStatusForInvoices>'
/Users/jameshong/Projects/tad_is_my_boss/toptutoring/db/migrate/20170801015229_change_type_for_column_status_for_invoices.rb:1:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
PG::DuplicateColumn: ERROR:  column "tutor_pay" of relation "invoices" already exists
/Users/jameshong/Projects/tad_is_my_boss/toptutoring/db/migrate/20170801015229_change_type_for_column_status_for_invoices.rb:2:in `<class:ChangeTypeForColumnStatusForInvoices>'
/Users/jameshong/Projects/tad_is_my_boss/toptutoring/db/migrate/20170801015229_change_type_for_column_status_for_invoices.rb:1:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
Tasks: TOP => db:rollback
(See full trace by running task with --trace)

As you can see, The migration properly adds column tutor_pay to relation invoices. However, when I rollback, the SQL that is performed is ADD COLUMN instead of DROP COLUMN. According to the rails guide, add_column is supposed to be a reversable migration. I've tried using change table instead. And I still get the same issue.
Would greatly appreciate it if someone could help me figure this out.

A: Use the below migration:
class ChangeTypeForColumnStatusForInvoices < ActiveRecord::Migration[5.1]
  def change
    add_column :invoices, :tutor_pay, :integer
      remove_column :invoices, :status, :integer
      add_column :invoices, :status, :string
    end
  end
end

Or you can also create self.up block for executing migration & self.down block for rollback for more info

A: I probably needed some sleep.
Didn't realize that I had to wrap all of this in a change method.
class ChangeTypeForColumnStatusForInvoices < ActiveRecord::Migration[5.1]
  def change
    add_column :invoices, :tutor_pay, :integer
    remove_column :invoices, :status, :integer
    add_column :invoices, :status, :string
  end
end


text:
Q: How to convert an audio stream's format? I need to convert an audio stream's format. For example: suppose audio stream format is 16 bit Little endian, I want to convert it to 16 bit Big endian.
How can I do this?

A: It should be something like this:
$ ffmpeg -i input-file.wav -acodec pcm_f32le -ar 96000 output-file.wav

And you have plenty plenty of choices if you use PCM, other codecs may be constrained to certain profiles.
$ ffmpeg -formats 2>/dev/null | grep endian
 DE f32be           PCM 32 bit floating-point big-endian format
 DE f32le           PCM 32 bit floating-point little-endian format
 DE f64be           PCM 64 bit floating-point big-endian format
 DE f64le           PCM 64 bit floating-point little-endian format
 DE s16be           PCM signed 16 bit big-endian format
 DE s16le           PCM signed 16 bit little-endian format
 DE s24be           PCM signed 24 bit big-endian format
 DE s24le           PCM signed 24 bit little-endian format
 DE s32be           PCM signed 32 bit big-endian format
 DE s32le           PCM signed 32 bit little-endian format
 DE u16be           PCM unsigned 16 bit big-endian format
 DE u16le           PCM unsigned 16 bit little-endian format
 DE u24be           PCM unsigned 24 bit big-endian format
 DE u24le           PCM unsigned 24 bit little-endian format
 DE u32be           PCM unsigned 32 bit big-endian format
 DE u32le           PCM unsigned 32 bit little-endian format

$ ffmpeg -codecs 2>/dev/null | grep endian
 D A D  pcm_bluray      PCM signed 16|20|24-bit big-endian for Blu-ray media
 D A D  pcm_dvd         PCM signed 20|24-bit big-endian
 D A D  pcm_f32be       PCM 32-bit floating point big-endian
 D A D  pcm_f32le       PCM 32-bit floating point little-endian
 D A D  pcm_f64be       PCM 64-bit floating point big-endian
 D A D  pcm_f64le       PCM 64-bit floating point little-endian
 D A D  pcm_lxf         PCM signed 20-bit little-endian planar
 D A D  pcm_s16be       PCM signed 16-bit big-endian
 D A D  pcm_s16le       PCM signed 16-bit little-endian
 D A D  pcm_s16le_planar PCM 16-bit little-endian planar
 D A D  pcm_s24be       PCM signed 24-bit big-endian
 D A D  pcm_s24le       PCM signed 24-bit little-endian
 D A D  pcm_s32be       PCM signed 32-bit big-endian
 D A D  pcm_s32le       PCM signed 32-bit little-endian
 D A D  pcm_u16be       PCM unsigned 16-bit big-endian
 D A D  pcm_u16le       PCM unsigned 16-bit little-endian
 D A D  pcm_u24be       PCM unsigned 24-bit big-endian
 D A D  pcm_u24le       PCM unsigned 24-bit little-endian
 D A D  pcm_u32be       PCM unsigned 32-bit big-endian
 D A D  pcm_u32le       PCM unsigned 32-bit little-endian


text:
Q: How to ensure "simple mail merge" doesn't duplicate emails I am trying to combine the principles on the following two tutorials:
https://developers.google.com/apps-script/articles/mail_merge https://developers.google.com/apps-script/articles/sending_emails
As I want the email to only be sent to each recipient once, and the form will be receiving ongoing responses. Before attempting to add in the "If" function I confirmed that the merge tags were working, but appear to have completed broken the code in my attempts to tweak it!
Heres what I currently have:
    function sendEmails() {var ss = SpreadsheetApp.getActiveSpreadsheet();  var dataSheet = ss.getSheets()[1];  var dataRange = dataSheet.getRange(2, 1, dataSheet.getMaxRows() - 1, 12);  var emailSent = getrange(12)  var templateSheet = ss.getSheets()[3];  var emailTemplate = templateSheet.getRange("A1").getValue();  objects = getRowsData(dataSheet, dataRange);  for (var i = 0; i < objects,length; ++i;   var rowData = objects[objects.length-1];;

    if (emailSent !== EMAIL_SENT){
    var emailText = fillInTemplateFromObject(emailTemplate, rowData);
    var emailSubject = "U+ Content Request Confirmation";
    MailApp.sendEmail(rowData.emailAddress, emailSubject, emailText);  sheet.getRange(startRow + i, 12).setValue(EMAIL_SENT);  SpreadsheetApp.flush();}
    function fillInTemplateFromObject(template, data) {

  var email = template;
  var templateVars = template.match(/\$\{\"[^\"]+\"\}/g);

  for (var i = 0; i < templateVars.length; ++i) {

    var variableData = data[normalizeHeader(templateVars[i])];
    email = email.replace(templateVars[i], variableData || "");
  }

  return email;
}
function getRowsData(sheet, range, columnHeadersRowIndex) {
  columnHeadersRowIndex = columnHeadersRowIndex || range.getRowIndex() - 1;
  var numColumns = range.getEndColumn() - range.getColumn() + 1;
  var headersRange = sheet.getRange(columnHeadersRowIndex, range.getColumn(), 1, numColumns);
  var headers = headersRange.getValues()[0];
  return getObjects(range.getValues(), normalizeHeaders(headers));
}

function getObjects(data, keys) {
  var objects = [];
  for (var i = 0; i < data.length; ++i) {
    var object = {};
    var hasData = false;
    for (var j = 0; j < data[i].length; ++j) {
      var cellData = data[i][j];
      if (isCellEmpty(cellData)) {
        continue;
      }
      object[keys[j]] = cellData;
      hasData = true;
    }
    if (hasData) {
      objects.push(object);
    }
  }
  return objects;
}
function normalizeHeaders(headers) {
  var keys = [];
  for (var i = 0; i < headers.length; ++i) {
    var key = normalizeHeader(headers[i]);
    if (key.length > 0) {
      keys.push(key);
    }
  }
  return keys;
}

function normalizeHeader(header) {
  var key = "";
  var upperCase = false;
  for (var i = 0; i < header.length; ++i) {
    var letter = header[i];
    if (letter == " " && key.length > 0) {
      upperCase = true;
      continue;
    }
    if (!isAlnum(letter)) {
      continue;
    }
    if (key.length == 0 && isDigit(letter)) {
      continue; // first character must be a letter
    }
    if (upperCase) {
      upperCase = false;
      key += letter.toUpperCase();
    } else {
      key += letter.toLowerCase();
    }
  }
  return key;
}

function isCellEmpty(cellData) {
  return typeof(cellData) == "string" && cellData == "";
}

function isAlnum(char) {
  return char >= 'A' && char <= 'Z' ||
    char >= 'a' && char <= 'z' ||
    isDigit(char);
}

function isDigit(char) {
  return char >= '0' && char <= '9';
}} )


text:
Q: Pipes and Redirection home output #include<errno.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>

int main(void) {
pid_t childpid;
int fd[2];

if (pipe(fd) == -1) { /* setup a pipe */
    perror("Failed to setup pipeline");
    return 1;
}
if ((childpid = fork()) == -1) { /* fork a child */
    perror("Failed to fork a child");
    return 1;
}
if (__________) {/* env is the child */

    if (dup2(fd[1], __________) == -1)
        perror("Failed to redirect stdout of env");
    else if (____________________) /* close unused file descriptor */
        perror("Failed to close extra pipe descriptors on env");
    else {
        execl(__________); /* execute env */
        perror("Failed to exec env");
    }
    return 1;
}
if (dup2(fd[0],__________) == -1)
/* grep is the parent */
    perror("Failed to redirect stdin of grep");
else if (____________________)
    perror("Failed to close extra pipe file descriptors on grep");
else {
    execl(__________); /*execute "grep HOME"*/
    perror("Failed to exec grep");
}
return 1;
}

i figured out most of the gaps but i couldn't seem to get the others to work the way  as intended. So basically, this program is meant uses redirect to implement env | grep HOME, which prints out my home directory. I am to use dup2 and excel, but need the gaps filled using c and linux system calls.


text:
Q: scenebuilder 8.5 custom jar not load, can't open fxml i download scenebuilder 8.5 java 8 version, before i used scenebuilder 8.4.1 without any problem.
With new one:
 - custom jar does not appear in list
 - open an fxml doesn't work (fxml created with scenebuilder 8.4.1 without any problem) even if i don't use my custom library
 - no log error appears, just no reaction on open project action button???
I try to install again the application but without success.
When i open scenebuilder in intellij, it works.
I have two questions:

*

*What should i check or do?

*How can i download scenebuilder 8.4.1

A: i found why, it's a problem of my custom jar, i fix it and know it's ok


text:
Q: rails gsub question How can i replace " " and "_" with "-" in my controller when creating a new post?
I have the following form fields:
title
url
content
I want to execute the gsub on the url field.
Thanks...

A: Remember that getting rid of space and "_" from URL is not enough as there are some other characters which my break your HTML code and even cause script injection. <>'"/\.
I suggest passing all letters and numbers - everything else translate to -.
class Post < ActiveRecord::Base
  attr_protected :url
  validates_presence_of :title
  before_create :generate_url

  private
    def generate_url
      self.url = title.strip.downcase.gsub(/[^a-z0-9]+/,'-')
    end
end

Controller is unchanged.

A: title.gsub(" ","-").gsub("_","-")

A: title.gsub(/[\s_]+/, '-').strip

A: If you're trying to slug the title, then you may find Norman's friendly_id of some use:
http://github.com/norman/friendly_id
It'll take care of creating permalinks for you, so you won't need to worry about duplication or generation of the url in your app. It'll also integrate with ActiveRecord to override the find methods.


text:
Q: Dynamically add filter options in angularjs Hello I have a small project in which I want to have perform search from multiple dynamically added text fields.
This is how I add the search fields:

     <button ng-show="showAddChoice(choice)" ng-click="addNewChoice()">Add another choice</button>
     <input type="text" ng-model="choice.name" name="" placeholder="Search criteria">

And later I have a table with ng-repeat and here is that part:

     .......

What I want to do is to have the contents filtered with all dynamically added search fields.

A: You'll have to create your own filter to handle that. I've gone ahead and gotten you started.
        $scope.myFilter = function(input){
            for(var key in input){
                for(var x = 0; x < $scope.choices.length; x++){
                    if(input[key] == $scope.choices[x].name){
                     return true;
                    }
                }
            }
            return false;
        }

Here is the jsFiddle of the output: http://jsfiddle.net/wsPrv/

A: Rather than using the filter, do the filtering in the controller yourself. Here is the updated fiddle with the solution. In the first textbox, replace choice1 with "some" and you will see the todo with text "Some stuff" being displayed.
See the relevant part below. For details, see the fiddle.
        $scope.$watch('choices', function(newValue) {
            $scope.DisplayedTodos = [];
            // Filter items here and push to DisplayedTodos. Use DisplayedTodos to display todos
        }, true);


text:
Q: log4j stopped logging to the file, I am using log4j in my java application, but after some time without throwing any exception it stopped logging
my log4j configuration is as below.
log4j.rootLogger=INFO,FILE
log4j.appender.FILE=com.test.TestFIleAppender
log4j.appender.FILE.MaxFileSize=20MB
log4j.appender.FILE.MaxBackUpIndex=200

My file appender contains some code to do the zip operation and to specify the log file format and all.
This was logging fine for some time, but suddenly stopped logging , no exception also thrown
can any body tell me what can be the issue?
any body know any log4j related issues like this?

A: This happened to me. Working one day and then not working the next. I went back and realized I had changed the POM dependencies and did some googling.
When I corrected this issue, my logging returned. I would make sure you have the following artifacts in sync:
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.1</version>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-simple</artifactId>
        <version>1.7.1</version>
    </dependency>

    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>

http://www.slf4j.org/manual.html

A: It is difficult to answer, why your logging is stopping.
First, check the hard disk space, whether this is full.
Than write a testcase in which a thread is polling a logging message of type INFO every second. Than you could check whether this is a space or memory issue.
Please notice: When you programm is waiting somewhere and no thread or action is working, you will not see any loging message. Please check, by debugging, whether a code line is executed in a loop (or as you expected to see messages) in which a logging message should be shown.
This is an example of my log4j properties file. May be is is helpful:
log4j.rootLogger=INFO, stdout, logfile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p (%t) [%c] - %m%n

log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.File=C:/log/client.log
log4j.appender.logfile.MaxFileSize=5MB
log4j.appender.logfile.MaxBackupIndex=0
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

A: Have you considered the possibility that log4j is still writing to a file, but that file has been unlinked from its parent directory by your custom appender?

A: It happened to me after adding sardine library to my dependencies. Then, from one of answers here I added slf4j-log4j12 library to the dependencies and it started to work again.

A: Probably a very rare situation, but I once encountered a similar problem that was caused by use of a Cloner. After cloning an object with log4j logging enabled, the logging just stopped working. The solution was to exclude log4j classes from the cloning with:
cloner.dontClone(org.apache.log4j.Logger.class, org.apache.log4j.LogManager.class,)


text:
Q: How to hide a List View column in Modern SharePoint I have a List in a SharePoint Online site that uses the Modern experience. I want to hide a column, but need to stay in Modern. The easy way I found was inserting a few lines of Javascript in a Script Editor webpart, but this would require switching to the Classic experience. I can't go to Classic because I have column formatting code with JSON that needs to be displayed. And I can't just remove the column from the view, because the JSON formatting references this column.

A: Check the article: Customizing "modern" lists and libraries
We can't add JavaScript or CSS code in the modern list view page.
As a workaround, we can hide the column value using column formatting below, we can't hide the whole column if you need use this column value in another column formatting.
{
   "$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
   "elmType": "div",
   "txtContent": "@currentField",
   "style": {
      "display": "none"
   }
}

A: What you need to do is create a new calculated column (or use one you already have in your view) and in its formula you will include all of the columns that you want to use in JSON formatting but don't want included in the list view itself.
If you make a new column, you should have the calculated column display the data stored in a column that you do want to display so you don't need to add an unnecessary column to your view.
Since you want to use the column [FSTSprintStatus] in your JSON formatting of column [FST Sprint], but you don't want [FSTSprintStatus] to be included in the view, you'll create a new calculated column (for this example, I'll assume the [Modified] column is in your view, so let's call the new column [FST Sprint Modified]), and you'll use a formula with a condition that always returns false, similar to this:
=IF(1==2, [FSTSprintStatus], [Modified])

You can also just use FALSE in the condition, like this:
 =IF(FALSE, [FSTSprintStatus], [Modified])

Then in the view, replace [Modified] with the new [FST Sprint Modified], and now you can successfully reference [FSTSprintStatus] in the [FST Sprint] column JSON without requiring [FSTSprintStatus] to be in your view.
You can even add more columns to this formula that you want to reference in the JSON but don't want in your view. For example, you can nest the conditions like this:
=IF(FALSE, [FSTSprintStatus], IF(FALSE, [FSTSprintAmount], IF(FALSE, [FSTSprintRange], [Modified])))

Now, [FSTSprintStatus], [FSTSprintAmount], and [FSTSprintRange] can all be used in your JSON formatting and you don't need to include any of them in your view.
The trick to making this work is by ensuring that any columns you use in this way get parsed and calculated by SharePoint before the formula returns its value. For example, a formula like this won't work:
=IF(TRUE, [Modified], [FSTSprintStatus])

Since this formula returns TRUE, SharePoint returns [Modified] and immediately stops processing anything else, so [FSTSprintStatus] never gets read into the page context and cannot be referenced in the JSON. I do not know why SharePoint does it this way, I just know from previous testing of my own view formatting that it does.
Although I'm replying almost a year after you asked the question, I hope my explanation helps you out if you're still having trouble with this, or else helps someone else who's in the same boat.


text:
Q: Using custom class as a parameter/field in J2EE application I am trying to pass the custom object value to Jasper report, I am using compiled jasper i.e .jasper file.
Passing the parameter in jrxml
<parameter name="STUDENT_ID" class="abc.xyz.Student"/>

Trying to access the parameter in jrxml
      <textField>
            <reportElement x="156" y="100" width="403" height="20" uuid="20cc6538-41d9-4fe5-ba43-e3152b073e10"/>
            <textFieldExpression><![CDATA[":    "+$P{STUDENT_ID}.getId()]]></textFieldExpression>
      </textField>

Structure:
jasper/
   temp.jasper
WEB-INF/
   classes/
   lib/
   web.xml

Service class
Student student = session.get("student")
HashMap<String, Object> map = new HashMap<String, Object>(1);
map.put("STUDENT_ID", student);
print = JasperFillManager.fillReport(ServletActionContext.getServletContext().getRealPath("/jasper/temp.jasper"), map, new JREmptyDataSource());

Student class will vary student to student, Student class has the fields id and name with getters and setters, but somehow values are not getting rendered on generated PDF file.
How to access the Student object?

A: At first view I can't see nothing wrong with your code, but if you are passing an empty data source, be sure to not place the field you want on Datails band. Without data source, this band is not rendered. Test it putting the field on Title band, for example.


text:
Q: What is the pre requisite to be able to use Unix's rlogin command? What is the pre requisite to be able to use Unix's rlogin command?
Regards
Chaitanya

A: See here: http://docs.hp.com/en/B2355-90164/ch06s05.html

A: In Mac OS X under the "Sharing" category in "System preferences" you need to enable "Remote Login" by clicking the checkbox.


text:
Q: Kiali not showing response time for MESH_EXTERNAL ServiceEntry configured as HTTPS We need to analyse network traffic, and specifically we need to get the response time value for internal service to service traffic and internal to external service traffic.
This works well for internal services where Kiali shows response time value including protocol (http). However, for MESH_EXTERNAL ServiceEntries despite defining HTTPS as protocol in the ServiceEntry manifest, Kiali does not show the response time. Instead of response time for the configured https protocol, Kiali's shows tcp  without any response time value.
apiVersion: networking.istio.io/v1beta1
kind: ServiceEntry
metadata:
  name: external-service-entry-foo
spec:
  hosts:
  - foo.bar.com
  location: MESH_EXTERNAL
  ports:
  - name: https
    number: 443
    protocol: HTTPS
  resolution: DNS

Internal traffic including response time and http as protocol

External traffic excluding response time and and https as protocol

Tried to change the protocol to TLS according to documentation https://istio.io/latest/docs/reference/config/networking/service-entry/ , however Kiali is still showing tcp flow.


text:
Q: how do i debug pindown python script? I'm try to work this python script aangfanboy/pindown in github
but I got this bug
Opening browser...:   0%|                                                                       | 0/12 [00:00<?, ?it/s]
DevTools listening on ws://127.0.0.1:49614/devtools/browser/9501c6f7-21b0-4297-96fb-e44c4fcfa4cb
Going to link...:   8%|█████▍                                                           | 1/12 [00:05<01:01,  5.63s/it][0122/062528.296:INFO:CONSOLE(0)] "A cookie associated with a cross-site resource at http://google.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.", source: https://www.pinterest.com/search/pins/?q=art (0)
Starting download...:  42%|█████████████████████████▍                                   | 5/12 [00:10<00:26,  3.82s/it][0122/062531.262:INFO:CONSOLE(1)] "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.", source: https://s.pinimg.com/webapp/js/pjs-entryChunk-www-unauth-93845af8c143b49d2f47.mjs (1)
Starting download...:  42%|█████████████████████████▍                                   | 5/12 [00:10<00:15,  2.18s/it]

I can't find any image about art
Exception ignored in: <function Popen.__del__ at 0x02F12C88>
    Traceback (most recent call last):
      File "C:\Users\windows user name\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 945, in __del__
        self._internal_poll(_deadstate=_maxsize)
      File "C:\Users\windows user name\AppData\Local\Programs\Python\Python38-32\lib\subprocess.py", line 1344, in _internal_poll
        if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
    OSError: [WinError 6] The handle is invalid

can you help me here?
You can get full codes from https://github.com/aangfanboy/pindown


text:
Q: Problem with view (read-only mode for vim) Sometimes when I'm editing code in a terminal, I want to open the same file in read-only mode using /usr/bin/view. However, when I do this, vim still warns me that a swap file exists. Why is this? I thought that view was explicitly read-only. Any ideas? Do I have something bogus in my system? I'm running Ubuntu 18.04.

A: Like you already said view is the read-only mode for vim - so effectively you are opening the same file two times with vim.
As vim doesn't check if there is another instance running with the same file open it will warn you about the swap file.
If you don't need swap files you can disable them permanently with set noswapfile in your .vimrc.
To only ignore swap files when using view you can use view -n to ignore the swap file. To avoid to type this every time, add alias view="view -n" to your shells rc file (most probably .bashrc).


text:
Q: Error in classifying SVM texts I'm trying to apply a text sorting algorithm and unfortunately I have an error
import sklearn
import numpy as np
from sklearn import svm
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.metrics import precision_recall_fscore_support as score
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import accuracy_score
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_recall_fscore_support
import pandas as pd
import pandas

dataset = pd.read_csv('train.csv', encoding = 'utf-8')
data = dataset['data']
labels = dataset['label']

X_train, X_test, y_train, y_test = train_test_split (data.data, labels.target, test_size = 0.2, random_state = 0)

vecteur = CountVectorizer()
X_train_counts = vecteur.fit_transform(X_train)

tfidf = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)

clf = MultinomialNB().fit(X_train_tfidf, y_train)

#SVM
clf = svm.SVC(kernel = 'linear', C = 10).fit(X_train, y_train)
print(clf.score(X_test, y_test))

I have the following error:

Traceback (most recent call last):
File "bayes_classif.py", line 22, in
dataset = pd.read_csv('train.csv', encoding = 'utf-8')
File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 678, in parser_f
return _read(filepath_or_buffer, kwds)
File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 446, in _read
data = parser.read(nrows)
File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 1036, in read
ret = self._engine.read(nrows)
File "/usr/local/lib/python3.6/dist-packages/pandas/io/parsers.py", line 1848, in read
data = self._reader.read(nrows)
File "pandas/_libs/parsers.pyx", line 876, in pandas._libs.parsers.TextReader.read
File "pandas/_libs/parsers.pyx", line 891, in pandas._libs.parsers.TextReader._read_low_memory
File "pandas/_libs/parsers.pyx", line 945, in pandas._libs.parsers.TextReader._read_rows
File "pandas/_libs/parsers.pyx", line 932, in pandas._libs.parsers.TextReader._tokenize_rows
File "pandas/_libs/parsers.pyx", line 2112, in pandas._libs.parsers.raise_parser_error
  pandas.errors.ParserError: Error tokenizing data. C error: Expected 2 fields in line 72, saw 3

My data
data, label
bought noon <product> provence <product> shop givors moment <price> bad surprise <time> made account price <price> catalog expect part minimum refund difference wait read brief delay, refund

parcel ordered friend n still not arrive possible destination send back pay pretty unhappy act gift birth <date> status parcel n not moved weird think lost stolen share quickly solutions can send gift both time good <time>, call

ordered <product> coat recovered calais city europe shops n not used assemble parties up <time> thing done <time> bad surprise parties not aligned correctly can see photo can exchange made refund man, annulation

note <time> important traces rust articles come to buy acting carrying elements going outside extremely disappointed wish to return together immediately full refund indicate procedure sabrina beillevaire <phone_numbers>, refund

note <time> important traces rust articles come to buy acts acting bearing elements going outside extremely disappointed wish to return together immediately full refund indicate procedure <phone_numbers>, annulation

request refund box jewelry arrived completely broken box n not protected free delivery directly packaging plastic item fragile cardboard box <product> interior shot cover cardboard torn corners <product> completely broken, call

A: Can you try to reproduce the same error with a clean code? Yours contain a few mistakes, and unnecessary lines. We also need a sample of your data that helps reproduce the error otherwise we won't be able to help.
Here is what I assume is you are trying to do, please try to launch it with your data and tell us if you still obtain the same error:
import pandas as pd
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer

dataset = pd.DataFrame({'data':['A first sentence','And a second sentence','Another one','Yet another line','And a last one'],
                    'label':[1,0,0,1,1]})
data = dataset['data']
labels = dataset['label']

X_train, X_test, y_train, y_test = train_test_split (data, labels, test_size = 0.2, random_state = 0)

vecteur = CountVectorizer()
tfidf = TfidfTransformer()

X_train_counts = vecteur.fit_transform(X_train)
X_train_tfidf = tfidf.fit_transform(X_train_counts)
X_test_tfidf = tfidf.transform(vecteur.transform(X_test))

clf = svm.SVC(kernel = 'linear', C = 10).fit(X_train_tfidf, y_train)
print(clf.score(X_test_tfidf, y_test))

EDIT:
According to your data, the error might be due to a comma character in your csv file, causing pandas parser to bug. You can tell pandas to ignore such rows by using erro_bad_lines argument in read_csv. Here is a short example:
temp=u"""data, label
A first working line, refund
a second ok line, call
last line with an inside comma: , character which makes it bug, call"""
df = pd.read_csv(pd.compat.StringIO(temp),error_bad_lines=False)


text:
Q: Azure DevOps Release Pipelines with "Failed to fetch Kudu App Settings. Error: Error: connect ETIMEDOUT x.x.x.x:443" When I'm running Azure DevOps pipeline with the Azure WebApp it is getting into failed stated with as below message.

2022-11-18T12:01:00.4889154Z ##[error]Error: Failed to fetch Kudu App Settings. Error: Error: connect ETIMEDOUT x.x.x.x:443

A: Your deployment agent isn't connecting to your app service. One way this can occur is if there's a transient network issue with your app service. These are uncommon, rare errors. As a workaround though, you can try creating a new app service and verify your deployment credentials.
A more common error is if you're deploying to an app service environment (ASE). This type of app service doesn't allow traffic from the internet. To correct this error, you'll need to configure a deployment agent that is on the same VNET as your app service


text:
Q: Sending a greeting/welcome message from the bot as soon as the Webchat control is loaded I'm developing a bot using Microsoft's Bot framework in C#. I'm trying to send a welcome message to the user as an introduction before he/she sends anything.
After researching, I somewhat achieved this using HandleSystemMessage function and sending the message in the case of a ConversationUpdate as follows:
if (activity.Type == ActivityTypes.ConversationUpdate)
{
    IConversationUpdateActivity update = activity;
    if (update.MembersAdded.Any())
    {
        foreach (var newMember in update.MembersAdded)
        {
            if (newMember.Id != activity.Recipient.Id)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));

                Activity reply = activity.CreateReply();
                reply.Text("Hello, how can I help you?");
                await connector.Conversations.ReplyToActivityAsync((Activity)bubble);
            }
        }
    }
}

The problem I am facing with this method:

*

*In the Emulator, the welcome message appears when you hit the refresh button above or when the user starts typing if it has been idle for a while. This is the behavior I'm looking for and it is working as intended.

*Now when using the Bot Framework Web Chat component, this message is send when the user initiate the conversation, i.e. when the user types something and sends it to the bot. This is not what I want, but rather, I'd like the message to be shown from the bot as soon as the web chat control is loaded as the message will contain some instructions on how to use the bot.

I assume my problem could be solved using another ActivityType perhaps or some Javascript 'hacky' way but I couldn't find a solution up until now.

A: For the webchat component, you can use the backchannel functionality to send a hidden message to your bot, in order to launch the greetings.
Heere is a sample of the implementation on the webchat side:
<!DOCTYPE html>
<html>
<head>
    <link href="https://cdn.botframework.com/botframework-webchat/latest/botchat.css" rel="stylesheet" />
</head>
<body>
    <div id="bot" />
    <script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
    <script>
        // Get parameters from query
        const params = BotChat.queryParams(location.search);
        // Language definition
        var chatLocale = params['locale'] || window.navigator.language;

        // Connection settings
        const botConnectionSettings = new BotChat.DirectLine({
            domain: params['domain'],
            secret: 'YOUR_SECRET',
            webSocket: params['webSocket'] && params['webSocket'] === 'true'
        });

        // Webchat init
        BotChat.App({
            botConnection: botConnectionSettings,
            user: { id: 'userid' },
            bot: { id: 'botid' },
            locale: chatLocale,
            resize: 'detect'
        }, document.getElementById('bot'));

        // Send hidden message to do what you want
        botConnectionSettings.postActivity({
            type: 'event',
            from: { id: 'userid' },
            locale: chatLocale,
            name: 'myCustomEvent',
            value: 'test'
        }).subscribe(function (id) { console.log('event sent'); });
    </script>
</body>
</html>

On your bot side, you will get this event on your Message Controlelr:
public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
{
    // DEMO PURPOSE: echo all incoming activities
    Activity reply = activity.CreateReply(Newtonsoft.Json.JsonConvert.SerializeObject(activity, Newtonsoft.Json.Formatting.None));

    var connector = new ConnectorClient(new Uri(activity.ServiceUrl));
    connector.Conversations.SendToConversation(reply);

    // Process each activity
    if (activity.Type == ActivityTypes.Message)
    {
        await Conversation.SendAsync(activity, () => new Dialogs.RootDialog());
    }
    // Webchat: getting an "event" activity for our js code
    else if (activity.Type == ActivityTypes.Event && activity.ChannelId == "webchat")
    {
        var receivedEvent = activity.AsEventActivity();

        if ("myCustomEvent".Equals(receivedEvent.Name, StringComparison.InvariantCultureIgnoreCase))
        {
            // DO YOUR GREETINGS FROM HERE
        }
    }
    // Sample for Skype: in ContactRelationUpdate event
    else if (activity.Type == ActivityTypes.ContactRelationUpdate && activity.ChannelId == "skype")
    {
        // DO YOUR GREETINGS FROM HERE
    }
    // Sample for emulator, to debug locales
    else if (activity.Type == ActivityTypes.ConversationUpdate && activity.ChannelId == "emulator")
    {
        foreach (var userAdded in activity.MembersAdded)
        {
            if (userAdded.Id == activity.From.Id)
            {
                // DO YOUR GREETINGS FROM HERE
            }
        }
    }

    var response = Request.CreateResponse(HttpStatusCode.OK);
    return response;
}

I made a working demo using this functionality to send the user locale, it's here on Github

A: This is a known issue in Web chat.

Using WebChat or directline, the bot's ConversationUpdate is sent when the conversation is created and the user's ConversationUpdate is sent when they first send a message. [1]

A work around would be to send a message to the bot from the web-chat.
<!DOCTYPE html>

<script src="https://cdn.botframework.com/botframework-webchat/latest/botchat.js"></script>
<script>

    var user = {
        id: 'user-id',
        name: 'user name'
    };

    var botConnection = new BotChat.DirectLine({
        token: '[DirectLineSecretHere]',
        user: user
    });

    BotChat.App({
        user: user,
        botConnection: botConnection,
        bot: { id: 'bot-id', name: 'bot name' },
        resize: 'detect'
    }, document.getElementById("bot"));

    botConnection
        .postActivity({
            from: user,
            name: 'requestWelcomeDialog',
            type: 'event',
            value: ''
        })
        .subscribe(function (id) {
            console.log('"trigger requestWelcomeDialog" sent');
        });
</script>

[2]
I didn't change anything in my bot code to achieve this.


text:
Q: how to acces files in directory in hadoop map job?

for(FileStatus status : status_list)
{
  FileInputFormat.addInputPath(job5, status.getPath());
}

I want to know that I have added directory files in input path. now, how can I use in hadoop map ?

A: You need to use MultipleInputs class instead of FileInputFormat. Frame work will take care of generating key, value pair for you for each of the file for your mapper.


text:
Q: best way to convert java.util.HashSet to Clojure set Datomic queries return java.util.HashSet for compatibility purposes. I'd like to use clojure.set functions like set difference on query result sets. Currently, I'm converting the result set to Clojure set using (set datomic_result). Is there an alternative to this?

A: I don't recommend you rely on the fact that the returned value is a java.util.Set, which is an implementation detail (according to the Datomic documentation, the return type is java.util.Collection).
You may get better performance by applying your set operation directly to the returned collection instead of coercing to a Set. For instance:
;; set difference
(into #{} (remove to-remove) query-result)
;; set intersection
(into #{} (filter to-keep) query-result)
;; set union
(into my-set query-result)

The use of into lets you leverage both Transients and Transducers, which can give you a significant performance boost on large inputs.


text:
Q: Alguem sabe me explicar o processo de gerar uma apk no React Native Não consigo de jeito nenhum gerar uma apk, sigo os passos da documentação mas logo de cara nao consigo gerar a keytool. Alguem sabe pode me explicar como se gera?

A: Para gerar uma apk ~signed~ você precisa primeiro gerar a .keystore.
Esse passo é bem simples. Apenas vá até onde você colocou sua jdk (C:\Program Files\Java\jdkx.x.x_x\bin - nesse caso fiz com versão jdk1.8.0_92)
E executa, como está aqui:
$ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000
Assim, vai digitando as informações que vai pedindo. As informações que tu vais precisar são:
name da keytool (vai gerar como my-release-key provavelmente) e password.
NOTA: precisei de permissão de admin pra gerar.
Feito isso, pega a keytool recém gerada e coloca em android/app no diretório do seu projeto React Native.
Depois, adiciona em android/gradle.properties:
MYAPP_RELEASE_STORE_FILE=my-release-key.keystore
MYAPP_RELEASE_KEY_ALIAS=my-key-alias
MYAPP_RELEASE_STORE_PASSWORD=*****
MYAPP_RELEASE_KEY_PASSWORD=*****

Depois disso, modifica o android/app/build.grade como diz no tutorial do React Native:
...
android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }
    }
}
...

Aí é só executar:
$ cd MyAPP/android
$ gradlew assembleRelease
Obs: Tive que colocar o gradlew no PATH pra rodar o último comando.
Sua apk vai aparecer em android/app/build/outputs/apk/ após o build.


text: Q: Глюк в Sublime Text с LiveStyle У меня установлены LiveStyle, Hayaku, Emmet. Когда подключён LiveStyle, и я начинаю что-то писать в CSS-коде, код копируется и вставляется в конец. Удаляю копию — удаляется оригинал, код вставляется не пойми куда. Кто ещё сталкивался с таким поведением LiveStyle?


text:
Q: PHP/mysql, Using foreign keys to get data from another table I have 2 tables, one called posts and one called users. Inside posts I have several columns, one being a foreign key of userid. In my users table I have several columns including a userid and a username. I want to use the posts.userid to find the users.userid and show users.username. Currently I am using:
SELECT posts.postid, posts.title, posts.text, posts.link, posts.good, posts.bad, posts.userid
FROM posts

To get the data about each post and,
SELECT users.username, users.userid, posts.userid
FROM users, posts
WHERE users.userid = posts.userid

to get the data about each user, but when I do this the output of echo $row_therealuserid['username']; is always just the first user.

A: You need to use an array to fetch the other rows, then loop through that array.
$query = 'SELECT users.username, users.userid, posts.userid
FROM users, posts
WHERE users.userid = posts.userid';

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result)){
    echo $row['username'];
    echo "<br />";
}

A: For SELECT and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
A resource is a special variable, holding a reference to an external resource. Resources are created and used by special functions, and it can has many types created and used by different functions.
for    mysql_query() the returned type a resource is "mysql result" which will be used by  mysql_fetch_array();
I will give you another example, for the function    mysql_connect() it returns a resource type "mysql link" which can be used by the function    mysql_query()


text:
Q: Is there a function with a removable discontinuity at every point? If memory serves, ten years ago to the week (or so), I taught first semester freshman calculus for the first time.  As many calculus instructors do, I decided I should ask some extra credit questions to get students to think more deeply about the material.  The first one I asked was this:
1) Recall that a function $f: \mathbb{R} \rightarrow \mathbb{R}$ is said to have a removable discontinuity at a point $x_0 \in \mathbb{R}$ if $\lim_{x \rightarrow x_0} f(x)$ exists but not does not equal $f(x_0)$.  Does there exist a function $f$ which has a removable discontinuity at $x_0$ for every $x_0 \in \mathbb{R}$?
Commentary: if so, we could define a new function $\tilde{f}(x_0) = \lim_{x \rightarrow x_0} f(x)$ and it seems at least that $\tilde{f}$ has a fighting chance to be continuous on $\mathbb{R}$.  Thus we have successfully "removed the discontinuities" of $f$, but in so doing we have changed the value at every point!
Remark: Lest you think this is too silly to even seriously contemplate, consider the function $f: \mathbb{Q} \rightarrow \mathbb{Q}$ given by $f(0) = 1$ and for a nonzero
rational number $\frac{p}{q}$, $f(\frac{p}{q}) = \frac{1}{q}$.  It is easy to see that this function has limit $0$ at every (rational) point!
So I mentioned this problem to my students.  A week later, the only person who asked me about it at all was my Teaching Assistant, who was an older undergraduate, not even a math major, I think.  (I hasten to add that this was not in any sense an honors calculus class, i.e., I was pretty clueless back then.)  Thinking about it a bit, I asked him if he knew about uncountable sets, and he said that he didn't.  At that point I realized that I didn't have a solution in mind that he would understand (so still less so for the freshman calculus students) and I advised him to forget all about it.

So my actual question is: can you solve this problem using only the concepts in a non-honors freshman calculus textbook?  (In particular, without using notions of un/countability?)
[Addendum: Let me say explicitly that I would welcome an answer that proceeds directly in terms of the least upper bound axiom.  Most freshman calculus books do include this, albeit somewhere hidden from view of the casual readers, i.e., actual freshman calculus students.]

If you can't figure out how to answer the question at all, I think the following related question helps.
2) Define a function $f: \mathbb{R} \rightarrow \mathbb{R}$ to be precontinuous if the limit exists at every point.  For such a function, we can define $\tilde{f}$ as above.  Prove/disprove that, as suggested above, $\tilde{f}$ is indeed continuous.  [Then think about $f - \tilde{f}$.]
Now that I think about it, there is an entire little area here that I don't know anything about, e.g.
3) The set of discontinuities of an arbitrary function is known -- any $F_{\sigma}$ set inside $\mathbb{R}$ can serve.  What can we say about the set of discontinuities of a "precontinuous function"?  [Edit: from the link provided in Chandru1's answer, we see that it is countable.  What else can we say?  Note that taking the above example and extending by $0$ to the irrationals, we see that the set of points of discontinuity of a precontinuous function can be dense.]

A: The uncountability of $\mathbb{R}$ must be used, but perhaps we can avoid mentioning it.
Below is a sketch of proof.  By restriction of domain and subtraction of its limit from itself, we may consider $f:[0,1]\rightarrow\mathbb{R}$ such that $f$ has zero pointwise limit and removable discontinuity everywhere.  If we replace $f$ by $|f|$, we may further assume that $f$ is strictly positive.
Denote the cardinality of a finite set $S$ by $|S|$.  Let
$I_0 = \lbrace x: 1\le f(x)\rbrace$ and $I_n = \lbrace x: \frac{1}{n+1}\le f(x)\lt \frac{1}{n}\rbrace$ for $n\ge 1$.
Then each $I_n$ must be finite, or else it has an accumulation point $p\in[0,1]$ and this contradicts the assumption that the limit of $f$ at $p$ is zero.  Let
$J_n = \lbrace x\in[0,1]: |x-y|<\frac{1/2}{3^{n+1}|I_n|} \textrm{ for some } y\in I_n\rbrace.$
($J_n$ is empty if $I_n$ is empty.)  Hence $[0,1] = \bigcup\limits_{n\ge 0} I_n \subseteq \bigcup\limits_{n\ge 0} J_n$.  But the latter has total length $\le \frac{1}{2}$.  So we arrive at a contradiction.
[Edit] Alternatively, $\lbrace J_n \rbrace_{n=1,2,...}$ is an open cover of $[0,1]$.  So there is a finite subcover.  This contradicts that the total length of all $J_n$'s is at most $1/2$.

A: I think the following works:
Here is a sketch, I will fill in the details later if required.
Let $g(x) = \lim_{t\rightarrow x} f(t)$. Then we can show that $g(x)$ is continuous.
Let $h(x) = f(x) - g(x)$. Then $\lim_{t \rightarrow x} h(t)$ exists and is $0$ everywhere.
We will now show that $h(c) = 0$ for some $c$.
This will imply that $f(x)$ is continuous at $c$ as then we will have $f(c) = g(c) = \lim_{t->c} f(t)$.
Consider any point $x_0$.
By limit of $h$ at $x_0$ being $0$, there is a closed interval $I_0$ (of length > 0) such that $|h(x)| < 1$ for all $x \in I_0$.
This is because, given an $\epsilon > 0$ there is a $\delta > 0$ such that $|h(x)| < \epsilon$ for all $x$ such that $0 < |x - x_{0}| < \delta$. Pick $\epsilon = 1$ and pick $I_{0}$ to be any closed interval of non-zero length in $(x_{0}, x_{0} + \delta)$.
Now pick any point $x_1$ in $I_0$.
By limit of $h$ at $x_1$ being $0$, there is a closed interval $I_1 \subset I_0$ (of length > 0) such that $|h(x)| < 1/2$ for all $x \in I_1$, by argument similar to above.
Continuing this way, we get a sequence of closed intervals $I_n$ such that
$|h(x)| < \frac{1}{n+1}$ for all $x \in I_n$. We also have that $I_{n+1} \subset I_n$ for each $n$, and that length $I_n$ > 0. We could also arrange so that length $I_n \rightarrow 0$.
Now there is a point $c$ (by completeness of $\mathbb{R}$) such that $c \in \bigcap_{n=0}^{\infty}I_{n}$.
Thus we have that $|h(c)| < \frac{1}{n+1}$ for all $n$ and so $h(c) = 0$ and $f(c) = g(c)$.

A: No.
Please see theorem 5.63 in this link:
http://books.google.com/books?id=6l_E9OTFaK0C&pg=PA249


text:
Q: Alternatives to redux-observable in a NextJS Application I am currently porting a project over to NextJS from Create-React-App.
One of the issues I'm running into at the moment is properly handling all of our redux state, some of which also uses redux-observable.
I really like the library for the asynchronous functionality it offers, however I am wondering if there are better alternatives. The library is currently in maintainence mode, so it might be a good time to switch.
In particular, one very useful feature is being able to launch actions based on other actions. In the following example we fetch multiple pages of data based on one action. I don't know how to effectively handle this using other methods.
For example:

// This epic is called when we want to fetch data from the API
const dataFetchEpic = (
  action$: any,
  state$: any,
  { api }: IDependencies
) =>
  action$.pipe(
    ofType(DATA_FETCH),
    withLatestFrom(state$),
    mergeMap(
      ([
        {
          payload: { config, uri },
        },
      ]: [{ payload: IDataFetchActionProps }, any]) => {
        // Fetch the data, and then launch a DATA_SET action
        // which will put it into the store, and decide if there is more
        // data that needs to be fetched
        const archive = config?.params.get('archive') || 'default'
        return from(api.get(uri, config)).pipe(
          mergeMap((res) => {
            // Launch the DATA_SET action (epic is below)
            return of(dataSetAction({ results: res, archive }))
          }),
          catchError((error) => {
            return of(
              apiErrorAction(
                error.response && error.response.data && error.response.data
                  ? error.response.data
                  : error
              ),
              dataCompleteAction()
            )
          })
        )
      }
    )
  )

const dataSetEpic = (action$: any, state$: any) =>
  action$.pipe(
    // Set data in the redux store
    ofType(DATA_SET),
    withLatestFrom(state$),
    mergeMap(
      ([
        {
          payload: { results },
        },
      ]: [{ payload: IDataSetActionProps }, any]) => {
        return of(results).pipe(
          mergeMap((response) => {
            if (!response.data.nextHref) {
              // No more data to fetch
              return of(dataCompleteAction())
            }
            // Construct the URL based on the last response, and then launch another
            // DATA_FETCH action
            const url = new URL(response.data.nextHref)
            const pathname = url.pathname.split('/').pop() || '/data'
            const params = url.searchParams
            return response.data.nextHref
              ? of(dataFetchAction({ uri: '/' + pathname, config: { params } }))
              : of(dataCompleteAction())
          })
        )
      }
    ),
    catchError((error) =>
      of(
        apiErrorAction(
          error.response && error.response.data && error.response.data
            ? error.response.data
            : error
        ),
        dataCompleteAction()
      )
    )
  )

Does anyone have any experience with this, or recommendations?


text:
Q: how to give action buttons in MUIDataTable Trying with MUIDataTable using reactJS. I need to integrate an action column. In action need to place an edit and view button. Below is my code.
Each Row with 2 action button. Edit & View using react JS.
mui-datatables - {mui-datatables} Datatables for Material-UI
React Code:
/**
 * Data Table
 */
import React from "react";
import MUIDataTable from "mui-datatables";
import axios from "axios";
import CustomToolbarSelect from "./CustomToolbarSelect";

// rct card box
import RctCollapsibleCard from "Components/RctCollapsibleCard/RctCollapsibleCard";

// intl messages
import IntlMessages from "Util/IntlMessages";

class Report1 extends React.Component {
  constructor(props) {
    super(props);

    Report1.handleClick = Report1.handleClick.bind(this);
  }

  componentWillMount() {}

  /*
   * This function for handle your action button click event
   * if you add action button you can get your own key from array using below command
   * please add indexColumn key to options object.
   */
  static handleClick(e) {
    /* Your code is here.alert is the example */
    alert("parent td#id: " + e.target.parentNode.id);
  }

  state = {
    data: []
  };
  componentDidMount() {
    axios
      .get("API_URL", {
        headers: {
          Authorization: `Bearer ${localStorage.authToken}`
        }
      })
      .then(response => {
        /* USER data is received here ! */
        var resultsets = response.data.data.data;
        console.log(resultsets);
        var UsersArray = [];
        for (let i = 0; i < resultsets.length; i++) {
          var fullName =
            resultsets[i].first_name + " " + resultsets[i].last_name;
          var contactNum = resultsets[i].mobile_number;
          var email = resultsets[i].email;
          var lastName = resultsets[i].last_name;
          var userKey = resultsets[i].user_key;

          var UserArray = [];
          UserArray.push(fullName);
          UserArray.push(contactNum);
          UserArray.push(email);
          UserArray.push(lastName);
          UserArray.push(userKey);

          UsersArray.push(UserArray);
        }

        this.setState({
          data: UsersArray
        });
      })
      .catch(error => {
        // handle error
        console.log(error);
        if (error.response.status == 401) {
          alert("Authentication Error! Please login again");
        }
      });

    /* axios
                      .get("https://jsonblob.com/api/f8ccdc14-2b64-11e9-9b76-6fdc16537d21")
                      .then(response => {
                        this.setState({
                          data: response.data
                        });
                        console.log(response);
                      })
                      .catch(error => {
                        // handle error
                        console.log(error);
                      });*/
  }

  render() {
    const columns = [
      "Name",
      "Contact",
      "Email",
      "LastName",
      "User Key",
      "Action"
    ];
    //const action = <Button onClick={Report1.handleClick}>Action</Button>; /* <-- action button */
    const data = this.state.data;
    const options = {
      filterType: "dropdown",
      responsive: "stacked"

      /*  customToolbarSelect: (selectedRows) => <CustomToolbarSelect selectedRows={selectedRows} />*/
    };

    customRender: (index, value, updateValue) => {
      debugger;
      return (

          {value}

      );
    };
    return (

        <MUIDataTable
          title={"User Listing"}
          data={data}
          columns={columns}
          options={options}
        />

    );
  }
}

export default Report1;

Placing action buttons in each row, Thanks in Advance.

A: Add the below code next to:  var userKey = resultsets[i].user_key;
 var edit        =  <Button onClick={this.handleClick.bind(this,[user_id_title,username_title,firstname_title,lastName_title,email_title,firstname_title,mobile_title,userKey_title,cityname_show,createdon_title,dob_title,gender_title,lastupdateon_title,subcription_enabled_title])}>info</Button>;**

A: You need to use customBodyRender method in column options as below.
columns={["No", "Name", {
    label: "Actions",
    options: {
        customBodyRender: (value, tableMeta, updateValue) => {
            return (
                <button onClick={() => console.log(value, tableMeta) }>
                    Edit
                </button>
            )
        }
    }
}]}

You can refer to the documentation and the example.


text:
Q: Removing trailing characters after email address with Regex I am using regex to identify if a string is a valid email address or not. Pattern:
private static final String EMAIL_PATTERN =
    "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
    + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

The problem is that this regex pattern cannot correctly identify the email address if it contains a trailing character. e.g: "test@example.com." or "test@example.com,"
Do you know of a regex pattern that can take this into account?

A: Before the $ sign, use [.,]? or any other punctuation(inside that []) if you want to be there to overcome this.
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})[.,]?$";
                                                   ^^^^^


text:
Q: Overhead caused while fetching the required client in WAMP WS I have created a websocket server using the WAMP WS provided in python programming language.
I have a requirement where I am subscribing about 500 clients with the WAMP WS server at a time.
But when I am publishing the data I will send it only to a single client based on certain conditions. I know that it is very much simple to just loop throgh the list of cliets and find out the eligible and then send the data to that respective client.
I would like to know, is there any other way without using the loops, as using loops will lead to a large overhead if in case the required client is at the last position.

A: presumably you loop through each client's eligibility data and do some sort of decision based on that data.  it would follow that an index on the eligibility data would give you near instant access. so, using pseudo code, something like:
client_array = []
client_index = {}
client_array.add(new client)
if not new client.eligibility_data in client_index:
    client_index[new client.eligibility_data] = []
client_index[new client.eligibility_data].add(new client)

I don't know what the eligibility data is, but, say it is the weight of the client.  If you wanted to send a message to everybody that weighs between 200 and 205 points you could find those clients in the client_index[200] through [205].
if the condition cannot be determined before hand then you may need a database which can handle arbitrary queries to determine the client targets.

A: When doing a publish, you can provide a list of eligible receivers for the event via options, e.g. similar to this. The list of eligible receiver should be specified as a list of WAMP session IDs (which is the correct way to identify WAMP clients in this case).
Internally, AutobahnPython uses Python sets and set operations to compute the actual receivers - which is quite fast (and built into the language .. means native code runs).


text:
Q: Why is this form of acceptable, but the other form raises a type error? While working through Real World Haskell, I tried to complete the palindrome exercise using the following code solution:
palin :: [a] -> [a]
palin list = list ++ rev list
    where rev list
           | null list = []
           | otherwise = rev (tail list) ++ (head list)

Which raised a "cannot construct an infinite type error. However, simply replacing the parenthesis around the head list with square brackets, and it works correctly, as demonstrated in the following example:
palin :: [a] -> [a]
palin list = list ++ rev list
    where rev list
           | null list = []
           | otherwise = rev (tail list) ++ [head list]

I don't really understand why it matters, nor do I understand what does the "cannot construct infinite type a = [a]" error means. Could someone explain this?

A: ++ operator has type [a] -> [a] -> [a], i.e. it takes two lists of some type and produces another list of the same type. OTOH head function has type [a] -> a, i.e. it takes a list of some type and returns a value of that type. In your first example ++ got [a] on the left hand and a on the right hand. Trying to unify these types type checker produces that error. In the second example you've constructed a single-element list from the result of head and it has type [a], so type checker is happy.

A: In the last line, you are trying to append a non-list to a list. head list gives the first item of the list, which is type a. When you try to use ++ to append, you can't append something that isn't a list to a list. By appending [head list], you are appending a list of 1 item to the other list. The [] construct the single item list in this case.

A: Assume you are the type checker and you see a this:
(tail list) ++ (head list)

You know already, the `list is a list of something. So you start with:
list::[a]

then this must be true:
(tail list)::[a]

and this:
(head list)::a

But then there's `++ which wants both its arguments to have the same type. But this means, that
a == [a]

or by substitution:
a == [a] == [[a]] == [[[a]]] ...etc.

which is indeed an infinite type.


text:
Q: Epoll with edge triggered and oneshot only reports once I'm currently adding sockfds created from accept to an epoll instance with the following events:
const int EVENTS = (
    EPOLLET |
    EPOLLIN |
    EPOLLRDHUP |
    EPOLLONESHOT |
    EPOLLERR |
    EPOLLHUP);

Once an event is triggered, I pass it off to a handler thread, read and then re-enable the sockfd through epoll_ctl with the same flags. However, I only receive the EPOLLIN event one time. Also, if I kill the client anytime after the first event is received, I do not get hangup events either. From reading the man pages, I thought I understood the correct approach with EdgeTriggered and OneShot.
Below is some pseudo code for the process I'm using:
const int EVENTS = (
    EPOLLET |
    EPOLLIN |
    EPOLLRDHUP |
    EPOLLONESHOT |
    EPOLLERR |
    EPOLLHUP);

void event_loop()
{
    struct epoll_event event;
    struct epoll_event *events;
    events = calloc(100, sizeof event);
    while (1)
    {
        int x;
        int num_events = epoll_wait(epfd, events, 100, -1);
        for (x = 0; x < num_events; x++)
        {
            another_thread(fd);
        }
    }
}

void another_thread(int fd)
{
    // Read stuff until EAGAIN

    struct epoll_event event;
    event.data.fd = fd;
    event.events = EVENTS;
    epoll_ctl(epfd, EPOLL_CTL_MOD, fd, &event);
}

When I do the EPOLL_CTL_MOD operation, I do not receive any errors, but never get notified of other events. If I leave the read loop on repeat after the first event, it will read all subsequent data sent by client, so I know that the data is coming in and the fd is still open and working.
From checking strace, threads are created from clone and have the flag CLONE_FILES, so all threads share the same fd table.
What is the correct way to re-enable a fd for read events from a separate thread?

A:
However, I only receive the EPOLLIN event one time. Also, if I kill the client anytime after the first event is received, I do not get hangup events either.

man page for epoll_ctl(2) says that:

EPOLLONESHOT (since Linux 2.6.2)
                  Sets the one-shot behavior for the associated file descriptor.
                  This means that after an event is pulled out with
                  epoll_wait(2) the associated file descriptor is internally
                  disabled and no other events will be reported by the epoll
                  interface.  The user must call epoll_ctl() with EPOLL_CTL_MOD
                  to rearm the file descriptor with a new event mask.

In your case, when you get the first event, epoll disables your sockfd.
When you re-enable your sockfd using EPOLL_CTL_MOD, it will notify all the events that are received by kernel after the re-registration. So any event between first notification and re-registration will be lost. This can be reason for not getting any hangup events or data.
Removing EPOLLONESHOT from events will correct your code, eventually you don't need to re-enable sockfd also.
And since you are using EPOLLET, there won't be any performance issue also.


text:
Q: Enumerate over list of integers and access list value by index I'm trying to solve a LeetCode problem and am not sure why what I have done does not work.  Moreso than simply getting a working solution, I am trying to figure out why this approach does not work.  The error that I am getting is:
TypeError: 'int' object is not subscriptable
    if value[0] == 0:
Line 22 in intToRoman (Solution.py)
    ret = Solution().intToRoman(param_1)
Line 123 in _driver (Solution.py)
    _driver()
Line 134 in <module> (Solution.py)

So, it seems to be complaining about the section where I enumerate my list and try to access the value of the index.  Here is my code:
class Solution:
    def intToRoman(self, num: int) -> str:

        answer = ""

        # Calculate length of num
        num = str(num)
        numLength = len(num)

        # Convert num to list of individual digits and reverse
        numArray = [int(digit) for digit in num]
        numArray.reverse()

        # Build Roman Numeral
        firstDigit = ""
        secondDigit = ""
        thirdDigit = ""
        fourthDigit = ""

        for count, value in enumerate(numArray):
            if numLength >= 1:
                if value[0] == 0:
                    firstDigit = None
                if value[0] == 1:
                    firstDigit = "I"
                if value[0] == 2:
                    firstDigit = "II"
                if value[0] == 3:
                    firstDigit = "III"
                if value[0] == 4:
                    firstDigit = "IV"
                if value[0] == 5:
                    firstDigit = "V"
                if value[0] == 6:
                    firstDigit = "VI"
                if value[0] == 7:
                    firstDigit = "VII"
                if value[0] == 8:
                    firstDigit = "VIII"
                if value[0] == 9:
                    firstDigit = "IX"
            if numLength >= 2:
                if value[1] == 0:
                    secondDigit = None
                if value[1] == 1:
                    secondDigit = "X"
                if value[1] == 2:
                    secondDigit = "XX"
                if value[1] == 3:
                    secondDigit = "XXX"
                if value[1] == 4:
                    secondDigit = "XL"
                if value[1] == 5:
                    secondDigit = "L"
                if value[1] == 6:
                    secondDigit = "LX"
                if value[1] == 7:
                    secondDigit = "LXX"
                if value[1] == 8:
                    secondDigit = "LXXX"
                if value[1] == 9:
                    secondDigit = "XC"
            if numLength >= 3:
                if value[2] == 0:
                    thirdDigit = None
                if value[2] == 1:
                    thirdDigit = "C"
                if value[2] == 2:
                    thirdDigit = "CC"
                if value[2] == 3:
                    thirdDigit = "CCC"
                if value[2] == 4:
                    thirdDigit = "CD"
                if value[2] == 5:
                    thirdDigit = "D"
                if value[2] == 6:
                    thirdDigit = "DC"
                if value[2] == 7:
                    thirdDigit = "DCC"
                if value[2] == 8:
                    thirdDigit = "DCCC"
                if value[2] == 9:
                    thirdDigit = "CM"
            if numLength == 4:
                if value[3] == 0:
                    fourthDigit = None
                if value[3] == 1:
                    fourthDigit = "M"
                if value[3] == 2:
                    fourthDigit = "MM"
                if value[3] == 3:
                    fourthDigit = "MMM"
                answer = (fourthDigit + thirdDigit + secondDigit + firstDigit)

        if numLength == 3:
            answer = (thirdDigit + secondDigit + firstDigit)

        if numLength == 2:
            answer = (secondDigit + firstDigit)

        if numLength == 1:
            answer = (firstDigit)

        return(answer)

The LeetCode problem is:
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000
For example, 2 is written as II in Roman numeral, just two one's added together. 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given an integer, convert it to a roman numeral.

Any comments about my general approach to solving the problem are welcome as well.
Note regarding the question being closed as duplicate -- none of the linked articles deal with Python enumerate() or answer my question, as far as I can tell.


text:
Q: What does "more flapper than sage; more purse than flag" mean?
Persiflage refers to the sort of light banter one just breezes through, breezy talk to shoot the breeze, mere raillery: more flapper than sage; more purse than flag; a trifle, a siffle, mere piffle.

I've been trying to decode the meaning of the phrase "more flapper than sage; more purse than flag' for about a day now. I bumped into this expression here . Please help me figure this out.

A: "More [x] than [y]" is an idiomatic way of saying that something more closely resembles one thing than another. It doesn't mean that the subject is not [x], just that it should perhaps be considered to be closer to [y].
For example, if someone said they were cooking a stew, but the consistency of it was more liquid than solid, you might say "it's more of a soup than a stew". You're not saying that it isn't a stew, or that it is a soup - just that it has perhaps turned out more like a soup than intended.
The text you quote comes from a piece about the definition of persiflage, which means "light banter". The two statements you are asking about are made to try and help define what that means.
A "flapper" is an old-fashioned word (possibly 1920s) for a party-goer. A "sage" is a wise person. I believe "more flapper than sage" is saying that "persiflage" or "light banter" means talking about trivial matters, not serious matters.
Likewise, a "purse" is something carried for fashion, a "flag" is something carried to represent national politics. Again, I believe "more purse than flag" means that light banter is more likely to be about trivial things like fashion than about serious matters like politics.
I can't be 100% certain these are the intended definitions and comparisons of those 4 words, but I do feel confident that this is the intended meaning in the context of the article.


text:
Q: decodeURI decodes space as + symbol I have created a Google Custom Search. The logic is when a user search, the page will display result and the title of the page will be changed to the search term using javascript. I use decodeURI to decode the unicode characters. But the space is decode as +. For example if  I search money making it will be decoded as money+making and it is displayed as title. Someone please help to solve this. I want to display space instead of the symbol +.
The code is
 if (query != null){document.title = decodeURI(query)+" | Tamil Search";}</script>

A: You can use replace function for this:
decodeURI(query).replace( /\+/g, ' ' )

A: The Google Closure Library provides  its own urlDecode function for just this reason. You can either use the library or below is the open source solution for how they solve it.
/**
 * URL-decodes the string. We need to specially handle '+'s because
 * the javascript library doesn't convert them to spaces.
 * @param {string} str The string to url decode.
 * @return {string} The decoded {@code str}.
 */
goog.string.urlDecode = function(str) {
  return decodeURIComponent(str.replace(/\+/g, ' '));
};


text:
Q: Lim sup sequence Let $(a_n)$ be a sequence of numbers. Show: If $(a_n)$ converges, than:
$\lim\limits \sup a_n= \lim\limits_{n \rightarrow \infty} a_n $
I can feel this is true intuitively, but I have no idea how to do formal proofs with lim sup as I've never really worked with the concept before. Can anyone give a helping hand?
Edit: Some more information:
The definition we've been thaught is that the lim sup is equal to sup V if the squence has an upperbound, with V being the set of all the limit points of the sequence. If the sequence has no upperbound lim sup is +infinity, and if the sequence has an upperbound but V is empty lim sup is -infinity.
So what I thought was if (An) converges than it must only have 1 limit point:lim (An). Therefor lim sup (An) must be equal to lim(An), because V only has 1 element. But I have no idea how to write this formally...

A: Hint:
Lemma: If a sequence converges (in the wide sense of the word) then any subsequence also converges and to the same limit.
Proof: In the finite limit case (the infinite limit case is left as an exercise):
$$\lim_{n\to\infty}a_n=L\implies \forall\,\epsilon>0\;\exists\,N_\epsilon\in\Bbb N\;\;s.t.\;\;n>N_\epsilon\implies|a_n-L|<\epsilon$$
Let now $\;\{a_{n_k}\}\subset\{a_n\}\;$ be a subsequence of our sequence. Remember that this means $\;n_1<n_2<\ldots\;$ . Thus, let $\;m\in\Bbb N\;$ be such that $\;n_m>N_\epsilon\;\implies\;n_k>N_\epsilon\;\;\forall\;k>m\;$ , so
$$\forall\;k>m\;\;:\;\;|a_{n_k}-L|<\epsilon \;\iff\;\;\lim_{k\to\infty}a_{n_k}=L\;\;\;\;\;\;\;\;\;\;\;\;\square$$


text:
Q: Solr-Atomic Update changes other fields While running on atomic update,language field is getting changed.We have flow as below.
During indexing object posted is
{
id:"234-567",
fileName:"file1",
content:""
}
In the pipeline we analyse content as part of language detection and create a new field "language" which is working as expected.
But while doing atomic update
{
id:"as above"
fileName:"changed"
}
to change fileName,we make use to "set" operation which is updating field correctly but language field is getting changed to fallback value.
What is happening here?Is it looking for content field to analysis again?Does atomic update also goes through processing pipeline

A: I'm guessing the language detection is run again, and there is no value available for that field for the language detection to actually detect anything for.
Run updates without language detection unless you're including the field you're running language detection on.
You might have to define a second request handler without the language detection settings if you have those defined as static settings in your request handler configuration.


text:
Q: How to initialize List inside Object using Spring Annotation How do I initialize List inside Object using Spring Annotation
@Component
class Accounts{
   private List<Transaction> _transaction;
   //getter setter
}

How do I initialize List<Transaction> _transaction; using Spring Annotation or else i
   have to define it in xml file.
But i dont want to write any xml file

A: You can use the Spring Java @Configuration for such a task:
@Configuration
public class SpringConfig {
    @Bean
    public List<Transaction> transactions() {
        ...... //Your logic to generate the list..
        return transactions;
    }
}

And in your Accounts class you have to use @Resource, not @Autowired, the semantics of injecting a list is a little different - if you use @Autowired, any bean of the same type will get injected into the list.
@Component
class Accounts{
   @Resource(name="transactions")
   private List<Transaction> _transaction;
   //getter setter
}

This is pure java solution and there is no xml involved in creating the list..

A: If Transaction is a Bean with @Service, @Component or @Repository Annotation, you can just write @Autowired on top of your field.
@Component
class Accounts{

   @Autowired
   private List<Transaction> _transaction;
   //getter setter
}


text:
Q: onClick javascript function shows only first child of wrapper I am learning javascript these days and I have a little problem with my code.
I have three elements on page wrapper1, wrapper2 and wrapper3 and every of these has its triggerand redbox element.
My goal is when the trigger is hit, it will show the redbox element corresponding to number.
Examples:
clicking trigger1 inside wrapper1 element shows up redbox1 element,
trigger2 inside wrapper2 element shows up redbox2 element etc.
The problem is, when I click on trigger3 for example it always shows redbox1 element. (as example shows).
What I am doing wrong? I am just a begginer.

function showTheRedBox() {
  var theRedBox = document.getElementsByClassName('redbox');
  theRedBox[0].style.display = 'block';
}
body {background: #222;}
.wrapper {
  background: yellow;
  width: 100px;
  height: 100px;
}
.trigger {
  background: blue;
  width: 50px;
  height: 50px;
  position: absolute;
  margin-top: 50px;
  margin-left: 50px;
}
.redbox {
  background: red;
  width: 200px;
  height: 100px;
  margin-left: 100px;
  position: absolute;
  display: none;
}

trigger1

hurrah1

wrapper1

trigger2

hurrah2

wrapper2

trigger3

hurrah3

wrapper3

A: You can use a for loop and a closure to access the .wrapper information for each onclick event. This method will work whether there are the same amount of children or not, and will always show the correct child.
Also, it is best to not use inline JavaScript attributes (e.g.  onclick="showTheRedBox();") you should always assign your event handlers in your script for readability and maintainability.
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');

for(i = wrappers.length - 1; i >= 0; --i) {
  (function(wrapper){
    wrapper.querySelector('.trigger').onclick = function() {
      hideAll();
      wrapper.querySelector('.redbox').style.display = 'block';
    }
  })(wrappers[i]);
}

function hideAll() {
  for(i = redboxes.length - 1; i >= 0; --i) {
    redboxes[i].style.display = 'none';
  }
}

var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');

for(i = wrappers.length - 1; i >= 0; --i) {
  (function(wrapper){
    wrapper.querySelector('.trigger').onclick = function() {
      hideAll();
      wrapper.querySelector('.redbox').style.display = 'block';
    }
  })(wrappers[i]);
}

function hideAll() {
  for(i = redboxes.length - 1; i >= 0; --i) {
    redboxes[i].style.display = 'none';
  }
}
body {background: #222;}
.wrapper {
  background: yellow;
  width: 100px;
  height: 100px;
}
.trigger {
  background: blue;
  width: 50px;
  height: 50px;
  position: absolute;
  margin-top: 50px;
  margin-left: 50px;
}
.redbox {
  background: red;
  width: 200px;
  height: 100px;
  margin-left: 100px;
  position: absolute;
  display: none;
}

trigger1

hurrah1

wrapper1

trigger2

hurrah2

wrapper2

trigger3

hurrah3

wrapper3

This method will also work, but it will use more memory as it queries the DOM once more than the above solution.
var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');

for(i = wrappers.length - 1; i >= 0; --i) {
  wrappers[i].querySelector('.trigger').onclick = function() {
    hideAll();
    this.parentNode.querySelector('.redbox').style.display = 'block';
  }
}

function hideAll() {
  for(i = redboxes.length - 1; i >= 0; --i) {
    redboxes[i].style.display = 'none';
  }
}

var wrappers = document.querySelectorAll('.wrapper'), i;
var redboxes = document.querySelectorAll('.redbox');

for(i = wrappers.length - 1; i >= 0; --i) {
  wrappers[i].querySelector('.trigger').onclick = function() {
    hideAll();
    this.parentNode.querySelector('.redbox').style.display = 'block';
  }
}

function hideAll() {
  for(i = redboxes.length - 1; i >= 0; --i) {
    redboxes[i].style.display = 'none';
  }
}
body {background: #222;}
.wrapper {
  background: yellow;
  width: 100px;
  height: 100px;
}
.trigger {
  background: blue;
  width: 50px;
  height: 50px;
  position: absolute;
  margin-top: 50px;
  margin-left: 50px;
}
.redbox {
  background: red;
  width: 200px;
  height: 100px;
  margin-left: 100px;
  position: absolute;
  display: none;
}

trigger1

hurrah1

wrapper1

trigger2

hurrah2

wrapper2

trigger3

hurrah3

wrapper3

A: The problem you have was that the method "getElementsByClassName", returns you an Array that contains all the elements of that class. So, when you where doing this:
theRedBox[0].style.display = 'block'

You were changing the display style of the First element of the Array, in this case "wrapper1".
Here's a modify version that functions whit the others wrappers:
<!DOCTYPE html>

        <title> MY TEST </title>

trigger1

hurrah1

        wrapper1

trigger2

hurrah2

        wrapper2

trigger3

hurrah3

        wrapper3