text:
Q: Laravel Eloquent builder - combining groupBy and orderBy I have a Laravel application, and I have a query that is supposed to function as follows. The aim is to get the best selling item by the total quantity_purchased.
item item_id   date      quantity_purchased
rice | 14  | 2019-03-23 | 3
chicken | 6 | 2019-03-23 | 2
chicken | 6| 2019-03-20 | 3
corn | 2 | 2019-02-10 | 1
rice | 14 | 2019-03-04 | 5
rice | 14 | 2017-02-10 | 2

The aim is to get the best selling item by the quantity_purchased.  It needs to group item by the item_id, then sum the quantity_purchased for that item and order the grouped Items by the total quantity_purchased. In the example above, this should return
item   total_quantity_purchased
rice | 10
chicken | 5
corn | 1

I have tried to accomplish this using the eloquent query below:
    return self::where('isRefundedCompletely', false)
     ->get()
     ->groupBy('item_id')->orderBy(function($item) {return $item->sum('qty_purchased');}, 'DESC');

but i got this error:

Illuminate\Database\Eloquent\Collection::orderBy does not exist.

Can you explain to me how to effectively resolve this issue, with a different approach, but without resorting to a raw query?

A: I'll just put this here. For reference purposes.
return self::select(DB::raw('item,sum(quantity_purchased) as total_quantity_purchase'))
        ->where('isRefundedCompletely',false)
        ->groupBy('item_id')
        ->orderBy('quantity_purchase','DESC')
        ->get();


text:
Q: asp.net regular expression validator for email or numeric Is it possible use a regular expression validator for a textbox which accepts either user email or phone number (11 digits number which begins with 09) ?
so one regex is needed which accepts one of two cases, email or number.

A: For Email : "\w+([-+.']\w+)@\w+([-.]\w+).\w+([-.]\w+)*"
[0][9][0-9]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Class hierarchy in templated types in C++ I am working on a simple project where there are publishers who read from one data source and construct events for subscribers to work on.
An event will have a unique ptr to the data and the subscribers will have a shared ptr to the event.
I want to have a common interface to an event so a subscriber can subscribe to an arbitrary Data publisher.
But a publisher can publish only one type of Data.
#include <memory>
#include <iostream>

class Data
{

};

class ChildData : public Data
{
};

template<typename T>
class Event
{
    std::unique_ptr<T> _data;
};

void someFunc(Event<Data> event)
{
    std::cout << "hello Word" << std::endl;
}

int main()
{
    Event<ChildData> event();
    someFunc(event);
    return 0;
}

but am getting the following compiler error
/home/rory/dev/cpp_sandbox/main.cpp: In function 'int main()':
/home/rory/dev/cpp_sandbox/main.cpp:27:19: error: could not convert 'event' from 'Event<ChildData> (*)()' to 'Event<Data>'
     someFunc(event);
                   ^
