text:
Q: CUDA: Runge-Kutta trajectory on each GPU thread Summary: How do you avoid performance loss caused by different work loads for different threads? (Kernel with a while loop on each thread)
Problem:
I want to solve particle trajectories (described by a 2nd order differential equation) using Runge-Kutta for many different initial conditions. The trajectories will generally have different lengths (each trajectory ends when a particle hits some target). Furthermore, to ensure numerical stability, the Runge-Kutta stepsize is set adaptively. This leads to two nested while-loops, with unknown number of iterations (see serial example below).
I want to implement the Runge-Kutta routine to run on a GPU with CUDA/C++. The trajectories have no dependency of each other, so as a first approach, I will just parallelize over the different initial conditions such that each thread will correspond to a unique trajectory. When a thread is done with a particle trajectory, I want it to start with a new one.
If I understand it correctly, however, the unknown length of each while loop (particle trajectory) means that different threads will get different amounts of work, which might lead to a severe performance loss on GPU.
Question: Is this possible to overcome (in a simple way) the performance losses caused by different work load for different threads? For example setting each warp size to be only 1, such that each thread(warp) can then run independently? r will this lead to other performance losses (e.g. no coalesced memory reads)?
Serial pseudo-code:
// Solve a particle trajectory for each inital condition
// N_trajectories: much larger than 1e6
for( int t_i = 0; t_i < N_trajectories; ++t_i )
{
    // Set start coordinates
    double x = x_init[p_i];
    double y = y_init[p_i];
    double vx = vx_init[p_i];
    double vy = vy_init[p_i];
    double stepsize = ...;
    double tolerance = ...;
    ...

    // Solve Runge-Kutta trajectory until convergence
    int converged = 0;
    while ( !converged )
    {
        // Do a Runge-Kutta step, if step-size too large then decrease it
        int goodStepSize = 0
        while( !goodStepSize )
        {
            // Update x, y, vx, vy
            double error = doRungeKutta(x, y, vx, vy, stepsize);

            if( error < tolerance )
                goodStepSize = 1;
            else
                stepsize *= 0.5;
        }

        if( (abs(x-x_final) < epsilon) && (abs(y-y_final) < epsilon) )
            converged = 1;
    }
}

A short test of my code shows that the inner while-loop runs 2-4 times in 99% of all cases and >10 times in 1% of all cases, before a satisfactory Runge-Kutta step-size was found.
Parallel pseudo-code:
int tpb = 64;
int bpg = (N_trajectories + tpb-1) / tpb;
RungeKuttaKernel<<<bpg, tpb>>>( ... );

__global__ void RungeKuttaKernel( ... )
{
    int idx = ...;

    // Set start coordinates
    double x = x_init[idx];
    ...

    while ( !converged )
    {
        ...

        while( !goodStepSize )
        {
            double error = doRungeKutta( ... );
            ...
        }

        ...
    }
}

A: I will attempt to answer the question myself, until someone comes up with a better solution.
Pitfalls with directly porting the serial code:
The two while loops will lead to significant branch divergence and performance loss. The outer loop is the "full" trajectory, while the inner loop is one Runge-Kutta step with adaptive step size correction. Inner loop: If we attempt to solve Runge-Kutta with a too large step size then the approximation error will be too large, and we need to redo the step with a smaller step size until the error is smaller than our tolerance. This means that threads that need very few iterations to find an appropriate step size will have to wait for threads that need more iterations. Outer loop: this reflects how many successful Runge-Kutta steps we need before the trajectory is completed. Different trajectories will reach their target in different amount of steps. We will always have to wait for the trajectory with the most iterations before we are completely done.
Proposed parallel approach:
We notice that every iteration consists of doing one Runge-Kutta step. The branching comes from the fact that we either need to reduce the step size for the next iteration, or update the Runge-Kutta coefficients (e.g. positon/velocity) if the step size was OK. I therefore propose that we replace the two while-loops with one for-loop. The first step of the for-loop is to solve Runge-Kutta, followed by an if-statement to check if the step size was small enough or if updating the positions (and checking for total convergence). All threads will now solve only one Runge-Kutta step at a time, and we trade away low occupancy (all threads wait for the thread that need the most attempts to find the correct step size) for the cost of branch divergence of a single if-statement. In my case, solving Runge-Kutta is expensive compared with the evaluations of this if-statement, so we have made an improvement. The issue now lies in setting an appropriate limit on the for-loop and flagging the threads that need more work. This limit will set an upper bound on the longest time a finished thread has to wait for others. Pseudo-code:
int N_trajectories = 1e6;
int trajectoryStepsPerKernel = 50;
thrust::device_vector<int> isConverged(N_trajectories, 0); // Set all trajectories to unconverged
int tpb = 64;
int bpg = (N_trajectories + tpb-1) / tpb;

// Run until all trajectories are converged
while ( vectorSum(isConverged) != N_trajectories )
{
    RungeKuttaKernel<<<bpg, tpb>>>( trajectoryStepsPerKernel, isConverged, ... );
    cudaDeviceSynchronize();
}

__global__ void RungeKuttaKernel( ... )
{
    int idx = ...;

    // Set start coordinates
    int converged = 0;
    double x = x_init[idx];
    ...

    for ( int i = 0; i < trajectoryStepsPerKernel; ++i )
    {
        double error = doRungeKutta( x_new, y_new, ... );

        if( error > tolerance )
        {
            stepsize *= 0.5;
        } else {
            converged = checkConvergence( x, x_new, y, y_new, ... );
            x = x_new;
            y = y_new;
            ...
        }
    }

    // Update start positions in case we need to continue on trajectory
    isConverged[idx] = converged;
    x_init[idx] = x;
    y_init[idx] = y;
    ...
}


text:
Q: TestFlight automatically creates new builds Since I began to use TestFlight, I constantly run into a weird issue : when an user (which I invited) downloads and uses my freshly uploaded build, TestFlight randomly creates new updates of my build, and an anonymous uses it and crash it without installing it or  even passing by checkpoints.
Here is my list of builds :

The build #2 is the one I uploaded, and the #7 and #8 are created automatically (I already deleted #3 to #6 to see if it would create new updates again)
Here's what I get when I check #8 informations :

And I can see that an Anonymous user successfully crashed my app on a x86_64 architecture, I believe this is a desktop iOS simulator :

I can't find what I'm doing wrong, I think I followed the workflow without mistake, as I retried it 2 times.
I've checked online and I didn't find a similar case so far...
Do you have any clue of what could be happening?

A: As one of the software engineers at TestFlight I can provide some insight into this.
This was the result of new feature code in TestFlight recently added to display (and automatically add) builds from production (non-beta). If you leave the TestFlight SDK code in the application when you submit it to Apple's store, then TestFlight will receive events from those production builds - it will automatically create those production builds so that crashes from them can be monitored (independent of beta build crashes).
In order to better communicate these changes to TestFlight users, these production builds will be removed in the meantime and rolled out at a future date.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL-Server 2008: How to update fields with a counter? On PostgrSQL its no problem for me to do this:
CREATE SEQUENCE serial_olw START 1;
update collections_elements set elementorder=(nextval('serial_olw')-1) WHERE collections_elements.collectionid=1;
drop sequence serial_olw;

Example: 1,2,3,4,5,6...
On a MS-SQL Server 2008 there is not a function SEQUENCE... so I tried this:
DECLARE @i int
SET @i = 0

WHILE @i<44
    BEGIN
    UPDATE collections_elements set elementorder=(@i) WHERE collections_elements.collectionid=1
        SET @i=@i+1
    END

But I have no success  with that loop...
Example: 43,43,43,43,43...
Any ideas for a solution?

A: Update t
Set t.elementorder = t.RowID
From
(
    Select ROW_NUMBER() Over(Order by collectionid) as RowID, * From collections_elements
)t

SQL Fiddle

A: update T
set elementorder = rn
from
  (
    select elementorder,
           row_number() over(order by (select 0)) as rn
    from collections_elements
    where collectionid = 1
  ) T

SE-Data

A: Try something like this - inline variable increment:
DECLARE @i int
SET @i = 0

WHILE @i<44
BEGIN
    UPDATE collections_elements
    SET @i = elementorder = @i + 1
    WHERE collections_elements.collectionid=1
END

A: this script is a sample.
Try something like this - inline variable increment:
DECLARE @i int
SET @i = 1

BEGIN
    UPDATE Questionnaire
    SET prioritize = @i
    ,  @i = @i +1
    WHERE documentTypeCode=2 and groupCode=02
END


text:
Q: How to create a new point file containing selected points? Using QGIS 2.16.3, I have uploaded a point dataset. Using the attribute table, I have made a selection of several points, and would like to create a new point layer containing only the selected points. I have consulted:
How to create a new layer from a selection in QGIS?
Problematically, my menu selection is somewhat different form the one here, and I can not choose 'Save selection as'. Is there any other way to choose the selection?


text:
Q: Problem with partitions in Kubuntu leading to pc crashing Question: Are my partitions causing problems with my Kubuntu and result in it crashing?
Problem: I think my partitions are wrong and thus my Kubuntu crashes often, which leads me to think it is a memory problem, since either my screen freezes or goes dark. Then I usually hit the restart button on my pc.
In KDE Partition Manager I deleted the windows partition after installing Kubuntu, so its marked as unallocated but still upon rebooting one of the boot options is "Windows Recovery Environment (on /dev/sdb1). Here a picture of KDE partition manager:#first pic of partiton manager for my disc
Now as you can see it is highest on the list(unallocated aka where windows used to be)(not sure if it matters), but looking at the properties of all of these it just seems weird, but since I do not have time to teach myself all of the necessary aspects I need your help to tell me if something is wrong. Here are pics of the properties:
Device Properties
Device Properties, /dev/sda
Unallocated partition properties(Old windows)
Unallocated properties
/dev/sda2 properties(So just under unallocated)
/dev/sda2 (green edges, the one which reads extented)
/dev/sda5 partition, which to my knowledge contains my Kubuntu OS
/dev/sda5 Kubuntu
So as you can see to me it looks off, but I do not know much about how these work and unfortunately my studies take up my time and I have attention problems. Next a small back story.
I recently changed from Ubuntu 20.04 to Kubuntu 20.04 after a friends recommendation. Now when I built my pc I tried Zorin(which I managed to break so it was unusable after 1h), then windows(which never worked) until I went with Ubuntu. Now when installing Kubuntu I tried clearing all old partitions etcetera but I think my error was doing it after installation of Kubuntu.
I am very grateful for anyone who could tell me if my partitions are a problem. If they are then I hope you can also help me fix it. Thank you in advance to anyone who can help, I need to focus on studies and my pc crashing all the time does not help.
Yannick


text:
Q: Gradle: How can I add some files to the root location of my jar file? I generate with gradle a jar file for my spring application and I want to add some resources to the root of the jar file.
Current result:
server.jar
|--org
|--META-INF
|--BOOT-INF
|----lib
|----classes
|------files from resources jar
|------other stuff

Desired result:
server.jar
|--files from resources jar <-- root location!!!
|--org
|--META-INF
|--BOOT-INF
|----lib
|----classes
|------other stuff

And here is my gradle jar task:
jar {
    baseName = 'chessgame-server'
    version = '1.0.0'
    from(zipTree("${rootProject.projectDir}/client/build/libs/chessgame-client-1.0.0.jar")) <-- resources
}

Anyone an idea how I can add files to the root location of my jar file?
Thanks


text:
Q: How to import package in online code editor? I'm trying to write in online editor with python2.7.  But I can't import library e.g import igraph.
How can I import it or every library to editors?
I can't find anything in their help.
Editors such as: tutorialspoint or repl

A: It seems as if neither the Tutorialspoint nor Repl.it interpreters have the igraph module installed on their end, and so you cannot import it. If you want to use igraph in an interpreter, you'll have to install it on your machine for use. Can be done with pip install python-igraph, and I'm sure there's a homebrew equivalent if you're on macOS.

