text:
Q: Stroustrup Chapter4 Exercise 11 I am working through Programming: Principles and Practice Using C++ and I am on chapter 4, exercise 11. The question wants you to write a program that detects all primes between 1 ans 100. This is what I have so far
//This program finds the prime numbers between 1 and 100
#include <iostream>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;

vector<int>primes;
bool ptest(int y)
{
    int p=0, x=0;
    for (x==0; x<primes.size(); ++p)
    {
        if (y%primes[x]==0)
        {
            return false;
        }
            return true;
    }
}

int main()
{
    int i=3;
    primes.push_back(2);
    vector<int>comp;
    for (i==3; i<=100; ++i)
    {
        if (ptest(i)==true)
        {
            primes.push_back(i);
        }

    }

    for (int x:primes)
    {
        cout << x << " ";
    }

}

For some reason, the program prints 2, followed by all of the odds from 3-100. I am not sure what I am missing here.
EDIT: Question has been answered. Thep was from a previous try that I forgot to change. The major mistake here was me not knowing that the return true value belonged outside of the loop.
Thanks

A: Errors:

*

*Your return true; is in wrong position. It should be after the loop.

*x have to be updated in the iterations.

Warnings:

*

*The first expression x==0 in for loop is meaningless.

*p is meaningless because its value is not used.

Try this:
bool ptest(int y)
{
    for (int x=0; x<primes.size(); ++x)
    {
        if (y%primes[x]==0)
        {
            return false;
        }
    }
    return true;
}


text:
Q: Cursor on a trigger I'm using SQL Server 2008.
I have an after trigger for INSERT, UPDATE and DELETE action defined in the table. My problem is that currently my trigger inserts one record at a time and I need multiple records as for one
SELECT TOP 1 @ParentID FROM ... WHERE ID = @ID

returns multiple unique records.
(See this comment below "-- this subquery returns more than 1 value, so I need to insert in the search Audit table as many ParentIDs as it returns")
I believe I need to use cursor, but I'm not sure where exactly to declare and open cursor.
--CREATE PROCEDURE [dbo].[SP_Auditing]
--      @ID INT, @Code VARCHAR(3), @AuditType VARCHAR(10), @ParentCode VARCHAR(3) = NULL, @ParentID INT = NULL
--AS
--BEGIN
--          INSERT INTO myDB.dbo.Table1 (ID, Code, AuditType, ParentCode, ParentID)

--          VALUES(@ID, @Code, @AuditType, @ParentCode, @ParentID)
--END

GO

CREATE TRIGGER [dbo].[Tr_MyFavouriteTable_UPD_INSERT_DEL]    ON [dbo].[MyFavouriteTable] AFTER INSERT, DELETE, UPDATE    NOT FOR REPLICATION

AS

BEGIN
            DECLARE @ID INT,            @Code VARCHAR(3),           @AuditType VARCHAR(10),             @ParentCode VARCHAR(3),             @ParentID INT       SET     @Code = 'DOC'

    IF EXISTS (SELECT 1 FROM inserted)          AND
       NOT EXISTS (SELECT 1 FROM deleted)
                BEGIN
                        SELECT TOP 1
                @ID = ins.ID,
                @ParentID = (
                    SELECT TOP 1 CAST(RIGHT(parentId,LEN(parentId) - LEN(LEFT(parentId,3))) AS INT)
                    FROM [MyDB].[dbo].[MyFavouriteTable] t WITH (NOLOCK)
                    INNER JOIN [MyDB2].[dbo].[MyView] v WITH (NOLOCK)
                        ON t.Id = v.ID
                    WHERE v.ID = @ID --284
                ), **-- this subquery returns more than 1 value, so I need to insert in the search Audit table as many ParentIDs as it returns**
                @AuditType = 'INSERT'           FROM inserted ins
                        IF @ID IS NOT NULL
               AND
               @ParentID IS NOT NULL
               AND
               @ParentCode IS NOT NULL

            EXEC [MyDB].[dbo].SP_Auditing] @ID, @Code, @AuditType, @ParentCode, @ParentID
                END

--  below is the same logic for UPDATE and DELETE actions...

The stored procedure above simply inserts data into the Audit table.

A: Never use scalar variables in triggers because insert, update, and delete may affect multiple rows. As to your trigger, try something like this.
CREATE TRIGGER [dbo].[Tr_MyFavouriteTable_UPD_INSERT_DEL]
    ON [dbo].[MyFavouriteTable] AFTER INSERT, DELETE, UPDATE
        NOT FOR REPLICATION
AS

BEGIN
    ;with act as (
    select isnull(i.id,d.id) id, --either deleted or inserted is not null
    case when i.id is not null and d.id is not null then 'update'
         when i.id is not null then 'insert'
         else 'delete' end auditType
    from inserted i full outer join deleted d on i.id = d.id
    ),
    audit_cte as (
    SELECT act.id, 'DOC' Code,
           CAST(RIGHT(parentId,LEN(parentId) - LEN(LEFT(parentId,3))) AS INT) parentid,
           act.auditType, 'parentcode' parentCode
    FROM [MyDB].[dbo].[MyFavouriteTable] t WITH (NOLOCK)
    INNER JOIN [MyDB2].[dbo].[MyView] v WITH (NOLOCK)  ON t.Id = v.ID
    inner join act on act.id = t.id
    )
    insert myDB.dbo.Table1 (ID, Code, AuditType, ParentCode, ParentID)
    select id,code,AuditType, ParentCode, ParentID
    from audit_cte
    where parentCode is not null and parentid is not null
end

A: Why do you need to get the records one by one? From my understanding you want to keep the log.
IF EXISTS (SELECT 1 FROM inserted)          AND
   NOT EXISTS (SELECT 1 FROM deleted)
            BEGIN
            INSERT INTO [Your_Log_Table]
            SELECT
            ins.ID, [Code],'INSERT',[PrentCode],
            (SELECT TOP 1 CAST(RIGHT(parentId,LEN(parentId) -
                LEN(LEFT(parentId,3))) AS INT)
                FROM [MyDB].[dbo].[MyFavouriteTable] t WITH (NOLOCK)
                INNER JOIN [MyDB2].[dbo].[MyView] v WITH (NOLOCK)
                    ON t.Id = v.ID
                WHERE v.ID = ins.ID --284
            )
                FROM inserted ins
            END

A: See Alex Kudryashev's answer. I needed to tweak a little his logic to sort out duplicate records with the same ParentIDs for the insertion into the Audit table. I added one more cte just below Alex's cte_Audit as follows
CREATE TRIGGER [dbo].[Tr_MyFavouriteTable_UPD_INSERT_DEL]
    ON [dbo].[MyFavouriteTable] AFTER INSERT, DELETE, UPDATE
        NOT FOR REPLICATION
AS

BEGIN
    ;with act as (
    select isnull(i.id,d.id) id, --either deleted or inserted is not null
    case when i.id is not null and d.id is not null then 'update'
         when i.id is not null then 'insert'
         else 'delete' end auditType
    from inserted i full outer join deleted d on i.id = d.id
    ),
    audit_cte as (
    SELECT act.id, 'DOC' Code,
           CAST(RIGHT(parentId,LEN(parentId) - LEN(LEFT(parentId,3))) AS INT) parentid,
           act.auditType, 'parentcode' parentCode
    FROM [MyDB].[dbo].[MyFavouriteTable] t WITH (NOLOCK)
    INNER JOIN [MyDB2].[dbo].[MyView] v WITH (NOLOCK)  ON t.Id = v.ID
    inner join act on act.id = t.id
    )
    insert myDB.dbo.Table1 (ID, Code, AuditType, ParentCode, ParentID)
    select id,code,AuditType, ParentCode, ParentID
    from audit_cte
    where parentCode is not null and parentid is not null
         ,CTE_dupsCleanup AS (
                SELECT DISTINCT
                Code,
                Id,
                AuditType,
                ParentCode,
                ParentId,

  --   ROW_NUMBER() OVER(PARTITION BY ParentId, ParentCode, AuditType ORDER BY ParentId) AS Rn

        FROM AUDIT_CTE
                WHERE ParentCode IS NOT NULL
                    AND ParentId IS NOT NULL )

Then using Rn = 1 inserted only unique records into the Auidt table. Like this:

                    INSERT [ISSearch].[dbo].[SearchAudit] (Code, ID, AuditType, ParentCode, ParentID)
                SELECT
                Code,
                ID,
                AuditType,
                ParentCode,
                ParentId
                FROM CTE_dupsCleanup
                --  WHERE Rn = 1
END

redpajama_set_name: RedPajamaStackExchange


text:
Q: Days that cashier will work A cashier wants to work five days a week, but he wants to have at least one of Saturday and Sunday off.
How many ways can he choose the days he will work?

A: Hint: Split up the problem into easier cases. If the cashier  wants the whole weekend off, there is $1$ way only. How many ways with Saturday off but not Sunday? How many with Sunday off but not Saturday? Add the three numbers.


text:
Q: Manage nginx rewrites in project folder I am trying to figure out on how to migrate from Apache to nginx, keeping rewrite rules flexible to change for developers. This is our current setup:

*

*We have a .htaccess file in the root folder of the project (and in some subfolders as well)