CMakeFiles/example.dir/build.make:62: recipe for target 'CMakeFiles/example.dir/main.cpp.o' failed
make[2]: *** [CMakeFiles/example.dir/main.cpp.o] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/example.dir/all' failed
make[1]: *** [CMakeFiles/example.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

Is this sort of thing possible in C++?

A: The problematic line is this:
Event<ChildData> event();

Per the most vexing parse rule, this is interpreted as a function declaration. You can omit the parenthesis, if your Event class has a default constructor that initializes all members. Otherwise use uniform initialization syntax:
Event<ChildData> event{};

Also, you will likely have to use std::move to pass event to someFunc, since Event is not copyable because of the std::unique_ptr data member. Also, you will have to implement conversion from Event<ChildData> to Event<Data>, which is required for someFunc.

I want to have a common interface to an event so a subscriber can subscribe to an arbitrary Data publisher. But a publisher can publish only one type of Data.

From this description, it looks like the Event template is superfluous. The common interface for Data descendants can be described in the Data class itself, so unless there is some need to separate event from data, it would be easier to deal just with data.
In order to discriminate different event types, you can use an enum.
enum class EventType
{
    A,
    B,
    C
};

class Data
{
private:
    const EventType m_type;

protected:
    explicit Data(EventType type) : m_type(type) {}

public:
    virtual ~Data() = default;

    // Prohibit copying to avoid accidental slicing
    Data(Data const&) = delete;
    Data& opreator= (Data const&) = delete;

    EventType get_type() const { return m_type; }
};

class ChildData :
    public Data
{
public:
    ChildData() : Data(EventType::A) {}
};

void receive(std::unique_ptr< Data > event)
{
    switch (event->get_type())
    {
    case EventType::A:
        {
            std::unique_ptr< ChildData > child_event{ static_cast< ChildData* >(event.release()) };
            // Process ChildData
        }
        break;

    case EventType::B:
        // ...
    case EventType::C:
        // ...
    }
}

void publish(std::unique_ptr< Data > event);

int main()
{
    std::unique_ptr< ChildData > event{ new ChildData() };
    // Fill ChildData event
    publish(std::move(event));
}


text:
Q: How to center DIV on the middle of the page I've been trying so many different ways on trying to center the ingredients with the middle of the page and it just hasn't been working out. When I add text-align: Center; to the "Ingredients" class, the ingredients do move towards the middle but they aren't aligned with each other, if that makes sense. Any way I can center the ingredients and have them aligned? An example of what happens when I use text-align: center; is below. Also, I am a novice on programming lol, just slowly learning through The Odin Project. Thank you.
HTML:

        <input type="checkbox" name="ingredients" id="sausage" value="sausage">
        1 pound sweet italian sausage

CSS:
.ingredients{
    font-size: 14px;
    line-height: 30px;
}

CSS
Screenshot of page
Example of text-align
HTML

A: Use flexbox for this.

.ingredients{
    font-size: 14px;
    line-height: 30px;
}

.border{
   display:flex;
   justify-content:center;
   align-items:center;
   height:100vh;

   }

   body, html{
   margin:0;
   padding:0;
   }

        <input type="checkbox" name="ingredients" id="sausage" value="sausage">
        1 pound sweet italian sausage

A: using CSS GRID

as you can see I tried to use multiple inputs, from the smaller text to the bigger text,  so they will be working fine on a Real-Scenario of your project (also with different lenghts).
so by using a grid layout they will be responsive with the minimum code needed!
grid-template-columns: auto 1fr; /* for making the inputs aligned one under the other */
place-items: center start;       /* for solving the bug about the positioning of text (label)*/

useful documentations:
- CSS grid: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout
- grid-template-columns https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns
- place-items: https://developer.mozilla.org/en-US/docs/Web/CSS/place-items
- gap: https://developer.mozilla.org/en-US/docs/Web/CSS/gap

the code used in the image of before:

.border {
    /* parent container, for centering the child */
    display: grid;
    place-items: center;
}

.ingredients {
    font-size: 14px;
    line-height: 30px;
    /* using grid layout */
    display: grid;
    /* all the child always have the same space (the bigger element width) */
    grid-template-columns: auto 1fr;
    /* centering the text vertically, but is in the start one under the other */
    place-items: center start;
    /* a gap between the input and the text */
    gap: 0 1rem;
}

            <input type="checkbox" name="ingredients" id="sausage" value="sausage">
            1

            <input type="checkbox" name="ingredients" id="sausage" value="sausage">
            1 pound

            <input type="checkbox" name="ingredients" id="sausage" value="sausage">
            1 pound sweet

            <input type="checkbox" name="ingredients" id="sausage" value="sausage">
            1 pound sweet italian

            <input type="checkbox" name="ingredients" id="sausage" value="sausage">
            1 pound sweet italian sausage


text:
Q: IntelliJ is not able to recognize behave run options in feature file [behave python BDD library] 1. Intellij is not able to recognize the Run options in the feature file, while able to run the file using the command-line tool.
getting Nothing here.

2. There is even no option in the right-click menu

3. Steps are identified as not implemented while steps are implemented and executing successfully with behave CLI tool

A: It is not ideal, since as you say the ideal is to have the appropriate version of IntelliJ. However, a workaround that has saved me in these situations is to select the step I want to go to and use Ctrl+Shift+F to search in the whole project the place where the method is declared.
This command is also useful to know in which Scenarios a certain step is used, because even if you have the Professional version of IntelliJ it only allows you to access from the Scenario to the Step and not the other way around.


text:
Q: Powershell Get-ChildItem Check file name not working What I want to do is look for particular files in a folder, then check the name of each file that macthes and drop it in another folder. Here is a sample of what I'm trying to do:
$FileABackupLoc = "C:\FolderA"
$FileBBackupLoc = "C:\FolderB"

Get-ChildItem -Path $SourceFolder -Include *Membership*.pgp -Name -Recurse |
%{

    Write-Host "Current file: $_"

    if($_ -like '*FileA*')
    {
        [System.IO.FileInfo]$FileADestination = (Join-Path -Path $FileABackupLoc -ChildPath $_.Name.replace("_","\"))
    move-item -Path $_.FullName -Destination $FileADestination.FullName -Verbose
   }

    if($_ -like '*FileB*')
    {
        [System.IO.FileInfo]$FileBDestination = (Join-Path -Path $FileBBackupLoc -ChildPath $_.Name.replace("_","\"))
    move-item -Path $_.FullName -Destination $FileBDestination.FullName -Verbose
   }

}

When I run the code, I get this error but have no idea why:
You cannot call a method on a null-valued expression.

A: Maybe try this:
Get-ChildItem -Path $SourceFolder -Include *Membership*.pgp -Recurse | % {

if ($_ -like '.*FileA.*')
{
  $FileADestination = Join-Path -Path $FileBBackupLoc -ChildPath (Split-Path -Leaf -Path $_.FullName)
  Move-Item -Path $_.FullName -Destination $FileADestination
}
...

I believe your use of the -Name argument in the original Get-ChildItem may be getting in your way here, from the docs:

-Name
Gets only the names of the items in the locations. If you pipe the output of this command to another command, only the item names are sent.


text:
Q: Xcode, Parse Crash Reporting, dSYM file not created I have an iOS app, written in Swift in Xcode 6.2, using the Parse SDK 1.7.0. I've gone through the Parse Quick Start instructions for setting up crash reporting (including ParseCrashReporting.enable() in the AppDelegate), but it seems that my run script is having an issue. The error is: App "/Users/ben/Library/Developer/Xcode/DerivedData/MyApp-ahydphsjgdgefbhcdodokcmofehe/Build/Products/Debug-iphonesimulator/MyApp.app.dSYM" wasn't found. Command /bin/sh failed with exit code 1.
According to this, it seems that Xcode is not creating the dSYM file. In my Build Settings > Build Options I have changed Debug Information Format to "DWARF with dSYM file" for both Debug and Release. (Previously, Debug was set to "DWARF")
Should I change anything else in the Build Options?
Also, could this be the issue? export DWARF_DSYM_FILE_SHOULD_ACCOMPANY_PRODUCT=NO
Here is my run script:
export PATH=/usr/local/bin:$PATH
cd $PROJECT_DIR/parse

parse symbols "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}"

Thank you in advance for any ideas about how to fix this.
Edit: Thanks to the answer from @udjat, I was able to run my app and run script (below) without the app crashing. And thanks to some bug fixes from Parse, the test crash reports are functioning now as well, though there is still a significant delay.
New run script:
echo "Parse Crash Reporting"
export PATH=/usr/local/bin:$PATH
CLOUD_CODE_DIR=${PROJECT_DIR}/parse

if [ -d ${CLOUD_CODE_DIR} ]; then
cd ${CLOUD_CODE_DIR}
parse symbols MyApp --path="${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}"
echo "Finished uploading symbol"
else
echo "Unable to upload symbols"
fi

Crash test in AppDelegate:
func crash() {
    NSException(name:NSGenericException, reason:"Everything is ok. This is just a test crash.", userInfo:nil).raise()
}

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {

    ParseCrashReporting.enable()

    dispatch_after(
        dispatch_time(DISPATCH_TIME_NOW, Int64(5.0 * Double(NSEC_PER_SEC))),
        dispatch_get_main_queue(),
        { () -> Void in
            self.crash()
    });
}

A: After reading through the Facebook link @jairobjunior posted, I found the fix (at least for myself) in Árni Jón Reginsson's answer and modified a bit.
In the Parse document, your run script is:
export PATH=/usr/local/bin:$PATH
cd YOUR_PATH
parse symbols "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}"

Instead, change it to:
echo "Parse Crash Reporting"
export PATH=/usr/local/bin:$PATH
CLOUD_CODE_DIR=${PROJECT_DIR}/ParseCloudCode(or wherever yours is)

if [ -d ${CLOUD_CODE_DIR} ]; then
    cd ${CLOUD_CODE_DIR}
    parse symbols YOUR_PARSE_APP_NAME --path="${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}"
    echo "Finished uploading symbol"
else
    echo "Unable to upload symbols"
fi

And it takes a lot more than "up to one minute" for your crash reports to show up on Parse (took me more than 15 minutes). If it finished uploading, it will be there, you just need to be patient.

A: There is an open thread about this issue here: https://developers.facebook.com/bugs/587774604658221/
I am having the same problem, even trying to do manually it says file "wasn't found", but the file is there. One thing that I've noticed is that .dSYM is not a file, for me it seems to be a folder/package.

A: I found this to work..
export PATH=/usr/local/bin:$PATH
cd YOUR_PATH
parse symbols AppName -p "${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}"

Adding the app name and the -p to the parse line

A: Sorry I don't have the reputation to comment so I'll leave this as an answer.
I got the exact problem. Also using the latest Parse SDK. It is suspected that it is the problem of the latest CLI 2.0.0 since developers start getting the issues you're getting (and also I'm getting) after updating to 2.0.0
Subscribe to this Facebook bug reporting post to get the solution in the future.
https://developers.facebook.com/bugs/466020460223551/
At this moment it seems like the problem is from the SDK. So there is nothing to do except waiting for Parse to fix this.
(Thanks @jairobjunior for introducing me the Facebook bug reporting page!)

A: just wanted to let you know you're not alone: although my DSYM seems to upload fine, no crash reports from any of my apps ever show up on parse.com, no matter what I do. I've spent an hour checking every setting... all looks good. I use the same test crash as you do...
So, please update here if you find a solution to crashes not showing up on parse.com. thanks!

A: In my case the problem was probably create by changing the project name, anyway using the following script made it :
parse symbols MyAppName --path="${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}"

Where MyAppName is was what I found in the parse/config file :
{
    "applications": {
        "MyAppName": {
            "applicationId": "....kjsldgjslkgjslkgj...",
            "masterKey": "....lksjmll242dg2d1g2..."
        },
        "_default": {
            "link": "MyAppName"
        }
    }
}


text:
Q: SQL SERVER (ON inner join) how to join two table one having multiple values separates by commas in one column and with other  column having single value.......like
1st table                                2nd table

name       course                       course name    course id
Tanisha     1,2,3                        Cisco             1
Ellen        3,4,5                        c++               2
honesty     4,2,1                       server            3
                                        java              4
                                        dot net           5

A: You can join the tables using like:
select *
from table1 t1 join
     table2 t2
     on ',' + t1.course + ',' like '%,'' + cast(t2.courseid as varchar(255)) + ',%';

In practice, this is a horrid data structure.  It stores numerical ids in a string field.  It stores lists in a comma delimited field.  The engine cannot take advantage of indexes for a basic query, such as the one above.  Relational databases have a great data structure for lists; it is called a table.  In this case the table would be a junction table.
Sometimes, you have to live with data formats that others have created.  If you cannot restructure the data, sometimes SQL is powerful enough to still let you accomplish what you need to do.


text:
Q: MVC App Deployed to Azure - Do I have to use SQL Server Azure I am completely new to Microsoft Azure. I have just about completed an MVC 5 application that uses SQL Server 2012. I'd ilke to deploy my app to Azure but have it hit a SQL Server 2012 database that is hosted someone else (another commercial web host). Is this possible, or do I have to use SQL Azure for my app?

A: Yes you can use another vendor but you'll have to check if they allow outside traffic in (usually on port 1433).  Even if they allow this, you'll have to think about the possible latency issue caused by such an architecture.


text:
Q: Adding an extra index to Pandas DataFrame I have a list of DataFrame, which is read something like this
data = [pd.read_csv(f, index_col=None, header=None) for f in temp]
flow = pd.DataFrame(data)

If I print the flow I get an output of
[[....
[128 rows x 14 columns]]
[128 rows x 14 columns]]
.
.
[128 rows x 14 columns]]]

So this means that each of the [128 rows x 14 columns] has one index, I have 60 as such. What I wanted to do was to read another CSV file which contains one column of data (60 rows) which looks something like this
[1 1 1 ... 2 2 2 ... 3 3 3]

I can read this by doing
new_data=pd.read_csv(f_new, index_col=None, header=None)

Now my question is can I keep everything as it is and just add the new_data as extra index, which should show something like this:
[[....
0 1 [128 rows x 14 columns]]
1 1 [128 rows x 14 columns]]
2 1 .
3 2 .
4 2 [128 rows x 14 columns]]]

Is this possible?

A: Try this:
flow = flow.set_index([flow.index, new_data]).rename_axis(['idx_col1','idx_col2'])


text:
Q: Replacing cursor with set based query I want to find count of set of tables. The table names are values in another table.
--like
      select count(*) from tablename

--tablename is obtained from
      select tablename from table1

--table1 has around 171 tablenames
I was using cursor to get each table name and select count for each, but it is taking time. Can you please help how to replace cursor code with set based solution?
Below is my cursor code
SET NOCOUNT ON;

if( OBJECT_ID('tempdb..#temptablenew') IS NOT NULL )
BEGIN
DROP table #temptablenew
END

select * into #temptablenew from table1

declare @srccount int
declare @tablename nvarchar(max);

declare @q2 nvarchar(max);

declare  @id int;

declare my_cursor cursor
local static read_only forward_only

for

select id,tablename from #temptablenew

open my_cursor
fetch next from my_cursor
into @id,@tablename
while @@fetch_status = 0
begin

  set @q2 =N'select @srccount= count(*) from '+@tablename+' with (nolock)';

  execute sp_executesql @q2,@PARAMS = N'@srccount INT OUTPUT',
      @srccount = @srccount OUTPUT

  select  @srccount,@id,@tablename

  fetch next from my_cursor
  into @id,@tablename
  end
  close my_cursor;
  deallocate my_cursor;

Thanks in advance

A: Try this,
SET NOCOUNT ON;

declare @q2 nvarchar(max) = '';

SELECT @q2 = @q2 + 'SELECT COUNT(*) AS cnt, ''' + tablename  + ''' AS TableName FROM ' + tablename  + ' (NOLOCK); '
FROM table1

--Print @q2
execute sp_executesql @q2


text:
Q: OpenGL single channel viability to multiple channel When I rasterize out a font, my code gives me a single channel of visability for a texture. Currently, I just duplicate this out to 4 different channels, and send that as a texture. Now this works, but I want to try and avoid unnecessary memory allocations and de-alocations on the cpu.
unsigned char *bitmap = new unsigned char[width*height] //How this is populated is not the point.

bitmap, now contains a 2d graphic.
It seems this guy also has the same problem: Opengl: Use single channel texture as alpha channel to display text

I do the same thing as a work around for now, where I just multiply the array size by 4 and copy the data into it 4 times.
unsigned char* colormap = new unsigned char[width * height * 4];
        int offset = 0;
        for (int d = 0; d < width * height;d++)
        {
            for (int i = 0;i < 4;i++)
            {
                colormap[offset++] = bitmap[d];
            }
        }

WHen I multiply it out, I use:
glTexParameteri(gltype, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(gltype, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(gltype, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, colormap);

And get:

Which is what I want.
When i use only the single channel:
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(gltype, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(gltype, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, width, height, 0, GL_RED, GL_UNSIGNED_BYTE, bitmap);

And Get:

It has no transparency, only red ext. makes it hard to colorize and ext. later.
Instead of having to do what I feel is a unnecessary allocations on the cpu side id like the tell OpenGL: "Hey your getting just one channel. multiply it out for all 4 color channels."
Is there a command for that?

A: In your shader, it's trivial enough to just broadcast the r component to all four channels:
vec4 vals = texture(tex, coords).rrrr;

If you don't want to modify your shader (perhaps because you need to use the same shader for 4-channel textures too), then you can apply a texture swizzle mask to the texture:
GLint swizzleMask[] = {GL_RED, GL_RED, GL_RED, GL_RED};
glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask);

When mechanisms read from the fourth component of the texture, they'll get the value defined by the red component of that texture.


text:
Q: How do I implement nested routing in react properly I'm going crazy here since two days. Guys please help. I'm trying to implement nested routing. But its not working. When I go to http://localhost:3000 it displays correctly. But when I go to http://localhost:3000/contact.  It doesn't work. I've tried all I can.  Please help
//App js
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Main from './features/Main/Main';
import Dashboard from './features/Dashboard/Dashboard';
import Nomatch from './features/Nomatch';

function App() {

    return (

            <Switch>
                <Route exact path='/'> <Redirect to='/home' /></Route>
                <Route path="/home" component={Main} />
                <Route path="/dashboard" component={Dashboard} />
                <Route component={Nomatch} />
            </Switch>

    );

}

export default App;

/////////////////////////////////////////
//Main.js
import React from 'react';
import { Switch, Route, useRouteMatch } from 'react-router-dom';
import Home from './Home';
import Contact from './Contact';

const Main = () => {
const { path, url } = useRouteMatch();
    return(

            <Switch>
                <Route exact path='/' component={Home} />
                <Route path={`${path}/contact`} component={Contact} />
            </Switch>

    )

}

export default Main

A: UPDATE
You could try changing in Main:
            <Switch>
                <Route exact path='/' component={Home} />
                <Route path={`${path}/contact`} component={Contact} />
            </Switch>

by
            <Switch>
                <Route exact path='/home'><Redirect to='/' /></Route>
                <Route exact path='/' component={Home} />
                <Route exact path='/contact' component={Contact} />
            </Switch>

And in App
            <Switch>
                <Route path="/" component={Main} />
            </Switch>


text:
Q: Javascript - It is possible to retrace the origins of a value of a Javascript variable with the dev.console? I'm working with React Redux. Seems there is a overwritting of values in my code. My this.props of a connected (mapStateTo...) component come from an unknow part of my code.
My quest is directly linked to an another quest about understanding why my React.Component doesn't update when the store.state updates.
I'm trying to retrace currently the origins of the value in Javascript.  My console displays me the line of the code but not the origins of the this.props of my file directly in the console.
My problem is that I have a this.props but can't figure out to which part of my code it correspond.
On my console I have access to map.file but fail to find the origin  of my this.props, would be great if a method permit it.
Thanks

A: If the console displays the output, then enter to debug mode, put a breakpoint where you are printing and follow the execution stack trace, so you can see the code flow and where your prop has been initialized...


text:
Q: RemObjects PascalScript How to get the value of the variable after compilation? RemObjects PascalScript.
How to get the value of the variable after compilation?
var a,b,c: integer;
begin
a := 5;
b := 6;
c := a+b;
end;

cc := IntTostr(????c????);

A: You have two options:
You can register a function with
Sender.AddDelphiFunction('procedure MyOwnFunction(Data: string)');

and
Exec := TPSExec.Create;  // Create an instance of the executer.
Exec.RegisterDelphiFunction(@MyOwnFunction, 'MYOWNFUNCTION', cdRegister);

and then call it from within your script.
Alternatively, you can define your script as a function and set the Result. Then you can retrieve it with
TestFunc := TTestFunction(Exec.GetProcAsMethodN('Test'));

Both methods are demonstrated in this example:
program sample8;

uses
  uPSCompiler,
  uPSRuntime,
  uPSUtils,

  Dialogs;

procedure MyOwnFunction(const Data: string);
begin
  // Do something with Data
  ShowMessage(Data);
end;

{$IFDEF UNICODE}
function ScriptOnExportCheck(Sender: TPSPascalCompiler; Proc: TPSInternalProcedure; const ProcDecl: AnsiString): Boolean;
{$ELSE}
function ScriptOnExportCheck(Sender: TPSPascalCompiler; Proc: TPSInternalProcedure; const ProcDecl: string): Boolean;
{$ENDIF}
{
  The OnExportCheck callback function is called for each function in the script
  (Also for the main proc, with '!MAIN' as a Proc^.Name). ProcDecl contains the
  result type and parameter types of a function using this format:
  ProcDecl: ResultType + ' ' + Parameter1 + ' ' + Parameter2 + ' '+Parameter3 + .....
  Parameter: ParameterType+TypeName
  ParameterType is @ for a normal parameter and ! for a var parameter.
  A result type of 0 means no result.
}
begin
  if Proc.Name = 'TEST' then // Check if the proc is the Test proc we want.
  begin
    if not ExportCheck(Sender, Proc, {$IFDEF UNICODE}[btUnicodeString, btUnicodeString]{$ELSE}[btString, btString]{$ENDIF}, [pmIn]) then // Check if the proc has the correct params.
    begin
      { Something is wrong, so cause an error. }
      Sender.MakeError('', ecTypeMismatch, '');
      Result := False;
      Exit;
    end;
    Result := True;
  end else Result := True;
end;

{$IFDEF UNICODE}
function ScriptOnUses(Sender: TPSPascalCompiler; const Name: AnsiString): Boolean;
{$ELSE}
function ScriptOnUses(Sender: TPSPascalCompiler; const Name: string): Boolean;
{$ENDIF}
{ the OnUses callback function is called for each "uses" in the script.
  It's always called with the parameter 'SYSTEM' at the top of the script.
  For example: uses ii1, ii2;
  This will call this function 3 times. First with 'SYSTEM' then 'II1' and then 'II2'.
}
begin
  if Name = 'SYSTEM' then
  begin

    Sender.AddDelphiFunction('procedure MyOwnFunction(Data: string)');
    { This will register the function to the script engine. Now it can be used from within the script. }

    Result := True;
  end else
    Result := False;
end;

type
  TTestFunction = function (const s: string): string of object;
  // Header of the test function, added of object.

procedure ExecuteScript(const Script: string);
var
  Compiler: TPSPascalCompiler;
  { TPSPascalCompiler is the compiler part of the scriptengine. This will
    translate a Pascal script into a compiled form the executer understands. }
  Exec: TPSExec;
   { TPSExec is the executer part of the scriptengine. It uses the output of
    the compiler to run a script. }
  {$IFDEF UNICODE}Data: AnsiString;{$ELSE}Data: string;{$ENDIF}

  TestFunc: TTestFunction;
begin
  Compiler := TPSPascalCompiler.Create; // create an instance of the compiler.
  Compiler.OnUses := ScriptOnUses; // assign the OnUses event.

  Compiler.OnExportCheck := ScriptOnExportCheck; // Assign the onExportCheck event.

  Compiler.AllowNoBegin := True;
  Compiler.AllowNoEnd := True; // AllowNoBegin and AllowNoEnd allows it that begin and end are not required in a script.

  if not Compiler.Compile(Script) then  // Compile the Pascal script into bytecode.
  begin
    Compiler.Free;
     // You could raise an exception here.
    Exit;
  end;

  Compiler.GetOutput(Data); // Save the output of the compiler in the string Data.
  Compiler.Free; // After compiling the script, there is no need for the compiler anymore.

  Exec := TPSExec.Create;  // Create an instance of the executer.

  Exec.RegisterDelphiFunction(@MyOwnFunction, 'MYOWNFUNCTION', cdRegister);

  if not Exec.LoadData(Data) then // Load the data from the Data string.
  begin
    { For some reason the script could not be loaded. This is usually the case when a
      library that has been used at compile time isn't registered at runtime. }
    Exec.Free;
     // You could raise an exception here.
    Exit;
  end;

  TestFunc := TTestFunction(Exec.GetProcAsMethodN('Test'));
  if @TestFunc <> nil then
    ShowMessage('Result from TestFunc(''test indata''): '+TestFunc('test indata'));

  Exec.Free; // Free the executer.
end;

const
  Script = 'function test(s: string): string; begin MyOwnFunction(''Test Called with param: ''+s); Result := ''Test Result: ''+s; end;';

begin
  ExecuteScript(Script);
end.


text:
Q: Get react component from library using a list I have a list:
var coins =["BTC", "ETH","LTC"]

And there is a react library where I can get Icons for these coins using the following schema:
<Icon.Eth /> or <Icon.Btc /> or <Icon.ltc />

But the list is retrieved using an API and it can change at any moment.
Is there a way to do something like this:
<Icon.coins[0] /> or <Icon.coins[1] /> or <Icon.coins[2] />

A: Use square brackets like this
let IconA = Icon[coins[0]];
let IconB = Icon[coins[1]];

// Then use them like this
<IconA /> or <IconB />

A: If you want to look up dynamically based on coin name, you can import all coins and look them up by string.
import * as Icons from 'react-cryptocoins';

const coins = ['Eth'];

class MyClass extends React.Component {
    render() {
        return (

                { React.createElement(Icons[coins[0]]) }

        );
    }
}

Note this requires your array to be title cased, not all capitals. Putting it all together, I would make a component for this:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import * as Icons from 'react-cryptocoins'

const Coin = ({ icon }) => (
    React.createElement(Icons[coins[0]]) }
);

Coin.propTypes = {
    icon: PropTypes.string.isRequired
};

export default Coin;

Usage:
import React, { Component } from 'react';
import Coin from './Coin';

const coins = ["BTC", "ETH", "LTC"];

function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();
}

class MyElement extends Component {
    render() {
        return (

                { coins.map( coin => (
                    <Coin icon={capitalize(coin)} />
                )}

        )
    }
}


text:
Q: How to create a simple video gallery in html? I want create a simple html video gallery in html, where many images show in tables and when we click on any then it play related video. I search but not found something. Is it not possible?
I tried this code:
   <video width="320" height="240" controls autoplay>
  <source src="movie.ogg" type="video/ogg">
  <source src="movie.mp4" type="video/mp4">
  <object data="movie.mp4" width="320" height="240">
    <embed width="320" height="240" src="movie.swf">
  </object>
</video>

but how link this video with any image when we click on that image, video plays.

A: Since you're not providing full HTML markup, I'll place the image right before
the video as an example:
<img class="galleryImg" src="your image src here" />
<video width="320" height="240" controls autoplay>
    <source src="movie.ogg" type="video/ogg">
    <source src="movie.mp4" type="video/mp4">
    <object data="movie.mp4" width="320" height="240">
        <embed width="320" height="240" src="movie.swf">
    </object>
</video>

Then you can do:
$('img.galleryImg').each(function() {
    $(this).next().get(0).play();
});

A: What you try in w3schools has the follow Live Preview
<video width="320" height="240" controls autoplay>
<source src="movie.ogg" type="video/ogg">
<source src="movie.mp4" type="video/mp4">
<object data="movie.mp4" width="320" height="240">
<embed width="320" height="240" src="movie.swf">
</object>
</video>

You can create a table like http://www.w3schools.com/css/css_image_gallery.asp and then remove, embed the images with your youtube video. So that i will play the video once you click it.
However w3layouts provide gallery template what you expect in easy way you can download it from here.


text:
Q: Typescript - Method is undefined I have angular application and calling one of my methods as callback(i do understand it's not the best practice in Angular but this is not a point of this question).
Inside of my class I have something like this:
My code looks like:
protected updateCtapIctapAdjudication(event: {aidx: number, value: boolean, comment: string}): Observable<AdjudicationResponse> {
  console.log(this.doUpdateCtapIctapAdjudication);
  return this.doUpdateCtapIctapAdjudication(event.aidx, event.value, event.comment);
}

protected doUpdateCtapIctapAdjudication(aidx: number, value: boolean, comment: string): Observable<AdjudicationResponse> {
  console.log('TESTING');
  return of();
}

What error I get:
Which seems to be quite simple code. When I run updateCtapIctapAdjudication() I see console.log inside of that method say that doUpdateCtapIctapAdjudication is undefined and line after that throw error that doUpdateCtapIctapAdjudication is not a function.
This is really strange as method is defined one line below in a same class. I was wondering what I am doing wrong.
What I tried:
As we all do when debugging I tried to simplify code as much as possible and run code below in chrome dev tools and things works fine:
class MyClass {
  updateCtapIctapAdjudication(event) {
    console.log(this.doUpdateCtapIctapAdjudication);
    return this.doUpdateCtapIctapAdjudication(event);
  }

  doUpdateCtapIctapAdjudication(x) {
    console.log('TESTING');
  }
}
x = new MyClass();
this.doUpdateCtapIctapAdjudication();

I'm obviously overlooking something but I don't know what, is there something I should focus on to debug this?


text:
Q: Regular expression to negate those div having class="image" I have string in which i want to get content of only those DIV tags which does not have the class image.
I am using this regular expression:
#<\s*?div\b[^>]*class="[^image]">(.*?)</div\b[^>]*>#s

but it escapes all the DIV tags, not just the ones with the class image

A: You're likely better off with a DOM parser instead.
In any case, here's a regex that should do what you're after:
<div[^>]+class="(?!(?:.+ )?image(?: .+)?")([^"]+)"

Demo: http://rubular.com/r/eekxdFdmFR

A: The expression [^image] will find only those classes that do not contain i AND m etc. letters. Maybe negative lookahead can do the trick:
#<\s*?div\b[^>]class=\"(?:(?!image).)*\">(.?)*>#s

It will dismiss the class="images" etc. too, but I hope this is a good beginning. :)
PS: I don't know the last ] is necessary or not, but it is missing from my regexp.


text:
Q: Compilar varias clases y ejecutar en Java Dispongo de dos clases simples denominadas Person y Main respectivamente tal y como se muestra a continuación. He compilado ambas clases haciendo uso del comando javac *.java y este me ha generado los correspondientes archivos .class pero cuando intento ejecutar la clase Main de la forma java Main este me muestra un error indicando que el símbolo Person no existe.
La duda reside en como puedo ejecutar el programa main compilado previamente. La salida esperada  al ejecutar el programa es el nombre resultado de la llamada al método getName() incluido en el método main()
Ejemplo:
package test;

public class Person {
    private final String name;
    private final int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return this.age;
    }
}

package test;

public class Main {

    public static void main(String[] args) {
        Person person = new Person("John", 30);
        System.out.println(person.getName());
    }
}

A: Si tienes ésta estructura:
- unDirectorio
  - Main.java
  - Person.java

Haz:
cd unDirectorio
javac -d . *.java
java test.Main

Observa que con -d se crea un directorio con el nombre del paquete;
de tal manera que al incluir dicho nombre de paquete al ejecutar
la Máquina Virtual sabrá dónde ubicar el código de bytes de la clase principal.
Otra forma, con una estructura mas recomendable (cada elemento de la ruta del paquete es un directorio):
- src
  - test
    - Main.java
    - Person.java

A partir del directorio src:
cd src
javac -d ./test test/*.java
java -cp test test.Main


text:
Q: Singularity structure of a multivalued function Consider the function
$$f(z) = \frac{1}{z} \ln \left( \frac{1-z}{1+z} \right).$$
This is clearly multivalued. There has to be two branch points at $\pm1$. Are there any other singularities, such as poles arising from the factor of $1/z$ or $\infty$? Does it depend on the choice of branch cuts?
For a simpler function such as $\ln(z)$, I know that there are branch points at $z=0$ and  $z=\infty$. A cut can be chosen to use multiple copies of the complex plane in order to define a single valued analytic function. Can someone please help me do such a construction for $f$?


text:
Q: remote ejb call trapped in the lookup in linux server  I'm using glassfish 3.1.1 with an application client container called via java web start.
My program is not working , it remain glued in the lookup() and never pass it .
        Context c = new InitialContext()
        geo = (GeoBeanRemote) c.lookup("java:global/server_side/server-ejb/GeoBean");
        System.out.println("end lookup");

I have already tested this in a windows server and it worked perfelcty but now , in the production server (ubuntu 11.04) it doesn't .
How can i fix this ?
Thanks.

A: It sounds like you might be having some routing issues. I suggest verifying your RMI port is open. The default is 3700.


text:
Q: MY_Model jamierumbelow Guys
I have been using this model in my project.But ,nowadays i m facing with performance noises due to repeated query by with method and of course the need to make and Inner Join with Where clause on related objects  and how could i ever does that?
I have Profile ,Media,Product table related.
When i want to get all products with profile , media and details i use below code.And , its working except the with createsrepeated select statements.
$all_products = $this->with('medias')->with('profile')->get_all();

Now , i want all products their profile is verified.
select * from products
inner join profile as p on p.id = product.profile_id
inner join media as m on m.product_id=p.product_id
where profile.is_verfied='true';

How can i ever do this using my MY_MODEL way or with little modifications.

A: I too use @Jamie Rumbelow's Base Model, with few modifications (one or two). When It comes to joining, it has a wonderful triggering method that you can use:  before_get observer. In your case, simply add an observer where you can join from needed tables like so:
In your model constructor:
public function __constrcutor()
{
    array_unshift(
        $this->before_get,
        'join_from_profile_and_media'
    );
    // Then
    parent::__construct();
}

And the observer would be:
protected function join_from_profile_and_media()
{
    $this->db->join('profile', 'profile.id = product.profile_id');
    $this->db->join('media', 'media.product_id = profile.product_id');
}

And now whenever you call get(), get_many(), get_by() or get_many_by() all tables are joint.

A: If you're having performance issues, don't use with()! It's a crude way of managing relationships, only to be used for prototyping or simple relationships.
I'd recommend doing the joins manually:
$products = $this->select('products.*')
    ->join('profile', 'p.id = products.profile_id', 'inner')
    ->where('profile.is_verified', true)
    ->get_all();

A: Danielad,
There are many caching technologies available. In my project, we are using Redis, Memcached as well. Also using client (Website) side caching for Javascripts, CSS, Images etc..
Redis/Memcached are very powerful tools. Facebook is using Memcached for very fast output and low load over database servers.
Hope this helps !!


text:
Q: The verb "bitch" in the transitive sene I've been having an agony of the use of the verb "bitch" in the transitive verb which was used many times in Aersosmith's songs, but may be it was I didn't give enough attention to it, after all if their rocks are catchy enough, they had become a hit.
It started after checking carefully the one of the above rockstar's song.
I know, no sense is perfectly OK to me when it comes to songs.
But "to bitch", assuming very offensive word, when it is used in the transitive mode, 2 dictionaries give
2 definition.
This Merriam Webster says,

transitive verb

1: SPOIL, BOTCH
bitched up their lives

2: CHEAT, DOUBLE-CROSS

3: to complain of or about

However, this dictionary gives different definitions.

verb transitive (Should we delete(+) this sense?) To make derogatory comments.

verb transitive To criticize spitefully, often for the sake of complaining rather than in order to have the problem corrected.

What's common between the 2 is that they have a definition "to complain about something".
So, does the verb bitch in the use of transitive mean "to complain"?
Thank you^^.

A: As far as I know, bitch is not used transitively in the UK. The Cambridge Dictionary agrees with this.
In the US, it is used transitively in very informal language in the same way as fuck, where it is simply a forceful negative that can be applied to any situation.
Note that the two transitive usages that Wordnik found are in the Wiktionary section (ie based on individual contributions), and there is a note for one of them saying "(Should we delete(+) this sense?)". The more reputable sources that Wordnik found only quote intransitive meanings.

A: Areosmith: Eat The Rich

Then I hope this does the trick
'Cause I'm sick of your complainin'
About how many bills
And I'm sick of all your bitchin'
'Bout your poodles and your pills

(source: lyrics search via Google search results)
Yes, it means complaining.
The mention of poodles in the same sentence is perhaps a garden path for some


text:
Q: Unity 3D leap motion I am currently working on a project and trying to get swipe gesture working. Current output is several instances of swipe gestures from just a swipe. How can i get one instance?
Thanks

A: if (Input.touchCount > 0)
{
    Input.GetTouch(0).phase == TouchPhase.Moved)
    {
        // One swipe gesture
    }
}

A: You can setup a Boolean variable to change state if a good swipe was performed and if it set to true, swipe recognition will be disable lets say 2 seconds or until some actions get completed.


text:
Q: Convex Optimization Problem - Least Squares with Euclidean Norm Inequality I have a problem of the form
$$\begin{equation*}
\begin{aligned}
& \underset{x}{\text{minimize}}
& & \lVert \mathbf{x-a} \rVert_2 \\
& \text{subject to}
& & \lVert \mathbf{x-v} \rVert_2 \leq \lVert \mathbf{s-v} \rVert_2
\end{aligned}
\end{equation*}$$
where $\mathbf{a}$, $\mathbf{s}$, $\mathbf{v}$ are constant. I am not sure how I could reformulate this into the standard form with $Ax \leq b$ inequality constraints and would appreciate any help. I have seen some examples for L1 norm (e.g. here) but not sure how to apply it in this case.

A: The feasible set is not a polyhedral, hence it can't be directly be described in terms of $Ax \le b$. Unless perhaps you change the feasible set of which the optimal solution is still preserved.
Your problem however can be solved.
First, we can see if $a$ is in the feasible set. If it is, then $x=a$ is the solution.
Suppose $a$ is not in the feasible set. Draw a straight line between the center, $v$ and $a$.  The closest point on the sphere that is the closest to $a$ must be on the surface and on the straight line.  $$x^*=v+\frac{(a-v)}{\|a-v\|}\|s-v\|$$


text:
Q: Nifi to mongodb My errors info pic :

I can't connect my datas to mongodb and cant figure it out because of this "UTC ERROR". I was getting that error when I tried connect my nifi to kafka but I solved it with correcting my ip address.
what I write to my
"Mongo URI:mongodb://****:*****@***.jmmuf5m.mongodb.net/?retryWrites=true&w=majority"

I am trying to put my datas to mongodb and analayze in BigQuery(I hope so)


text:
Q: How to limit Max Length of Draft js How to limit max characters in draft js?
I can get length of the state like that, but how to stop updating component?
var length = editorState.getCurrentContent().getPlainText('').length;

A: Mikhail's methods are correct, but the handler return value is not. 'not_handled' is a fall-through case that allows the Editor component to process the input normally. In this case, we want to stop the Editor from processing input.
In older versions of DraftJS, it looks like the presence of a string evaluated to 'true' in the handling code, and so the above code behaved correctly. In later versions of DraftJS, the above fiddle doesn't work - I don't have the reputation to post more that one Fiddle here, but try Mikhail's code with v0.10 of DraftJS to replicate.
To correct this, return 'handled' or true when you don't want the Editor to continue handling the input.
Fiddle with corrected return values
For example,
_handleBeforeInput = () => {
  const currentContent = this.state.editorState.getCurrentContent();
  const currentContentLength = currentContent.getPlainText('').length

  if (currentContentLength > MAX_LENGTH - 1) {
    console.log('you can type max ten characters');
    return 'handled';
  }
}

See the DraftJS docs on Cancelable Handlers for more.

A: You should define handleBeforeInput and handlePastedText props. In handler-functions, you check the length of current content + length of pasted text and if it reaches the maximum you should return 'handled' string.
UPD 21.03.2018: Upgraded to the last versions of react/react-dom (16.2.0) and Draft.js (0.10.5).
Working example - https://jsfiddle.net/Ln1hads9/11/
const {Editor, EditorState} = Draft;

const MAX_LENGTH = 10;

class Container extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      editorState: EditorState.createEmpty()
    };
  }
  render() {
    return (
      <div className="container-root">
        <Editor
          placeholder="Type away :)"
          editorState={this.state.editorState}
          handleBeforeInput={this._handleBeforeInput}
          handlePastedText={this._handlePastedText}
          onChange={this._handleChange}
        />
      </div>
    );
  }

  _getLengthOfSelectedText = () => {
    const currentSelection = this.state.editorState.getSelection();
    const isCollapsed = currentSelection.isCollapsed();

    let length = 0;

    if (!isCollapsed) {
      const currentContent = this.state.editorState.getCurrentContent();
      const startKey = currentSelection.getStartKey();
      const endKey = currentSelection.getEndKey();
      const startBlock = currentContent.getBlockForKey(startKey);
      const isStartAndEndBlockAreTheSame = startKey === endKey;
      const startBlockTextLength = startBlock.getLength();
      const startSelectedTextLength = startBlockTextLength - currentSelection.getStartOffset();
      const endSelectedTextLength = currentSelection.getEndOffset();
      const keyAfterEnd = currentContent.getKeyAfter(endKey);
      console.log(currentSelection)
      if (isStartAndEndBlockAreTheSame) {
        length += currentSelection.getEndOffset() - currentSelection.getStartOffset();
      } else {
        let currentKey = startKey;

        while (currentKey && currentKey !== keyAfterEnd) {
          if (currentKey === startKey) {
            length += startSelectedTextLength + 1;
          } else if (currentKey === endKey) {
            length += endSelectedTextLength;
          } else {
            length += currentContent.getBlockForKey(currentKey).getLength() + 1;
          }

          currentKey = currentContent.getKeyAfter(currentKey);
        };
      }
    }

    return length;
  }

  _handleBeforeInput = () => {
    const currentContent = this.state.editorState.getCurrentContent();
    const currentContentLength = currentContent.getPlainText('').length;
    const selectedTextLength = this._getLengthOfSelectedText();

    if (currentContentLength - selectedTextLength > MAX_LENGTH - 1) {
      console.log('you can type max ten characters');

      return 'handled';
    }
  }

  _handlePastedText = (pastedText) => {
    const currentContent = this.state.editorState.getCurrentContent();
    const currentContentLength = currentContent.getPlainText('').length;
    const selectedTextLength = this._getLengthOfSelectedText();

    if (currentContentLength + pastedText.length - selectedTextLength > MAX_LENGTH) {
      console.log('you can type max ten characters');

      return 'handled';
    }
  }

  _handleChange = (editorState) => {
    this.setState({ editorState });
  }
}

ReactDOM.render(<Container />, document.getElementById('react-root'))

A: This is a bit of an old thread, but thought I would share a solution for anyone else facing the problem of character limit and behaviour while pasting text...
Put together something pretty quickly based on the above code by Mikhail to handle this use case which works for me - although I haven't done any work on trying to optimise it.
Basically the handle pasted text looks like so:
      const __handlePastedText = (pastedText: any) => {
        const currentContent = editorState.getCurrentContent();
        const currentContentLength = currentContent.getPlainText('').length;
        const selectedTextLength = _getLengthOfSelectedText();

        if (currentContentLength + pastedText.length - selectedTextLength > MAX_LENGTH) {
            const selection = editorState.getSelection()
            const isCollapsed = selection.isCollapsed()
            const tempEditorState = !isCollapsed ? _removeSelection() : editorState
            _addPastedContent(pastedText, tempEditorState)
          return 'handled';
        }
        return 'not-handled'
      }

We have a helper function to handle the deletion of the selection prior to pasting new characters which returns the new editor state:
      const _removeSelection = () => {
        const selection = editorState.getSelection()
        const startKey = selection.getStartKey()
                const startOffset = selection.getStartOffset()
                const endKey = selection.getEndKey()
                const endOffset = selection.getEndOffset()
                if (startKey !== endKey || startOffset !== endOffset) {
                    const newContent = Modifier.removeRange(editorState.getCurrentContent(), selection, 'forward')
                    const tempEditorState = EditorState.push(
                        editorState,
                        newContent,
                        "remove-range"
                    )
                    setEditorState(
                        tempEditorState
                    )
                    return tempEditorState
                }
                return editorState
      }

and finally the function to add the pasted text with a limit:
      const _addPastedContent = (input: any, editorState: EditorState) => {
        const inputLength = editorState
        .getCurrentContent()
        .getPlainText().length;
        let remainingLength = MAX_LENGTH - inputLength;

        const newContent = Modifier.insertText(
            editorState.getCurrentContent(),
            editorState.getSelection(),
            input.slice(0,remainingLength)
        );
        setEditorState(
            EditorState.push(
                editorState,
                newContent,
                "insert-characters"
            )
        )
      }

Link to worked example:
https://codesandbox.io/s/objective-bush-1h9x6

A: As Mikhail mentioned, you need to handle typing and pasting text. Here are both handlers. Note the paste handler will preserve text that is not outside the limit
function handleBeforeInput(text: string, state: EditorState): DraftHandleValue {
    const totalLength = state.getCurrentContent().getPlainText().length + text.length;
    return totalLength > MAX_LENGTH ? 'handled' : 'not-handled';
  }

function handlePastedText(text: string, _: string, state: EditorState): DraftHandleValue {
    const overflowChars = text.length + state.getCurrentContent().getPlainText().length - MAX_LENGTH;

    if (overflowChars > 0) {
      if (text.length - overflowChars > 0) {
        const newContent = Modifier.insertText(
          state.getCurrentContent(),
          state.getSelection(),
          text.substring(0, text.length - overflowChars)
        );
        setEditorState(EditorState.push(state, newContent, 'insert-characters'));
      }
      return 'handled';
    } else {
      return 'not-handled';
    }
  }

A: Let's think about this for a second. What is called to make the changes? Your onChange, right? Good. We also know the length. Correct? We attact the "worker" which is the onChange:
const length = editorState.getCurrentContent().getPlainText('').length;

// Your onChange function:
onChange(editorState) {
 const MAX_LENGTH = 10;
 const length = editorState.getCurrentContent().getPlainText('').length;

 if (length <= MAX_LENGTH) {
  this.setState({ editorState }) // or this.setState({ editorState: editorState })
 }
} else {
 console.log(`Sorry, you've exceeded your limit of ${MAX_LENGTH}`)
}

I have not tried this but my 6th sense says it works just fine.


text:
Q: Add a link to the title of references I'm creating a document with rmarkdown (pandoc), which includes some bibliography in a .bib file. What I'd like to do is add a link to the title of the references, so that each of them links to a page of the form http://sample.com/citation-key.html, like this:

Author. (2017). Sample Title. Journal, 1(1), 1–2.

I've tried modifying the .csl file by adding prefixes and suffixes to the title, but everything I put in there is escaped, whether I use markdown or HTML syntax. Unfortunately, I can't change the .bib file. The relevant part of the .csl file is this:
<text variable="title"/>

Sample files are:

*

*literature.Rmd:
---
output: html_document
bibliography: literature.bib
csl: literature.csl
---

@author2017word says this doesn't work.

## References

*literature.bib
@article{author2017word,
         author = {Author},
         journal = {Journal},
         number = {1},
         pages = {1--2},
         title = {{Sample Title}},
         volume = {1},
         year = {2017}
}

*literature.csl: I'm using the APA style from here (line 231).

A: My pull request to citeproc adding support this feature was recently merged, and as a result, the latest release of Pandoc (v2.14.2) now hyperlinks titles by default when the citation does not already show a raw URL!  From the citeproc readme:

When linkBibliography=True automatically linkifies any identifiers (DOI, PMCID, PMID, or URL) appearing in a bibliography entry. When an entry has a DOI, PMCID, PMID, or URL available but none of these are rendered by the style, add a link to the title (or, if no title is present, the whole entry), using the URL for the DOI, PMCID, PMID, or URL (in that order of priority). See Appendix VI of the CSL v1.0.2 spec.

In pandoc, this option is controlled by the link-bibliography metadata field, which is True by default.


text:
Q: WPF hosting a WinForm, Tab Navigation problems I have run into issues when hosting a WinForms form within a WindowsFormsHost and the tab navigation. To solve I have made this simple example:

*

*Created WPF Window (starting point of app)

*Created WinForms Form with two TextBox on it

*WPF window: Added WindowsFormsHost to it

*WPF window: Added OnLoaded handler

*WPF window: Added Textbox positioned under the WindowsFormsHost
In the OnLoaded handler I got:
System.Windows.Forms.Form f = new WinFormsForm();
f.TopLevel = false;
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.windowsFormsHost1.Child = f;

When I now run the application:

*

*Nothing is focussed (ok)

*I click on the first TextBox in the WindowsFormsHost, it gets focus (ok)

*I press tab, focus goes to 2nd TextBox in the WindowsFormsHost (ok)

*I press tab again, focus goes back to 1st TextBox in the WindowsFormsHost (not ok; should have left WindowsFormsHost and given focus to the textbox at the bottom of the WPF window)

*I click on the textbox in the wpf (placed after and under the WindowsFormsHost), it gets focus (ok)

*I press tab, focus goes to 1st textbox in WindowsFormsHost - as it should go to beginning after the end. So this is ok too

*I click the wpf textbox again and press shift+tab, focus goes to 2nd textbox in WindowsFormsHost (ok)

*I press tab, focus goes to 1st textbox in WindowsFormsHost (goes to beginning in WFH) (not ok)

How do I make the focus behave like if I had only controls of one type? Meaning a tab order of WFH-1st-Textbox, WFH-2nd-Textbox, WPF-Textbox in this case.

A: According to the articles I have found, that seems not possible to accomplish. According to a MSDN Blog Entry (section Hwnds) the Windows Forms controls always are on top of WPF controls in the hierarchy. The MSDN article (section Acquiring Messages from the WPF Message Loop) states that events occurring in a WindowsFormsHost element will be processed before WPF is even aware of them.
So I assume that the event fired by pressing the TAB key is processed by the WindowsFormsHost element (resulting in the focus of the other textbox). In the enclosing WPF window the event will never be encountered because "it has already been processed". On the other side when you press the TAB key in the WPF textbox, WPF is handling the event itself and the control chain is processed normally. With this the focus will get to a textbox in the WindowsFormsHost element and from there you can't leave it using the keyboard.
I know this will not help your current problem but I hope it explains some things.

ADDENDUM
If you are not dependent on using a form control, you could change it into a WinForms user-control with the same control elements in it. After that you change the initialization of the WindowsFormsHost element in the following way:
System.Windows.Forms.UserControl control = new WinFormUC();
windowsFormsHost1.Child = control;

The class WinFormUC is my WinForms user-control containing the mentioned textboxes. In my test the pressing of the TAB key focused the textboxes one after another regardless whether its a Winforms or a WPF textbox.

A: You could do this with a little trick. Suppose that your wpf form with host looks like this:
<StackPanel>
    <TextBox LostFocus="TextBox_LostFocus" />
    <wf:WindowsFormsHost Name="host" />
    <TextBox/>
</StackPanel>

In the LostFocus event of the first textbox you set the focus to the first button on the winform. In this way you assure that focus always starts at the first button.
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
    Form1 f = (Form1)host.Child;
    f.EnableTabStops(true);
}

In the winform you have to code EnableTabStops as follows:
public void EnableTabStops(bool IsEnabled)
{
    this.button1.TabStop = IsEnabled;
    this.button2.TabStop = IsEnabled;
    if (IsEnabled) button1.Focus();
}

Next, you tab through the buttons of the winform. Upon entering the last button on the winform you disable/remove all tabstops so that the next tab only can jump to its parent wpf form, like this:
private void button2_Enter(object sender, EventArgs e)
{
    EnableTabStops(false);
}

This should do the job.

A: This is the way i implemented this:
I created a control that inherits from WindowsFormsHost
public class MyWpfControl: WindowsFormsHost
{
    private MyWindowsFormsControl _winControl = new MyWindowsFormsControl ();

    public MyWpfControl()
    {
        _winControl.KeyDown += _winControl_KeyDown;
    }

    void _winControl_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab && e.Shift)
        {
            MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
        }
        else if (e.KeyCode == Keys.Tab)
        {
            MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
        }
    }
}

worked perfectly for me
using the same approach you can also make your windows control have the needed wpf data bindings:
public static readonly RoutedEvent SelectionChangedEvent =    EventManager.RegisterRoutedEvent("SelectionChanged", RoutingStrategy.Bubble,  typeof(RoutedEventHandler), typeof(MyWpfControl));

    public event RoutedEventHandler SelectionChanged
    {
        add { AddHandler(SelectionChangedEvent, value); }
        remove { RemoveHandler(SelectionChangedEvent, value); }
    }

    void RaiseSelectionChangedEvent()
    {
        var newEventArgs = new RoutedEventArgs(SelectionChangedEvent);
        RaiseEvent(newEventArgs);
    }

    private void InitDependencyProperties()
    {
        _winControl.EditValueChanged += (sender, e) =>
        {
            SetValue(SelectedValueProperty, _winControl.EditValue);

            if (!_disabledSelectionChangedEvent)
            {
                RaiseSelectionChangedEvent();
            }
        };

    }

public static readonly DependencyProperty SelectedValueProperty = DependencyProperty.Register("SelectedValue", typeof(string), typeof(MyWpfControl),
   new PropertyMetadata("",
     (d, e) =>
     {
         var myControl = d as MyWpfControl;
         if (myControl != null && myControl._brokersCombo != null)
         {
             var val = myControl.GetValue(e.Property) ?? string.Empty;
             myControl._winControl.EditValue = val;
         }
     }, null));

Here is the XAML:
<u:MyWpfControl x:Name="myWpfControl" Margin="5,0,0,0" DataSource="{Binding BindingData,     UpdateSourceTrigger=PropertyChanged}" SelectedValue="{Binding SelectedPropertyNameOnViewModel, Mode=TwoWay}">
</u:MyWpfControl>

A: Just Add that in App.xaml.cs :
System.Windows.Forms.Integration.WindowsFormsHost.EnableWindowsFormsInterop();
Reference : WindowsFormsIntegration.dll


text:
Q: The sum of two projective spaces Let $K$ be a field and let $V$ be a vector space on $K$. We consider the projective space $P(V)$ on $V$ (the set of the vector subespaces $A$ in $V$ such that $\dim A = 1$). Let $S , T$ be two vector subespaces in $V$. By definition $P(S)$ and $P(T)$ are two projective spaces in $P(V)$. I want to prove that $P(S) + P(T)$ is a new projective space in $P(V)$ (the sum of two projective spaces is a new projective space). Obviously, $S + T$ is a vector space in $V$, so $P(S + T)$ is a projective space in $P(V)$. Must I use this argument to prove that $P(S) + P(T)$ is a projective space in $P(V)$? Is the equality $P(S) + P(T) = P(S + T)$ a definition? Thank you very much.

A: The expression $P(T) + P(S)$ does not make sense since there is no addition in $P(V)$. More precisely, the operation "$+$" does not pass to quotient.
So the only thing which wake sense is to look at $P(T + S)$ which is in fact the smallest projective space which contains both $P(T)$ and $P(S)$. But I won't call it $P(T) + P(S)$ since really the notion of addition does not exist when you do projectivize.


text:
Q: Why do I get Unable to include RenderObjectSuccess.php error when using inline in grid? I'm setting up a grid with an inline field, pretty much the sames than in the examples in the demo, but I just keep getting error: Unable to include RenderObjectSuccess.php when chaning the value in the inline field. What a I doing wrong?
class page_alumnos_pago extends Page {
    function init(){
        parent::init();

        $this->api->stickyGET('id');
        $mAlumno=$this->add('Model_Alumno')->loadData($_GET['id']);

        $g = $this->add('Grid');
        $g->addColumn('date','fechaVencimiento');
        $g->addColumn('text','concepto');
        $g->addColumn('money','monto');
        $g->addColumn('inline','temp_pago');
        $g->setSource('programaPago');
        $g->dq->where('alumno_id',$_GET['id']);
    }
}

This is my ProgramaPago model:
class Model_ProgramaPago extends Model_Table {
public $entity_code='programaPago';
function init(){
    parent::init();

    $this->addField('alumno_id')->caption('Alumno')->refModel('Model_Alumno')->mandatory(true);
    $this->addField('fechaVencimiento')->caption('Fecha de Vencimiento')->type('date')->mandatory(true);
    $this->addField('monto')->caption('Monto')->type('money')->mandatory(true);
    $this->addField('concepto')->caption('concepto')->type('text')->mandatory(true);
}
}

A: Eh, that's a bug.

*

*https://github.com/atk4/atk4/issues/37

*fix: https://github.com/atk4/atk4/commit/3694996
Please let me know if the fix works.


text:
Q: Move partition from one table to another table PostgreSQL 10.11 I am new to postgreSQL, I am working on a project where I am requested to move all the partitions older than 6 months to a legacy table so that the query on the table would be faster. I have the partition table with 10 years of data.
Lets assume if myTable is the table with current 6 months data and myTable_legacy is going to have all the data older than 6 months for up-to 10 years. The table is partitioned by monthly range
My questions that I researched online and unable to conclude are
I am currently testing before finalizing the steps, I was using below link as reference for my lab testing, and before performing the actual migration.
How to migrate an existing Postgres Table to partitioned table as transparently as possible?
 create table myTable(
 forDate date not null,
 key2 int not null,
 value int not null
 ) partition by range (forDate);

 create table myTable_legacy(
 forDate date not null,
 key2 int not null,
 value int not null
 ) partition by range (forDate);

1)Daily application query will be only on the current 6 month data. Is it necessary to move data older than 6 months to a new partition to get a better response of query. I researched online but wasn't able to find any solid evidence related to the same.
2)If performance going to be better, How to move older partitions from myTable to myTable_legacy. Based on my research, I can see that we don't have option of exchange partition in PostgreSQL.
Any help or guidance would help me proceed further with the requirement.
When I try to attach partition to mytable_legacy, I am getting error
 alter table mytable detach partition mytable_200003;
 alter table mytable_legacy attach partition mytable_200003
      for values from ('2003-03-01') to ('2003-03-30');

results in:

ERROR:  partition constraint is violated by some row
SQL state: 23514

The contents of the partition:
select * from mytable_200003;

"2000-03-02"    1   19
"2000-03-30"    15  8

A: It's always better to keep the production table light, One of the practices that i do is to use timestamp and write trigger function that will insert row in the other table if timestamp is less than now() (6 months old data).

A: Quote from the manual

When creating a range partition, the lower bound specified with FROM is an inclusive bound, whereas the upper bound specified with TO is an exclusive bound

(emphasis mine)
So the expression to ('2003-30-03') does not allow March, 30st to be inserted into the partition.
Additionally your data in mytable_200003 is for the year 2000, not for the year 2003 (which you use in your partition definition). To specify the complete march, simply use April, 1st as the upper bound
So you need to change the partition definition to cover March 2000 not March 2003.
alter table mytable_legacy
   attach partition mytable_200003
   for values from ('2000-03-01') to ('2000-04-01');
                        ^ here            ^ here

Online example


text:
Q: HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers.(For basic Authentication) I want to enable "Basic" Authentication to my service. Disabled anonymous and windows Auth. And enabled "basicAuthentication" in applicationhost.config, but im not able access the service. Getting below error.
HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers.
I am using IIS Express 10. Here is my applicationhost.config
<authentication>

                <anonymousAuthentication enabled="false" userName="" />

                <basicAuthentication enabled="true" />

                <clientCertificateMappingAuthentication enabled="false" />

                <digestAuthentication enabled="false" />

                <iisClientCertificateMappingAuthentication enabled="false">
                </iisClientCertificateMappingAuthentication>

                <windowsAuthentication enabled="false">
                    <providers>
                        <add value="Negotiate" />
                        <add value="NTLM" />
                    </providers>
                </windowsAuthentication>

            </authentication>

And here is my Web.config
<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2">
      <assemblies>
        <add assembly="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5.2"/>
  </system.web>

  <!--Enable directory browsing in the Server-->
  <system.webServer>
    <directoryBrowse enabled="true"/>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

  <system.serviceModel>

    <bindings>
      <webHttpBinding>
        <binding name="webHttpTransportSecurity">
          <security mode="Transport">
            <transport clientCredentialType="Basic"></transport>
          </security>
        </binding>
      </webHttpBinding>
    </bindings>

    <services>
      <service name="MyWCFServices.DemoREST" behaviorConfiguration="DemoREST">

        <!--Define base https base address-->
        <host>
          <baseAddresses>
            <add baseAddress="https://localhost:44300/HelloWorldService.svc/"/>
          </baseAddresses>
        </host>

        <!--webHttpBinding allows exposing service methods in a RESTful manner-->
        <endpoint name="rest" address="" binding="webHttpBinding"
             contract="MyWCFServices.IDemoREST" bindingConfiguration="webHttpTransportSecurity"
                  behaviorConfiguration="DemoREST"/>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="DemoREST">
          <!-- To avoid disclosing metadata information, set the value below to
         false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.
         Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>

          <!--Using custom username and Password-->
          <serviceCredentials>
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="MyWCFServices.CustomUserNameValidator, HelloWorldService" />
          </serviceCredentials>
          <serviceAuthenticationManager authenticationSchemes="Basic"/>
        </behavior>

      </serviceBehaviors>

      <!--Required default endpoint behavior when using webHttpBinding-->
      <endpointBehaviors>
        <behavior name="DemoREST">
          <webHttp/>
        </behavior>
      </endpointBehaviors>

    </behaviors>

  </system.serviceModel>
</configuration>

And Custom validator class:
namespace MyWCFServices
{
    class CustomUserNameValidator : UserNamePasswordValidator
    {
        // This method validates users. It allows in two users, user1 and user2
        // This code is for illustration purposes only and
        // must not be used in a production environment because it is not secure.
        public override void Validate(string userName, string password)
        {

            if (null == userName || null == password)
            {
                throw new ArgumentNullException("You must provide both the username and password to access this service");
            }

            if (!(userName == "user1" && password == "test") && !(userName == "user2" && password == "test"))
            {
                // This throws an informative fault to the client.
                throw new FaultException("Unknown Username or Incorrect Password");
                // When you do not want to throw an informative fault to the client,
                // throw the following exception.
                // throw new SecurityTokenException("Unknown Username or Incorrect Password");
            }
        }

    }

}

Please guide me if I am wrong anywhere.


text:
Q: Oracle scheduler max_jobs_Slave_processes is set to null, how many will be allocated? Executing the following query against my database:
select value
from dba_scheduler_global_attribute
where attribute_name='MAX_JOB_SLAVE_PROCESSES';

yields a value of NULL.  My question is what is the maximum number of slave processes that could be allocated, for job runs, when this value is set to null?

A: NULL implies no limits. Anything other than NULL sets a limit.
See the documentation here.


text:
Q: Codeigniter pagination libraries I'm looking for codeigniter pagination library, where my pages would be displayed like this:

1 2 3 4 5 ... 11 12 13 14 ... 27 28 29

I mean with adjacent. Where can I find it? My php knowledge is not so good to rewrite pagination library

A: use codeigniter user guide Pagination

A: try this code. You can change the logic according to your needs:-
let totalcount = Math.ceil(JSON.parse(this.response).total / limit), HTML = "", j = 1;
(page > 3) ? HTML += "<button>...</button>" : null;
(page === 1) ? page = page + 1 : (page === totalcount) ? page = (totalcount - 1) : page;
for (let i = Math.max(2, page - j); i <= Math.min(totalcount - 1, page + j); i++) {
    HTML += "<button onclick=loadDoc(" + i + ")>" + (i) + "</button>"
}
(page < 10) ? HTML += "<button>...</button>" : null;
HTML += "<button onclick=loadDoc(" + totalcount + ")>" + (totalcount) + "</button>";
document.getElementById("pager").innerHTML = HTML;


text:
Q: Android swipe left and right in RelativeLayout I am trying to implement swipe left or right in my RelativeLayout. I wrote some code but could not get swipe left or right working. I am using GestureDetector
this is a my source
private GestureDetector gesturedetector = null;
private RelativeLayout swipelayout;

@SuppressLint("UseValueOf")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.strada_menu_result_loadmore,
            container, false);

    swipelayout = (RelativeLayout) rootView.findViewById(R.id.swipelayout);

    gesturedetector = new GestureDetector(new MyGestureListener());
    swipelayout.setOnTouchListener(new OnTouchListener() {

        @Override

        public boolean onTouch(View v, MotionEvent event) {

        gesturedetector.onTouchEvent(event);

        return true;

        }

        });

    return rootView;

}

public boolean dispatchTouchEvent(MotionEvent ev){

    return gesturedetector.onTouchEvent(ev);
}

class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

    private static final int SWIPE_MIN_DISTANCE = 150;

    private static final int SWIPE_MAX_OFF_PATH = 100;

    private static final int SWIPE_THRESHOLD_VELOCITY = 100;

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
            float velocityY) {

        float dX = e2.getX() - e1.getX();

        float dY = e1.getY() - e2.getY();

        if (Math.abs(dY) >= SWIPE_THRESHOLD_VELOCITY
                && Math.abs(velocityX) >= SWIPE_THRESHOLD_VELOCITY &&

                Math.abs(dX) >= SWIPE_MIN_DISTANCE) {

            if (dX > 0) {

                Toast.makeText(getActivity(), "Right Swipe",
                        Toast.LENGTH_SHORT).show();

            } else {

                Toast.makeText(getActivity(), "Left Swipe",
                        Toast.LENGTH_SHORT).show();

            }

            return true;

        }
        return false;

    }
}

what am i doing wrong? if anyone knows solution please help me
thanks

A: You just need an OnTouchListener, that should be all for simple answer. Take a look.
I used this code in some working project, so everything should work fine. But let me know if there is something missing and doesn't work.
yourRelativeLayout.setOnTouchListener(new OnTouchListener() {

    int downX, upX;

     @Override
     public boolean onTouch(View v, MotionEvent event) {

         if (event.getAction() == MotionEvent.ACTION_DOWN) {
             downX = (int) event.getX();
             Log.i("event.getX()", " downX " + downX);
             return true;
         }

         else if (event.getAction() == MotionEvent.ACTION_UP) {
             upX = (int) event.getX();
             Log.i("event.getX()", " upX " + upX);
             if (upX - downX > 100) {

                 // swipe right
             }

             else if (downX - upX > -100) {

                 // swipe left
             }
             return true;

             }
             return false;
         }
     });

A: Try this will help you....
OnSwipeTouchListener.java:
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class OnSwipeTouchListener implements OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener (Context ctx){
        gestureDetector = new GestureDetector(ctx, new GestureListener());
    }

    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight();
                        } else {
                            onSwipeLeft();
                        }
                    }
                } else {
                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffY > 0) {
                            onSwipeBottom();
                        } else {
                            onSwipeTop();
                        }
                    }
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }
}

Usage:
imageView.setOnTouchListener(new OnSwipeTouchListener() {
    public void onSwipeTop() {
        Toast.makeText(MyActivity.this, "top", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeRight() {
        Toast.makeText(MyActivity.this, "right", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeLeft() {
        Toast.makeText(MyActivity.this, "left", Toast.LENGTH_SHORT).show();
    }
    public void onSwipeBottom() {
        Toast.makeText(MyActivity.this, "bottom", Toast.LENGTH_SHORT).show();
    }

public boolean onTouch(View v, MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}
});


text:
Q: python writing to text file options I have a text file with the following lines
test1
test2
test3

and I want the python script to insert a new line in the top of the file then edit each line after that like the following
Python
Test : test1 -t
Test : test2 -t
Test : test3 -t

Any suggestions ?
Thanks

A: I would stay away from trying to manipulate the file directly - I am even not sure if this is working. It is much simpler to read in the file and then overwrite the new file - as long as your input file will never exceed your memory:
with open('file.txt') as fin:
    # get lines of the file as list
    lines = fin.readlines()
# Overwrite file.txt with new content
with open('file.txt','w') as fout:
    fout.write('Python\n')
    for line in lines:
        fout.write('Test: ' + line.strip() + ' -t\n')

If memory is of concern and you don't mind to get a new file:
with open('file.txt') as fin:
    fout = open('newfile.txt','w')
    fout.write('Python\n')
    for line in fin:
        fout.write('Test: ' + line.strip() + ' -t\n')
    fout.close()


text:
Q: Как скачать картинку с blob: Есть картинка на сайте в таком виде:
blob:https://esia.gosuslugi.ru/d5a078a6-cb94-46e0-a81a-074c638d8930
blob означает что картинка хранится в памяти. То-есть просто запросом скачать её не получается.
Мне всего лишь нужно скачать её. Но не получается, подскажите пожалуйста.


text:
Q: boost::make_recursive_variant has no member named 'apply_visitor' First time using Boost, and trying to grok how to use boost::variant. Please find below an example program and the error message (GCC v5.3.0, -std=c++14)
#include <vector>
#include <iostream>
#include <sstream>

#include <boost/variant.hpp>

using int_tree_t =
    boost::make_recursive_variant <
      int,
      std::vector<boost::recursive_variant_>>;

auto operator << (std::ostream& out, const int_tree_t& tree) ->
std::ostream&
{
  struct stringify :
    public boost::static_visitor <std::string>
  {
  public:
    auto operator () (int i) const ->
    std::string
    {
      return std::to_string (i);
    }

    auto operator () (const std::vector<int_tree_t>& vec) const ->
    std::string
    {
      std::stringstream ss;
      ss << "(";

      auto it = std::begin (vec);

      if (!vec.empty ()) {
        ss << *it;
      }

      for (; it != std::end (vec); ++it) {
        ss << " " << *it;
      }

      ss << ")";

      return ss.str ();
    }
  };

  std::stringstream ss;
  ss.flags (out.flags ());

  ss << boost::apply_visitor (stringify (), tree);

  return (out << ss.str ());
}

Error message:
In file included from /usr/local/include/boost/variant/apply_visitor.hpp:16:0,
                 from /usr/local/include/boost/variant/detail/hash_variant.hpp:23,
                 from /usr/local/include/boost/variant/variant.hpp:34,
                 from /usr/local/include/boost/variant.hpp:17,
                 from test2.cpp:5:
/usr/local/include/boost/variant/detail/apply_visitor_unary.hpp: In instantiation of 'typename Visitor::result_type boost::apply_visitor(const Visitor&, Visitable&) [with Visitor = operator<<(std::ostream&, const int_tree_t&)::stringify; Visitable = const boost::make_recursive_variant<int, std::vector<boost::recursive_variant_, std::allocator<boost::recursive_variant_> > >; typename Visitor::result_type = std::__cxx11::basic_string<char>]':
test2.cpp:50:43:   required from here
/usr/local/include/boost/variant/detail/apply_visitor_unary.hpp:84:43: error: 'const struct boost::make_recursive_variant<int, std::vector<boost::recursive_variant_, std::allocator<boost::recursive_variant_> > >' has no member named 'apply_visitor'
     return visitable.apply_visitor(visitor);
                                           ^

If I understand correctly, boost::make_recursive_variant is supposed to create a type which acts identical to boost::variant... but the error message appears to indicate that it doesn't have the apply_visitor function, which is necessary for visitation. I've read over [this(http://www.boost.org/doc/libs/1_60_0/doc/html/variant/tutorial.html) page, but there's nothing there about having to use a "special" visitation pattern with recursive variants.
How should I be writing this program?

A: make_recursive_variant is a metafunction, not a type in its own right. So you have to evaluate the metafunction:
using int_tree_t =
    boost::make_recursive_variant <
      int,
      std::vector<boost::recursive_variant_>>::type;
                                             ↑↑↑↑↑↑

Otherwise, you're using a metafunction type instead of a variant type.


text:
Q: How to add links to modal window in ExtJs I am trying to create a list of links from a data store, and then use an XTemplate to loop through and display all the links in the data store.  I am trying to display the links in a modal window.  This is my code:
var win;

var tpl = new Ext.XTemplate("<p>Field1: {f1}, Field2: {f2} </p>").compile();
var data = {
    f1: 'a',
    f2: null
};

if(!win){
    win = new Ext.Window({
        el:'hello-win',
        layout:'fit',
        width:500,
        height:300,
        closeAction:'hide',
        plain: true,

        items: [
            {
                xtype: 'component',
                autoEl: {
                    html: '<input type="text">'
                },
                listeners: {
                    render: function(_component) {
                        _component.getEl().on('keyup', function(e) {
                            //console.log(this);
                            console.log(this.dom.childNodes[0].value);
                        });
                    }
                }
            },
            {
                xtype: 'panel',
                title: 'test',
                height: 100,
                bodyPadding: 10,
                tpl: tpl,
                data: data,
                renderTo: Ext.get('hello-win')
            }
        ]
    });
}
win.show(this);

There are no errors in console, but the links never load.  It just shows my modal window and my textbox, but no links.  I would put in in a jsfiddle, but I don't know how (I'm new to ExtJs).
How can I display a list of links in this modal window?

A: *

*You should not define renderTo in you panel config. Component defined in items array will be rendered to parent component automatically.

*Your window have two items so you can not use fit layout. This layout can be used only if component have only one child component. You can remove layout definition and Ext JS framework will use auto layout or you can use some layout which support more child items, like hbox, vbox, etc.

Your code should look like this:
var win = new Ext.Window({
    width:500,
    height:300,
    closeAction:'hide',
    plain: true,
    items: [
        {
            xtype: 'textfield',
            enableKeyEvents: true,
            listeners: {
               keyup: function(c) {
                   console.log(c.getValue());
               }
            }
        },
        {
            xtype: 'panel',
            title: 'test',
            height: 100,
            bodyPadding: 10,
            tpl: tpl,
            data: data
        }
    ]
});

Also you should consider using textfield component instead of creating textfield by using component with autoEl config.


text:
Q: Delete files with regular expression with negation Tried to create a script to delete files from the directory in a first script argument that does not contain a sequence of symbols in a second script argument. But It doesn't do a thing.
What I tried:
find $1 -name !\(.*$2.*\) | tee file | cat

Where am I wrong?

A: Use -regex for a regex, not -name. Use -! or -not for negation:
find "$1" -not -regex ".*$2.*"

Quoting the variables should be safer than using them unquoted.


text:
Q: Astronaut is freed from mind parasite when he leaves Earth's gravity well In the late 90s I read a short story (probably written much earlier) in which an astronaut on a mission to Mars is surprised to discover that he has spent his whole life with an invisible and undetectable entity controlling his mind.
The entity can only exist within a gravity well, so when he escapes Earth's gravity it releases control and falls back to Earth. The astronaut realizes that all humans on Earth are infected and controlled by these beings, who cloud men's minds and keep them embroiled in war and strife to keep humans down and maintain their control. He plans to bring more humans out of Earth's gravity to Mars where they can live free, and eventually strike back and free Earth.
Ending spoiler:

 As his ship lands on Mars he feels his brain being taken over, and realizes that he was a fool to think that such creatures only existed on Earth.

Can anyone identify the story?

A: In the late 90s I read a short story (probably written much earlier)
"Unwelcome Tenant" by Roger Dee, first published in Planet Stories, Summer 1950, available at the Internet Archive. If you read it in the '90s, it was probably in the anthology Fifty Short Science Fiction Tales edited by Isaac Asimov and Groff Conklin.
in which an astronaut on a mission to Mars

The feeling that he was a pioneer, an advance guard for a conquering people, elated him and multiplied the eagerness in him when he turned his eyes to the forward port where Mars hung, full and ruddy, a spotted enigmatic disc of promise.

is surprised to discover that he has spent his whole life with an invisible and undetectable entity controlling his mind.

He had been host to a parasitic intelligence, without knowing it, all his life. He had moved at Its dictates, following his own will only when It slept or tired or was distracted, never succeeding fully in any endeavor of his own because It was in control and must be obeyed. He knew when he had explored the vacated premises of his newly freed mind that It was only one of many, that all earthmen had Tenants like It, intangible parasitic entities subsisting upon and controlling the human life force.

The entity can only exist within a gravity well, so when he escapes Earth's gravity it releases control and falls back to Earth.

His first conclusion was inescapable: his Tenant had left him because It could not exist outside Earth's gravity. It had been forced to quit him or perish, and Its departure had made him the first truly free man.

The astronaut realizes that all humans on Earth are infected and controlled by these beings, who cloud men's minds and keep them embroiled in war and strife to keep humans down and maintain their control.

He thought: No wonder we have wars on Earth! We have no common ground for agreement because we are under Their compulsion. They know our inherent abilities and keep us at each others' throats lest we learn of and destroy them. Everything that man had accomplished has been done in spite of Them.

He plans to bring more humans out of Earth's gravity to Mars where they can live free, and eventually strike back and free Earth.

In a few hours he would land on Mars, and in a matter of minutes he would set up a beam transmitter to report back to the scientific foundation that had sent him out. He could not tell his fellows the truth because they were still captive, and their Tenants must not be warned; but he could invent a plausible story of easily acquired wealth on Mars that would bring other and larger commercial expeditions swarming after him. With the help of other freed men he could found a new civilization on the red planet, develop means to carry the fight back to Earth and exterminate the Tenants utterly. It would take time, but in the end men would be free.

Ending spoiler:

Something impinged sharply upon his new perception, a chill groping tentacle of questioning intelligence. The smile froze on his face; he sat up stiffly, numbed with the unforeseen horror of what was happening to him. The groping ceased, and the hungry Intelligence from outside poured into his mind like smoke into an empty room, smothering his feeble attempt at resistance.He rose and went to the forward port, staring dully down at the uprushing sandy wastes and trying to recall what glorious thing it was that he had been thinking. Or had it been only a dream? Somewhere in the farthest recess of his blunted consciousness a thought formed and floated like a bubble up into his awareness; but like a bubble it burst, and its meaning was lost on him.There were Tenants on Earth, it said. Why not on Mars, too?


text:
Q: Why is there a long delay between WCF TransportReceive and ServiceLevelReceiveReply? I have two environments running the same WCF web service but one of them seems to have a 3-5 minute delay returning the XML data.  The slow down seems to occur in relation to the size of the data being returned.  The web service just retrieves an XML string from a database so the processing time is constant.
The endpoint bindings are the same for both but I'm wondering what else would cause a delay.
I ran a trace and it shows that the TransportReceive happens at the same time on both environments, but on the delayed environment the ServiceLevelReceiveReply occurs after 3-5 minutes.
Any idea what could cause this?  I'm happy to provide as much data as possible.

Here are the two bindings that are used.  MyPolicySoap is used for getting the XML.
<basicHttpBinding>
      <binding name="MyPolicySoap" closeTimeout="00:11:00" openTimeout="00:11:00" receiveTimeout="00:10:00" sendTimeout="00:11:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="5000000" maxBufferPoolSize="524288" maxReceivedMessageSize="5000000" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
         <readerQuotas maxDepth="32" maxStringContentLength="5000000" maxArrayLength="16384" maxBytesPerRead="5000000" maxNameTableCharCount="16384"/>
      <security mode="None">
            <transport clientCredentialType="Windows" proxyCredentialType="None" realm=""/>
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>
    </binding>
</basicHttpBinding>

<wsHttpBinding>
      <binding name="MyConfig" maxReceivedMessageSize="2147483647">
         <readerQuotas maxStringContentLength="2147483647"/>
         <security mode="None">
            <transport clientCredentialType="Windows" proxyCredentialType="None" realm=""><!--<extendedProtectionPolicy policyEnforcement="Never" />--></transport>
            <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true"/>
      </security>
    </binding>
</wshttpbinding>


text:
Q: How to make a script that checks if a number is an integer in batch I'm trying to make a script that requires an integer number, and i need to be able to check if the number is an integer.

A: You don't need to keep the examples at the top; they're just there to show you how to use the function. Also, it's modular so you can just throw it in your code and it will work unless you've already got those variable names used.
@echo off
cls
:: This is a positive integer and will return TRUE
Call :isNum 54
echo %retval%

:: This is a negative integer and will return TRUE
Call :isNum -13
echo %retval%

:: This is not an integer and will return FALSE
Call :isNum 15a7
echo %retval%

:: This is a decimal and will return FALSE
Call :isNum 12.7
echo %retval%
exit /b

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Determines if a string argument is an integer value
::
:: Arguments: %1 - the string to check
:: Returns:   TRUE if the string is an integer, FALSE otherwise
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:isNum
setlocal enabledelayedexpansion
set num=%1

:: Strip the leading negative symbol if there is one
if "!num:~0,1!"=="-" set num=!num:~1!

:: Use all digits as delimiters. If there is anything left, it's not an integer.
for /f "delims=1234567890" %%A in ("%num%") do (
    set new_num=%%A
)

set is_num=TRUE
if not "!new_num!"=="" set is_num=FALSE

endlocal&set retval=%is_num%

A: This script takes advantage of EXIT /B:
@echo off
setlocal EnableDelayedExpansion

set /p x=
call :isint %%x%%
echo %errorlevel%

pause
exit /b

:isint
set "arg=%~1"
if NOT "!arg:?=!" == "!arg!" exit /b 1

cmd /c exit /b !arg!
if NOT "%ERRORLEVEL%" == "!arg!" exit /b 1

exit /b 0

Returns a ERRORLEVEL of 0 if a integer, 1 otherwise.
Even works with ", & and /?.

The definition of a int32 is any value from 2^31-1 to -2^31. (2^31 will overflow)