A: The online editor doesn't support installation of modules. You have to use something like PyCharm, Python IDE, or Anaconda to be able to install modules.


text:
Q: Python Classes ( AttributeError: '' object has no attribute '') Having trouble understanding the problem in my code, new to classes (generally python too, so sorry if I name things wrong). I receive this error:
I think my code is too long winded to include in here, so I made a simplified version to test the concept below.
The question is, how can I create a new self object  "self4"? Which would then be available to other functions within the class. Currently I get this error.

AttributeError: 'className' object has no attribute 'self4'

class className(object):

   def __init__(self, self1=1,self2=2,self3=3):
        self.self1=self1
        self.self2=self2
        self.self3=self3

   def evaluate(self, self5):
        print className.func1(self) + className.func2(self)
        self.self5=self5
        print className.func1(self)

   def func1(self):
       return self.self1 + self.self5

   def func2(self):
       self.self4 = self.self1+self.self2+self.self3
       return self.self4

filename tester.py
import tester.py

mst=tester.className()

mst.evaluate()

A: Edit:
Your code works fine!
What is the Problem?
I still think it is better to move self4 into the init!
Original
I think the most logical thing would be to define self4 on init:
class className(object):
    def __init__(self, self1=1, self2=2, self3=3):
        self.self1 = self1
        self.self2 = self2
        self.self3 = self3
        self.self4 = None

   #rest of class

A: If anyone still has this issue: you get this error when your indentation is goofed.To fix the asked question above, you just have to add a space before the last two functions definitions, that is;
class className(object):

    def __init__(self, self1=1,self2=2,self3=3):
        self.self1=self1
        self.self2=self2
        self.self3=self3

    def evaluate(self, self5):

        print className.func1(self) + className.func2(self)
        self.self5=self5
        print className.func1(self)

    def func1(self):
        return self.self1 + self.self5

    def func2(self):
        self.self4 = self.self1+self.self2+self.self3
        return self.self4

just make sure they all have similar indentation, and you are good to go.

A: You should pass self4 in method.


text:
Q: How to re-attach the fragment to the activity? When I rotate my screen the fragment will detach from the activity. However I have a listener in my fragment which runs the asynctask after a button is pressed. That works fine. So I'm searching way to do the same without the button so directly when the page is changed.
In my MainActivity I have a onPageChangeListener looking like this :
    @Override
    public void onPageSelected(int position)
    {
        // TODO Auto-generated method stub
        currentSelectedFragmentPosition = position;
        frag.onPageVisible(currentSelectedFragmentPosition);
                    frag2.onPageVisible(currentSelectedFragmentPosition);
    }

Then in my fragment the onPageVisible function is this :
public void onPageVisible(int position)
{
    tabstrippos = position;

    if (MainActivity.selected[0])
    {
        if (tabstrippos == pageNumber)
        {
            mainActivity = getContext();
            if (totalItems < 3)
            {
                if (isAdded())
                {
                    startNewAsyncTask();
                }
                else
                {
                    Log.w("tag", "its not added");
                }
            }
        }
    }
}