*In this .htaccess file, the developers can define rewrites for pretty permalinks to specific scripts (we don't use a "global" index.php file)

*This .htaccess file is included in our Git repo, so adding/changing rewrites does not require the developer to change the server configuration (which he has no permissions to)

As far as I learned already, there is no such thing as a per-directory .htaccess equivalent with nginx. So how can we possibly solve this? Do we have to use a "global" index.php file to resolve the rewrites? That would probably decrease the overall performance significantly.
P.S. As you might have noticed, I never used nginx before.

A: OK, so firstly I think you should consider carefully whether nginx will really help you with your performance problem (per your comment), and test that in a development environment before worrying about how your deployment will work.
It is true that nginx is faster, and that it's multi-threaded architecture helps deal with high loads, but yours would be an extraordinarily unusual PHP site if the part of your operation you are looking to speed up accounts for more than one or two percent of the total delays.  Your bottleneck will almost certainly be in your database and PHP execution.
You should probably look first at PHP compilation caching (eg APC), a front end proxy (eg varnish or squid), internal caching within your application (is this wordpress?  there's some good caching modules there).   Handing off delivery of static files only to nginx might be agood idea, but it's probably better to look at using either your own proxies, or a Content Distribution Network for that content anyway.
If you do decide to proceed though, some tools come to mind, albeit they are fairly heavy weight tools.  You could use continuous integration and configuration management tools (eg Jenkins and Puppet, or equivalents) to deploy your configuration from a version control repository to your server whenever its checked into the appropriate branch.  This is a lot of infrastructure complexity to learn about and build though, and without a good deal knowledge, skill and care, you might as well be just giving your developers root access anyway.  Apache's system of delegation through .htaccess has been developed over many years, and you're not going to replicate it's security in a hurry.
Go back and check your assumptions with a profiling tool about how much of a performance issue your regex handling is.  I've used mostly Xdebug, but there are other good alternatives.


text:
Q: How to protect my ren'py project from being copied? For all those who are not familiar with ren'py: It's basically python with some modifications. Since the project is coded in python, which can easily be edited by anyone it is not a good idea to include a license validation in the python files.
An executable starts the game, so I thought about wrapping it with a license validation in an .exe (but I honestly don't know how I can take an executable, put some code around and have one executable including the actual one). Maybe there is another way, which is safer than the one I named, suggestions?

A: You don't. Ren'Py only features basic encryption to prevent players from accidentally deleting/modifying files.
As security, game encryption isn't a fight worth picking. You have to decrypt the files to run them and that will always be a weak point to exploit. Anything you put on top is just delaying whoever wants in. You can write your game in binary and it will do exactly squat to someone who really wants to take it apart.
Ren'Py is designed to be mod friendly. Nothing you do will stop someone from dropping a rpyc file into the game directory and hooking into the game. Even if you modify the engine to only read specific files, you won't stop someone who can just insert the functionality back in. All you're really doing is making it more difficult to preserve the game after you're dead.
Nintendo can't stop people from extracting assets from their games. You don't stand a chance. You should hope to be so lucky as to have people interested enough in your game to want to mess around with the assets and code.
If you're talking about a license players need or some sort of login mechanism, you need to implement an online server to validate the credentials they input. There is no secure front-end way to validate credentials.


text:
Q: Hibernate CompositeUserType mapping has wrong number of columns I am new to Hibernate. Writing a CompositeUserType. When I run the code I am getting error.
property
mapping has wrong number of columns:
Please help me what am I missing?
My CompositeUserType goes as follows
 public  class EncryptedAsStringType implements CompositeUserType {
 @Override
 public String[] getPropertyNames() {
    return new String[] { "stockId", "stockCode", "stockName","stockDescription" };
}

@Override
public Type[] getPropertyTypes() {
    //stockId, stockCode,stockName,modifiedDate
    return new Type[] {
            Hibernate.INTEGER, Hibernate.STRING, Hibernate.STRING,Hibernate.STRING

    };
}
@Override
public Object getPropertyValue(final Object component, final int property)
        throws HibernateException {
    Object returnValue = null;
    final Stock auditData = (Stock) component;

    if (0 == property) {
        returnValue = auditData.getStockId();
    } else if (1 == property) {
        returnValue = auditData.getStockCode();
    } else if (2 == property) {
        returnValue = auditData.getStockName();
    }   return returnValue;
}

@Override
public void setPropertyValue(final Object component, final int property,
        final Object setValue) throws HibernateException {
    final Stock auditData = (Stock) component;

}

 @Override
    public Object nullSafeGet(final ResultSet resultSet,
            final String[] names,
            final SessionImplementor paramSessionImplementor, final Object paramObject)
            throws HibernateException, SQLException {
        //owner here is of type TestUser or the actual owning Object
     Stock auditData = null;
        final Integer createdBy = resultSet.getInt(names[0]);
        //Deferred check after first read
        if (!resultSet.wasNull()) {
            auditData = new Stock();

            System.out.println(">>>>>>>>>>>>"+resultSet.getInt(names[1]));
            System.out.println(">>>>>>>>>>>>"+resultSet.getString(names[2]));
            System.out.println(">>>>>>>>>>>>"+resultSet.getString(names[3]));
            System.out.println(">>>>>>>>>>>>"+resultSet.getString(names[4]));
                 }
        return auditData;
    }

    @Override
    public void nullSafeSet(final PreparedStatement preparedStatement,
            final Object value, final int property,
            final SessionImplementor sessionImplementor)
            throws HibernateException, SQLException {
        if (null == value) {

        } else {
            final Stock auditData = (Stock) value;
            System.out.println("::::::::::::::::::::::::::::::::"+auditData.getStockCode());
            System.out.println("::::::::::::::::::::::::::::::::"+auditData.getStockDescription());
            System.out.println("::::::::::::::::::::::::::::::::"+auditData.getStockId());
            System.out.println("::::::::::::::::::::::::::::::::"+auditData.getStatus());

        }
    }

My Domain class Stock has five attributes. (stockId,stockCode,StockName,Status , Stock
Description)
I need to declare the field Stock description as Composite field Type.
 private Integer stockId;
private String stockCode;
private String stockName;
private String status;
private String stockDescription;

//Constructors

@Column(name = "STOCK_CC", unique = true, nullable = false, length = 20)
@Type(type="com.mycheck.EncryptedAsStringType")
@Columns(columns = { @Column(name="STOCK_ID"),
    @Column(name="STOCK_CODE"),
    @Column(name="STOCK_NAME")

   })
public String getStockDescription() {
    return stockDescription;
}

}
When I try to execute a insert for Stock. I am getting the error  Error creating bean with name
'sessionFactory' defined in class path resource [spring/config/../database/Hibernate.xml]:
Invocation of init method failed. nested exception is org.hibernate.MappingException:
property mapping has wrong number of columns: com.stock.model.Stock.stockDescription type:
com.mycheck.EncryptedAsStringType
Where am I going wrong ?

A: One can extract the answer from the code samples and the comments to the original question, but to save everyone some reading, I've compiled a quick summary.
If you declare a CompositeUserType that maps a type to n columns, you have to declare n columns in @Columns besides the @Type annotation. Example:
public class EncryptedAsStringType implements CompositeUserType {
    @Override
    public String[] getPropertyNames() {
       return new String[] { "stockId", "stockCode", "stockName","stockDescription" };
    }

    // ...
}

This CompositeUserType maps to 4 separate columns, therefore 4 separate @Column annotations have to be declared:
@Type(type="com.mycheck.EncryptedAsStringType")
@Columns(columns = {
    @Column(name="STOCK_ID"),
    @Column(name="STOCK_CODE"),
    @Column(name="STOCK_NAME"),
    @Column(name="STOCK_DESCRIPTION")
})
public String getStockDescription() {
    return stockDescription;
}

That's it and Hibernate is happy.


text:
Q: Is there a tool that allows the same functionality of extend/trim feature that was available in 9.3? In ArcGIS 9.3 there was a tool called Extend/Trim Features that allowed you to select multiple segments and extend or trim them to a feature.
In 10.1 that seems to have been moved to the Production Mapping Extension at a hefty price. It was replaced by two tools that don't seem to have the same functionality as the previous versions tool.
My question: Is anybody aware of an add in or way that I could create this functionality with python or a custom tool?
EDIT
The old tool can be found referenced HERE, there is also a screenshot of the tool location from 9.3:

Essentially, it did both of the functions that are shown in @Jakub's answer.
It looks like the same tool from 9.3 was moved to the Production Mapping toolbar in 10.1.
There seems to be an ESRI Idea out there suggesting they bring it back, and that I'm not, in fact, imagining that it used to be this way.

A: The tools are in Advanced Editing toolbar. Customize->Toolbars->Advanced Editing Tools.

A: I am not sure about 10.1, but in 10.0 you can get the 9.3 editor toolbar including the 'Extend/Trim Features'.

*

*Go to :\Program Files\ArcGIS\Desktop10.1\Utilities

*Open AdvancedArcMapSettings.exe

*Under Editor tab, UNCHECK 'Create features using templates'

*The Editor toolbar will now look and function like in 9.3.

A: At 10.1 there is a Trim Line and also an Extend Line geoprocessing tool.


text:
Q: Execution failed for task ':app:externalNativeBuildDebug' when using cpp and java in android My android studio project is failing to build with this error when linking c++ to java using jni
Build command failed.
Error while executing process C:\Users\conno\AppData\Local\Android\Sdk\cmake\3.10.2.4988404\bin\ninja.exe with arguments {-C D:\Connor\DMA\Pipes\Android\Smart_Pipes\app\.cxx\cmake\debug\arm64-v8a native-lib}
ninja: Entering directory `D:\Connor\DMA\Pipes\Android\Smart_Pipes\app\.cxx\cmake\debug\arm64-v8a'
[1/1] Linking CXX shared library D:\Connor\DMA\Pipes\Android\Smart_Pipes\app\build\intermediates\cmake\debug\obj\arm64-v8a\libnative-lib.so
FAILED: D:/Connor/DMA/Pipes/Android/Smart_Pipes/app/build/intermediates/cmake/debug/obj/arm64-v8a/libnative-lib.so
cmd.exe /C "cd . && C:\Users\conno\AppData\Local\Android\Sdk\ndk\21.4.7075529\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++.exe --target=aarch64-none-linux-android21 --gcc-toolchain=C:/Users/conno/AppData/Local/Android/Sdk/ndk/21.4.7075529/toolchains/llvm/prebuilt/windows-x86_64 --sysroot=C:/Users/conno/AppData/Local/Android/Sdk/ndk/21.4.7075529/toolchains/llvm/prebuilt/windows-x86_64/sysroot -fPIC -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security   -O0 -fno-limit-debug-info  -Wl,--exclude-libs,libgcc.a -Wl,--exclude-libs,libgcc_real.a -Wl,--exclude-libs,libatomic.a -static-libstdc++ -Wl,--build-id -Wl,--fatal-warnings -Wl,--no-undefined -Qunused-arguments -shared -Wl,-soname,libnative-lib.so -o D:\Connor\DMA\Pipes\Android\Smart_Pipes\app\build\intermediates\cmake\debug\obj\arm64-v8a\libnative-lib.so CMakeFiles/native-lib.dir/oboe/samples/debug-utils/trace.cpp.o CMakeFiles/native-lib.dir/jni_bridge.cpp.o CMakeFiles/native-lib.dir/AudioEngine.cpp.o CMakeFiles/native-lib.dir/LatencyTuningCallback.cpp.o CMakeFiles/native-lib.dir/SoundGenerator.cpp.o  -llog oboe/liboboe.a -llog -lOpenSLES -latomic -lm && cd ."
CMakeFiles/native-lib.dir/jni_bridge.cpp.o: In function `Java_com_android_smartpipes_PlaybackEngine_native_1setNote':
D:/Connor/DMA/Pipes/Android/Smart_Pipes/app/src/main/cpp/jni_bridge.cpp:189: undefined reference to `SoundGenerator::_Frequency'
D:/Connor/DMA/Pipes/Android/Smart_Pipes/app/src/main/cpp/jni_bridge.cpp:189: undefined reference to `SoundGenerator::_Frequency'
CMakeFiles/native-lib.dir/SoundGenerator.cpp.o: In function `SoundGenerator::tap(bool)':
D:/Connor/DMA/Pipes/Android/Smart_Pipes/app/src/main/cpp/SoundGenerator.cpp:(.text._ZN14SoundGenerator3tapEb+0x58): undefined reference to `SoundGenerator::_Frequency'
D:/Connor/DMA/Pipes/Android/Smart_Pipes/app/src/main/cpp/SoundGenerator.cpp:(.text._ZN14SoundGenerator3tapEb+0x5c): undefined reference to `SoundGenerator::_Frequency'
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
ninja: build stopped: subcommand failed.

The Method in jni_bridge.cpp
JNIEXPORT void JNICALL
Java_com_android_smartpipes_PlaybackEngine_native_1setNote(JNIEnv *env, jclass clazz, int note) {
    double freqScale[] = {419.98,   //LG
                          480.00,   //LA
                          540.03,   //B
                          599.88,   //C
                          644.42,   //D
                          720.02,   //E
                          802.60,   //F
                          839.96,   //HG
                          960.00    //HA
    };

    SoundGenerator::_Frequency = freqScale[note];
}

My java code PlaybackEngine.java
    static void setNote(ENote note){
        switch (note){
            case ELG:
                native_setNote(0);
            case ELA:
                native_setNote(1);
            case EB:
                native_setNote(2);
            case EC:
                native_setNote(3);
            case ED:
                native_setNote(4);
            case EE:
                native_setNote(5);
            case EF:
                native_setNote(6);
            case EHG:
                native_setNote(7);
            case EHA:
                native_setNote(8);
            default:
                native_setNote(8);
        }
    }

    private static native void native_setNote(int note);

SoundGenerator.cpp
void SoundGenerator::tap(bool isOn) {

    for (int i = 0; i < mChannelCount; ++i) {
        mOscillators[i].setFrequency(SoundGenerator::_Frequency);
        mOscillators[i].setWaveOn(isOn);
    }
}

SoundGenerator.h
class SoundGenerator{
   static double _Frequency;
}

I am trying to pass the java enum note through to the cpp as an int and then convert it to a double for c++.
Thanks for your help

A: Probably, you need to define actual variable separately in .cpp file for the static class-member, SoundGenerator::_Frequency, as follows.
SoundGenerator.cpp
double SoundGenerator::_Frequency = 440.0; // A


text:
Q: Adobe XD Apple UI resources I want to design a page for Apple using Adobe XD.
When I looked for resources and download them, they were all in .dmg fines.
However, I am using Windows 10. What do I do?

A: It looks like you can open DMGs on Windows with 7-Zip (via context menu) or DMG Extractor (via UI tool).
How to Geek has a usage overview of both.

A: You can download Windows 10 version from Adobe XD's official website. Addition to that, now you can install various useful plugins of Adobe XD in the application under plugins menu.
As UI components please have a look official website of xD, xdguru, blog adobe and xdresources. Those are some of the websites where you can find free components for Adobe XD.
When you use search engine, try to search like "Apple UI kit, IOS kits, Material kits etc. "
Hope it will help


text:
Q: prevent reading and returning of string value int getIndex(){
    int index = 0;
    do{
        printf("Enter your Index(0..80),-1 to STOP,-2 to RESTART,-3 to START NEW BOARD: ");
        scanf("%d", &index);
    } while (!(index >= -3 && index <=80));

    return index;

}

Hello, given that i have written the above method in C for a sudoku game board . what can i do to prevent the user from entering a alphabet? and keep prompting until the valid input is gotten. i have just started C .what is limiting me is the scanf flag specifier, i specified a int flag which means if a user enters a string, im screwed.

A: All you need is to check the return value of scanf and then clear the character from the input buffer(stdin) if any invalid input was entered. So change your code to the following:
int getIndex()
{
    int index = 0;

    while(1) //infinite loop
    {    printf("Enter your Index(0..80),-1 to STOP,-2 to RESTART,-3 to START NEW BOARD: ");
        if(scanf("%d", &index)==1) //scanf is successful scanning a number(input is a number)
        {
          if(index >= -3 && index <= 80) // if input is in range
          break; //break out of while loop
          printf("Number must be in range of -3 to 80\n"); //input is a number,but not in range
        }
        else  //input is not a number
        {
        scanf("%*s"); //Clear invalid input
        //printf("Invalid input\n");
        fprintf(stderr, "Invalid input\n"); //printf also works but errors are meant to be in the stderr
        }

    }

    return index;
}


text:
Q: Improve discontinuity detection algorithm I'm trying to create an algorithm that detects discontinuities (like vertical asymptotes) within functions between an interval for the purpose of plotting graphs without these discontinuous connecting lines. Also, I only want to evaluate within the interval so bracketing methods like bisection seems good for that.

EDIT
https://en.wikipedia.org/wiki/Classification_of_discontinuities
I realize now there are a few different kinds of discontinuities. I'm mostly interested in jump discontinuities for graphical purposes.

I'm using a bisection method as I've noticed that discontinuities occur where the slope tends to infinity or becomes vertical, so why not narrow in on those sections where the slope keeps increasing and getting steeper and steeper. The point where the slope is a vertical line, that's where the discontinuity exists.
Approach
Currently, my approach is as follows. If you subdivide the interval using a midpoint into 2 sections and compare which section has the steepest slope, then that section with the steepest slope becomes the new subinterval for the next evaluation.
Termination
This repeats until it converges by either slope becoming undefined (reaching infinity) or the left side or the right side of the interval equaling the middle (I think this is because the floating-point decimal runs out of precision and cannot divide any further)
(1.5707963267948966 + 1.5707963267948968) * .5 = 1.5707963267948966
Example
function - floor(x)

(blue = start leftX and rightX, purple = midpoint, green = 2nd iteration midpoints points, red = slope lines per iteration)
As you can see from the image, each bisection narrows into the discontinuity and the slope keeps getting steeper until it becomes a vertical line at the discontinuity point at x=1.
To my surprise this approach seems to work for step functions like floor(x) and tan(x), but it's not that great for 1/x as it takes too many iterations (I'm thinking of creating a hybrid method where I use either illinois or ridders method on the inverse of 1/x as it those tend to find the root in just one iteration).
Javascript Code
/* Math function to test on */
function fn(x) {
    //return (Math.pow(Math.tan(x), 3));
    return 1/x;
    //return Math.floor(x);
    //return x*((x-1-0.001)/(x-1));
}

function slope(x1, y1, x2, y2) {
    return (y2 - y1) / (x2 - x1);
}

function findDiscontinuity(leftX, rightX, fn) {
    while (true) {
        let leftY = fn(leftX);
        let rightY = fn(rightX);
        let middleX = (leftX + rightX) / 2;
        let middleY = fn(middleX);
        let leftSlope = Math.abs(slope(leftX, leftY, middleX, middleY));
        let rightSlope = Math.abs(slope(middleX, middleY, rightX, rightY));

        if (!isFinite(leftSlope) || !isFinite(rightSlope)) return middleX;

        if (middleX === leftX || middleX === rightX) return middleX;

        if (leftSlope > rightSlope) {
            rightX = middleX;
            rightY = middleY;
        } else {
            leftX = middleX;
            leftY = middleY;
        }
    }
}

Problem 1 - Improving detection
For the function x*((x-1-0.001)/(x-1)), the current algorithm has a hard time detecting the discontinuity at x=1 unless I make the interval really small. As an alternative, I could also add most subdivisions but I think the real problem is using slopes as they trick the algorithm into choosing the incorrect subinterval (as demonstrated in the image below), so this approach is not robust enough. Maybe there are some statistical methods that can help determine a more probable interval to select. Maybe something like least squares for measuring the differences and maybe applying weights or biases!

But I don't want the calculations to get too heavy and 5 points of evaluation are the max I would go with per iteration.

EDIT

After looking at problem 1 again, where it selects the wrong (left-hand side) subinterval. I noticed that the only difference between the subintervals was the green midpoint distance from their slope line. So taking inspiration from linear regression, I get the squared distance from the slope line to the midpoints [a, fa] and [b, fb] corresponding to their  (left/right) subintervals. And which subinterval has the greatest change/deviation is the one chosen for further subdivision, that is, the greater of the two residuals.
This further improvement resolves problem 1. Although, it now takes around 593 iterations to find the discontinuity for 1/x. So I've created a hybrid function that uses ridders method to find the roots quicker for some functions and then fallback to this new approach. I have given up on slopes as they don't provide enough accurate information.

Problem 2 - Jump Threshold
I'm not sure how to incorporate a jump threshold and what to use for that calculation, don't think slopes would help.
Also, if the line thickness for the graph is 2px and 2 lines of a step function were on top of each other then you wouldn't be able to see the gap of 2px between those lines. So the minimum jump gap would be calculated as such
jumpThreshold = height / (ymax-ymin) = cartesian distance per pixel
minJumpGap = jumpThreshold * 2
But I don't know where to go from here! And once again, maybe there are statistical methods that can help to determine the change in function so that the algorithm can terminate quickly if there's no indication of a discontinuity.
Overall, any help or advice in improving what I got already would be much appreciated!

EDIT

As the above images explains, the more divergent the midpoints are the greater the need for more subdivisions for further inspection for that subinterval. While, if the points mostly follow a straight line trend where the midpoints barely deviate then should exit early. So now it makes sense to use the jumpThreshold in this context.
Maybe there's further analysis that could be done like measuring the curvature of the points in the interval to see whether to terminate early and further optimize this method. Zig zag points or sudden dips would be the most promising. And maybe after a certain number of intervals, keep widening the jumpThreshold as for a discontinuity you expect the residual distance to rapidly increase towards infinity!
Updated code
let ymax = 5, ymin = -5; /* just for example */
let height = 500; /* 500px screen height */
let jumpThreshold = Math.pow(.5 * (ymax - ymin) / height, 2); /* fraction(half) of a pixel! */

/* Math function to test on */
function fn(x) {
    //return (Math.pow(Math.tan(x), 3));
    return 1 / x;
    //return Math.floor(x);
    //return x * ((x - 1 - 0.001) / (x - 1));
    //return x*x;
}

function findDiscontinuity(leftX, rightX, jumpThreshold, fn) {
    /* try 5 interations of ridders method */
    /* usually this approach can find the exact reciprocal root of a discountinuity
     * in 1 iteration for functions like 1/x compared to the bisection method below */
    let iterations = 5;
    let root = inverseRidderMethod(leftX, rightX, iterations, fn);
    let limit = fn(root);

    if (Math.abs(limit) > 1e+16) {
        if (root >= leftX && root <= rightX) return root;
        return NaN;
    }

    root = discontinuityBisection(leftX, rightX, jumpThreshold, fn);
    return root;
}

function discontinuityBisection(leftX, rightX, jumpThreshold, fn) {
    while (true) {
        let leftY = fn(leftX);
        let rightY = fn(rightX);
        let middleX = (leftX + rightX) * .5;
        let middleY = fn(middleX);

        let a = (leftX + middleX) * .5;
        let fa = fn(a);

        let b = (middleX + rightX) * .5;
        let fb = fn(b);

        let leftResidual = Math.pow(fa - (leftY + middleY) * .5, 2);
        let rightResidual = Math.pow(fb - (middleY + rightY) * .5, 2);

    /* if both subinterval midpoints (fa,fb) barely deviate from their slope lines
         * i.e. they're under the jumpThreshold, then return NaN,
         * indicating no discountinuity with the current threshold,
         * both subintervals are mostly straight */
        if (leftResidual < jumpThreshold && rightResidual < jumpThreshold) return NaN;

        if (!isFinite(fa) || a === leftX || a === middleX) return a;
        if (!isFinite(fb) || b === middleX || b === rightX) return b;

        if (leftResidual > rightResidual) {
            /* left hand-side subinterval */
            rightX = middleX;
            middleX = a;
        } else {
            /* right hand-side subinterval */
            leftX = middleX;
            middleX = b;
        }
    }
}

function inverseRidderMethod(min, max, iterations, fn) {
    /* Modified version of RiddersSolver from Apache Commons Math
     * http://commons.apache.org/
     * https://www.apache.org/licenses/LICENSE-2.0.txt
     */
    let x1 = min;
    let y1 = 1 / fn(x1);
    let x2 = max;
    let y2 = 1 / fn(x2);

    // check for zeros before verifying bracketing
    if (y1 == 0) {
        return min;
    }
    if (y2 == 0) {
        return max;
    }

    let functionValueAccuracy = 1e-55;
    let relativeAccuracy = 1e-16;
    let oldx = Number.POSITIVE_INFINITY;
    let i = 0;
    while (i < iterations) {
        // calculate the new root approximation
        let x3 = 0.5 * (x1 + x2);
        let y3 = 1 / fn(x3);
        if (!isFinite(y3)) return NaN;

        if (Math.abs(y3) <= functionValueAccuracy) {
            return x3;
        }
        let delta = 1 - (y1 * y2) / (y3 * y3); // delta > 1 due to bracketing
        let correction = (signum(y2) * signum(y3)) * (x3 - x1) / Math.sqrt(delta);
        let x = x3 - correction; // correction != 0
        if (!isFinite(x)) return NaN;
        let y = 1 / fn(x);

        // check for convergence
        let tolerance = Math.max(relativeAccuracy * Math.abs(x), 1e-16);
        if (Math.abs(x - oldx) <= tolerance) {
            return x;
        }
        if (Math.abs(y) <= functionValueAccuracy) {
            return x;
        }

        // prepare the new interval for the next iteration
        // Ridders' method guarantees x1 < x < x2
        if (correction > 0.0) { // x1 < x < x3
            if (signum(y1) + signum(y) == 0.0) {
                x2 = x;
                y2 = y;
            } else {
                x1 = x;
                x2 = x3;
                y1 = y;
                y2 = y3;
            }
        } else { // x3 < x < x2
            if (signum(y2) + signum(y) == 0.0) {
                x1 = x;
                y1 = y;
            } else {
                x1 = x3;
                x2 = x;
                y1 = y3;
                y2 = y;
            }
        }
        oldx = x;
    }
}

function signum(a) {
    return (a < 0.0) ? -1.0 : ((a > 0.0) ? 1.0 : a);
}

/* TEST */
console.log(findDiscontinuity(.5, .6, jumpThreshold, fn));

Python Code
I don't mind if the solution is provided in Javascript or Python
import math

def fn(x):
    try:
        # return (math.pow(math.tan(x), 3))
        # return 1 / x
        # return math.floor(x)
        return x * ((x - 1 - 0.001) / (x - 1))
    except ZeroDivisionError:
        return float('Inf')

def slope(x1, y1, x2, y2):
    try:
        return (y2 - y1) / (x2 - x1)
    except ZeroDivisionError:
        return float('Inf')

def find_discontinuity(leftX, rightX, fn):

    while True:
        leftY = fn(leftX)
        rightY = fn(rightX)
        middleX = (leftX + rightX) / 2
        middleY = fn(middleX)
        leftSlope = abs(slope(leftX, leftY, middleX, middleY))
        rightSlope = abs(slope(middleX, middleY, rightX, rightY))

        if not math.isfinite(leftSlope) or not math.isfinite(rightSlope):
            return middleX

        if middleX == leftX or middleX == rightX:
            return middleX

        if leftSlope > rightSlope:
            rightX = middleX
            rightY = middleY
        else:
            leftX = middleX
            leftY = middleY


text:
Q: How to import a SQL dump file into Hasura we have a big file SQL dump that we need to import to Hasura, currently running on Heroku.
What is the mechanism to import the dump file into Hasura?

A: Importing a SQL file to Hasura is the same as importing the SQL file to the Heroku Postgres instance.
Install psql (the command line tool for Postgres) and then restore the SQL file using that.
Head to your Heroku dashboard and then head to Setting tab and Reveal Config Vars. There you'll find DATABASE_URL.
Copy the DATABASE_URL and execute the following command:
psql DATABASE_URL -1 -f file.sql

This will execute all statements in the file against the database.


text:
Q: how to optimize mysql query in phalcon i used this query:
$brands = TblBrand::find(array("id In (Select p.brand_id From EShop\\Models\\TblProduct as p Where p.id In (Select cp.product_id From EShop\\Models\\TblProductCategory as cp Where cp.group_id_1='$id'))", "order" => "title_fa asc"));
            if($brands != null and count($brands) > 0)
            {
                foreach($brands as $brand)
                {
                    $brandInProductCategory[$id][] = array
                    (
                        "id" => $brand->getId(),
                        "title_fa" => $brand->getTitleFa(),
                        "title_en" => $brand->getTitleEn()
                    );
                }
            }

TblBrand => 110 records
TblProduct => 2000 records
TblProductCategory => 2500 records

when i used this code, my site donot show and loading page very long time ...
but when i remove this code, my site show.
how to solve this problem?

A: The issue is your query. You are using the IN statement in a nested format, and that is always going to be slower than anything else. MySQL will need to first evaluate what is in the IN statement, return that and then do it all over again for the next level of records.
Try simplifying your query. Something like this:
SELECT *
FROM   Brands
INNER JOIN Products ON Brand.id = Products.brand_id
INNER JOIN ProductCategory ON ProductCategory.product_id = Products.id
WHERE ProductCategory.group_id_1 = $id

To achieve the above, you can either use the Query Builder and get the results that way
https://docs.phalconphp.com/en/latest/api/Phalcon_Mvc_Model_Query_Builder.html
or if you have set up relationships in your models between brands, products and product categories, you can use that.
https://docs.phalconphp.com/en/latest/reference/model-relationships.html

A: example:
$Brands = Brands::query()
->innerJoin("Products", "Products.brand_id = Brand.id")
->innerJoin("ProductCategory", "ProductCategory.product_id = Products.id")
->where("ProductCategory.group_id_1 = :group_id:")
->bind(["group_id" => $id])
->cache(["key" => __METHOD__.$id] // if defined modelCache as DI service
->execute();
$brandInProductCategory[$id] = [];
foreach($Brands AS $Brand) {
array_push($brandInProductCategory[$id], [
    "id" => $Brand->getId(),
    "title_fa" => $Brand->getTitleFa(),
    "title_en" => $Brand->getTitleEn()
]);
}


text:
Q: TortoiseSVN auto detecting existed files and checkout from svn I'm working on git and svn.
Is there a way to auto detect the folders/files, which are already existed(one of the folder cloned from git) by svn and checkout at same time?
What I do is:

*

*Clone my project from Git.

*Make svn checkout those folders/files under the folder "sass".

I know there is a way to checkout manually. But if there are a lot, it may be a trouble.


text:
Q: How can I generate three buttons in JavaScript? I know how to generate only one the button. I'm doing it this way:
var mylist = ['first', 'second', 'third', 'fourth', 'fifth']
var rand = Math.floor(Math.random() * mylist.length)
var word = mylist[rand]

var btn = document.createElement('input')
btn.id = 'b1'
btn.value = word
btn.type = 'button'
document.body.appendChild(btn)

But I need to generate a few buttons(for example 3 buttons).
        document.body.appendChild(btn)

A: Just wrap your logic in a for-loop .
Example :
var mylist = ['first', 'second', 'third', 'fourth', 'fifth']
var rand = null;
var word = null;
var threshold = 3

    for(var i = 0 ; i < threshold ; i++){

        rand = Math.floor(Math.random() * (mylist.length - 1)) + 1;
        word = mylist[rand];
        var btn = document.createElement('input');
        btn.id = 'b' + i;
        btn.value = word;
        btn.type = 'button';
        document.body.appendChild(btn);

    }

Updated with proof :
http://codepen.io/theConstructor/pen/WoJEGy?editors=1010
Hope this helps.

A: Most performant solution as you're only appending the buttons to the DOM just once by using a document fragment.

const mylist = ['first', 'second', 'third', 'fourth', 'fifth']
const frag = document.createDocumentFragment();

for (let i = 0, listLen = mylist.length; i < listLen; i++) {
  let button = document.createElement('input');
  button.type = 'button'
  button.id = `b${i + 1}`;
  button.value = mylist[Math.floor(Math.random() * listLen)]

  frag.appendChild(button);
}

document.body.appendChild(frag);

A: Use a for-loop in conjunction with the <button> element (rather than <input type="button">).

var list = ['first', 'second', 'third', 'fourth', 'fifth']

for (var i = 0; i < 100; i++) {
    var btn = document.createElement('button')
    var random = Math.floor(Math.random() * list.length)
    btn.textContent = list[random]
    document.body.appendChild(btn)
}


text:
Q: Copy content from  into a text box using jQuery With the code below, I don't seem to be able to just set the textbox to the value of an TD element. What I need to achieve is to populate Enter Refund Amount box with the already present value of Grand Total field above. Nothing else is needed except copying the content from one element to the other.
window.onload = function() {
    var src = document.getElementById("grand_total").innerHTML;
    dst = document.getElementById("refund_amount").innerHTML;
    src.addEventListener('#refund_amount', function() {
        dst = src;
    });
};

A: Firstly, #refund_amount isn't a valid event name. Given the context of the code and your goal I would assume that should be click instead. You also need to bind the event handler on the Element reference, not the a string variable containing its innerHTML value. In addition, to set the value of an input element you need to use the value property of the Element directly. Try this:

var src = document.getElementById("grand_total");
var dst = document.getElementById("refund_amount");

src.addEventListener('click', function() {
  dst.value = src.textContent;
});

      Grand total:
      26.58

      Refund amount:
      <input type="text" id="refund_amount" />


text:
Q: Package not found but its there import org.flarrison.scripts.flarrifarm.tasks.livid.DetectLivid;

I'm getting a Package not found error. It doesn't show up as error before i compile. I used the auto completion for it to import. I even clicked CTR-Z until i got back to where the script did run. But it's not now and i have no clue what to do.
Is there any way to get it to recognize it's there? Because it definitely is.
Its telling me that the package "livid" isn't there. BUT IT IS!


text:
Q: running rstudio in docker and Error in file(file, ifelse(append, "a", "w")) : cannot open the connection I am running rstudio in docker.
I have this piece of code:
save_path = str_c(image_dir, "neat", sub('-','_',current), ".png")

save_as_image(ft,
              path = save_path,
              zoom = 3 ,
              webshot = "webshot2") # save flextable as png

When I run it on my local instance, it runs fine.
when I run it in docker, I get

I tried installing webshot ans webshot2 packages to no avail.
here is the full list of packages I am installing:
install.packages('DT')
install.packages('odbc')
install.packages('RSQL')
install.packages('markdown')
install.packages("AzureKeyVault")
install.packages('plotly')
install.packages('rhandsontable')
install.packages('officer')
install.packages('flextable')
install.packages('rmarkdown')
install.packages('markdown')
install.packages('flexdashboard')
install.packages("reticulate")
install.packages("miniconda")
install.packages("webshot2")
install.packages("shiny")

Has anyone faced similar issues? any suggestions how to overcome this?


text:
Q: git: can't push (unpacker error) related to permission issues I have this problem when i try to push in git:
error: insufficient permission for adding an object to repository database ./objects

fatal: failed to write object
error: unpack failed: unpack-objects abnormal exit
To ssh://<repo url>/<repo dir>
 ! [remote rejected] master -> master (n/a (unpacker error))
error: failed to push some refs to 'ssh://<repo url>/<repo dir>'

I've had this before sporadically and we've always had to solve it by each user sshing to the repo and setting group permissions on all the files therein with
chmod -R g+w *

This was never a satisfactory solution and now it's bitten us in the arse as one of the guys is away and no-one knows his repo user's password.  So, i'm trying to solve it properly.
The error seems to occur when someone tries to push up a change that will alter a repo dir that is owned by another user (hence setting the group write option above).  I've done a bit of googling around this and have found a couple of solutions being discussed (neither of which worked for me)
1) make sure that the group that the repo dirs are shared with is each users' primary group (i believe that is the case already: each user has only one group so that must be their primary group, right?)
2) git repo core.sharedRepository setting, as detailed here: Git: Can't push from one computer
I changed this but it didn't make any difference.  Do i need to reload the config or something to actually effect the change?
Here's what my repo config looks like atm:
[core]
        repositoryformatversion = 0
        filemode = true
        bare = true
        sharedRepository = all
[receive]
        denyNonFastForwards = True

Grateful for any advice or suggestions!
max

A: It is a permission error. The way that was most appropriate and secure for me was adding users to a supplementary group that the repo. is owned by (or vice versa):
groupadd git
chgrp -R git .git
chgrp -R git ./
usermod -G -a git $(whoami)

A:
In case anyone else is stuck with this: it just means the write
permissions are wrong in the repo that you're pushing to. Go and chmod
-R it so that the user you're accessing the git server with has write access.

A: For me, this error occurred when I was out of space on my remote.
I just needed to read the rest of the error message:
error: file write error (No space left on device)
fatal: unable to write sha1 file
error: unpack failed: unpack-objects abnormal exit

A: For the permission error using git repository on AWS instance, I successfully solved it by creating a group, and assigning it to the repository folder recursively(-R), and give the written right to this group, and then assign the default aws instance user(ec2-user or ubuntu) to this group.
1. Create a goup name share_group or something else
     sudo groupadd share_group

2. change the repository folder from 'root'  group to 'share_group'
     sudo chgrp -R share_group /path/to/your/repository

3.  add the write authority to share_group
     sudo chmod -R g+w /path/to/your/repository

4. The last step is to assign current user--default user when login (by default ec2 is 'ec2-user', user of ubuntu instance is 'ubuntu' in ubuntu on aws) to share_group. I am using ubuntu insance on aws, so my default user is ubuntu.
     sudo usermod -a -G share_group ubuntu

By the way, to see the ownership of the folder or file just type:
    ls -l  /path/to/your/repository

'
Output:
    drwxr-x--x  2 root shared_group

(explanation please see:https://wiki.archlinux.org/index.php/File_permissions_and_attributes).

After step 3, you will see
    drwx--x--x  2 root root

changed to
    drwxr-x--x  2 root share_group

In this case, I did not assign user 'ubuntu' to root group, for the consideration of security. You can just try to assign you default user to root according to step 4 (just skip the first 3 steps

In another  way, tried the solution by :
    chmod -Rf u+w /path/to/git/repo/objects

It did not work for me, I think it should be the reason that my repository folder belong to the root user, not to Ubuntu user, and 'git' by default use the default user(ec2-user or Ubuntu user.  You can try to change the user and test it.

Finally, below code definitely work for me, but 777 is not good for security
    sudo chmod -R 777 /path/to/your/repo

A: I had this error for two weeks, and the majority of the solutions stated 'chmod -R' as the the answer, unfortunately for me my git repos (local / remote / shared - with team) were all on Windows OS, and even though chmod -Rv showed all the files changed to 'rwxrwxrwx', a subsequent 'ls -l' still showed all files as 'rwxr-xr-x' and the error repeated itself. I eventually saw this solution by Ariejan de Vroom. It worked and we were all able to pull and push again.
On both local (the local that is having trouble pushing) and remote repos, run the following commands:
$ git fsck
$ git prune
$ git repack
$ git fsck

On a side note, I tried using Windows' native file permissions / ACL and even resorted to elevating the problem user to Administrator, but none of that seemed to help. Not sure if the environment is important, but it may help someone with a similar setup - problem team member and remote (Windows Server 2008 R2 Standard), my local (Windows 7 VM).

A: A simpler way to do this is to add a post-receive script which runs the chmod command
after every push to the 'hub' repo on the server. Add the following line to hooks/post-receive inside your git folder on the server:
chmod -Rf u+w /path/to/git/repo/objects

A: I use gitosis for managing this kind of stuff. Gitosis has a single user (usually called "git") that owns all the repositories, and it uses public-key-based access control to each repo. It might not suit your setup but is probably worth checking out (no pun intended).

A: This problem can also occur after Ubuntu upgrades that require a reboot.
If the file /var/run/reboot-required exists, do or schedule a restart.

A: I was getting similar error and please see below how I resolved it.
My directory structure:
/opt/git/project.git
 and git user is  git
$ cd /opt/git/project.git
$ sudo chown -R git:git .

chown with -R option recursively changes the ownership and and group (since i typed git:git in above command) of the current directory. chown -R is necessary since git changes many files inside your git directory when you push to the repository.

A: I was having trouble with this too, thinking my remote gitolite-admin was corrupted or something wrong.
My setup is Mac OS X (10.6.6) laptop with remote Ubuntu 10 server with gitolite.
It turned out that the problem was with my local checkout of gitolite-admin.
Despite the "unpack failed" error, it turned out the the problem was local.
I figured this out by checking it out again as gitolite-admin2, making a change, and the pushing.
Voila!  It worked!

A: For what it worth, I had the same problem over my own VPS and it was caused by my low hard disk space on VPS. Confirmed by df -h command and after i cleaned up my VPS' hard disk; the problem was gone.
Cheers.

A: Where I work we have been using this method on all of our repositories for a few years without any problems (except when we create a new repository and forget to set it up this way):

*

*Set 'sharedRepository = true' in the config file's '[core]' section.

*Change the group id of the repository to a group shared by all users who are allowed to push to it:
chgrp -R shared_group /git/our_repos
chmod -R g+w /git/our_repos

*Set the setgid bit on all directories in the repository so that new files/directories keep the same group:
find /git/our_repos -type d -exec chmod g+s {} +

*Add this line to the pre-receive hook in the repository to ensure new file permissions allow group read/write:
umask 007

A: For me its a permissions issue:
On the git server run this command on the repo directory
sudo chmod -R 777 theDirectory/

A: A git configuration mistake can also product this error. I give my students and example of configuration like this:
git config --global user.name "John Doe"
git config --global user.email johndoe@example.com

One of my students was getting the unpacker error. Other students were fine, but I still did a double check on the git server's permissions and to be sure the student was in proper group.
Finally, I had the student do a git log and saw that he had John Doe for his configuration, but his branch was his own name.
Setting up his configuration properly eliminated the error .

A: I had similar problem like this before:
 ! [remote rejected] master -> master (unpacker error)
error: failed to push some refs to 'https://mywebsite.com/my-git-directory.git'

In my case, I have checked wrong directory ownership with ls -l. I change the directory owner to www-data to solve the problem like this:
sudo chown -R www-data:www-data my-git-directory.git/

But in this case I not use SSH method, I use HTTP method.
Maybe when we make sure the directory owner is correct, it can solve the problem.


text:
Q: How can I make each data in new row [data to csv]? Each data is in 1 row and 1 column. I want to separate them in csv file
from dataclasses import field, fields
import os
import csv
import collections
y=[]
Dict_New=[]
a=['Name','Count']
d={}
path = r"C:\Users\piotr\Desktop\CV"
files = os.listdir(path)
files_file = [f for f in files if os.path.isfile(os.path.join(path, f))]
print(files_file)   # ['file1', 'file2.txt', 'file3.jpg']
for x in files_file:
   y.append(x[:-4])
print(y)
Counter=collections.Counter(y)
print(Counter)
for key, values in Counter.items():
    Dict_New.append({'Name': key, "Count": values})
print(Dict_New)
with open ("test.csv",'w') as f:
    write = csv.DictWriter(f,fieldnames=a)
    write.writeheader()
    write.writerows(Dict_New)

I don't know why data are not separte in each row

A: csv docs stipulates you should provide newline='' when working with files, observe how opening is done in csv.DictWriter example
with open('names.csv', 'w', newline='') as csvfile:

this does apply also to csv.writer and csv.reader and allow code to work correctly indepedent from used ends of line.


text:
Q: Get feature by ID in OpenLayers I have a VectorLayer layer with a feature collection in GeoJSON. The GeoJSON format is as following:
{
    "type": "FeatureCollection",
    "totalFeatures": "unknown",
    "features": [
        {
            "type": "Feature",
            "id": "ES.RRTN.CP.1010001",
            "geometry": {
                "type": "MultiPolygon",
                "coordinates": [
                    [
                        [
                            [
                                570389.865,
                                4722149.567
                            ],
                            [
                                570391.945,
                                4722149.769
                            ],
                            [
                                570394.939,
                                4722150.04
                            ],
                            [
                                570395.084,
                                4722144.205
                            ]
                        ]
                    ]
                ]
            },
            "properties": {
                "validTo": {
                    "simpleContent": null
                },
                "validFrom": {
                    "simpleContent": null
                },
                "inspireId": {
                    "Identifier": {
                        "localId": "1010001",
                        "namespace": "ES.RRTN.CP"
                    }
                },
                "label": "1",
                "nationalCadastralReference": "1010001",
                "areaValue": 101.2779,
                "beginLifespanVersion": {
                    "simpleContent": null
                }
            }
        }
    ]
 }

I know the feature id=1010001, so I can identify a feature by its id, localid and nationalCadastralReference.

Is there a way to get the Feature object from the
  VectorLayer/VectorSource/Map with one of this parameters?

A: The solution given in the comments finally was:

source.getFeatureById('ES.RRTN.CP.1010001')


text:
Q: Is Postgres cache (shared_buffers) data sorted according to indexes? I'm not well versed in Postgres, so bear with me.
Since indexing a table doesn't physically order it on disk according to the index, my question is - is shared_buffers contents ordered according to it?

A: When PostgreSQL needs to read an 8K block, it finds the first available clean buffer with usage count 0 and loads the block into it. So (index or table) blocks are in shared buffers in a random fashion.
That shouldn't matter, since memory is random access these days.
According to your comment you actually want to know what is affected by the command CLUSTER:
CLUSTER rewrites a table so that the rows are physically ordered on disk in the logical order of an index. Within one block, that ordering will be preserved when data are in shared buffers (since the block is copied to memory as it is). But different table blocks will not be put into shared buffers close to each other or in any particular order.
The idea is to make sure that an index scan that accesses more than one row only has to read as few table blocks from disk as possible, and those in sequential order. In memory, it does not matter if blocks are read sequentially or not.


text:
Q: Is it correct to use hreflang in link alternate tags to suggest region-specific alternatives, to evade them being determined duplicates? Please help me out here people so that I can give a middle finger to the small firm where I was the sole web developer, from which I was sacked after only 2 days into a trial.
So, for just an afternoon, they asked me to look into their SEO markup. Which I did.
They were using Magento, and using subdomains with separate instances to market a slightly different product set and slightly different pricing to different countries under au.subdomain, uk.subdomain, can.subdomain etc. Pants way of doing it I know but I'm thinking heyho, let's see what I can do.
To try and avoid their content being considered duplicate by search engines, they were using link tags pointing to alternates with hreflang pointing to language codes, for example en_GB, en_US to point to their respective UK and US sites on each of their pages on each of their subdomains, where relevant.
This wasn't completely new to me, but in terms of internationalised sites was a little alien because the approach I took with Drupal was different.
Nevertheless, I looked into it, and decided their approach was wrong. Because their situation was region-centric and not language-centric.
I tried to explain that to them, that while yes it's possible to specify a region alongside a language, it indicates a regional variant of a language, not a language and the region which you are targeting. I.e. you could be speaking British English in the USA.
I was told I was wrong, that this was an industry standard way of approaching the situation, and that my understanding was dated.
The next day I was fired because apparently my SEO technical understanding wasn't up to scratch.
You know when you think surely what I said was right but you doubt yourself?! Would appreciate any thoughts, was I right? ☹

A: The definition of hreflang says it uses BCP47 tags, which clearly defines region subtags as regional linguistic variations.
This says you're technically correct on the semantics of hreflang; it doesn't say anything about whether you're correct on the way it is used as standard in the SEO industry (on which I have no insight).

A: I don't know about SEO, but the way that I would target sites to different regions would be by using IP address, and rather than having different sites (which would be harder to maintain anyway), I would use translation functionality (e.g. Angular Translate) to target them to regions. The different sites could also convert between currencies, or get prices by region, once the IP address has been detected. So their entire approach is wrong.
And I agree that en-GB is meant to target speakers of British English, who may be anywhere, not the region where en-GB is the majority language.


text:
Q: How to make a script restart itself if user says so at the end? I've made a little program that scrapes links from yahoo with any keyword or phrase you want and as far as you want. I added an input at the end to ask the user if they want to input more terms and scrape more links (basically restart the program without them exiting and clicking again if they need to do more than one keyword). how would I make my code restart itself?
import bs4
import requests
import time
import lxml
from colorama import Fore, init
init()
print(Fore.RED + "▓██   ██▓ ▄▄▄       ██░ ██  ▒█████   ▒█████       ██████  ██▓    ▄▄▄  ░▒████   ██▓▓█████  ██▀███  ")
print(" ▒██  ██▒▒████▄    ▓██░ ██▒▒██▒  ██▒▒██▒  ██▒   ▒██    ▒ ▓██▒   ▒████▄    ▒██  ██░░█   ▀ ▓██ ▒ ██▒")
print("  ▒██ ██░▒██  ▀█▄  ▒██▀▀██░▒██░  ██▒▒██░  ██▒   ░ ▓██▄   ▒██░   ▒██  ▀█▄   ▒██ ██░▒███   ▓██ ░▄█ ▒")
print("  ░ ▐██▓░░██▄▄▄▄██ ░▓█ ░██ ▒██   ██░▒██   ██░     ▒   ██▒▒██░   ░██▄▄▄▄██  ░ ▐██▓░▒██  ▄ ▒██▀▀█▄  ")
print("  ░ ██▒▓░ ▓█   ▓██▒░▓█▒░██▓░ ████▓▒░░ ████▓▒░   ▒██████▒▒░██████▒▓█   ▓██▒ ░ ██▒▓░░█████▒░██▓ ▒██▒")
print("   ██▒▒▒  ▒▒   ▓▒█░ ▒ ░░▒░▒░ ▒░▒░▒░ ░ ▒░▒░▒░    ▒ ▒▓▒ ▒ ░░ ▒░▓  ░▒▒   ▓▒█░  ██▒▒▒ ░░ ▒░ ░░ ▒▓ ░▒▓░")
print(" ▓██ ░▒░   ▒   ▒▒ ░ ▒ ░▒░ ░  ░ ▒ ▒░   ░ ▒ ▒░    ░ ░▒  ░ ░░ ░ ▒  ░ ▒   ▒▒ ░▓██ ░▒░  ░ ░  ░  ░▒ ░ ▒░")
print(" ▒ ▒ ░░    ░   ▒    ░  ░░ ░░ ░ ░ ▒  ░ ░ ░ ▒     ░  ░  ░    ░ ░    ░   ▒   ▒ ▒ ░░     ░     ░░   ░ ")
print(" ░ ░           ░  ░ ░  ░  ░    ░ ░      ░ ░           ░      ░  ░     ░  ░░ ░        ░  ░   ░     ")
print(" ░ ░                                                                      ░ ░                     ")
print("")
print("The Link Scraper For Yahoo")
print("")
print("Created By IronKey | V1.0 beta | python 3.7.4")
print("")
your_keyword = input("enter your dork or search term : ")
print("")

linkNumber = int(  input("link depth? ") ) # <--- Raises Error if input is not a number

lst = []
# https://search.yahoo.com/search?p=bruhmoment&pz=10&ei=UTF-8&fr=yfp-t&bct=0&fp=1&b=31&pz=10&bct=0&xargs=0
link = "https://search.yahoo.com/search?p={}&pz=10&ei=UTF-8&fr=yfp-t&bct=0&fp=1&b={}&bct=0&xargs=0"
for i in range( linkNumber ):
    lst.append( link.format( your_keyword, 1 + (i+1)*10 ) )
print("")
print( lst )
print("")
print("beginning search... ")
print("")
for x in tqdm(range(i)):
    time.sleep(0.0001)
for i in lst:
    source = requests.get(i)
    bs4call = bs4.BeautifulSoup(source.text, "lxml")
    links = bs4call.findAll('a', {'class':'ac-algo fz-l ac-21th lh-24'})
    for link in links:
        with open('links.txt', 'a') as out:
            out.write(str(link['href']) + "\n")

print("links scraped and saved to file : links.txt")
print("")
deepParseInput = input("would you like to run more dorks? :  ")
print("")
if deepParseInput == "y" or deepParseInput == "Y":
    reload()
else:
    print("I really hope you liked my program! Bye Bye - IronKey")
print("")
input("Press ENTER to leave the program --> ")
#for link in links:
  #with open('baselinks.txt', 'a') as out:
    #out.write(str(link['href']) + "\n")
print("")
deepParseInput = input("would you like to run more dorks? :  ")
print("")
if deepParseInput == "y" or deepParseInput == "Y":
    #restart the program
else:
    print("I really hope you liked my program! Bye Bye - IronKey")
print("")
input("Press ENTER to leave the program --> ")

A: A good idea would be transforming your code into a function and call the function in case the user wants to restart the program.


text:
Q: Using Android Studio, "MyApp Unfortunately Has Stopped" I am new to programming for android, I am developing an application in android studio in which I have to press buttons to enter numbers, my problem is to test the application on a phone in debug mode, when I opened the app is closed immediately by sending this message: "MyApp Unfortunately has stopped". Below i have my code with the Logcat. I'm using an a Samsung SM-G360T1 (ANDROID, 5.1.1, API 22)
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.dom.myapp.MainActivity"
    android:background="@color/colorWhite">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/relLayout">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:id="@+id/relLayoutTopBar"
            android:layout_alignParentTop="true">

            <android.support.design.widget.AppBarLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbarTop"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@drawable/white_gray_border_bottom">

                </android.support.v7.widget.Toolbar>

            </android.support.design.widget.AppBarLayout>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:id="@+id/relLayoutBotBar"
            android:layout_alignParentBottom="true">

            <android.support.design.widget.BottomNavigationView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/bottomNavView_Bar"
                android:background="@drawable/white_gray_border_top"
                app:menu="@menu/bottom_navigation_menu">

            </android.support.design.widget.BottomNavigationView>

        </RelativeLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:id="@+id/relLayoutMiddle"
            android:layout_below="@+id/relLayoutTopBar"
            android:layout_above="@+id/relLayoutBotBar" />

        <android.support.v4.view.ViewPager
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/container">

        </android.support.v4.view.ViewPager>

        </RelativeLayout>

</android.support.design.widget.CoordinatorLayout>

Here's my MainActivity
    package com.example.dom.myapp;
import android.os.StrictMode;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private SectionPagerAdapter mSectionPagerAdapter;

    private ViewPager mViewPager;

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

        mSectionPagerAdapter = new SectionPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.container);
        setupViewPager(mViewPager);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        tabLayout.getTabAt(0).setIcon(R.drawable.ic_prayer);
        tabLayout.getTabAt(1).setIcon(R.drawable.ic_cam);
        tabLayout.getTabAt(2).setIcon(R.drawable.ic_person);

    }

    private void setupViewPager(ViewPager ViewPager) {
        SectionPagerAdapter adapter = new SectionPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new Tab1Fragment());
        adapter.addFragment(new Tab2Fragment());
        adapter.addFragment(new Tab3Fragment());
        ViewPager.setAdapter(adapter);

And here's my LogCat
    04-25 16:04:59.356 3751-3751/? E/Zygote: MountEmulatedStorage()
04-25 16:04:59.356 3751-3751/? E/Zygote: v2
04-25 16:04:59.376 3751-3751/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
04-25 16:05:00.786 3751-3751/com.example.dom.myapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                     Process: com.example.dom.myapp, PID: 3751
                                                                     java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dom.myapp/com.example.dom.myapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.TabLayout.setupWithViewPager(android.support.v4.view.ViewPager)' on a null object reference
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3120)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3219)
                                                                         at android.app.ActivityThread.access$1000(ActivityThread.java:198)
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1676)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:145)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6838)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at java.lang.reflect.Method.invoke(Method.java:372)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
                                                                      Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.TabLayout.setupWithViewPager(android.support.v4.view.ViewPager)' on a null object reference
                                                                         at com.example.dom.myapp.MainActivity.onCreate(MainActivity.java:29)
                                                                         at android.app.Activity.performCreate(Activity.java:6535)
                                                                         at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1120)
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3073)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3219)
                                                                         at android.app.ActivityThread.access$1000(ActivityThread.java:198)
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1676)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:145)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:6838)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at java.lang.reflect.Method.invoke(Method.java:372)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

A: <android.support.v4.view.ViewPager
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/container">

        </android.support.v4.view.ViewPager>

Just add the id in ViewPager in your activity_main.xml.


text:
Q: Why is knitr unable to find framed.sty or kpsewhich? knit('test2.rnw')

processing file: test2.rnw
  |>>>>>>>>>>>>>                                                    |  20%
  |>>>>>>>>>>>>>>>>>>>>>>>>>>                                       |  40%
label: setup (with options)
List of 2
 $ include: logi FALSE
 $ cache  : logi FALSE

sh: kpsewhich: command not found
  |>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>                          |  60%
  |>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>             |  80%
  |>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>| 100%
  ordinary text without R code

output file: /Users/xxx/Desktop/R_meetup/documentation/test2.tex

Warning message:
In test_latex_pkg("framed", system.file("misc", "framed.sty", package = "knitr")) :
  unable to find LaTeX package 'framed'; will use a copy from knitr
 >

I'm on OSX Lion 10.7.3
Path for kpsewhich:
   $ which kpsewhich
    /usr/texbin/kpsewhich

$ which pdflatex
/usr/texbin/pdflatex

Both paths are in my .bash_profile in my home directory. I do have the framed package in my Tex install.
PATH=$PATH:/usr/texbin/pdflatex
PATH=$PATH:/usr/texbin/kpsewhich
export PATH

Solution
Adding this to my .rprofile fixed it:
Sys.setenv("PATH" = paste(Sys.getenv("PATH"),"/usr/texbin",sep=":"))

A: Just FYI, now knitr will automatically add /tex/texbin to PATH for Mac OS if it is not already in PATH.

A: Installing texlive-latex-extra solved for me. The original answer (https://stackoverflow.com/a/25517332/1169233) is intended for Ubuntu, but AFAIK it should work verbatim on Mac OS too.


text:
Q: Editing custom module installed in VENDOR folder through a custom theme I have a custom theme setup in Magento 2.2.5 where I am able to modify module files.
I know that to modify something installed in app/code i do this;
    app/code/WeltPixel/ProductPage/view/frontend/templates/product/view/addto.phtml
becomes
app/design/frontend/Pearl/weltpixel_custom/WeltPixel_ProductPage/templates/product/view/addto.phtml
This all works ok and my modifications are shown in the front end
However I have a module installed that i wish to change at;
vendor/cart2quote/module-quotation-encoded/view/frontend/templates/quote/form.phtml
Can somebody please tell me what what the path would be to modify this file in my custom theme? i.e.
app/design/frontend/Pearl/weltpixel_custom/XXXX/XXXX/XXXX/form.phtml

A: Use Below Path for it

app/design/frontend/Pearl/weltpixel_custom/Cart2Quote_Quotation/templates/quote/form.phtml


text:
Q: Как понять, что вьюха изменилась? какое событие за это отвечает? Например, есть вьюха

                    Table Name
                    Field
                    Condition
                    Definition

                    {{ tableName }}
                    {{fields.alias}}

                            {{condition.operand}} {{condition.value}} {{condition.type}}

                        Payment Methods: {{payment}} or
                        Status: {{status}} or

И есть код, который её заполняет:
 var app = angular.module('myApp', []);
var parentTr;
app.controller('customersCtrl', function ($scope, $http) {
    $(".report-generator").on("click", ".dynamicTableReportsGenerator tbody tr td", function (e) {
        parentTr = $(this).closest('tr');
        if (!$(this).is('td:first')) {
            e.preventDefault();
            $http({
                url: "/report-generator/getReportById",
                method: "post",
                data: $.param({"id": parentTr.find('input[type="checkbox"]').val()}),
                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
            }).success(function (response) {
                $scope.reports = response;
                $scope.$apply('myApp', function() {
                    $(".popup-wrapper").remove();
                    $("

").insertAfter(parentTr);
                    $(".popup-wrapper td").append($("#requestModal").html()); //Я пробовал с apply, но не вышло.
                }, true);
            });
        }
    });
});

Нужно проделать необходимые пертурбации с вьюхой, после того, как данные в неё подставятся.
п.с. Я с ангуларом фигарю второй час) Но касательно этого вопроса ничего не смог нарыть.

A: Если данные для view получаете с помощью ajax-запроса, изменения с view можно провести после успешного получения данных(success-function).
Если данные модели будут изменяться периодически в разных ситуациях(с помощью ajax-запроса, сервиса, наследования и т.д.) можно использовать watch
$scope.$watch('myId', function(newValue, oldValue) { ... });


text:
Q: Confuse about jquery queue and dequeue I have an array, I want use jquery queue and a print function to print them out:
var show = function (el) { //print function
    console.log('el', el);
}

var arr = ["a", "b", "c", "d", "e"];
var que = $({});
for (var i in arr) {
    que.queue('custom', function (next) {
        show(arr[i]);
        next();
    })
}
que.dequeue('custom');

but the all the print info is e, Why this happened?How can print is like the array order?
The second question is when I try to change the way of the for loop writing,like:
for (var i = 0; i < arr.length; i++) {
    //...
}

All the print info will be undefined . Is there difference between the two writing way? It always like the same ,doesn't it?
Here is the demo:http://jsfiddle.net/hh54188/L8ExM/

A: This is a scoping issue. When your functions are called variable i in inner function is equal to arr.length, so arr[i] is undefined. You need to wrap it with an anonymous function:
var show = function (el) {
    console.log('el', el);
}

var arr = ["a", "b", "c", "d", "e"];
var que = $({});
for (var i = 0; i < arr.length; i++) {
    (function(i) {
        que.queue('custom', function (next) {
            show(arr[i]);
            next();
        });
    })(i);
}
que.dequeue('custom');

Also, when you use for (var i in arr) you get e, because the loop stops at the last element which is 4. The first loop stops at 5 because the condition is checked after incrementation.


text:
Q: How can I interpret a year-naive, RFC 3339 datetime string in Python? I am interfacing with an API which gives year-naive RFC 3339 datetime strings for representing a users birthday. Naturally, I want to interpret this as some sort of datetime object - However, the python datetime library doesn't support datetime strings with values less than one.
Here's an example datetime string given by the API: 0000-09-01T00:00:00-00:00 (Notice the year is set to 0000). If I were to just throw this into datetime.fromisoformat, it unsuprisingly raises an error:
In [1]: from datetime import datetime

In [2]: datetime.fromisoformat("0000-09-01T00:00:00-00:00")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-e1d8a5624d92> in <module>
----> 1 datetime.fromisoformat("0000-09-01T00:00:00-00:00")

ValueError: year 0 is out of range

If I were to entirely remove the year section of the string, It gives the following:
In [1]: from datetime import datetime

In [2]: datetime.fromisoformat("09-01T00:00:00-00:00")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-2-a027335f00c1> in <module>
----> 1 datetime.fromisoformat("09-01T00:00:00-00:00")

ValueError: Invalid isoformat string: '09-01T00:00:00-00:00'

At first, I thought this was a bug or limitation. But after a little research, I found that the RFC3339 Standard states the following in its introduction:

All dates and times are assumed to be in the "current era", somewhere between 0000AD and 9999AD.

Assuming that this range is inclusive (This is based on the other uses of the term "between" within the standard, although it is never strictly specified), it is implied that the datetime module does not conform to the RFC3339 standard as it hard codes a minimum and maximum year value and also makes it a required value. However, it never claims that it does conform to the standard. So the new issue is that if the included library doesn't support RFC3339, what does?
My question is: Is there a method of interpreting this string as some kind of datetime object or use a third-party library?

A: There is no year 0 in the Anno Domini date presentation system.
A quick look at the common datetime alternatives (Pendulum, Arrow) show that the ValueError error for parsing an ISO format string with 0000- as the year is universal. That is not a valid year and the error lies with the data source.
A date with only a month and a day is not really a date - it is ambiguous. Is the date 2/23 before or after 3/1? Is 2/23 + 6 days the end of February or the first of March? In both cases, it depends entirely on the year.
It appears that the Square API is using 0000- as a flag for the year being optional since some people do not want to disclose their age.
If your data is standardized to year 0000, you can probably just do a string replacement to standardize on year 1:
from datetime import datetime

s="0000-09-01T00:00:00-00:00"

>>> datetime.fromisoformat(s.replace("0000-","0001-"))
datetime.datetime(1, 9, 1, 0, 0, tzinfo=datetime.timezone.utc)

Or, as stated in comments, perhaps use 0004 to accommodate 2/29 as a birthday:
s="0000-02-29T00:00:00-00:00"

>>> datetime.fromisoformat(s.replace("0000-","0004-"))
datetime.datetime(4, 2, 29, 0, 0, tzinfo=datetime.timezone.utc)

This is a partial solution at best. Again, a date without a year is not a date and you will need to write and validate a lot of code to try and solve the ambiguity for sorting, comparisons, date offsets, presentation, etc.


text:
Q: How to load an XML file and get values from the nodes - VC++ I'm new to VC++ and i want to load an XML file and read the values from the nodes using VC++. Any guidance?
Thank you
NLV

A: You should use one of the XML parsers libraries. In our projects we use Xerces. There are also solutions from Microsoft MSXML or XmlLite.


text:
Q: Cumulative measure with a conditional reset I have the need of creating a cumulative measure that resets when a certain condition happens.
The target is to create the 'Longest Stock Out Period' measure. That will be inserted in a matrix visual like this.

Date
No. of Negative Days
Longest Stock Out Period

08-03-2022
0
0

09-03-2022
1
1

10-03-2022
1
2

11-03-2022
0
0

The logic is that 'Longest stock out period' should  cumulative sum 'No. of negative days' until 'No. of negative days' is 0, then it should reset.
This is what I have currently tried, which just computes a 0. I believe there should also be some logic in the measure regarding no. of negative days should not be 0 or alike.
Longest Stock Out =
VAR _date =
    SELECTEDVALUE ( 'Calendar'[Date] )
RETURN
    CALCULATE (
        [No of Days],
        FILTER ( ALL ( 'Calendar'[Date] ), 'Calendar'[Date] <= _date )
    )

A: Try this Measure:
Longest Stock Out Period :=
VAR ThisDate =
    MIN( 'Table'[Date] )
VAR DateOfLatestZero =
    CALCULATE(
        MAX( 'Table'[Date] ),
        FILTER(
            ALL( 'Table' ),
            'Table'[Date] <= ThisDate
                && 'Table'[No. of Negative Days] = 0
        )
    )
RETURN
    CALCULATE(
        SUM( 'Table'[No. of Negative Days] ),
        FILTER(
            ALL( 'Table' ),
            'Table'[Date] <= ThisDate
                && 'Table'[Date] >= DateOfLatestZero
        )
    )

Adapt so as to use your Calendar dates as required.


text:
Q: How to view deployed source file in GCP Console(AppEngine Flexible Environment)? I'm pretty new to the Google Cloud Platform. I have deployed a Python 3 Flask app in AppEngine Flexible Environment using the Google Cloud SDK and the app works fine. I just want to view the source files deployed, in the cloud. Is there any way to view my project files in GCP?

A: You can view the source files by clicking on tools > debug next to the app version on your versions page
Alternative, you can go to your instances page, click on SSH next to one of the instances and you will enter the debug mode for that specific instance.
This will open a console in your browser and you can start a shell in the container that is running your app, as described here.
PS: apparently this is possible only for the Flexible Environment


text:
Q: Openning a new form from a tab I'm creating forms with VBA/Access to access my database.
In a form, I have a *lst_sinistres* listbox that displays the results of my SQL query and when I doubleclick on one of the results it opens me another form with thanks to this code
Private Sub lst_sinistres_DblClick(Cancel As Integer)

    DoCmd.OpenForm "F_SINISTRE_MRH", acNormal, , , , , Me.lst_sinistres.Value

End Sub

I wanted to change my form, and add tabs to make it more ergonomic. So I placed my *lst_sinistres* listbox inside a tab.
The problem is that when I doubleclick on one of the results in this listbox (now placed in the tab), the form *F_SINISTRE_MRH* does not open.
Does someone have an idea of where the problem might come?
Thank you

A: A quirk of VBA control events is that event code can become detached from the control object. Things that cause this tend to be re-naming controls and copy/pasting similar code between controls. To move your listbox onto a tab control you needed to cut and paste it temporarily. That broke the link between the written code and the object name. When the code and object are properly linked, [Event Procedure] shows up in the property sheet (as suggested by @4dmonster).
If you are in the VBA editor, choosing Debug->Compile will search through all the code and re-link event code with like-named controls. This step is worth a try before re-writing because you may end up with orphan blocks of
Private Sub OldControlName_DblClick(Cancel As Integer)
MsgBox "Why don't I work anymore?"
End Sub

that are treated as Form-level subroutines that just happen to never be called.
pT


text:
Q: Singleton or class with all static members What's better to use in Java: a singleton or a class with all static members? Or does it not matter?
For example, I want to access an X class from different classes, but the X class has to contain similar values for all classes which use it.

A: There are some cases, where static classes makes sense than Singleton. You can see the example of java.lang.Math. This is not singleton -. its just providing us a bunch of static methods.
If your class is not maintaining any state, and just providing global access to some methods, then you should go with using static class, as static methods are faster than Singleton, because of static binding during compile time. Remember you cannot use polymorphism with static methods as static methods cannot be overridden.
If you want to maintain the state of the object, you have to go with the singleton instead of static methods.When you need a class with full OO capability , chose Singleton, while if you just need to store bunch of static methods together, than use static class.
You can have a detailed description here
Read more: http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html#ixzz2iNE3rW4i

A: For me: Singleton is an anti-pattern and should only be used if there is a strong reason, also a class only holing public static variables is not acceptable in my opinion, this sound not realy object orientated to me. You could use Dependency Injection, the benefits are testability and you can avoid the doublecheck on creating a singleton (if you don't use an enum).
this would look like:
public class SharedObject{
// content
}

public class Worker{
private final SharedObject sharedObject;
public Worker(SharedObject sharedObject){
this.sharedObject = sharedObject;
}
}

With this way you also see, where the objects come from, you can easyly mock the shared object using Mocktio. It forces you to structure your code for easy testing, meanwhile it will go in a more modular direction.

A: I prefer static methods for classes which are stateless, just like Math or System class, and singleton as vice versa->for statefull classes, like FacesContext.

A: An all-static class is often used for shared utility methods that are grouped logically together but do not share state (fields) between them.
A singleton is better if:

*

*You might want different objects with different behaviors to play that role.

*The object needs to implement an interface (e.g. a shared ActionListener)

(Another way of saying this: If you need polymorphism, your singleton must be an object and not a class)

A: It is preferable not-heritable and non-instantiable class with static methods. e.g.:
public final class Constants {

    private Constants() {
        // non-public constructor
    }

    public static final Pattern ID_PATTERN = Pattern.compile("^\\d{4,10}$");

    public static final Locale DEFAULT_LOCALE = new Locale("en", "US");

    ...

}

Use singleton only if you want to maintain some state, similar to the application scope. However, must be two classes if you want a clean design.


text:
Q: Calling jQuery selectors in HTML links? I'm trying to make these jQuery commands execute later through links in html:
                $(document).ready(function(){
                    $('#2wa').click(function() {
                           $('#ownstream').hide();
                           $('#movstream').hide();
                           $('#2wastream').fadeIn();
                    });
                $(document).ready(function(){
                    $('#own').click(function() {
                            $('#2wastream').hide();
                            $('#movstream').hide();
                            $('#ownstream').fadeIn();
                            return false;
                    });
                $(document).ready(function(){
                    $('#mov').click(function() {
                            $('#2wastream').hide();
                            $('#ownstream').hide();
                            $('#movstream').fadeIn();
                            return false;
                    });

These three selector commands are supposed to hide two items and show one when the ID on their second line is shown, but nothing happens when I click on it. The links are formatted as such:

and the elements that are shown/hidden as such:

For these I have two problems: the links themselves are not causing any change to take place, and none of them are taking place when the page loads, causing all three elements to appear. How do I solve this? Also, should I be placing the jquery script in the head or below the body?

A: You should place your jquery script in your head tag.  Then you can use this code anywhere below it.
Make sure your anchor tags have the matching ID name like so:

And not:

And for the links to hide on load, use this:
$(document).ready(function(){
    $('#2wastream').hide();
    $('#ownstream').hide();
});

Or add a css style attribute like so:

A: There are a few things you can try to get this working.
Be sure your script is being pulled into the page, one way to check is by using the 'sources' tab in the Chrome Debugger and searching for the file else in the html head section
Be sure that you've included the datatale script after you've included jQuery, as it is most certainly dependant upon that.
Check whether jQuery is included properly and once only.
Watch out for jQuery conflicts. There is some other library which is overridding $, so your code is not working because $ is not an alias for jQuery anymore. You can use jQuery.noConflict() to avoid conflicts with other libraries on the page which use the same variable $.
According to your code why not pull all the code into one document.ready and close it correcly as below
 $(document).ready(function(){

                    $('#2wa').click(function() {
                           $('#ownstream').hide();
                           $('#movstream').hide();
                           $('#2wastream').fadeIn();
                    });

                    $('#own').click(function() {
                            $('#2wastream').hide();
                            $('#movstream').hide();
                            $('#ownstream').fadeIn();
                            return false;
                    });

                    $('#mov').click(function() {
                            $('#2wastream').hide();
                            $('#ownstream').hide();
                            $('#movstream').fadeIn();
                            return false;
                    });
});

Lastly make sure that elements(2wastream, ownstream, movstream) that you refer actually exists with the ids.

A: First of all, you are not propertly closing the $(document).ready(function(){
Second you only need one of those.. not one for each binding ..
Finally add a common class to the links, for example stream-opener

and another on the elements that show/hide

and use this one script
$(document).ready(function(){
   $('.stream-opener').click(function(e){
       e.preventDefault();
       var targetStream = '#' + this.id + 'stream';
       $('.stream').hide().filter( targetStream ).fadeIn();
   });
});