This goes to the else after rotate because the activity is detached
The listener I was talking about comes from a gitHub class I use gitHub
and looks like this inside my fragment :
onStart()
{
....

    ((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener()
    {
        @Override
        public void onRefresh()
        {
            // Do work to refresh the list here.
            startNewAsyncTask();
        }
    });

A: There is no looping like in other systems, here, as soon as you change the boolean, you have to call some method to react to it.


text:
Q: How to give #3f51b5 color code programmatically for shadow color in ios I want to make shadow color with #3f51b5.
How can I do that. hope your help. this type cannot use to do that.
cell.layer.shadowColor = [UIColor purpleColor].CGColor;

A: after setting the color give shadow radius,offset and opacity, convert the color to rgba and use this
  cell.layer.shadowColor = [UIColor colorWithRed:0.2471 green:0.3176 blue:0.7098 alpha:1.0].CGColor;
  cell.layer.shadowRadius=10;
  cell.layer.shadowOffset=CGSizeMake(1, 1);
  cell.layer.shadowOpacity=1;

if you want to use hex color only use this
How can I create a UIColor from a hex string?

A: you need to set shadow first
cell.layer.shadowRadius=8;
cell.layer.shadowOffset=CGSizeMake(-1, -1);// this make top left shadow
cell.layer.shadowOpacity=1;
cell.layer.shadowColor = [UIColor colorWithRed:0.2471 green:0.3176 blue:0.7098 alpha:1.0].CGColor;


text:
Q: Batch not-equal (inequality) operator According to this, !==! is the not-equal string operator.
Trying it, I get:
C:\> if "asdf" !==! "fdas" echo asdf
!==! was unexpected at this time.

What am I doing wrong?

A: NEQ is usually used for numbers and == is typically used for string comparison.
I cannot find any documentation that mentions a specific and equivalent inequality operand for string comparison (in place of NEQ).  The solution using IF NOT == seems the most sound approach.  I can't immediately think of a circumstance in which the evaluation of operations in a batch file would cause an issue or unexpected behavior when applying the IF NOT == comparison method to strings.
I wish I could offer insight into how the two functions behave differently on a lower level - would disassembling separate batch files (that use NEQ and IF NOT ==) offer any clues in terms of which (unofficially documented) native API calls conhost.exe is utilizing?

A: Try
if NOT "asdf" == "fdas" echo asdf

A: I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and @Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)
I pulled this from the example code in your link:
IF !%1==! GOTO VIEWDATA
REM  IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM  PRINT LINE WITH STRING MATCH, THEN EXIT.

:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM  SHOW ENTIRE FILE, 1 PAGE AT A TIME.

:EXIT0

!%1==! is simply an idiomatic use of == intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The ! in this case is just a character placeholder. It could be anything. If %1 has content, then the equality will be false, if it does not you'll just be comparing ! to ! and it will be true.
!==! is not an operator, so writing "asdf" !==! "fdas" is pretty nonsensical.
The suggestion to use if not "asdf" == "fdas" is definitely the way to go.

A: Try:
if not "asdf" == "fdas" echo asdf

That works for me on Windows XP (I get the same error as you for the code you posted).

A: The easiest way I found is to:
IF %ERRORLEVEL% NEQ 0 Echo An error was found

or
IF %ERRORLEVEL% GRT 0 goto error1

The operator !==! has not right value, which means that's used only to know whether a variable was set or not.
IF !%1==! GOTO main

A: Use NEQ instead.
if "asdf" NEQ "fdas" echo asdf


text:
Q: JCL SYNCSORT: OMIT and INCLUDE are not interchangeable? I'm getting different output for these two sort cards, can someone tell me why?
1.
INCLUDE COND=((1,3,CH,NE,C'ABC',AND,5,3,CH,NE,C'PQR'),OR,
              (1,3,CH,NE,C'CAB'),OR,
              (1,3,CH,NE,C'CBA'),OR,
              (1,3,CH,NE,C'ABC',AND,5,3,CH,NE,C'PQR'))
SORT FIELDS=COPY

2.
   OMIT COND=((1,3,CH,EQ,C'ABC',AND,5,3,CH,EQ,C'PQR'),OR,
              (1,3,CH,EQ,C'CAB'),OR,
              (1,3,CH,EQ,C'CBA'),OR,
              (1,3,CH,EQ,C'ABC',AND,5,3,CH,EQ,C'PQR'))
SORT FIELDS=COPY

This is basically, INCLUDE when NOT-EQUAL and OMIT when EQUAL.

A: The problem is you have not reversed the and's and or's. This means
they are very different sort tests so will give different answers
If you look at the first Test, in particular:
          (1,3,CH,NE,C'CAB'),OR,
          (1,3,CH,NE,C'CBA')

Is always true,
While the following is false when chars 1,3 is anything but CAB or CBA:
          (1,3,CH,EQ,C'CAB'),OR,
          (1,3,CH,EQ,C'CBA')

with boolean logic, the rules are
 not (a and b) = (not A) or (not b)
 not (a or b) = (not A) and (not b)

So when changing from omit to include, you must reverse the And & or's
OMIT COND=((1,3,CH,EQ,C'ABC',AND,5,3,CH,EQ,C'PQR'),OR,
          (1,3,CH,EQ,C'CAB'),OR,
          (1,3,CH,EQ,C'CBA'),OR,
          (1,3,CH,EQ,C'ABC',AND,5,3,CH,EQ,C'PQR'))
SORT FIELDS=COPY

becomes:
INCLUDE COND=((1,3,CH,NE,C'ABC',or,5,3,CH,NE,C'PQR'),and,
          (1,3,CH,NE,C'CAB'),and,
          (1,3,CH,NE,C'CBA'),and,
          (1,3,CH,NE,C'ABC',or,5,3,CH,NE,C'PQR'))
SORT FIELDS=COPY


text:
Q: Flex compiler breaking when I use -raw-metadata parameter So I have this shell script that compiles my AS3 classes to the SWF format.
Today I wanted to add a fancy timestamp to the "date" parameter on the metadata list. I'm trying to use the compiler option -raw-metadata but everytime I try to compile it gives me this error:
Adobe Flex Compiler (mxmlc)
Version 4.6.0 build 23201
Copyright (c) 2004-2011 Adobe Systems, Inc. All rights reserved.

command line: Error: default arguments may not be interspersed with other options

Use 'mxmlc -help' for information about using the command line.

Do you guys have any idea of why this is happening at all? Am I doing something stupid?
It works fine if I don't use -raw-metadata but set every single parameter individually.
Here is my build process (Makefile):
#
# Rafael Rinaldi (rafaelrinaldi.com)
# Feb 20, 2013
#

# Flex compiler.
mxmlc=/Users/rafaelrinaldi/Code/Flash/SDK/flex_sdk_4.6/bin/mxmlc

# Flash player.
player=/Applications/Adobe\ Flash\ CS6/Players/Debug/Flash\ Player\ Debugger.app

# Setup.
main=./src/Main.as
libraries=./libs
swc=./swc
source-path=./src
output=./bin/static/Main.swf
run=$(output)

# .swf settings.
fp=11.1
fps=60
bg=0xFFFFFF
dimension=865,720

# Flags.
as3=true
debug=true
strict=true

# Application info.
title=Main
creator=Rafael Rinaldi (rafaelrinaldi.com)
publisher=Rafael Rinaldi (rafaelrinaldi.com)
description=My application.
language=en-US
date=$(shell date +'%B %d, %Y')
timestamp=$(shell date +'%D %T')

# SWF meta data.
define swf_metadata
<metadata>
    <title>$(title)</title>
    <description>$(description)</description>
    <publisher>$(publisher)</publisher>
    <creator>$(creator)</creator>
    <language>$(language)</language>
    <date>$(timestamp)</date>
</metadata>
endef

export swf_metadata

all: compile run

# Compile main file into a .swf
compile:
    @echo "\nCompiling '$(main)'...\n"
    @$(mxmlc) \
    -as3=$(as3) \
    -debug=$(debug) \
    -strict=$(strict) \
    -target-player=$(fp) \
    -default-frame-rate=$(fps) \
    -default-background-color=$(bg) \
    -default-size=$(dimension) \
    -static-link-runtime-shared-libraries=true \
    -source-path=$(source-path) \
    -source-path+=$(libraries) \
    -library-path=$(swc) \
    $(main) \
    -raw-metadata=$$swf_metadata \
    -o $(output)
    @echo "\nCompiled '$(output)' at `date "+%H:%M of %d/%m"`."

# Runs the application.
run:
    @echo "\nRunning '$(run)'\n"
    @open -a $(player) $(run)

# Aliases.
c: compile
r: run

.PHONY: all


text:
Q: IOS VIPER: How protocol helps in Unit Testing? I am little confused with the benefit of protocols in VIPER architecture.
I understand that DI (Dependency Injection) achieved via protocols and helps avoid direct dependency between objects - I Agree.
But i am looking at a real benefit from usage perspective, an example may be - especially how protocols help benefit in unit testing (testing the Interactor portion).
Can't we achieve the same via method Callback's using blocks?
Hope someone can help me understand from usage perspective with some example
Cheers

A: Using a callback, e.g. from the Interactor to  the Presenter, can make it harder to test the Presenter.
When writing tests for how the Presenter processes input (sent from the Interactor) your test would have to call some method on the Presenter that would cause the Presenter to make a call on the Interactor, which would cause the Interactor to send data to the Presenter.
By having the Presenter implement a protocol defined by the Interactor, your test can just directly call the appropriate input method on the Presenter.
As far as declaring protocols, I practice TDD in the style of mock roles, not objects (http://www.jmock.org/oopsla2004.pdf). The protocols help provide a better abstraction by focusing on what the object does (its role), not how it does it.
Protocols, on their own, are of little value for the unit tests. Your unit tests will provide test doubles (http://martinfowler.com/bliki/TestDouble.html) for the dependencies of the system under test. Even if you expose dependencies as concrete classes you can still create test doubles for your test.
In Objective-C, you can use a mocking library, such as OCMock (http://ocmock.org), or OCMockito (https://github.com/jonreid/OCMockito), to create stubs, spies, or mocks of the concrete class.
In Swift, you could create your test doubles by subclassing each of the concrete classes used as dependencies.
In short, protocols are not used to ease unit testing, but to describe at a higher level of abstraction, what the application does.
Here is an example of how having the abstract protocols were beneficial after the fact:
I created a protocol to represent the actions a user could perform on a screen, e.g. ProfileUserActions, that had actions such as changeName, and changeAddress. The Presenter implemented ProfileUserActions, and the View accepted a ProfileUserActions as a dependency. When the user tapped a button on screen, the View would send the appropriate message to its userActions object.
When I wanted to add analytics, I was able to create a new, independent ProfileAnalytics class which also implemented ProfileUserActions. I inserted the analytics object between the View and the Presenter, which allowed the app to capture analytics, without having to modify either the View or the Presenter.

A: By using a protocol it is easier for you to swap out an implementation in your VIPER structure. For example, you might have an interactor that is working with a class that is writing to the filesystem. You don't want to be testing the filesystem in your unit tests so instead if you put the filesystem write operations in your interactor behind a protocol you can then replace the filesystem write operations with an in-memory implementation.
As for a protocol on the interactor itself, I think it pays to be a bit more pragmatic about your choice. If it's easy to build your interactor for the test and it doesn't cause any side effects as part of testing then there's probably no need for the protocol. On the other hand, if you have to create a number of other dependencies then it might pay to have the interactor conform to a protocol so that you can more easily fake the output you get from the interactor.


text:
Q: Retrieving text from FileTable SQL Server Is it possible to retrieve the actual text from a File Table in SQL Server 2014?
I want to implement some hit-highlighting functionality, but in order to do so, I need to retrieve the actual text in the file I indexed, since the content is in a varbinary column.
If it's not possible, I suppose the only alternative to do this is forgetting about FileTables and implementing an application-side "document reader", so that I'll have real text inside my "file_stream" column instead of the varbinary. Or maybe even defining an UDF that uses iFilters behind some C# code, right?
Please, any advice would be really useful.

A: Before you do start with your own implementation, take a look at the very similar question:
SQL Server 2012 FTS with Hit-Highlighting?
Also this blog entry from 2012 is still current:
Hit-Highlighting in Full-Text Search
I would take a look at the mentioned HitHighlight function (which is actually a commercial product, ThinkHighlight). Most likely it's not worth the effort to build your own solution. But if you do so - tell me ;)


text:
Q: Como quitar la barra de titulo de un JInternalFrame - Java Quisiera saber como quitar la barra de titulo de un JInternalFrame.
He estado intentando con este código pero no se borra la barra.
   setUI(null);

A: Tomo como referencia la solución que me funcionó:
((javax.swing.plaf.basic.BasicInternalFrameUI)this.getUI()).setNorthPane(null);


text:
Q: How to create a variadic template string formatter We need to format strings all the time. It would be so nice to be able to say:
std::string formattedStr = format("%s_%06d.dat", "myfile", 18); // myfile_000018.dat

Is there a C++ way of doing this? Some alternatives I considered:

*

*snprintf: uses raw char buffers. Not nice in modern C++ code.

*std::stringstream: does not support format pattern strings, instead you must push clumsy iomanip objects into the stream.

*boost::format: uses an ad-hoc operator overload of % to specify the arguments. Ugly.

Isn't there a better way with variadic templates now that we have C++11?

A: It can certainly be written in C++11 with variadic templates. It's best to wrap something that already exists than to try to write the whole thing yourself. If you are already using Boost, it's quite simple to wrap boost::format like this:
#include <boost/format.hpp>
#include <string>

namespace details
{
    boost::format& formatImpl(boost::format& f)
    {
        return f;
    }

    template <typename Head, typename... Tail>
    boost::format& formatImpl(
        boost::format& f,
        Head const& head,
        Tail&&... tail)
    {
        return formatImpl(f % head, std::forward<Tail>(tail)...);
    }
}

template <typename... Args>
std::string format(
        std::string formatString,
        Args&&... args)
{
    boost::format f(std::move(formatString));
    return details::formatImpl(f, std::forward<Args>(args)...).str();
}

You can use this the way you wanted:
std::string formattedStr = format("%s_%06d.dat", "myfile", 18); // myfile_000018.dat

If you don't want to use Boost (but you really should) then you can also wrap snprintf. It is a bit more involved and error-prone, since we need to manage char buffers and the old style non-type-safe variable length argument list. It gets a bit cleaner by using unique_ptr's:
#include <cstdio> // snprintf
#include <string>
#include <stdexcept> // runtime_error
#include <memory> // unique_ptr

namespace details
{
    template <typename... Args>
    std::unique_ptr<char[]> formatImplS(
            size_t bufSizeGuess,
            char const* formatCStr,
            Args&&... args)
    {
        std::unique_ptr<char[]> buf(new char[bufSizeGuess]);

        size_t expandedStrLen = std::snprintf(buf.get(), bufSizeGuess, formatCStr, args...);

        if (expandedStrLen >= 0 && expandedStrLen < bufSizeGuess)
        {
            return buf;
        } else if (expandedStrLen >= 0
                   && expandedStrLen < std::numeric_limits<size_t>::max())
        {
            // buffer was too small, redo with the correct size
            return formatImplS(expandedStrLen+1, formatCStr, std::forward<Args>(args)...);
        } else {
            throw std::runtime_error("snprintf failed with return value: "+std::to_string(expandedStrLen));
        }
    }

    char const* ifStringThenConvertToCharBuf(std::string const& cpp)
    {
        return cpp.c_str();
    }

    template <typename T>
    T ifStringThenConvertToCharBuf(T const& t)
    {
        return t;
    }
}

template <typename... Args>
std::string formatS(std::string const& formatString, Args&&... args)
{
    // unique_ptr<char[]> calls delete[] on destruction
    std::unique_ptr<char[]> chars = details::formatImplS(4096, formatString.c_str(),
                details::ifStringThenConvertToCharBuf(args)...);

    // string constructor copies the data
    return std::string(chars.get());
}

There are some differences between snprintf and boost::format in terms of format specification but your example works with both.

A: The fmt library implements exactly that, string formatting using variadic templates. Example:
// printf syntax:
std::string formattedStr = fmt::sprintf("%s_%06d.dat", "myfile", 18);

// Python-like syntax:
std::string formattedStr = fmt::format("{}_{:06}.dat", "myfile", 18);

Disclaimer: I'm the author of the library.


text:
Q: Why can't I load my google map in jquery mobile? I'm doing rel="external" on the link that opens this page, so the DOM reloads which should rule out a lot of problems.
Nevertheless, with the following code I get a huge red background with a nice header and footer-- the map just doesn't initialize despite that the function is being called. Can anyone spot the problem? This bug has been holding me up forever; I've tried a million things including redesigning it as a multipage template without rel="external", but that didn't work either.
<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css"/>

Map Page

Working!

A: Your code doesn't load the google maps script. Like this for example:


text:
Q: What are synthetic fields in Java? Can someone explain in an easy to understand way the importance of synthetic fields in Java. I recall reading it in context of non static inner classes where each such inner class instance  maintains a reference to the enclosing class. Why are such references/fields called synthetic fields?

A: A synthetic field is a compiler-created field that links a local inner class to a block's local variable or reference type parameter. The compiler synthesizes certain hidden fields and methods in order to implement the scoping of names. These fields are private unless noted otherwise, or they are at most of package scope. You can get more information here and in JLS

A class member that does not appear in the source code must be marked using a Synthetic attribute, or else it must have its ACC_SYNTHETIC flag set. The only exceptions to this requirement are compiler-generated methods which are not considered implementation artifacts, namely the instance initialization method representing a default constructor of the Java programming language (§2.9), the class initialization method (§2.9), and the Enum.values() and Enum.valueOf() methods..


text:
Q: Equivalent of swift code in firebase to objective c Firebase suggested to use this to support multiple environments when you only have a single target. This is on swift though, what would it be on objective c since the appledelegate.m in react-native doesnt use swift.
let filePath = Bundle.main.path(forResource: "MyGoogleService", ofType: "plist")
guard let fileopts = FIROptions.init(contentsOfFile: filePath)
  else { assert(false, "Couldn't load config file") }
FIRApp.configure(with: fileopts)

A: In Objective-C you can write like this way.
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"MyGoogleService" ofType:@"plist"];
FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:filePath];
[FIRApp configureWithOptions:options];


text:
Q: Como puedo hacer una consulta con un pivot dinamico en SQL Developer? Ayuda
Tengo algo como esto:

Country_name
First_name
Last_name

USA
Elen
Abel

USA
Emilia
Carolina

UK
Jose
Lopez

GERMANY
David
Austin

USA
Gabriela
Gonzalez

UK
Sarha
Bell

Y necesito algo como esto:

Country_name
1
2
3

USA
Elen Abel
Emilia Carolina
Gabriela Gonzalez

GERMANY
David Austin
Sin empleado
Sin Empleado

UK
Sarha Bell
Jose Lopez
Sin Empleado

como puedo hacer esto usando pivot en sql.
Esto es lo que he intentado:
SET SERVEROUTPUT ON
DECLARE
  sqlqry clob;
 cols clob;
BEGIN
  SELECT listagg ('''' ||FULL_NAME || ''' ,"' || FULL_NAME || '"', ',') WITHIN GROUP (ORDER BYFULL_NAME)
INTO  cols
FROM (SELECT DISTINCT ``FIRST_NAME||' '||LAST_NAME AS FULL_NAME FROM EMPLOYEES);
  sqlqry :=
'SELECT * :FROM (
 SELECT  :EMPLOYEE_ID, COUNTRY_NAME, FIRST_NAME
  FROM COUNTRIES C INNER JOIN LOCATIONS L ON (C.COUNTRY_ID=L.COUNTRY_ID)
  INNER JOIN DEPARTMENTS D ON(D.LOCATION_ID=L.LOCATION_ID)
 INNER JOIN EMPLOYEES E ON (E.DEPARTMENT_ID=D.DEPARTMENT_ID) ) T;
  pivot
 (MIN(EMPLOYEE_ID) for COUNTRY_NAME in (' || cols  || '))P';
END;


text:
Q: Cannot invoke initializer for type 'Range<_>' with an argument list of type '(Range)'
Since Xcode 10 I receive an error message Cannot invoke initializer for type 'Range<_>' with an argument list of type '(Range<String.Index>)' at the return line in the code below, which is an extension used to get a substring when needed.

I have found another good answer given by Martin R at Cannot invoke initializer for type 'Range<String.Index>' with an argument list of type '(Range<String.Index>)', but didn't find a way yet to fix my problem.
extension String {
    subscript (i: Int) -> Character { return self[index(startIndex, offsetBy: i)] }
    subscript (i: Int) -> String { return String(self[i] as Character) }
        subscript (r: Range<Int>) -> String {
        let start = index(startIndex, offsetBy: r.lowerBound)
        let end = index(startIndex, offsetBy: r.upperBound)

        return String(self[Range(start ..< end)])
    }
}


text:
Q: I can't delete or hide Displaying all results in woocomerce Adding to CSS did nothing, adding snippets from php below also.
CSS:
.woocommerce-result-count {
display: none;
}```

Snippets:
```removeaction ('woocommercebeforeshoploop', 'woocommerceresultcount', 20);```

A: Override woocommerce default styling like so:
.archive .woocommerce-result-count {
    display: none !important;
}


text:
Q: Chrome open DevTools, web workers don't run I found a compatibility problem about Android 8 and Chrome 71~72.
Web Workers are executable before opening DevTools, but not work after opening DevTools.
The following is the test result.
Example code:
<!DOCTYPE html>
<html>
    <body>
        <script id="worker" type="app/worker">
            addEventListener('message', function () {
              postMessage('some message');
            }, false);
          </script>
        <script type="text/javascript">
            console.log('script-in')
            var blob = new Blob([document.querySelector('#worker').textContent]);
            var url = window.URL.createObjectURL(blob);
            // console.log('scripe.url',url)
            var worker = new Worker(url);

            worker.onmessage = function (e) {
                console.log('onmessage-in')
                // console.log('onmessage.e', e)
                // e.data === 'some message'
                console.log('onmessage-end')
            };
            worker.postMessage('')
            console.log('script-end')
        </script>
    </body>
</html>

Execute JavaScript, and open DevTools afterwards:

Open DevTools first, then execute JavaScript.


text:
Q: AlwaysOn High Availability doesn't work , can't activate it I am trying to activate the high availability
on my SQL server and getting below message:

SQL server version: Microsoft SQL Server 2017 (RTM) - 14.0.1000.169
(X64) Aug 22 2017 17:04:49 Copyright (C) 2017 Microsoft Corporation
Express Edition (64-bit) on Windows Server 2012 R2 Datacenter 6.3
 (Build 9600: ) (Hypervisor)
Operating System: windows server 2012.

Appreciate any help.

A: If you read the message above in your screenshot, its very clear that it requires enterprise edition in order to enable always on availability group, even for basic AG you need to have standard edition of Sql server. This also requires WSFC hotfix to be installed on the operating system. It doesn't work on SQL server express edition.
Please read the prerequisite before doing set-up of always on availability:
https://learn.microsoft.com/en-us/sql/database-engine/availability-groups/windows/prereqs-restrictions-recommendations-always-on-availability?view=sql-server-ver15
https://learn.microsoft.com/en-us/sql/sql-server/install/hardware-and-software-requirements-for-installing-sql-server?view=sql-server-ver15
https://learn.microsoft.com/en-us/sql/sql-server/failover-clusters/windows/windows-server-failover-clustering-wsfc-with-sql-server?view=sql-server-ver15
Once you meet the prerequisite, please follow step by step instructions and coomplete the setup. you may refer this article written by Mr. Brent Ozar.

A: You need Enterprise edition for fully functional Always ON AG and a minimum Standard edition to use the basic Always On AG. Express edition of SQL Server does not supports Availability Groups


text:
Q: Bootstrap modal and drop down menu not working in the same nav bar, how do I override CSS? So here's the code I'm using to create a NAV bar.

Login

            My Account

List item

Another item

I added the modal funcationality to my NAV bar first, here's my trigger for the modal window.
$('#myModal').on('hide',function(){
    $('.nav > li > a.modal-open-li').removeClass('modal-open-li');
});

I then added the drop-down menu. However my modal isn't working now. Are they in the same CSS namespace? How do I override this?
Here are the scripts files that I am using:

Here's the CSS files I'm using
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/bootstrap.responsive.css" rel="stylesheet">
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/docs.css" rel="stylesheet">
<link href="css/datepicker.css" rel="stylesheet">

If I comment the following two scripts my modal starts working but my drop-down menu stops working.
<link href="static/css/bootstrap.min.css" rel="stylesheet">

A: CSS
1)  Use either bootstrap.css or bootstrap.min.css but not both.
2) If you want override styles from bootstrap, create a style file and add it after the bootstrap.css
ie,
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap.responsive.css" rel="stylesheet">

<link href="css/custom.css" rel="stylesheet">

Now in your custom.css file give !important to the styles you're overriding.
JAVASCRIPT
1) Use either bootstrap.js or bootstrap.min.js but not both.
2) bootstrap.js or bootstrap.min.js will contain all the javascript functionality.
no need to add the modal.js, dropdown.js, datepicker.js again, so remove it.


text:
Q: Prove that $3+ 3\cdot5+...+3\cdot5^n = \frac{3(5^{n+1}-1)}{4}$ for all nonnegative integers. I have been stuck on this one for a while. Supposed to use induction to prove that $3+ 3\cdot5+...+3\cdot5^n = \Large\frac{3(5^{n+1}-1)}{4}$ for all nonegative integers.
I don't know if I'm taking the wrong steps but I can't get past
$P(k+1) = \Large\frac{3((5^{n+1}-1)+4(5^{n+1}))}{4}$

A: Hint
Forget momentarily the $3$ it's just a factor and prove by induction that
$$1+5+5^2+\cdots+5^n=\frac{5^{n+1}-1}{4} $$
Inductive step:
$$1+5+5^2+\cdots+5^n+5^{n+1}=\frac{5^{n+1}-1}{4}+ 5^{n+1}=\frac{5^{n+2}-1}{4}$$

A: You're almost there.  The next step is to combine like terms.
$$5^{n+1}+4(5^{n+1})=(1+4)5^{n+1}$$
Can you take it from here?

A: If
$$3+3\cdot5+...+3\cdot5^n=\frac{3(5^{n+1}-1)}{4}\iff 1+5+...+5^n=\frac{5^{n+1}-1}{4}$$
then
$$1+5+...+5^n+5^{n+1}=\frac{5^{n+1}-1}{4}+5^{n+1}=$$
$$=\frac{5^{n+1}-1+4\cdot5^{n+1}}{4}=\frac{5\cdot5^{n+1}-1}{4}=\frac{5^{(n+1)+1}-1}{4}$$


text:
Q: Imagick Installation Errors - Class Undefined Okay, Here's a breakdown of what's up:

*

*<? $foo = new Imagick(); ?> works without error when ran from the command-line (e.g., sudo php myscript.php

*However, when run via the web browswer I get Fatal error: Class 'Imagick' not found in /var/www/lhackwith_www/test_html/magic.php on line 1.

*magickwand is not installed

*extension=imagick.so is in imagick.ini which is successfully being read according to phpInfo();

*However, imagick is NOT showing up in PHP info.

Any advice would be appreciated.

A: I had a similar problem with imagick after upgrading ubuntu from 12.04 to 12.10.
After much fiddling I eventually discovered that there is a different package needed (for php5?) and fixed it with:
sudo apt-get install php5-imagick

A: I take it you're absolutely sure you've edited the right php.ini...
Did you check the webserver's error.log for hints? You might want to increase the LogLevel for that test. If it's an apache see http://httpd.apache.org/docs/2.2/mod/core.html#loglevel and http://httpd.apache.org/docs/2.2/logs.html#errorlog
or maybe ldd - print shared library dependencies can shed some light on the issue:
<?php
$p = get_cfg_var('extension_dir');
$modpath = $p.DIRECTORY_SEPARATOR.'imagick.so';
echo $modpath, is_readable($modpath) ? ' readable':' not readable', "
\n";
echo '
';
passthru('ldd '.$modpath.' 2>&1'); // in case of spaces et al in the path-argument use escapeshellcmd()
echo '
';please run this script both on the command line and through the webserver. Does it complain about a missing dependency?

edit2: So the script running "within" the webserver isn't even able to see the extension .so... Let's test at which point of the path the trouble starts<?php
function foo($path) {
  if ( $path==($dir=dirname($path)) ) {
    return;
  }
  foo($dir);

echo
    is_dir($path) ? ' d':' -',
    is_readable($path) ? 'r':'-',
    is_writable($path) ? 'w':'-',
    is_executable($path) ? 'x ':'- ',
    $path, "
\n";
}

$modpath = get_cfg_var('extension_dir').DIRECTORY_SEPARATOR.'imagick.so';
foo($modpath);

A: What operating system are you using?  I've had several problems on Mac OSX that basically makes installing some extensions OVERLY painful. However, the Imagick install should be really simple, for most operating systems.
On your command line, type php -i | grep ini, and make sure the php.ini that is listed as being loaded is the same as the php.ini that phpinfo() says is being loaded.  If these are different, that's where you have to start.  Make sure extension=imagick.so is in both ini files, also - verify that they are loading extensions from the same directory (99% chance they will be, but who knows - you could be an exception).
After you've verified that (possibly) both php.ini files are loading imagick.so and it's still not working, try to tail -f /path/to/apache/error_log (assuming you're using apache, of course..) and restart apache.  You're looking here for php warnings about loading libraries and/or extensions. Hopefully it will point you in the right direction.
Hope this helps,
Jim

A: What I ended up doing:
Storing the orientation of the image in the DB and then using alternatiff to dynamically rotate the image to the orientation that was stored. No image manipulation needed.
Thanks for your help though.


text:
Q: How to host / point asp.net website as umbraco sub site I have two website one is umbraco site and other one is asp.net site both on different location on same server
1)   Umbraco site ( umbraco V6 and IIS 7)  And bind on let say Eg.  http://localhost:8090/
2)  Asp.net website. (Simple Asp.net Site)
Now I have added Asp.net website as Application in umbraco web site IIS and given Alias let say AspSubSite
My  umbraco site is running fine. But when I try to access asp.net site by URL http://localhost:8090/AspSubSite
It is not working.
I have try adding respective Url to umbraco config key "umbracoReservedUrls" but that also didn't work

A: You have to add the folders to exclude (/aspSubSite) in the web.config of the umbraco installation.
Umbraco will not interfere at all with this folders.  To do this, add the folder to the umbracoReservedPaths in the appSettings section of the web.config.
<add key="umbracoReservedPaths" value="/umbraco,/install/,/aspSubSite/" />

(leave the existing paths, but just add your path at the end.)
Note: this will exclude ALL umbraco functionality from this folder.  Including rendering partial's, macro's, ...  Only do this if you really want to do this.  If you want to use e.g. a common menu, this won't work anymore.


text:
Q: Twig: add json_decode as a filter I'm trying to decode a JSON string in my twig file. Of course I've done some research and I've found this earlier question on StackOverflow: here. They give a method to decode JSON in twig, but I don't really understand the way I should do it.
They say something about creating files etc. but I don't understand where they should be created. So I'm trying to find another way.
I've come up with this page. When we take a look at 'filters', these lines come up:
$filter = new Twig_Filter('rot13', function ($string) {
    return str_rot13($string);
});

So I thought I could use them like this:
$filter = new Twig_Filter('json_decode', function ($string) {
    return json_decode($string);
});

Now, I'd like to know whether this way should work. Also, where I'd have to put these lines of code. And finally, would I have to use the filter like this:
{{ data.params|json_decode }}

When I'm wrong, please give me the points that I mis, or, give me an easy solution that should do the job for me.
Edit
I'm using twig in the Silex framework!

A: <?php
    $app = new \Silex\Application();
    $app->register(new \Silex\Provider\TwigServiceProvider(), []);
    $app['twig']->addFilter(new Twig_SimpleFilter('json_decode', function ($string) {
        return json_decode($string);
    }));

A: Twig is a pain as almost all info you find is for another Version of it, the people behind Twig are good developers they also significantly make it better than before.
But they also break just anything you were used to in the progress.
$twig_env->addFilter(new \Twig\TwigFilter('json_decode','json_decode'));


text:
Q: conditional layout based on if Innerblocks is not empty This seems like a simple issue, but I can't seem to find an answer. I'm using InnerBlocks to stack some paragraphs in a wrapper. If there are no blocks set I'd like to not output the wrapper at all. Is there (currently) a straight-forward way of doing this? It seems I can maybe test against InnerBlocks itself, but I haven't seen any documentation that suggests this is reliable.
save( { attributes } ) {
  return (

        <InnerBlocks.Content />

  );
}

Basically I don't need the header__text if InnerBlocks is empty.

A: I am not sure this is possible in a straightforward way.
You could add an attribute which checks if the block has innerBlocks. Then use it in save to render the wrapper or not. It works but it's not a very clean solution:
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { InnerBlocks } = wp.blockEditor;
const { useSelect } = wp.data;
const { useEffect } = wp.element;

registerBlockType("my-plugin/my-block", {
    title: __("My block"),
    icon: "carrot",
    category: "common",
    attributes: {
        innerBlocks_length: {
            type: "number",
            default: 0
        }
    },
    edit: props => {
        const { className, clientId, setAttributes } = props;
        const { innerBlocks_length } = useSelect(select => ({
            innerBlocks_length: select("core/block-editor").getBlockCount(clientId)
        }));

        useEffect(() => {
            setAttributes({ innerBlocks_length });
        }, [innerBlocks_length]);

        return (

                    <InnerBlocks />

        );
    },
    save: props => {
        const { innerBlocks_length } = props.attributes;

        return (

                {innerBlocks_length > 0 && (

                        <InnerBlocks.Content />

                )}

        );
    }
});


text:
Q: How to check if anyone is logged in with php? this code returns true whether I logged in or not
if (!isset($_SESSION['LoggedIn']) && $_SESSION['LoggedIn'] != 1) {
    do_something();
}

I wanna check if any user (session) is logged in or not

A: First you have to define, what logged-in means. Example:
LOGGED_IN = NOT_LOGGED_OUT && LAST_VISIT > time() - 15*60 # 15 minutes

Then you have to store the last visit time into a database table on each user activity:
UPDATE user_table SET last_visit = UNIX_TIMESTAMP() WHERE user_id=?

And now you can retrieve the number of logged_in users:
SELECT COUNT(*) from user_table
WHERE !logged_out && last_visit > UNIX_TIMESTAMP() - 15*60

Hope it is clear, that this is only a schematic solution.

A: I'll assume that $_SESSION['LoggedIn'] is a boolean.
So, you shouldn't use AND in this if, but OR. Something like this:
if (
     !isset($_SESSION['LoggedIn'])
     ||
     (int)$_SESSION['LoggedIn'] != 1
) {
     //not logged in
} else {
    //logged in
}


text:
Q: Related questions under Creative Commons? Stack Exchange releases its user-generated content in a data dump under a Creative Commons license—this is an incredible resource for researchers like myself, and as far as I know no other site has made their data so readily available to this degree.
There is some data however that is publicly accessible through the API but not in the data dump (e.g. related questions). Is this data also covered under the Creative Commons license, or does some other protocol need to be followed for the data to be republished?


text:
Q: How to check the existence of file before reading it in Angular? I have a function that gets the data from a saved file into the myJson variable. How can I check that the file exists without it affecting the below methods? Also, the file is in another folder that the one of the src of the project. It is in the backend dedicated folder. How can I access it from Angular and also to check if the file exists?
import myJson from 'src/assets/myFile.json' ;

readFile() {
  this.savedData=myJson;
  console.log("this is data from file "+this.savedData);
  return myJson;
}
constructor (){
    this.savedData= this.readFile();
  }

A: Giving more context to my comments, I would do the async function as follow:
public async readFile() {
  return await new Promise((resolve,reject) => {
    this.http.get("your_path_to_file").toPromise().then(res => {
      resolve(res);
    }).catch(err => {
      reject(err);
    });
  });
}

Then the funcion that calls the readFile :
public getFile() {
  this.saveData = this.readFile();
  // more code here if needed
}

Then instead of calling it in the constructor I'd use the OnInit life cycle:
public ngOnInit(): void {
  this.getFile();
}

More datails on why it's a bad practise to return a promise in the constructor here: Is it bad practice to have a constructor function return a Promise?


text:
Q: Subversion: how to auto update a repository With subversion is there a way to automatically update a repository at say 6am every morning?

A: To run a command to update an SVN working copy at 6:00 am every morning on Windows:
at 06:00 /every:M,T,W,Th,F,S,Su svn up path\to\wc

You could take out S and Su to have it only run on weekdays.

A: You can do it by command line and scheduler build on your OS.

A: You can write a small script for this.


text:
Q: Possible to use Gii funcationlity from the command line? I'm new to Yii (coming from the world of Django, Rails, etc) and wondering if it is possible to to use the Gii scaffolding functionality for controllers, models, views, etc. from the command line.
I'm interested in creating a site from scratch and not building off the site that is packaged with the framework.
What is the best way to go about this?
Thanks!

A: You can use YIIC's shell to create controllers and models from command line
%YiiRoot/framework/yiic shell

>> controller message helloWorld
generate MessageController.php
mkdir /Webroot/demo/protected/views/message
generate helloworld.php
generate index.php
Controller 'message' has been created in the following file:
/Webroot/demo/protected/controllers/MessageController.php
You may access it in the browser using the following URL:
http://hostname/path/to/index.php?r=message
>>

~Agile Web Application Development with Yii 1.1 and PHP5 {book}
hope this helps


text:
Q: What is the wrong step in the integral $ \int {\ln x \over x\sqrt{1-4\ln x -\ln^2 x}}dx $?
Evaluate the following integral:
  $$
I= \int {\ln x \over x\sqrt{1-4\ln x -\ln^2 x}}dx
$$

I've started with a substitution: $t = \ln x$, then:
$$
dt = {dx \over x} \iff dx = xdt\\
I = \int {tdt\over \sqrt{1 - 4t - t^2}}
$$
Completing the square in the denominator I got:
$$
1-4t-t^2 = -(t^2 + 4t - 1 +5-5) = -(t+2)^2 + 5 = 5-(t+2)^2
$$
Then the integral becomes:
$$
\int \frac{tdt}{\sqrt{5-(t+2)^2}}
$$
Substitute $t+2 = s$, then $dt = ds$, and $t = s-2$:
$$
\int \frac{(s-2)ds}{\sqrt{5 - s^2}} = \int \frac{sds}{\sqrt{5 - s^2}} - \int\frac{2ds}{\sqrt{5 - s^2}} \tag1
$$
Then:
$$
I_1 = \int \frac{sds}{\sqrt{5 - s^2}}
$$
Substitute $p = s^2$, $dp = 2sds$, and $ds = {dp \over 2s}$:
$$
I_1 = \int
\frac{dp}{2\sqrt{5-p}} = {1\over 2}\arcsin{\sqrt{p}\over \sqrt5}+C = \\
{1\over 2}\arcsin{\ln x + 2\over \sqrt5}+C
$$
Going back to $(1)$:
$$
I_2 = \int\frac{2ds}{\sqrt{5 - s^2}} = 2\arcsin{s\over \sqrt5}+C= \\
2\arcsin{\ln x + 2\over \sqrt5}+C
$$
Which means:
$$
I = I_1 - I_2 = \boxed{{1\over 2}\arcsin{\ln x + 2\over \sqrt5} - 2\arcsin{\ln x + 2\over \sqrt5}+C}
$$
And that is not correct since the answer suggests:
$$
I = -\sqrt{1-4\ln x - \ln^2 x} - 2\arcsin{\ln x + 2\over \sqrt5}+C
$$
I've been trying to spot the error for a while without any success, where did it go wrong? Obviously my answer is wrong. By the way, I'm supposed to use substitution to solve the integral. Thank you in advance!

A: Your computation of $I_1$ is wrong. $\int \frac 1 {\sqrt {5-p}} dp$ is $-2\sqrt {5-p}+C$


text:
Q: Evaluate $\lim_{x\to0} \frac{6}{x}-\frac{42}{x^2+7x}$ Evaluate $\lim_{x\to0} \frac{6}{x}-\frac{42}{x^2+7x}$
I'm I want to say that you cross multiply to get the same denominator, but I could be wrong.
Please Help!!

A: You are correct that a common denominator is necessary:
\begin{align}
\frac 6 x - \frac {42} {x^2 + 7x} &= \frac 6 x - \frac {42} {x(x + 7)}\\
&= \frac{6(x + 7) - 42}{x(x + 7)} \\
&= \frac{6x}{x(x + 7)} \\
&= \frac{6}{x + 7}
\end{align}
for $x \ne 0$. Do you see how to compute the limit now?

A: $$\lim_{x \to 0} \frac1x \frac{6x+42-42}{x+7} = \lim_{x \to 0}\frac1x \frac{6x}{x+7} = \lim_{x \to 0}\frac{6}{x+7} = ?.$$

A: First, we find the common denominator:
$\require{cancel}$
$$\frac ab - \frac c{bd} = \frac{ad - c}{bd}$$
Applying the "general rule" in your case:
$$\begin{align}
\frac 6x - \frac{42}{x^2 + 7x} & = \frac 6x - \frac{42}{x(x + 7)} \\ \\
& = \frac{6(x + 7) - 42}{x(x + 7)} \\ \\ & = \frac{6x}{x(x+7)} \\ \\ & = \frac{6\color{blue}{\cancel{x}}}{\color{blue}{\cancel{ x}}(x + 7)} \\ \\ & = \frac{6}{x + 7}
\end{align}$$
And so we have that $$\lim_{x\to 0} \frac 6x - \frac{42}{x^2 + 7x} \quad = \quad \lim_{x\to 0} \frac 6{x+7} \quad = \quad\frac 67$$

A: \begin{align}
{6 \over x} - {42 \over x^{2} + 7x}
&=
{6 \over x}\left(1 - {1 \over 1 + x/7}\right)
=
{6 \over x}
\left\lbrace
1
-
\left\lbrack 1 - {x \over 7} + {\rm O}\left(x^{2}\right)\right\rbrack
\right\rbrace
=
{6 \over x}\left\lbrack {x \over 7} + {\rm O}\left(x^{2}\right)\right\rbrack
\\[3mm]&=
{6 \over 7} + {\rm O}\left(x\right)
\color{#ff0000}{\large\to {6 \over 7}}
\end{align}


text:
Q: Web-SQL query triggers both success and failure callbacks I am using web data base in google chrome and the executeSql function trigger both succes and failure signal !
function succes(){
    alert("succes");
}

function failure(){
    alert("failure");
}

var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql("CREATE TABLE IF NOT EXISTS " +
              "goal(ID INTEGER PRIMARY KEY ASC, goals TEXT, added_on DATETIME, appartient INTEGER, ok INTEGER)", []);
 });

 $('#button').click(function(){
    db.transaction(function(tx){
    var goalText = $('#entry').val();
    var addedOn = new Date();
    var appartient = 0;
    var ok = 0;
    alert(goalText);
    tx.executeSql("INSERT INTO goal(goals, added_on, appartient, ok) VALUES (?,?,?,?)",
    [goalText, addedOn, appartient, ok],
    succes(),
    failure());
 });

});

What is the problem ?

A: You are calling succes and failure and passing their (undefined) return values to executeSql.
Take away the () and pass the functions instead.


text:
Q: Parsing CLI options for a product type I want to parse command line options corresponding to a product type resembling below.

data SumType1 = d | e | f

data SumType2 = g | h | i

data Config = Config {
    a :: Bool,
    b :: SumType1,
    c :: SumType2
}

pB :: Parser SumType1
pB = flag' d <|> flag' e <|> flag' f

pC :: Parser SumType2
pC = flag' g <|> flag' h <|> flag' i

pConfig :: Parser Config
pConfig = Config <$> pA <*> pB <*> pC

opts :: ParserInfo Config
opts = info (pConfig <**> helper)
       (fullDesc <> progDesc "My CLI" <> header "CLI executable")

main :: IO()
main = do
       (Config a b c) <- execParser opts
-- Populate a default config using a b c values

For simplicity I did not add "long" and "help" here with flag'.
The above is what I have right now. It may also be that "d" itself is another sum type. In this the problem is each of the a, b, c values I need to specify on the command line.
How do I specify such that either of a, b or c may not be specified and the CLI parser still works. Currently if I do not pass even one of a, b or c the parser fails with an error message. I understand that my builder construction is incorrect, but, I am not able to grasp how to fix it. Hope I have described the problem correctly, if not please let me know.

A: Try adding a default alternative to the sum parsers:
pB :: Parser SumType1
pB = flag' d <|> flag' e <|> flag' f <|> pure d  -- defaults to d


text:
Q: Javascript sorting of multiple digit numbers I have a ul that I'm trying to sort using javascript (or jQuery if easier or necessary):

1 - 5 days

11 - 15 days

16 - 20 days

6 days - 10 days

The order I'm hoping for is: 1 - 5 days, 6 days - 10 days, 11 - 15 days, 16 - 20 days.
Now, I could always change the single digit items so that 1 - 5 is 01 - 05, but aesthetically I'm hoping theres a way around that!
I've tried the process described in What is the easiest way to order a
/
 in jQuery?, but it doesn't apply for this case where I have multiple digits mixed in with text.
If it helps as a starting point: http://jsfiddle.net/5gHet/
Thanks so much! Would really appreciate any ideas.

A: Use parseInt to convert the string to the the first number that appears.
items.sort(function(a,b){
  var keyA = parseInt($(a).text(), 10);
  var keyB = parseInt($(b).text(), 10);

  if (keyA < keyB) return -1;
  if (keyA > keyB) return 1;
  return 0;
});

FYI, if there were non-numeric/whitespace characters that came before the first number, parseInt() would return NaN, so you'd need to extract the number manually.

A: Split the string on spaces, and then get the first number.
var items = $('ul li').get();
items.sort(function(a,b){
  var strA = $(a).text().split(' ');
  var strB = $(b).text().split(' ');

  if (parseInt(strA[0]) < parseInt(strB[0])) return -1;
  if (parseInt(strA[0]) > parseInt(strB[0])) return 1;
  return 0;
});
var ul = $('ul');
$.each(items, function(i, li){
  ul.append(li);
});

Demo at: http://jsfiddle.net/5gHet/1/

A: Fiddle
In addition to parseInt you can do a little regex:
var $items = $('ul li');
var regex_first_num = /(\d+)/;

$items.sort(function(a,b){
  var keyA = $(a).text().match(regex_first_num)[0] *1;
  var keyB = $(b).text().match(regex_first_num)[0] *1;
  return keyA > keyB;
});

$('#newlist').append($items.clone());


text:
Q: Laravel Spatie\Browsershot Error For some reason Chrome did not write a file at `/home/______/public_html/myfiles/storage/public/cv/file.pdf Spatie\Browsershot
Laravel
My Code :
$save_to_file = storage_path('public/cv/file.pdf');

Browsershot::html('<h1>test<h1>')
->noSandbox()
->save($save_to_file);

The Error :
For some reason Chrome did not write a file at `/home/______/public_html/myfiles/storage/public/cv/file.pdf`.

A: Maybe try this : how to fix Spatie/Browsershot error somehow Chrome did not write a file at `screenshot.pdf`
This work for me with spatie/browsershot in GitHub Actions CI.
Although composer install puppetter, installing manually puppetter and chromium on the system made the generation of PDFs work.

npm install -g puppeteer

npm install -g chromium


text:
Q: final-form-arrays - Nested arrays mutations - Dynamic array of dynamic array How do I use final-form-arrays in MultiSelectInput which handle payload as presented in the image?

*

*Framework - React.js

*Form handler - final-form + final-form-arrays

The problem is, its nested arrays. Dynamic array of objects which include a dynamic array. And all this logic need to be handled from single input as displayed in the image.

*

*If no Provider selected -> empty products: [] array.

*When at least one Provider selected -> products array need to include the selected Product + the selected Provider.

*When selecting more Providers, add them to the specific Product - providers array.

*If unselecting all the Providers, remove the Product and its providers from the products array.

P.S. Can also accept answers for package named 'Formik', but i prio final-form due to I already use it in my project.


text:
Q: How to join Urdu alphabets in c# i am developing an urdu based application using c#. i have done with segmentation now problem is after segmentation i got letters of Urdu language any one give me idea how to join them to make words from letters like

*

*ب ڑ ی = بڑی

*ب  ا ت = بات

A: You should simply be able to concatenate letters into words.  Just make sure there is no whitespace and the letters should join together properly automatically.
 string a = "ب";
 string b = "ڑ";
 string c = "ی";
 textBox1.Text = a + b + c;

produces :


text:
Q: Condition of continuity In paper  Tempered distributions and the Fourier transform, on page 16,  we can find following quote:

If we fix $\phi\in\mathcal{S}(\mathbb{R}^n)$ this defines a continuous linear linear map:
  $$ T_{\phi}:\;\mathcal{S}\ni\psi\mapsto\int\phi(x)\psi(x)dx. $$
  Continuity becomes the condition:
  $$ \exists \; k, C_k \;\text{s.t.}\;|T_{\phi}(\psi)| \le C_k||\psi||_k \; \forall \;\psi\in\mathcal{S}(\mathbb{R}^n). $$

Note that norms on $\mathcal{S}(\mathbb{R}^n)$ are defined as

$$||\phi||_k = \max_{|\alpha|+|\beta|\le k} \sup_{x\in\mathbb{R}^n} |x^\alpha D^\beta \phi(x)|.$$

where $\alpha, \beta \in \mathbb{N}^{n}_{0}$.
My question are,

*

*Why does Continuity becomes the condition?

*What is the definition of Continuity the author refers to?

A: I found an answer to my question in Kôsaku Yosida, Functional analysis.


text:
Q: How to extend Dell Laptop Latitude E6410 screen to 2 external LCD monitors using a dock with 2 DVI ports? I'm running Windows 7 enterprise.
Two of my external LCD monitors are connected to my Latitude E6410 through the 2 DVI ports on the dock. However, I could only get 2 screens to display at the same time. Either the laptop screen & 1 LCD monitor or just the 2 external LCD monitors. How do I make the 3 to display at the same time?

A: The GPU in the E6410 only supports up to two monitors at a time.
You should look at a USB video adapter if you need more than two screens.


text:
Q: Eclipse project which depends on another one - Class not found exception I've got 2 projects in the same workspace where one of them is added as a "required project" to the properties of the other one.
If I try to run the project I keep getting ClassNotFound Exceptions (probably because the bin directory isn't part of the runtime classpath?!)
Is there any nice way to fix this?
Maybe there is any solution where my teammates who work on the same project (via SVN) don't have to do any configuration on their machines.
Thanks a lot in advance,
Martin

A: Try cleaning and rebuilding your work space.


text:
Q: Deriving OLS estimates using method of moments I've worked the slope all the way down to $\sum [x_i(y_i - \bar{y})] = \hat\beta_1 \sum[x_i(x_i - \bar{x})]$
But I can not figure out how to show the steps for:
$\sum[x_i(y_i - \bar{y})] = \sum(x_i - \bar{x})(y_i - \bar{y})$
and
$\hat \beta_1 \sum[x_i(x_i - \bar{x})] = \hat \beta_1 \sum(x_i - \bar{x})^2$

A: Add and subtract and then look whether the unwanted term disappears:
$$\sum[x_i(y_i-\bar y)]=\sum[(x_i-\bar x+\bar x)(y_i-\bar y)]=\sum[(x_i-\bar x)(y_i-\bar y)]+\sum [\bar x(y_i-\bar y)].$$
Now
$$\sum [\bar x(y_i-\bar y)]=\bar x\sum [y_i-\bar y]=\bar x\left[\sum y_i-n\bar y\right]=0,$$
where $n$ is the number of the terms in the sum. Apply the same trick for the second equation.


text:
Q: Passing a C++ Member Function Pointer to an STL Algorithm I have a member function as follows:
class XYZ{
public:
    float function(float x);
private:
    float m_DensityMin;
    float m_DensityMax;
};

Now, I'm trying to transform a std::vector<float> foo using the std::transform STL algorithm by passing the member function function, and storing the resulting values in a vector bar.
If I use the function as a global function, with random data that should denote the member variables of the class, it works fine.
However, as the function requires the use of member variables m_DensityMin and m_DensityMax of the class, I need to use it as a member function. This is what I've tried:
std::transform(foo.begin(), foo.end(), bar.begin(), &XYZ::function);

but I end up with the error in VS2010:
error C2065: term does not evaluate to a function taking 1 arguments

As far as I can tell I'm passing only 1 argument. Any pointers?
Here's a similar question, I've tried with std::mem_fun, as std::mem_fn is not available to me, but to no avail.

A: std::mem_fun itself only povides a wrapper for a member function, so that one will be invoked in the context of the first argument passed to its operator(). Having said that, you need to bind the proper instance of XYZ prior to passing the function object to the std::transform algorithm:
XYZ xyz;

std::transform(foo.begin(), foo.end(),
               std::back_inserter(bar),
               std::bind1st(std::mem_fun(&XYZ::function), &xyz));
//                  ~~~~~~^      ~~~~~~^                  ~~~^

DEMO

A: Unless the function is static, it needs an instance of the class to call the function off of. Because non-static functions should depend on the internal state of that class. If the function is independent of the class's state, it should probably be static.
If you had to leave your class as written, you could get around this by default constructing an XYZ just for the purposes of having an instance to call the function from.
std::transform(foo.begin(),
               foo.end(),
               std::back_inserter(bar),
               [](float a){ return XYZ{}.function(a); });

But this feels hacky, I would prefer that the function be static if it isn't dependent on the state of the XYZ instance, and only depends on the input float.

A: lambda version
std::vector<float> foo;
std::vector<float> bar;
foo.push_back(1.0f);
foo.push_back(2.0f);
XYZ xyz;
std::transform(foo.begin(), foo.end(), std::back_inserter(bar),
        [&xyz](float& a){ return xyz.function(a); });
 for ( auto & x : bar)
   std::cout<<x<<"\n";


text:
Q: How can I get contact first name and last name in the same column? How can I get contact first name and last name in the same column as shown in the picture?
Here  is my incomplete query:
SELECT
    customernumber,
    customername,
    contactfirstname,
    contactlastname
FROM
    dbs211_customers
WHERE
    country = 'Canada'
ORDER BY
    customernumber;

Here is the link for img: https://i.stack.imgur.com/5e5C2.png

A: just use concatenation
SELECT customernumber, customername, CONCAT(conctractfirstname, ' ', contractlastname) as `contract_fullname` FROM dbs211_customers WHERE country = 'Canada' ORDER BY customernumber;

A: There's no picture shown in your question.
But assuming you're asking for something like this:
SELECT customernumber,
(contactfirstname + ' ' + contactlastname) AS ContactFullName
FROM dbs211_customers
WHERE country = 'Canada'
ORDER BY customernumber;

A: SELECT
    customernumber,
    customername,
    concat(concat(contactlastname, ', '), contactfirstname) as "Contact Name"
FROM
    dbs211_customers
WHERE
    country = 'Canada'
ORDER BY
    customernumber;

A: Hi one way you can try is as follows.
SELECT
    customernumber,
    customername,
    contactfirstname || ' , ' ||  contactlastname
FROM
    dbs211_customers
WHERE
    country = 'Canada'
ORDER BY
    customernumber;


text:
Q: Arquivo .bat para gerar backup e restore em PostgreSQL Estou criando arquivos .bat para realizar o backup e restauração de uma base de dados em PostgreSQL utilizo windows 10 e pg 9.4
Realizo o seguinte comando para realizar o backup
set PGUSER=postgres
set PGPASSWORD=postgres123

"C:/Program Files/PostgreSQL/9.4/bin\"pg_dump.exe --host localhost --port 5432 --format custom --blobs --verbose --file "D:\bkp.sql" "dbsibcom"

ele funciona perfeitamente.
E para realizar o restore tenho o seguinte comando
set PGUSER=postgres

set PGPASSWORD=postgres123
"C:/Program Files/PostgreSQL/9.4/bin\pg_restore.exe -i -h localhost -p 5432 -c -d "testrestore" -v " D:\bkp.sql"

Crio o arquivo bat e tento restaurar, ele apenas abre e fecha a tela do dos rapidamente e não funciona.
Existe algo errado ou outro método de fazer o restore ?
tenho que dar alguma permissão para o pg ter acesso ao meu arquivo de backup ou algo do gênero?
Edição

Também tentei esses comandos para tentar realizar o restore e não funciona
set PGUSER=postgres
set PGPASSWORD=postgres123

C:/Program Files/PostgreSQL/9.4/bin\pg_restore.exe --host localhost --port 5432 --username "postgres" --dbname "testrestore"   --verbose "D:\bkp.sql"

A: Considerando:

*

*O nome do banco de dados como: minha_database

*O arquivo de backup como: C:\bkp\backup_database.dump

*Instalação do PostgreSQL 9.1 em C:\Program Files (x86)\PostgreSQL

Pra fazer o backup:

C:\Progra~2\PostgreSQL\9.1\bin\pg_dump -h servidor -p 5432 -U postgres --inserts -c -f C:\bkp\backup_database.dump minha_database

Pra fazer o restore:

C:\Progra~2\PostgreSQL\9.1\bin\psql -U postgres -d minha_database -f C:\bkp\backup_database.dump

*

*Você pode manter o comando set PGPASSWORD=postgres123 pra não pedir a senha e automatizar a execução.

*Você pode colocar um comandou pause no final do .bat para ver qual erro ocorre.

*No seu ambiente, o caminho da pasta bin\ será: C:\Progra~1\PostgreSQL\9.4\bin\. Utilize esse caminho para colocar os comandos.

*O arquivo de dump será gerado em formato sql, e em texto puro, sem nenhuma proteção / criptografia.

A: Script de backup
Windows

@Echo Off
 @For /F "tokens=1,2,3,4 delims=/ " %%A in ('Date /t') do @(
 Set DayW=%%A
 Set Day=%%B
 Set Month=%%C
 Set Year=%%D
 Set All=%%A_%%B_%%C_%%D
 )
 @For /F "tokens=1,2,3 delims=:,. " %%A in ('echo %time%') do @(
 Set Hour=%%A
 Set Min=%%B
 Set Sec=%%C
 Set Allm=%%A.%%B.%%C
 )
 @For /F "tokens=3 delims=: " %%A in ('time /t ') do @(
 Set AMPM=%%A
 )
set datestr=%All%%Allm%%AMPM%
echo datestr is %datestr%

set BACKUP_FILE=E:\BACKUP\WMSBACKUP_%datestr%.backup
echo backup file name is %BACKUP_FILE%
SET PGPASSWORD=suasenha
echo on
cd "\Program Files\PostgreSQL\10\bin\"
pg_dump.exe -h localhost -U postgres -p 5432 wms > %BACKUP_FILE%

pause

A: @echo off

rem Coloca o nome do banco aqui

set banco=

REM Senha da base de dados

SET PGPASSWORD=

rem Caminho da pasta do backup

set pastabk=D:\backup_sistema

rem Caminho do pg_dump

set pg_dump=C:\Program Files\PostgreSQL\9.3\bin

rem Unidade do HD EXTERNO

set pendrive=G:\

rem Nome do Servidor

set servidor=

if not exist %pastabk% (mkdir %pastabk%)

color 1f

Title BACKUP SISTEMA

echo ----------------------------------------------------------------------------

echo -----------------------Backup de banco de dados-----------------------

echo ----------------------------------------------------------------------------

echo.

set dia=%date:~0,2%%date:~3,2%%date:~6,4%_%time:~0,2%%time:~3,2%

set dia=%dia: =%

echo Banco de Dados.: %banco%

echo.

cd\

CD %pg_dump%

pg_dump.exe -h %servidor% -p 5432 -U postgres -F c -b -v -f
"%pastabk%\%banco%%dia%.backup" %banco%

echo.

echo ----------------------------------------------------------------------------

echo ----------------------------------------------------------------------------

echo.

if exist %pastabk%\%banco%%dia%.backup (

    echo Backup Concluido...

    echo Criado no arquivo: "%pastabk%\%banco%%dia%.backup".

    echo.

    if exist %pendrive% (

        echo Copiando arquivo para dispositivo removivel.

        if not exist %pendrive%\BancosBk\ (md %pendrive%BancosBk\)

        copy "%pastabk%\%banco%%dia%.backup"
"%pendrive%\BancosBk\%banco%%dia%.backup"

        echo.

        echo Backup copiado para dispositivo removivel.

        echo Copiando em %pendrive%\BancosBk\%banco%%dia%.backup

    ) else (echo Dispositivo removivel nao encontrado.)

) else (echo Não foi possivel concluir o backup.)

echo.

pause


text:
Q: How to check if an element exists? In my C# Windows Forms application using Firefox Selenium WebDriver I need to check if an element exists and if it doesn't, click a different one. If there is a video, after it is watched it becomes W_VIEWED:
driver.FindElement(By.XPath("//div[@class='video']/a")).Click();
else
{
    driver.FindElement(By.XPath("//div[@class='W_VIEWED']/a")).Click();
}

Error 3 Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement    242

A: You can check if an element exits or not by using
bool isElementDisplayed = driver.findElement(By.xpath("element")).isDisplayed()

Remember, findElement throws an exception if it doesn't find an element, so you need to properly handle it.
In one of my applications, I handled an exception by checking the element in a separate function:
private bool IsElementPresent(By by)
{
    try
    {
        driver.FindElement(by);
        return true;
    }
    catch (NoSuchElementException)
    {
        return false;
    }
}

Call function:
if (IsElementPresent(By.Id("element name")))
{
    // Do if exists
}
else
{
    // Do if does not exists
}

A: You can use FindElements with an "s" to determine if it exists, since FindElement results in an Exception.  If FindElements does not return an element then it returns an empty list.
List<IWebElement> elementList = new List<IWebElement>();
elementList.AddRange(driver.FindElements(By.XPath("//input[@att='something']")));

if(elementList.Count > 0)
{
    //If the count is greater than 0 your element exists.
    elementList[0].Click();
}

A: So I recently figured out another way, which is much faster. If your element has a unique ID or some attribute that exists nowhere else on the page, you can check the PageSource.
driver.PageSource.Contains("UniqueID");

It checks the page to see if the ID or other unique text exists.  This happens almost instantaneously, as opposed to using a Try/Catch statement, which takes ~20 seconds.  FindElements takes a long time to run too.

A: This is what I use. The "verify" method will return a true or false based on if the element exists. The method named "testfunc" is where you enter the element name. In this example I am looking to see if "English" is displayed on the page.
Also, I notice in the comments in previous posts, people are saying they have to wait 10 seconds or more for the catch to work. Try remove the explicit wait in your code for the catch to work immediately.
static public bool verify(string elementName)
{
    try
    {
        bool isElementDisplayed = driver.FindElement(By.XPath(elementName)).Displayed;
        return true;
    }
    catch
    {
        return false;
    }
    return false;
}

static void testfunc()
{
    bool test = verify("//option[contains(.,'English')]");
    Console.WriteLine(test);
}

A: I used the accepted answer's solution for some time, but I needed a faster way to check, without waiting for the timeout period every time a check failed. So I made some extension functions that work on IWebElement and IWebDriver that check for the existence of a tag or class.
public static class ExtensionMethods {

    public static bool ContainsTag(this IWebElement element, string tagName)
    {
        string elementText = element.GetAttribute("innerHTML");
        return CheckStringForTag(elementText, tagName);
    }

    public static bool ContainsClass(this IWebElement element, string className)
    {
        string elementText = element.GetAttribute("innerHTML");
        return CheckStringForClass(elementText, className);
    }

    public static bool ContainsTag(this IWebDriver driver, string tagName)
    {
        return CheckStringForTag(driver.PageSource, tagName);
    }

    public static bool ContainsClass(this IWebDriver driver, string className)
    {
        return CheckStringForClass(driver.PageSource, className);
    }

    private static bool CheckStringForTag(string text, string tagName)
    {
        if (!string.IsNullOrWhiteSpace(text))
        {
            return text.Contains("<" + tagName + ">") || text.Contains("</" + tagName + ">") || text.Contains("<" + tagName + " ");
        }
        return false;
    }

    private static bool CheckStringForClass(string text, string className)
    {
        if (!string.IsNullOrWhiteSpace(text))
        {
            string pattern = string.Format(".*class[\\s]?=[\\s]?.*[\\s'\"]{0}[\\s'\"].*.*", className);
            Match m = Regex.Match(text, className, RegexOptions.IgnoreCase);
            return m.Success;
        }
        return false;
    }

    public static string InnerHTML(this IWebElement element)
    {
        return element.GetAttribute("innerHTML");
    }

}

Note: This is similar to, but expands on Dominic Giallombardo's answer.

A: Dominic Giallombardo's answer worked for me. On Ajax-based information which loads on background, it is a required loop to wait for the element to appear.
So if you want to wait and do an action when the element appear it is possible with a label and a go to label + else condition. Here is the modified code which will wait for the element to appear through a loop:
checksomeelement:
List<IWebElement> elementList = new List<IWebElement>();
elementList.AddRange(driver.FindElements(By.XPath("//div[@class='video']/a")));

if (elementList.Count > 0)
{
     elementList[0].Click();
}
else
{
     System.Threading.Thread.Sleep(2000);
     goto checksomeelement;
}

A: This method will allow you to wait for an element to exist. This is especially important in front end SPA frameworks that conditionally create elements, like Vue.js. You can tweak your retry count based on the performance of your application. In any case, it will wait for your ELEMENT_FIND_WAIT_TIME * ELEMENT_FIND_WAIT_RETRY_COUNT milliseconds before failing completely. This solved the problem we were having.
protected Func<IWebElement> GetLazyElement(By by, int retryCount=0)
{
    if (retryCount >= ELEMENT_FIND_WAIT_RETRY_COUNT)
    {
        throw new Exception("Wait timeout for element to show up" + by.ToString());
    }
    return new Func<IWebElement>(() => {
        try
        {
            Debug.WriteLine("Finding element " + by.ToString());
            var element = _webDriver.FindElement(by);

            return element;
        }
        catch (Exception)
        {
            Debug.WriteLine($"Failed to find element: {by} (Waiting {ELEMENT_FIND_WAIT_TIME}ms)");
            Thread.Sleep(ELEMENT_FIND_WAIT_TIME);
            var lazyFunc = GetLazyElement(by, retryCount++);
            return lazyFunc();
        }
    });
}

A: If you are using ImplicitWait and want to see if an element is present by using FindElement without waiting, try this code:
ElementExists(By.Id(id));

static public bool ElementExists(By method)
{
    var oldTime = _driver.Manage().Timeouts().ImplicitWait;
    _driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(1);
    try
    {
        bool isElementDisplayed = _driver.FindElement(method).Displayed;
        _driver.Manage().Timeouts().ImplicitWait = oldTime;
        return true;
    }
    catch
    {
        _driver.Manage().Timeouts().ImplicitWait = oldTime;
        return false;
    }
}


text:
Q: schema hasnt been registred for model (MEAN STACK) I'm learning the mean stack and when I try to start the server using
npm start

I get an exception saying that:
      throw new mongoose.Error.MissingSchemaError(name);
      ^
MissingSchemaError: Schema hasn't been registered for model "Firms".

here is my code Firms.js
   var mongoose = require('mongoose');
var CommentSchema = new mongoose.Schema({
  body: String,
  author: String,
  upvotes: {type: Number, default: 0},
  post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post' }
});

CommentSchema.methods.upvote = function(cb) {
  this.upvotes += 1;
  this.save(cb);
};

CommentSchema.methods.downvote = function(cb) {
  this.upvotes -= 1;
  this.save(cb);
};

mongoose.model('Firms', CommentSchema);

as I can see the schema should be registered for the model 'Firms', but what can be possibly causing the exception to be thrown?
here's the app.js code with the mongoose initialization:
   var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var passport = require('passport');
var jwt = require('express-jwt');

var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
var Firm = mongoose.model('Firms');
var User = mongoose.model('User');

//var Crime = mongoose.model('Crime');

var auth = jwt({secret: 'SECRET', userProperty: 'payload'});

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index');
});

A: Try using module.exports = mongoose.model('Firms', CommentSchema); also in your app.js try var Firms = require('Firms');


text:
Q: If statement not working in Spotfire I hope you can help I am attempting to use an If statement in Spotfire. What I am trying to achieve is this
I have 13 unique numbers and what I am trying to say is that if column [GL_ACCOUNT(2)] = any of these 13 numbers then return me "Not EFPIA" in my new calculated column 'GL Account Filter'
It works up to two numbers but once i increase the amount of numbers the formula will not work.
My Code is below. As always any help is greatly appreciated
if([GL_ACCOUNT(2)]="0063304000","0063401000", "0062001000", "Not EFPIA")

A: Without using TERR or JS or IronPY you'll have to explicitly OR these together. I think you are trying to do something like the IN clause in TSQL as explained here but I'm unaware of that functionality in Spotfire.
if([GL_ACCOUNT(2)]="0063304000" or
   [GL_ACCOUNT(2)]="0063401000" or
   [GL_ACCOUNT(2)]="0062001000", "Not EFPIA")

You can also do this with a CASE if that's more legible for you.
case
   when [GL_ACCOUNT(2)] = "0063304000" then "Not EFPIA"
   when [GL_ACCOUNT(2)] = "0063401000" then "Not EFPIA"
   when [GL_ACCOUNT(2)] = "0062001000" then "Not EFPIA"
   else NULL
end

Or with the OR....
case
   when [GL_ACCOUNT(2)] = "0063304000" OR
        [GL_ACCOUNT(2)] = "0063401000" OR
        [GL_ACCOUNT(2)] = "0062001000" then "Not EFPIA"
   else NULL
end

A: The expression can be used as
if([GL_ACCOUNT(2)] in "0063304000","0063401000", "0062001000", "Not EFPIA")


text:
Q: Hotkey keypress with random delay My problem is simple, my code need to hotkey the number "1" for simulate the keypress of numbers "2, 3, 4"
Now, i want to put a random delay on it, i mean: when i press number "1" he wait "random seconds" then he simulate the keypress event for number "2" etc, here is my pattern:
Press number "1" with hotkey numbers "2, 3, 4"
random seconds
keypress simulate number "2"
random secs
keypress simulate number "3"
random secs
keypress simulate number "4"
repeat when i press again the hotkey number "1"

Here my code, with no random delay, how can i put delay on like my example upside? i try with time.sleep but didnt work.
import keyboard
import time
import random

def cont():
    while True:
        keyboard.add_hotkey('1', lambda: keyboard.press_and_release('2'))
        keyboard.add_hotkey('1', lambda: keyboard.press_and_release('3'))
        keyboard.wait('esc')

if __name__ == '__main__':
    cont()

A: It may treads keyboard.press_and_release() as next argument in add_hotkey, not part of lambda and execute keyboard.press_and_release() at start - before you even press key.
You may have to use () to group commands in lambda like
 keyboard.add_hotkey('1', (lambda: time.sleep(2), keyboard.press_and_release('2')) )

Or better create normal function and use its name in add_hotkey()
import keyboard
import time
import random

def function()
    time.sleep(random.randint(1, 5))
    keyboard.press_and_release('2')
    time.sleep(random.randint(1, 5))
    keyboard.press_and_release('3')
    time.sleep(random.randint(1, 5))
    keyboard.press_and_release('4')

if __name__ == '__main__':
    keyboard.add_hotkey('1', function)
    keyboard.wait('esc')

EDIT: if you press 1 two times at once then it will run function two times at the same time. If you don't want it then you would have to use some global variable to control if function is still running:
import keyboard
import time
import random

running = False # global variable with value at start

def function():
    global running

    if running:
        return

    running = True
    time.sleep(random.randint(1, 5))
    keyboard.press_and_release('2')
    time.sleep(random.randint(1, 5))
    keyboard.press_and_release('3')
    time.sleep(random.randint(1, 5))
    keyboard.press_and_release('4')
    running = False

if __name__ == '__main__':
    keyboard.add_hotkey('1', function)
    keyboard.wait('esc')


text:
Q: PPM/PNG to GIF conversion results in very low quality The raytracer we're programming generates simple PPM image files. We wrote a little something that generates scene definitions for us, so that we can create an animation with these files.
The initial workflow was opening all files in Photoshop via File > Scripting > Load Files into Stack and exporting the result as a gif. This works well, although the workflow is bumpy. The quality is good, the file size huge.
Now when using ImageMagick to convert from PPM to GIF, the quality of the resulting image is horrible. That is, the quality of single GIF files produced by ImageMagick is already bad. Combining them to a GIF of course does not change that.
Original File (saved as PNG with Photoshop):

GIF (converted from PPM with ImageMagick):

(Especially notice the spots around the point where the light emits)
I just used mogrify -path ../gif -format gif 006.ppm for that result. I don't really know where to start to tweak this (although I played around with a couple of options from the reference).
Further Notes:

*

*For reference, here are some example files (original ppm file, ImageMagick gif, …) to play with: https://github.com/kleinfreund/raytracer/tree/master/assets

*Quality is very good when exporting a single image via Photoshop (selective, diffuse dither 100%, no transparency, 256 colors, no meta data)

*Quality is also very good when batch-converting the PPM files to PNG with ImageMagick

*I'm open to other workflows, so I'm fine if you can provide an alternative solution as well

(a little animation of the difference between the two files so the issues are easier to see. by Mark Setchell)

A: Other Option
Another option may be to convert to MPG format, something like this:
convert -delay 1 a-*png m2v:movie.mpg

or
convert -delay 1 a-*ppm m2v:movie.mpg

Updated Answer
I see - you have to use GIF for your animation, so PNG is not an option. Maybe you can quantize in a different colourspace, e.g. like this for Lab colorspace:
convert orig.ppm -quantize Lab -colors 256 result.gif

Other options might be YUV, RGB - you can get a list of all options with
identify -list colorspace

Original Answer
The problem is that your PPM file has more colours than the GIF format can contain. You can count the colours used like this:
convert orig.ppm -print "%k\n" null:
642

which shows your image has 642 colours.
The GIF format ony allows a palette of 256 colours - reference. Can you use PNG format instead?


text:
Q: Filesystem- ext4 : Application corrupting superblock I found many links but almost all are pointing to fix not the reason.
I created a 7GB ext4 partition on a sd card connected via USB card reader to PC. I have an application which is writing 10488576 bytes to the mentioned partition (/dev/sdc2). After the application run the filesystem is looking corrupt:
#fsck.ext4 -v /dev/sdc2
e2fsck 1.42.8 (20-Jun-2013)
ext2fs_open2: Bad magic number in super-block
fsck.ext4: Superblock invalid, trying backup blocks...
Superblock has an invalid journal (inode 8).
Clear<y>? no
fsck.ext4: Illegal inode number while checking ext3 journal for /dev/sdc2

/dev/sdc2: ***** FILE SYSTEM WAS MODIFIED *****

/dev/sdc2: ********** WARNING: Filesystem still has errors **********

#dumpe2fs /dev/sdc2
dumpe2fs 1.42.8 (20-Jun-2013)
dumpe2fs: Bad magic number in super-block while trying to open /dev/sdc2
Couldn't find valid filesystem superblock.

The application is simply using something like below (i can't post exact code):
    char *write_buf; //declared in header
    write_buf = (char *) malloc(size) // where size = 10488576. This allocation is happening in function a() called from main
    char *buf; // declared locally in function b()
    buf = write_buf; // in function b()
    write(fd,buf,size); // in function b()

The filesystem block size is 4K.
Backup superblock at 32768 , 98304 ,163840 ,229376 , 294912 ,819200, 884736 ,1605632
Let me know if any more information required. I need to understand what might cause this corruption , because I'm very much affirmative that something may be wrong with application code.
EDIT:
 I can see that primary superblock starts at 0 , and the lseek() call before write() is also doing SEEK_SET to 0, which would overwrite superblock information. I am going to try lseek far from superblock before write().
EDIT:
I have got this fixed by doing as I mentioned above. As per dumpe2fs o/p I had below for group 0:
Group 0: (Blocks 0-32767)
  Checksum 0x8bba, unused inodes 8069
  Primary superblock at 0, Group descriptors at 1-1
  Reserved GDT blocks at 2-474
  Block bitmap at 475 (+475), Inode bitmap at 491 (+491)
  Inode table at 507-1011 (+507)
  24175 free blocks, 8069 free inodes, 2 directories, 8069 unused inodes
  Free blocks: 8593-32767
  Free inodes: 12-8080

So before writing I did lseek to 8593*4096 .Now filesystem is not getting corrupt.

A: I have got this fixed by doing as I mentioned above. As per dumpe2fs o/p I had below for group 0:
Group 0: (Blocks 0-32767)
  Checksum 0x8bba, unused inodes 8069
  Primary superblock at 0, Group descriptors at 1-1
  Reserved GDT blocks at 2-474
  Block bitmap at 475 (+475), Inode bitmap at 491 (+491)
  Inode table at 507-1011 (+507)
  24175 free blocks, 8069 free inodes, 2 directories, 8069 unused inodes
  Free blocks: 8593-32767
  Free inodes: 12-8080

So before writing I did lseek to 8593*4096.Now filesystem is not getting corrupt.


text:
Q: Is there a name for this method of writing that includes pictograms? I've seen people write (usually in a humorous way) a 'code-like' message where parts of words are replaced with a pictogram that sounds like that word-part.  E.G.:

(eyeball) (tin can)(rope knot) get the (hole in ground) (earth) in my head,
  yet.

becomes

I cannot get the whole world in my head, yet.

I once saw this used in a fictional book, and wonder if it has an actual name.
Edit: the answer also helped by re-find this wonderfully imagined race that communicates via rebuses.

A: This is called a rebus:

A rebus is an allusional device that uses pictures to represent words
  or parts of words. It was a favourite form of heraldic expression used
  in the Middle Ages to denote surnames, for example in its basic form 3
  salmon fish to denote the name "Salmon".

Here is an example:

A: It is called a rebus.

a puzzle in which words are represented by combinations of pictures and individual letters; for instance, apex might be represented by a picture of an ape followed by a letter X.


text:
Q: Why does $Failed have attribute HoldAll? Why does $Failed have attribute HoldAll?  Are there typical situations where $Failed is returned as a head that must not evaluate further, or is this just a relic from Mathematica's early times?
In[1]:= Attributes[$Failed]
Out[1]= {HoldAll, Protected}

A: It is not very common, but sometimes, $Failed is used as a head, like
f[x___]:= $Failed[x]

This makes it possible to have "return code" returned, rather than just a fact of failure.
Basically, when this is used, it is usually in the error-reporting fall-back rule. In some cases, one may want to not evaluate the arguments x (e.g. if f is Hold*). I don't use $Failed in such fashion myself, but I've seen such code, and I don't find any particular reason not to use it in this way. Of course, one could also use $Failed[Hold[x]], but arguably this is a clumsier method.


text:
Q: how to fix the running order between html and css files? I have placed the css links into a separate page and include the page into the html file, in running time the html shows without the css design for 1 second then the page load correctly.
I am using Atom application and Laravel framework. I have reformat the css by removing the unnecessary lines and merge the codes in one line.

A: In order to load the css styling before the html, you have got to include the css file in the header of the html.