text:
Q: JaCoCo Gradle Kotlin DSL exclude file from violation rules I am trying to set my project up to run JaCoCo and to fail the build if it has less that 80% test coverage.  The caveat is that I want to exclude a particular file and I can't seem to make that work.  I have scoured the web and read oodles of Stack Overflow answers, blog posts, and the documentation for the plugin, but I cannot make anything work.  It always still includes the file that I am trying to exclude.
I started with:
tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}

which obviously will include everything and it does. I have tried the following variations based on what I have read, but none of them have worked:
tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            classDirectories.setFrom(sourceSets.main.get().output.asFileTree.matching {
                exclude("path.to.my.class.HelloWorld")
            })
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}

tasks.jacocoTestCoverageVerification {
    classDirectories.setFrom(
            sourceSets.main.get().output.asFileTree.matching {
                exclude("path.to.my.class.HelloWorld")
            }
    )
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}

tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}
tasks {
    getByName<JacocoReport>("jacocoTestReport") {
        afterEvaluate {
            classDirectories.setFrom(files(classDirectories.files.map {
                fileTree(it) {
                    exclude("path.to.my.class.HelloWorld")
                }
            }))
        }
    }
}

tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}
tasks.withType<JacocoReport> {
    classDirectories.setFrom(
        sourceSets.main.get().output.asFileTree.matching {
            exclude("path.to.my.class.HelloWorld")
        }
    )
}

The output of all of these is exactly the same:
Execution failed for task ':jacocoTestCoverageVerification'.
> Rule violated for bundle OneUIBackend: instructions covered ratio is 0.6, but expected minimum is 0.8

Does anyone have any insight in to how to do this properly?

A: An addition to the accepted solution (that also worked for me; for kotlin project using kotlin gradle dsl; gradle 7.2; jacoco plugin 0.8.7)

*

*In case you are trying to figure out how to exclude classes from coverage report using afterEvaluate {...} the following worked for me:
tasks.withType<JacocoReport> {
    afterEvaluate {
        classDirectories.setFrom(classDirectories.files.map {
            fileTree(it).matching {
                exclude("com/**")
            }
        })
    }
}

Putting the afterEvaluate block inside tasks.jacocoTestReport {...} result in an error:

Project#afterEvaluate(Action) on root project 'demo' cannot be executed in the current context

*You can reuse classDirectories from jacocoTestReport task in jacocoTestCoverageVerification:
tasks.jacocoTestReport {
    dependsOn(tasks.test)
    finalizedBy(tasks.jacocoTestCoverageVerification)

    classDirectories.setFrom(classDirectories.files.map {
        fileTree(it).matching {
            exclude("com/**")
        }
    })
}

tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            classDirectories.setFrom(tasks.jacocoTestReport.get().classDirectories)
            limit {
                minimum = "0.78".toBigDecimal()
            }
        }
    }
}

A: So it turns out that I was declaring the excluded file as a classpath rather than a filepath.  The final solution is:
tasks.jacocoTestReport {
    dependsOn(tasks.test)
    finalizedBy(tasks.jacocoTestCoverageVerification)
    classDirectories.setFrom(
            sourceSets.main.get().output.asFileTree.matching {
                exclude("path/to/my/file/HelloWorld*")
            }
    )
}
tasks.jacocoTestCoverageVerification {
    violationRules {
        rule {
            classDirectories.setFrom(sourceSets.main.get().output.asFileTree.matching {
                exclude("path/to/my/file/HelloWorld*")
            })
            limit {
                minimum = "0.8".toBigDecimal()
            }
        }
    }
}

A: It is possible to exclude a bit clearer:
tasks.jacocoTestReport {
    classDirectories.setFrom(
        files(classDirectories.files.map {
            fileTree(it) {
                exclude(
                    "com/example/integration/**",
                    "com/example/application/*Ext*"
                )
            }
        })
    )
}


text:
Q: Real-time Camera Streaming I'm trying to develop an application to do real-time streaming video and audio monitoring service.
Capturing the camera from an iPhone, iPad, or iPod and showing it in real time on another device or devices such as an iPhone, iPad, or iPod.
At the same time, I want to allow audio communication and data transfer between the 2 (or more) devices simultaneously.
As far as I know, Bonjour, GameKit, and NSStream allow data transfer between devices, via wifi or Bluetooth.
Until now, I have used the AVCaptureSession (from AVFoundation) to capture every frame from the camera and send it
using the GKSession (from GameKit), to another device (Bluetooth or wifi).
Here is the main process to send frames from the camera capturing:

    - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:   (CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection
    {
        // Get a CMSampleBuffer's Core Video image buffer for the media data
        CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

        // Lock the base address of the pixel buffer
        CVPixelBufferLockBaseAddress(imageBuffer, 0);

        // Get the number of bytes per row for the pixel buffer
        void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);

        // Get the number of bytes per row for the pixel buffer
        size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);

        // Get the pixel buffer width and height
        size_t width = CVPixelBufferGetWidth(imageBuffer);
        size_t height = CVPixelBufferGetHeight(imageBuffer);

        // Create a device-dependent RGB color space
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

        // Create a bitmap graphics context with the sample buffer data
        CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8, bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);

        // Create a Quartz image from the pixel data in the bitmap graphics context
        CGImageRef quartzImage = CGBitmapContextCreateImage(context);

        // Unlock the pixel buffer
        CVPixelBufferUnlockBaseAddress(imageBuffer,0);

        // Free up the context and color space
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);

        // Create an image object from the Quartz image
        UIImage *image = [UIImage imageWithCGImage:quartzImage];

        NSData *data = UIImageJPEGRepresentation(image, 0.0);

        // Release the Quartz image
        CGImageRelease(quartzImage);

        // Send image data to peers, using GKSession from GameKit
        [self.gkSession sendDataToAllPeers:data withDataMode:GKSendDataReliable error:nil];

        CVPixelBufferUnlockBaseAddress(imageBuffer, 0);
    }

And here is the other end (where i display the received frames in a UIImageView):

    - (void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session context:(void *)context
    {
        // Receive image data from peers
        self.imageView.image = [UIImage imageWithData:data];
    }

The problem I am finding is that GameKit doesn't give me the results I need.
If I want to transfer the camera with a mild performance (15 fps ), the quality of the image within the sender is really terrible and the receiver end is even worse.
If I want to transfer with a normal or great quality via camera, I have only 0.2 fps on the receiver side (only 1 image every 5 seconds)
I wanted to stream the camera in real time with the best image quality and with the most fps as possible, in order to have a smooth and detailed real-time camera streaming,
at the same time having audio communication and data transfer.
I would like to know what is the best way to achieve this: If I need to be registered to a server or not or if I need another type of software or application?
Summarizing this for you, the features I want to use within the App (any iPhone, iPad or iPod):
Sending OR receiving camera with the best quality and performance ( facial detection will be used as our main feature)
Sending AND receiving microphone with the best audio quality.
Sending OR receiving another type of data (e.g. NSStrings, BOOLs, NSArrays, C Arrays, Loops.
What would be the very best way to achieve these features and which tools do I need to use to achieve them?
Thank you very much in advance
Pedro Monteverde

redpajama_set_name: RedPajamaStackExchange


text:
Q: A doubt on a problem in Manifolds, Tensor Analysis and Applications Having tried to solve exercise 4.4-7 to have another proof of Frobenius Theorem, I would ask you a question.
This is what I have understood:
In Step 2 there is to  prove, for any tangent subbundle $E$ on a manifold $M,$ that if the module $\Gamma(E)$ of its sections is a  Lie subalgebra of $\Gamma(TM)$ then it is locally generated by $k$ independent commuting vector fields.
In Step 1 there is to prove the integrability of $E$ when it is locally generated by $k$ independent commuting vector fields.
Now this is the question:
Because, in the step 1, the authors assume additionally that $\Gamma(E)$ has to be an abelian Lie subalgebra of $\Gamma(TM)$?
There is some point that I don't understand? or is it a lapsus calami?
Thank you very much for the attention.


text:
Q: How to avoid regex catastrophic backtracking on identifying links in a long string? For context, the Python script I work with must analyze a constant stream of moderately sized strings (anywhere from 100 to 1000 characters) to identify whether they contain links and how many characters the string is if links were removed. After a good few iterations of various regex code found online, the most reliable and effective method of identifying the links I have tested is the following:
(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»""'']))

A generalized version of the script I am running can be found below:
link_identifiers = r"(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|("
                        r"\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,"
                        r"<>?«»""'']))"

for string in string_stream:
    # Find all links within the string text and sum the total character count
    links = re.findall(link_identifiers, string, re.IGNORECASE)
    link_char = sum(len(link[0]) for link in links)

    # Report the text count without links
    print(len(string) - link_char)

However, this format causes an immense amount of CPU usage due to catastrophic backtracking on the link_identifiers regex code. The strings within string_stream often contain uncommon link formats such as URL shorteners and custom domains, so simply checking for the common "com/gov/org" is not sufficient.
My application requires that code be as minimal as possible when it comes to RAM and CPU usage. How can I design a regex link identifier that is comprehensive but does not use immense resources?
Thank you.


text:
Q: Oracle function get least value I am trying to create a simple function that returns the least value passed to the function... but when running it doesn't work it just returns the same values I pass into the function 15,2,3 which should return 2... can someone help me and tell me why it doesn't work?
CREATE OR REPLACE
function
 GET_LEAST_VALUE(in_numbers IN VARCHAR2)
 RETURN VARCHAR2
 IS
 vReturn varchar2(50);

   BEGIN
       vReturn := least(in_numbers);
     return vReturn;
   END;

A: As commented, it can't work as you're actually passing a string to the function.
Here's one option - it splits that string into rows; regexp_substr returns a string (again) so - trim it first (to remove possible spaces) and apply to_number (otherwise you'd compare strings, and that's different from comparing numbers). Finally, apply the min aggregate function because least won't work if you passed more than a single number (you'd get too_many_rows error).
SQL> CREATE OR REPLACE FUNCTION get_least_value (in_numbers IN VARCHAR2)
  2     RETURN VARCHAR2
  3  IS
  4     vreturn  VARCHAR2 (50);
  5  BEGIN
  6     WITH
  7        temp
  8        AS
  9           (    SELECT TO_NUMBER (TRIM (REGEXP_SUBSTR (in_numbers,
 10                                                       '[^,]+',
 11                                                       1,
 12                                                       LEVEL))) val
 13                  FROM DUAL
 14            CONNECT BY LEVEL <= REGEXP_COUNT (in_numbers, ',') + 1)
 15     SELECT MIN (val)
 16       INTO vreturn
 17       FROM temp;
 18
 19     RETURN vreturn;
 20  END;
 21  /

Function created.

SQL> SELECT get_least_value ('15,2,3') result FROM DUAL;

RESULT
--------------------------------------------------------------------------------
2

SQL>

A: CREATE OR REPLACE FUNCTION get_least_value (in_numbers IN VARCHAR2) RETURN NUMBER IS
    w_result NUMBER ;
BEGIN
    SELECT MIN(value) INTO w_result FROM
    json_table (
        '[' || in_numbers || ']',
        '$[*]'
        columns (
            value NUMBER PATH '$'
        )
    )
    ;
    RETURN w_result ;
END ;
/

SELECT get_least_value('4,1,9,0,-5') from dual ;

-5

A: Why it doesn't work?
It does work as you pass in a single string and LEAST finds the least value when comparing that single string to nothing else so it returns that single string; which is exactly what LEAST is intended to do.
However, it is not what you expect it to do.
Why does it not do what I expect?
You are expecting '15,2,3' to be evaluated as a list of numbers (i.e. LEAST(15,2,3)) but it is not a list of numbers it is a single string literal that happens to look, to a human, like a list of numbers but, to the SQL engine, it is actually only one string value and will be evaluated as LEAST('15,2,3').
How to fix it?
You need to either pass in multiple values via a collection (for example, the built-in SYS.ODCINUMBERLIST varray collection type):
CREATE FUNCTION GET_LEAST_VALUE(
  in_numbers IN SYS.ODCINUMBERLIST
) RETURN NUMBER
IS
  v_least NUMBER;
BEGIN
  SELECT MIN(column_value)
  INTO   v_least
  FROM   TABLE(in_numbers);

  RETURN v_least;
END;
/

and then call it as:
SELECT get_least_value(SYS.ODCINUMBERLIST(15,2,3))
FROM   DUAL;

or
BEGIN
  DBMS_OUTPUT.PUT_LINE(get_least_value(SYS.ODCINUMBERLIST(15,2,3)));
END;
/

fiddle
Or alternatively, you need to split the string into separate values and then find the minimum of those values.

A: It could be done in an old way with one user defined function spliting a string by delimiter and returning an array of elements. In that case the simple plsql fuction could be like here:
create or replace Function Get_Least(P_LIST VARCHAR2, P_DELIMITER VARCHAR2 := ',') Return NUMBER AS
BEGIN
    Declare
        elements      STRING_ARRAY := STRING_ARRAY();
        least_element Number(12) := 999999999999;
    Begin
        elements := split(P_LIST , P_DELIMITER);
        For i In 1..elements.count Loop
            If To_Number(elements(i)) < least_element Then
                least_element := To_Number(elements(i));
            End If;
        End Loop;
        RETURN least_element;
    End;
END get_Least;

Here are the user defined type STRING_ARRAY and SPLIT() function:
create or replace TYPE STRING_ARRAY AS
VARRAY(4000) OF VARCHAR2(1000);
/

create or replace FUNCTION split ( csvString  IN  VarChar2, delimiter  IN  VarChar2 := ',')
                  RETURN STRING_ARRAY AS
BEGIN
    Declare
        elements     STRING_ARRAY := STRING_ARRAY();
        CURSOR c IS
            SELECT  COL1
            FROM    (   SELECT INDX, MY_STR1, COL1_ELEMENTS, COL1
                  FROM  (   SELECT 0 "INDX", COL1 "MY_STR1", COL1_ELEMENTS, COL1
                          FROM(
                                SELECT
                                  REPLACE(COL1, delimiter || ' ', delimiter) "COL1",
                                  Trim(Length(Replace(COL1, delimiter || ' ', delimiter))) - Trim(Length(Translate(REPLACE(COL1, delimiter || ' ', delimiter), 'A' || delimiter, 'A'))) + 1 "COL1_ELEMENTS"
                                FROM (SELECT csvString "COL1" FROM DUAL)
                              )
                      )
                  MODEL
                      DIMENSION BY(0 as INDX)
                      MEASURES(COL1, COL1_ELEMENTS, CAST('a' as VarChar2(4000)) as MY_STR1)
                      RULES ITERATE (1000)      --UNTIL (ITERATION_NUMBER <= COL1_ELEMENTS[ITERATION_NUMBER + 1]) -- If you don't know the number of elements this should be bigger then you aproximation. Othewrwise it will split given number of elements
                      (
                        COL1_ELEMENTS[ITERATION_NUMBER + 1] = COL1_ELEMENTS[0],
                        MY_STR1[0] = COL1[CV()],
                        MY_STR1[ITERATION_NUMBER + 1] = SubStr(MY_STR1[ITERATION_NUMBER], InStr(MY_STR1[ITERATION_NUMBER], delimiter, 1) + Length(delimiter)),
                        COL1[ITERATION_NUMBER + 1] = SubStr(MY_STR1[ITERATION_NUMBER], 1, CASE WHEN InStr(MY_STR1[ITERATION_NUMBER], delimiter) <> 0 THEN InStr(MY_STR1[ITERATION_NUMBER], delimiter)-1 ELSE Length(MY_STR1[ITERATION_NUMBER]) END)
                      )
                )
            WHERE INDX > 0 And INDX <= COL1_ELEMENTS;  -- And COL1 Is Not Null;
        cStr    VarChar2(1000);
        i       Number := 1;
    Begin
        If c%ISOPEN Then CLOSE c; End If;
        OPEN c;
        LOOP
            FETCH c Into cStr;
            EXIT WHEN c%NOTFOUND;
            elements.extend;
            elements(i) := cStr;
            i := i + 1;
        END LOOP;
        CLOSE c;
        RETURN elements;
    End;
END split;
/

Test call with string containing comma separated list of numbers
SET SERVEROUTPUT ON
Declare
    least_one    NUMBER(3);
    Numbers_List VARCHAR2(100) := '123, 46, 756, 3, 918, 4';
Begin
    least_one := GET_LEAST(Numbers_List);
    DBMS_OUTPUT.PUT_LINE(least_one);
End;
--
--  Result:
--
--  anonymous block completed
--  3

SPLIT() function could split  any string by any delimiter (including space character for splitting words in a sentence). It works with db versions without regexp too.
Example: - the same numbers separated by 'xo' - same result
SET SERVEROUTPUT ON
Declare
    least_one    NUMBER(3);
    Numbers_List VARCHAR2(100) := '123xo46xo756xo3xo918xo4';
Begin
    least_one := GET_LEAST(Numbers_List, 'xo');
    DBMS_OUTPUT.PUT_LINE(least_one);
End;
--
--  Result:
--
--  anonymous block completed
--  3

Regards...


text:
Q: Qt creator remote debugger I am trying to hook my beagle board to qt creator 2.3.1 running on Ubuntu Linux. I tried to find a good tutorial for this and found that qt documentation has nothing on this.(I do not understand why there is a feature which documentation does not bother to explain how to use). Could some one please explain how to do this?

A: *

*Cross compile qt for beagle board This post should be at help

*Open Qtcreator and go to project tab and select the tools -> options. Select Linux devices and add the device. For this beagle board need to be attached. For the option of host name it is required to add the ip address of the device. Other than this other fields are self explanatory. Test Button would assist in checking the device addition.

*Then in the project settings under Run configuration in the Deployment drop-down box select Build tar ball and install.

*At this point tool chain and the cross compiled qt version should be added in the qt creator.

*Basic procedure should be done by now and when the application is run it should be deployed on the device at the specified location.


text:
Q: How to expose total number of days in each month via OLAP cube I'd like an easy way of getting the total number of days for each month in the date dimension.
Currently this information is not exposed in our cubes. Therefore I need to write custom mdx such as the following:
WITH
  SET [13Mth] AS Tail([Date].[Date - Calendar Month].[Calendar Month].MEMBERS ,13)
  SET [m] AS Tail([13Mth])
  MEMBER [Measures].[TotalNumDaysMth] AS
    Datepart
    ("D",
        Dateadd
        ("M",1,
          Cdate(Cstr(VBA!Month([m].Item(0).Item(0).Lag(1).Name)) + "-01-" + Cstr(VBA!Year([m].Item(0).Item(0).Lag(1).Name)))
        )
      - 1
    )
  MEMBER [Measures].[TotalNumDaysMth-1] AS
    Datepart
    ("D",
        Dateadd
        ("M",1,
          Cdate(Cstr(VBA!Month([m].Item(0).Item(0).Lag(1).Name)) + "-01-" + Cstr(VBA!Year([m].Item(0).Item(0).Lag(1).Name)))
        )
      - 1
    )

I don't believe our users will need this information within our cube browsing client but from a developer point of view I could do without having to always implement the above.
What approach should we use to make the above data more easily available?

A: I have always added an attribute to the date dimension "days in month", of type integer. You can hide this attribute, if you do not want to expose the attribute hierarchy to your users.
But you can still use in calculations.
So my advise would be add a proper attribute to your time dimension and base your calculations of on the attributes.
Hope this helps somehow.

A: I am assuming that in your development scenario, the month will come from Web Service/Front End/SSRS report etc. In any such cases, you can create a measure that will return the count.
Approach 1: Year-Quarter-Month-Date exists
It is a good practice to have a similar hierarchy in place. The following MDX will work:
with set CurrentMonth as
[Date].[Year-Quarter-Month-Date].currentmember

set DatesInCurrentMonth as
descendants(abc, [Date].[Year-Quarter-Month-Date].[Date])

member [Measures].countofdaysinmonth as
count(DatesInCurrentMonth)

select measures.CountOfDaysInMonth on 0
from [MyCube]
where [Date].[Year-Quarter-Month-Date].[Month].&[Feb-2004]

Approach 2: Such hierarchy doesn't exist
with set CurrentMonth as
[Date].[Month].currentmember

set DatesInCurrentMonth as
exists([Date].[Date].children, abc, "<<Any Measure group>>")

member measures.countofdaysinmonth as
count(DatesInCurrentMonth)

select measures.countofdaysinmonth on 0
from [MyCube]
where [Accident Date].[Month].&[Feb-2004]

Let me know if they work/have issues.


text:
Q: In Java, why is the call foo() not ambigious given 2 varags methods foo(int... ints) and foo(Object... objects)? If I declare just the 2 varargs methods as follows:
public void foo(String... strings) {
    System.out.println("Foo with Strings");
}

and
public void foo(int... ints) {
    System.out.println("Foo with ints");
}

and then have the code:
foo();

this is a compiler error due to the ambiguity as expected.
However if I have just the following 2 versions of foo:
public void foo(Object... objects) {
    System.out.println("Foo with Objects");
}

and
public void foo(int... ints) {
    System.out.println("Foo with ints");
}

then the code
foo();

calls the ints version of the method. Can anyone explain why the second example isn't similarly ambiguous and why it resolves to the int method over the Object method. Thanks.

A: Java will always use the closest type possible, so when you pass ints into the method, if you didn't have the int... method, it would autobox them into Integers and use Object....  Since there is an int... method, Java will use that first.  This is a choice in the Java compiler design.

A: If I recall properly from when I was preparing the scjp, in the first case you have 2 arguments with no relation between them, so the compiler can't choose one.
In the second, with boxing enabled (1.5+), int can be Integer which is a subset of Object, and the compiler, in case of conflict, will always use the most specific definition. So Integer (int) is prioritized.


text:
Q: Remove background noise from recorded audio I am trying to record and play the audio at a time on android. But the recorded audio has more noise like zzzzz....
I want to filter the noise from the audio. My code is
private void record() {

    // Get the minimum buffer size required for the successful creation
    // of an AudioRecord object.
    int N = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);
    audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, N * 10,
            AudioTrack.MODE_STREAM);

    AudioRecord audioRecorder = null;
    int bufferSizeInShorts;
    int shortsRead;
    short audioBuffer[];

    try {

        bufferSizeInShorts = (N / 2);

        // Initialize Audio Recorder.
        audioRecorder = new AudioRecord(MediaRecorder.AudioSource.VOICE_RECOGNITION, RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, N * 10);

        NoiseSuppressor.create(audioRecorder.getAudioSessionId());

        // Start Recording.
        audioBuffer = new short[bufferSizeInShorts];
        audioRecorder.startRecording();
        isRecording = true;

        audioTrack.play();
        while (isRecording) {
            shortsRead = audioRecorder.read(audioBuffer, 0, bufferSizeInShorts);

            if (shortsRead == AudioRecord.ERROR_BAD_VALUE || shortsRead == AudioRecord.ERROR_INVALID_OPERATION) {
                Log.e("record()", "Error reading from microphone.");
                isRecording = false;
                break;
            }

            audioTrack.write(audioBuffer, 0, audioBuffer.length);
        }
    } finally {
        if (audioRecorder != null) {
            audioRecorder.stop();
            audioRecorder.release();
        }

        if (audioTrack != null) {
            audioTrack.stop();
            audioTrack.release();
        }
    }
}

How can I filter the background noise, so that I can hear only voices.

A: For clear and good quality voice
Try using *44100 or 16000 sample rate *
Note:- 44100 sample rate may not work on Amulator.
and also make sure you have correct header format
Ignore variables which are not related to this
Using AudioRecord class to record
 public class Mediarec extends Activity {

    public static final int SAMPLE_RATE = 44100;

    public static int count=0;
    private AudioRecord mRecorder;
    private File mRecording;
    private byte[] mBuffer;
    private final String startRecordingLabel = "Start recording";
    private final String stopRecordingLabel = "Stop recording";
    private boolean mIsRecording = false;
    OnGainSelected gs;
    SharedPreferences sp;
    String Shared = "Shared";
    String stored_gain;
    AudioManager am;
    protected int bitsPerSamples = 16;

    private Button show_gain;
    Switch bluetooth;
    Button button;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_mediarec);
        sp = getSharedPreferences(Shared, Context.MODE_PRIVATE);
        button = (Button) findViewById(R.id.start);
        bluetooth = (Switch) findViewById(R.id.switch1);

        initRecorder();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {

                    Log.d("Normal()","Recordng frm Normal MIC");
                    Normal();

            }
        });

    }

    protected void Normal() {
        // TODO Auto-generated method stub
        if (!mIsRecording ) {
            button.setText(stopRecordingLabel);
            mIsRecording = true;
            Log.d("Normal","Rec Started");
            mRecorder.startRecording();
            mRecording = getFile("raw");
            startBufferedWrite(mRecording);
        } else {
            button.setText(startRecordingLabel);
            mIsRecording = false;
            mRecorder.stop();
            File waveFile = getFile("wav");
            try {
                rawToWave(mRecording, waveFile);
            } catch (IOException e) {
                Toast.makeText(Mediarec.this, e.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
            Toast.makeText(Mediarec.this, "Recorded to " + waveFile.getName(),
                    Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroy() {
        mRecorder.release();
        super.onDestroy();
    }

    private void initRecorder() {
        int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE,
                AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
        mBuffer = new byte[bufferSize];
        mRecorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE,
                AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT,
                bufferSize);
    }

    private void startBufferedWrite(final File file) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                DataOutputStream output = null;
                try {
                    output = new DataOutputStream(new BufferedOutputStream(
                            new FileOutputStream(file)));
                    while (mIsRecording) {

                        int readSize = mRecorder.read(mBuffer, 0,
                                mBuffer.length);

                        for (int i = 0; i < readSize; i++) {
                            output.write(mBuffer[i]);
                        }

                    }
                } catch (IOException e) {
                    Toast.makeText(Mediarec.this, e.getMessage(),
                            Toast.LENGTH_SHORT).show();
                } finally {

                    if (output != null) {
                        try {
                            output.flush();
                        } catch (IOException e) {
                            Toast.makeText(Mediarec.this, e.getMessage(),
                                    Toast.LENGTH_SHORT).show();
                        } finally {
                            try {
                                output.close();
                            } catch (IOException e) {
                                Toast.makeText(Mediarec.this, e.getMessage(),
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }
            }
        }).start();
    }

    private void rawToWave(final File rawFile, final File waveFile)
            throws IOException {

        byte[] rawData = new byte[(int) rawFile.length()];
        DataInputStream input = null;
        try {

            input = new DataInputStream(new FileInputStream(rawFile));
            input.read(rawData);
        } finally {
            if (input != null) {
                input.close();
            }
        }

        DataOutputStream output = null;
        try {
            output = new DataOutputStream(new FileOutputStream(waveFile));
            // WAVE header
            // see http://ccrma.stanford.edu/courses/422/projects/WaveFormat/
            writeString(output, "RIFF"); // chunk id
            writeInt(output, 36 + rawData.length); // chunk size
            writeString(output, "WAVE"); // format
            writeString(output, "fmt "); // subchunk 1 id
            writeInt(output, 16); // subchunk 1 size
            writeShort(output, (byte) 1); // audio format (1 = PCM)
            writeShort(output, (byte) 1); // number of channels
            writeInt(output, SAMPLE_RATE); // sample rate
            writeInt(output, SAMPLE_RATE * 2); // byte rate
            writeShort(output, (byte) 2); // block align
            writeShort(output, (byte) 16); // bits per sample
            writeString(output, "data"); // subchunk 2 id
            writeInt(output, rawData.length); // subchunk 2 size

            output.write(rawData);

        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_LONG)
                    .show();
        } finally {
            if (output != null) {
                output.close();
            }
        }
    }

    private File getFile(final String suffix) {
        Time time = new Time();
        time.setToNow();
        return new File(Environment.getExternalStorageDirectory(),
                time.format("%Y%m%d%H%M%S") + "." + suffix);
    }

    private void writeInt(final DataOutputStream output, final int value)
            throws IOException {
        output.write(value >> 0);
        output.write(value >> 8);
        output.write(value >> 16);
        output.write(value >> 24);
    }

    private void writeShort(final DataOutputStream output, final short value)
            throws IOException {
        output.write(value >> 0);
        output.write(value >> 8);
    }

    private void writeString(final DataOutputStream output, final String value)
            throws IOException {
        for (int i = 0; i < value.length(); i++) {
            output.write(value.charAt(i));
        }
    }

}

A: This kind of noise come from you or your phone acting like antenna for the electromagnetic waves coming from the wiring in your house, they have a frequency from 50-60Hz, you can filter them using high pass digital filter ( it is just an equation that you can apply to your signal before playing it back)


text:
Q: AJAX/javascript page edit, wait to complete, say ok I am looking for a way to make a function:

*

*Edit a page: document.getElementById("page_0").src = "lots_of_code.php";

*Wait to complete

*Edit something else: document.getElementById("page_1").innerHTML = "OK";

If I try to do this, then the second edit starts before the first is done.
How to do this using AJAX/javascript?


text:
Q: What is the issue with with synchronization in nodejs+mongoose+async with the following code? What is the issue with the following code? I have collections of Fruits, Vegetables, and Candy in mongo. "testlist" contains strings containing food that fall under one of the three categories to be looked up in the collections.
For some reason, the convertedList never appears to be consisting of "candy", but only Fruits and Vegetables.
var async = require("async"),
    testlist = ["Tomato", "Carrot", "Orange", "Chocolate"];

async.map(testlist, function (food, next) {
  async.parallel([function (done) {
    Fruit.findOne({"name": food}, done);
  },
  function (done) {
    Vegetables.findOne({"name": food}, done);
  },
  function (done) {
    // The line below appears to execute successfully but never end up in "convertedList"
    Candy.findOne({"name": food}, done);
  }
], function (err, foods) {
         next(err, foods[0] || foods[1]);
      });
    },
    function (err, result) {

      var convertedList = [].concat(result);
      res.send(convertedList);
    });

Why is Candy not being added to the resulting "convertedList"? How do I fix the issue?
Note: I've noticed when I rearrange the function(done) call for Candy and Vegetables, it appears that Vegetables dont get added to the final convertedList, but Candy does. It appears to always be the third function(done) being ignored for adding into convertedLIst.

A: This line in your async.parallel callback isn't passing along the result from the Candy query:
next(err, foods[0] || foods[1]);

Try this instead:
next(err, foods[0] || foods[1] || foods[2]);

A: @JohhnyHK is right. Other than suspecting that your queries are returning something other than null, there is no other explanation as to why Candy never appears in your list.
This test passes (using mocha):
var async = require('async'),
  should = require('should'),
  sinon = require('sinon');

describe('async map', function () {
  var Fruit, Vegetables, Candy, service;
  var noop = function () {};

  beforeEach(function () {
    Fruit = sinon.stub({ findOne: noop });
    Vegetables = sinon.stub({ findOne: noop });
    Candy = sinon.stub({ findOne: noop });

  });

  it('should map', function (done) {

    var testlist = ["Tomato", "Carrot", "Orange", "Chocolate"];

    // return null record for everything
    Fruit.findOne.yields(null);
    Vegetables.findOne.yields(null);
    Candy.findOne.yields(null);

    // return some value when query matches (simulating mongo queries basically)
    Fruit.findOne.withArgs({name: 'Orange'}).yields(null, 'Orange');
    Vegetables.findOne.withArgs({name: 'Tomato'}).yields(null, 'Tomato');
    Vegetables.findOne.withArgs({name: 'Carrot'}).yields(null, 'Carrot');
    Candy.findOne.withArgs({name: 'Chocolate'}).yields(null, 'Chocolate');

    async.map(testlist, function (food, next) {
      async.parallel([function (done) {
        Fruit.findOne({
          "name": food
        }, done);
      },
          function (done) {
        Vegetables.findOne({
          "name": food
        }, done);
      },
          function (done) {
        // The line below appears to execute successfully but never end up in "convertedList"
        Candy.findOne({
          "name": food
        }, done);
      }
      ], function (err, foods) {
        next(err, foods[0] || foods[1] || foods[2]);
      });
    }, function (err, result) {

      var convertedList = [].concat(result);
      convertedList.should.eql(testlist);
      done();
    });

  });
});


text:
Q: How do I attach a pdf file to my whatsapp desktop app on process start? (C# and WA desktop app) Writing a local WinForm app that will run on a single pc. The App creates a Document, converts to PDF, and then the invoice (generated pdf) has to be sent to the client using the desktop version of Whatsapp. I am not going for API as I am making the software for free.
private void btnAMFormPrintPDF_Click(object sender, EventArgs e)
{
        //Custom class DPFController creates pdf document called doc
        PDFController control = new PDFController(dtable);
        Document  doc = control.CreateDocument();

        //render the document to pdf
        PdfDocumentRenderer render = new PdfDocumentRenderer();
        render.Document = doc;
        render.RenderDocument();

        //name the pdf
        string openPDF = "PreviewPDF.pdf";

        //save the pdf to the directory
        string fileName =   Convert.ToString(Path.GetDirectoryName
        (System.Reflection.Assembly.GetExecutingAssembly().Location))
                + "\\PDF\\"+ openPDF;
        render.PdfDocument.Save(fileName);

        //open the pdf in adobe
       // Process.Start(openPDF);

        //THIS IS THE PROBLEMATIC LINE!!!

        var process = $"whatsapp://send?phone={0616589} &attachment={fileName}";
        Process.Start(process);

    }

that is what I am trying to use and tried some variations therof, but to no avail:
var process = $"whatsapp://send?phone={0616589} &attachment={fileName}";


text:
Q: Annotate a column field from relation on django I got two models defined Owner and Dog
class Dog(models.Model):
    name = models.CharField(max_length=255)
    owner = models.ForeignKey(Owner)
    adopted_date = models.DateTimeField()

class Owner(models.Model):
    name = models.CharField(max_length=255)

I want to make a list with all the owners with the amount of dogs adopted by date.
Example:
OwnerName  Date       Amount
Richard    15/11/24   2
Jow        15/11/24   2
I am making this query
Dog.objects.values('owner', 'adopted_date').annotate(Count('owner')).order_by()

The problem here is that this query return owner id not the name.
{
    'owner':1,
    'adopted_date': 'date',
    'owner_count': 2
}

I need to get on the owner the name of the owner, something like.
{
    'owner':'Richard,
    'adopted_date': 'date',
    'owner_count': 2
}

Any help will be appreciated.

EDITION
This solution works, But I'm having a few doubts about it, making this query Dog.objects.values('owner__name', 'owner', 'adopted_date').annotate(Count('owner'))
We can get a good result, but I am worry about performance, this will generate a group by for every column inside values, but I don't need to group by owner_name because that column is not unique.
I am looking for something like
Dog.objects.values('owner', 'adopted_date').annotate(Count('owner'), Column('owner__name')).order_by()

I know that the Column aggregator function don't exist, but maybe is a way to do something like this.
Thanks in advance.

A: If you change your query to
Dog.objects.values('owner__name', 'adopted_date').annotate(Count('owner'))

You will get a list of dictionaries of the form you want:
{
    'owner__name': 'Richard',
    'adopted_date': 'date',
    'owner__count': 2
}

I actually couldn't find this in the documentation for the values() clause, but it's common in the Django ORM syntax to refer to the members of a foreign key related field of a query (ie, "owner") by using double underscores (ie, "owner__name").

EDIT
With the above solution, there is still the problem that if two dogs have the same adoption date and two different owners with the same name, they will be grouped. If you want to group the output by dog (which will ensure one owner per group, since there is one owner per dog) then anywhere in the query you could add .order_by('pk').
This works, but it seems hackish since it utilizes order_by for a purpose other than ordering. I'll update again if I come across a better way of doing it.


text:
Q: setting Cygwin's $HOME to Windows profile directory Are there any drawbacks to having Cygwin and Windows share the same $HOME directory, in this case the Windows profile directory?

A: Merging them will work fine.
Cygwin proper doesn't store anything in your HOME directory. On first running Cygwin with a fresh home directory, default versions of .bash_profile and such get put there, but again, there is no conflict with things that already get put there.
I, too, find it frequently convenient to be able to use Cygwin on things that live under your Windows profile directory. However, I don't want the two to be the same[*], so I just make a symlink to it in my home directory. I'm never farther from my Windows profile directory than a cd ~/WinHome.
[*] So many programs feel privileged to throw random junk in the Windows profile directory that it would annoy me to see it every time I say ls in my home directory. I prefer to keep that mess at arm's length. I feel my home directory should be mine. I'm happy to let ~/WinHome be a midden.

A: It is simple
go to .bashrc file and set an alias to your desired folder
    alias someName="cd path/to/your/home/directory"

save it and wherever you are in cygwin, just type someName and you will be there in a blink. I have used this hack to make links to my folders and it is super fast in my navigations.


text:
Q: pass parameters to ajax call in javascript Currently I'm editing a string, query, to pass to my .getJSON function. Its starting to get messy, and I'm wondering if there is a better way to pass parameters in javascript?
  var twitter = {
   query: "https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=" + user_name + "&count=" + count + "&callback=?",
   tweets: 3
   };

 $.getJSON(twitter.query,
 function(json) {

       console.log(json);
       }
 });
})

A: $.getJSON() optionally accepts a data argument which will build that string for you:
var url = 'https://api.twitter.com/1/statuses/user_timeline.json?callback=?';

var parameters = {
  include_entities: true,
  include_rts: true,
  screen_name: user_name,
  count: count
}

$.getJSON(url, parameters, function(json) {
  console.log(json);
});

A: Assuming you're using jQuery.getJSON, you can pass the parameters as an object, separate from the URL:
$.getJSON('https://api.twitter.com/1/statuses/user_timeline.json', {
        include_entities:true,
        include_rts:true,
        screen_name:user_name,
        count:count
        /* I excluded callback */
    }, function(json) {
        console.log(json);
    }
);


text:
Q: Is it possible to toggle a modal and open an URL in another tab at the same time when a link is clicked? I have 4 buttons ( tags stylized to look like buttons), from which only two matter for this question:

*

*First one opens a link in another tab with its respective href value and with the target="_blank" attribute.

*Second one toggles a modal with some text fields to be manually filled with information inside the page at the URL linked in the first button.
I would like to open the same link from the first button by clicking the second one, but only the modal is shown and nothing else happens.
So far I've tried these options:
Option 1. Setting href and target equally for both buttons:
Left click toggles the modal only. Scroll wheel click opens the link in another tab and the modal is not shown.
Btn 1
Btn 2

Option 2. Clicking button 1 from button 2 with jQuery code:
Left click on button 2 toggles the modal and the button 1 is clicked (I guess) since the line printed shows on the console.
Btn 1
Btn 2

$('#button-2').click(function(){
    $('#button-1').click();
});

$('#button-1').on('click', function(){
    console.log('Clicked ' + $(this).prop('id'));
});

A: I suppose you're using bootstrap.
$('#my-modal').on('show.bs.modal', function (e) {
  $('#button-1').trigger('click');
});

Here you'll simulate the click when the modal is displayed.
Give it a try and tell me if it works

A: You need avoid the default event of link and set your custom action
var openPage = function (e) {
 e.preventDefault();
 window.open(e.target.href,e.target.target)
}

Here you have a example using boostrap
Code-pen snipet


text:
Q: Call constructor/function by name, within requirejs I have code like this
var e = new window[className](...);

where
className

is a name of some "class" I've created and is specified in an attribute in my html.
All I had to do was make sure I had loaded a constructor/function of the name in className and it worked.
I've started getting all my stuff into require and this has unsurprisingly stopped working.
I have a file Eric.js which I have required, and contains
define('Eric',function(){
var Eric = function (ED) {
...
};
// etc

return Eric;
});

but
require(['wtt/Eric']);
className='Eric';
var e = new window[className](...);

produces
TypeError: window[className] is not a constructor

A: Typical usage of requirejs is:
require(['wtt/Eric'], function(Eric) {
    var e = new Eric(...);
});

Is it possible for you to use require in that way?
P.S. By the way, you should avoid usage of global vars in your code and add small fix to Eric module definition:
define('Eric', function() {
    var Eric = function (ED) { // <- here comes the "var" keyword
        // ...
    };
    // etc

    return Eric;
});

You can read more let's say here: http://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals

A: You seem to be unaware that RequireJS operates asynchronously. Let's look at your code:
require(['wtt/Eric']);
className='Eric';
var e = new window[className](...);

The first line (require...) will cause RequireJS to initiate loading your module. You do not actually know when the module will be loaded. In fact, given the way JavaScript works, you are guaranteed that by the time var e = new window[className](...); executes, your module will not be loaded and this line will fail. So you have to structure you code so that the line which fails is guaranteed to run after the module is loaded. You do this by passing a callback to require:
require(['wtt/Eric'], function () {
    var e = new window['Eric'](...);
    ...
});

Or even better, don't leak anything in the global space and do:
require(['wtt/Eric'], function (Eric) {
    var e = new Eric();
    ...
});

Regarding the comment you left on the other answer, note that it is possible to compute what module to load at run time:
var mod = document.getElementById("myid").attributes.foo.value;
require(['wtt/' + mod], function (Constructor) {
    var e = new Constructor();
});

If you ever use r.js to combine your modules, you'll have to explicitly list the modules you load in the manner I've just shown above because r.js is not able to follow computed dependencies.


text:
Q: Send HTML email with php? I have a script that sends an email using the paypal IPN after a successful purchase. How can I modify the script to send HTML email?
<?php

// read the post from PayPal system and add 'cmd'
$req = 'cmd=_notify-validate';

foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$req .= "&$key=$value";
}

// post back to PayPal system to validate

$header = "POST /cgi-bin/webscr HTTP/1.1\r\n";

// If testing on Sandbox use:
// $header .= "Host: www.sandbox.paypal.com:443\r\n";
$header .= "Host: ipnpb.paypal.com:443\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

// If testing on Sandbox use:
//$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
$fp = fsockopen ('ssl://ipnpb.paypal.com', 443, $errno, $errstr, 30);

// assign posted variables to local variables
$item_name = $_POST['item_name'];
$item_number = $_POST['item_number'];
$payment_status = $_POST['payment_status'];
$payment_amount = $_POST['mc_gross'];
$payment_currency = $_POST['mc_currency'];
$txn_id = $_POST['txn_id'];
$receiver_email = $_POST['receiver_email'];
$payer_email = $_POST['payer_email'];

//set email variables
$From_email = "From: admin@domain.com";
$Subject_line = "Thanks";

$email_msg = "Thanks for purchasing my item. Your order will be delivered in 3-4 days. We       appreciate your business.";
$email_msg .= "\n\nThe details of your order are as follows:";
$email_msg .= "\n\n" . "Transaction ID: " .  $txn_id ;
$email_msg .= "\n" . "Payment Date: " . $payment_date;

if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
// check the payment_status is Completed
// check that txn_id has not been previously processed
// check that receiver_email is your Primary PayPal email
// check that payment_amount/payment_currency are correct
// process payment

$mail_From = $From_email;
$mail_To = $payer_email;
$mail_Subject = $Subject_line;
$mail_Body = $email_msg;

mail($mail_To, $mail_Subject, $mail_Body, $mail_From);

}
else if (strcmp ($res, "INVALID") == 0) {
// log for manual investigation

$mail_From = $From_email;
$mail_To = $receiver_email;
$mail_Subject = "INVALID IPN POST";
$mail_Body = "INVALID IPN POST. The raw POST string is below.\n\n" . $req;

mail($mail_To, $mail_Subject, $mail_Body, $mail_From);

}
}
fclose ($fp);
}
?>

A: You need to send full headers with content type, not just mail_from. Heres an example
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= $mail_From . "\r\n";
mail($mail_To,$mail_Subject,$mail_Body,$headers);

http://www.w3schools.com/php/func_mail_mail.asp
In your code:
$mail_From = $From_email;
$mail_To = $payer_email;
$mail_Subject = $Subject_line;
$mail_Body = $email_msg;
mail($mail_To, $mail_Subject, $mail_Body, $mail_From);
The $mail_From is the fourth parameter (headers). Create a new string that contains full headers for html email plus: $_From
$mail_From = $From_email;
$mail_To = $payer_email;
$mail_Subject = $Subject_line;
$mail_Body = $email_msg;
//start $headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n"; //adds content type to headers
$headers .= $mail_From . "\r\n"; //adds the sender details
mail($mail_To,$mail_Subject,$mail_Body,$headers); //sends the email

If you echo $headers it will be something like this
MIME-Version:1.0
Content-type:text/html;charset=iso-8859-1
From:email@email.com

A: Just put HTML in the mail body, and most mail clients should be able to figure it out.
A more correct answer would also include the appropriate Content-Type header in the mail (text/html).
A complete answer would be what I do:
<?php
$html = <<<HTML
<!DOCTYPE HTML>

        <meta http-equiv="Content-Type" value="text/html; charset=iso-8859-1" />
        <title>Title here</title>

My mail content here.

Some signature here

HTML;
$text = preg_replace("(\n{2,})","\n",strip_tags(str_replace(Array("\t","
"),Array("","===================="),$html)));
$seperator = uniqid();
mail("user@example.com","Title here",
        "--".$seperator."\r\n"
        ."Content-Type: text/plain\r\n\r\n"
        .$text."\r\n"
        ."--".$seperator."\r\n"
        ."Content-Type: text/html\r\n\r\n"
        .$html."\r\n"
        ."--".$seperator."--",
    "From: My name <me@example.com>\r\n"
    ."MIME-Version: 1.0\r\n"
    ."Content-Type: multipart/alternative; boundary=".$seperator);
?>

Not only does this send all the correct headers to leave no guesswork on the client, it also generates a plaintext version automatically for the users who don't want HTML emails.

A: Sending HTML Email through PHP uses the exact same mail function as text email:
mail($to, $subject, $message, $headers);

$to = 'bob@example.com';

$subject = 'Website Change Reqest';

$headers = "From: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
$headers .= "CC: susan@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

$message = '';
$message .= '
Hello, World!
';
$message .= '';

Source and donwload available on css tricks


text:
Q: MissingReferenceException when gameObject has been destroyed I'm trying to learn how to make camera follow player in Unity. everything went fine. the scripts works, no problem with the game, it just when my Character(Player) dead(destroyed), the console keep updating this error message

MissingReferenceException: The object of type 'Transform' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
UnityEngine.Transform.get_position () (at <f53c831f77784ef08ef348217b5117fa>:0)
CameraClamp.Update () (at Assets/Scripts/CameraClamp.cs:12)

and this

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
CameraFollow.FixedUpdate () (at Assets/Scripts/CameraFollow.cs:25)

and here's the scripts
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CameraFollow : MonoBehaviour
{

    public GameObject FollowObject;
    public Vector2 followOffset;
    public float speed = 3f;

    private Rigidbody2D rb;
    private Vector2 threshold;
    // Start is called before the first frame update
    void Start()
    {
     threshold = calculateThreshold();
     rb = FollowObject.GetComponent<Rigidbody2D>();

    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Vector2 follow = FollowObject.transform.position;
        float xDifference = Vector2.Distance(Vector2.right * transform.position.x, Vector2.right * follow.x);
        float yDifference = Vector2.Distance(Vector2.up * transform.position.y, Vector2.up * follow.y);

        Vector3 newPosition = transform.position;
        if(Mathf.Abs(xDifference) >= threshold.x)
        {
            newPosition.x = follow.x;
        }
        if(Mathf.Abs(yDifference) >= threshold.y)
        {
            newPosition.y = follow.y;
        }

        float moveSpeed =  rb.velocity.magnitude > speed ? rb.velocity.magnitude : speed;
        transform.position = Vector3.MoveTowards(transform.position, newPosition, moveSpeed * Time.deltaTime);
    }

    private Vector3 calculateThreshold(){
        Rect aspect =  Camera.main.pixelRect;
        Vector2 t = new Vector2 (Camera.main.orthographicSize * aspect.width / aspect.height, Camera.main.orthographicSize);
        t.x -= followOffset.x;
        t.y -= followOffset.y;
        return t;
    }
    private void OnDrawGizmos() {
        Gizmos.color = Color.blue;
        Vector2 border = calculateThreshold();
        Gizmos.DrawWireCube(transform.position, new Vector3(border.x * 2, border.y * 2, 1));

    }
}

How to get rid of the error message?

A: There's two reasonable solutions

*

*When you delete the player, you should delete this script too. This could be achieved by deleting the first parent of both FollowObject, CameraFollow, and Camera lamp. If they don't have a common parent, consider refactoring it so they do

*Check for null before accessing the transform
void FixedUpdate()
{
if(FollowObject.transform == null)
{
Destroy(this);
}
}


text:
Q: Shortest invariant meeting point on the directed graph with loops I have directed graph with loops. Here is the example:
{
 0: [1,2],
 1: [1,3],
 2: [3],
 3: [4],
 4: []
}

*

*Edge 0 flows into 1 and 2

*Edge 1 flows into itself and into 3

*Edge 2 flows into 3

*And edge 3 flows into edge 4 (without any reason so much)

If some imagionary actor will stand on the edge 0, and will start moving, no matter what he will arive to the edge 3 (let's ignore infinite loops).
Is there an algorithm, where it is possible to supply such graph with some edge (0 from example), and it will give me shortest invariant meeting point (3 from example)?

A: If I understand right, the following algorithm can handle your request. However, it may not be the efficient algorithm which may you find.
get g as DAG (Directed and Asyclic)
get s as start node
get d as destination node

arr(paths) <= find All Paths From s to d

if(paths.size <=1) print("There is no meeting point")

intersects = paths[0]

for(int i=1; i< paths.size(); i++) {
    intersetcs <= find intersection nodes between paths i and intersects
}

foreach (node: intersects) {
    if(node has no outgoing)
        intersects.remove(node);
}

print(intersects)

output of program for your example:
path 0 : [0, 1, 3, 4]
path 1 : [0, 2, 3, 4]
meeting points: [0, 3]

another output of program:
g:{
 0: [1,2],
 1: [3,4],
 2: [3,4],
 3: [5],
 4: [5],
 5: [6,7],
 6: [],
 7: []
}
s=0, d=7

path 0: [0, 1, 3, 5, 7]
path 1: [0, 1, 4, 5, 7]
path 2: [0, 2, 3, 5, 7]
path 3: [0, 2, 4, 5, 7]
meeting points: [0, 5]

At last an example without meeting points:

g:{
 0: [1,2],
 1: [2,3],
 2: [5],
 3: [4],
 4: [5],
 5: []
}

s=0, d=5
path 0: [0, 1, 3, 4, 5]
path 1: [0, 1, 2, 5]
path 2: [0, 2, 5]
meeting points: [0]

I provide you an example in Java too based this algorithm.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

// A directed graph using
// adjacency list representation
public class Graph {

    // No. of vertices in graph
    private int v;

    // adjacency list
    private ArrayList<Integer>[] adjList;

    // Constructor
    public Graph(int vertices)
    {

        // initialise vertex count
        this.v = vertices;

        // initialise adjacency list
        initAdjList();
    }

    // utility method to initialise
    // adjacency list
    @SuppressWarnings("unchecked")
    private void initAdjList()
    {
        adjList = new ArrayList[v];

        for (int i = 0; i < v; i++) {
            adjList[i] = new ArrayList<>();
        }
    }

    // add edge from u to v
    public void addEdge(int u, int v)
    {
        // Add v to u list.
        adjList[u].add(v);
    }

    // Prints all paths from
    // s to d
    public void printAllPaths(int s, int d)
    {
        boolean[] isVisited = new boolean[v];
        ArrayList<Integer> pathList = new ArrayList<>();

        // add source to path[]
        pathList.add(s);

        // Call recursive utility
        printAllPathsUtil(s, d, isVisited, pathList);
    }

    List<List<Integer>> allPaths = new ArrayList<>();

    private void printAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList)
    {

        if (u.equals(d)) {
            //System.out.println(localPathList);
            allPaths.add(new ArrayList<>(localPathList));
            // if match found then no need to traverse more till depth
            return;
        }

        // Mark the current node
        isVisited[u] = true;

        // Recur for all the vertices adjacent to current vertex
        for (Integer i : adjList[u]) {
            if (!isVisited[i]) {
                // store current node in path[]
                localPathList.add(i);
                printAllPathsUtil(i, d, isVisited, localPathList);

                // remove current node in path[]
                localPathList.remove(i);
            }
        }

        // Mark the current node
        isVisited[u] = false;
    }

    // Driver program
    public static void main(String[] args)
    {
        // Create a sample graph
        Graph g = new Graph(6);
        /*g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 3);
        g.addEdge(2, 3);
        g.addEdge(3, 4);*/

        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 3);
        g.addEdge(1, 2);
        g.addEdge(2, 5);
        g.addEdge(3, 4);
        g.addEdge(4, 5);
        // arbitrary source
        int s = 0;

        // arbitrary destination
        int d = 5;
        System.out.println(
                "Following are all different paths from "
                        + s + " to " + d);
        g.printAllPaths(s, d);

        System.out.println(g.allPaths);
        findMeetingPoint(g);

        /*for (int d=0; d<=4; d++) {
            System.out.println(
                    "Following are all different paths from "
                            + s + " to " + d);
            g.printAllPaths(s, d);
        }*/
    }

    private static void findMeetingPoint(Graph g) {
        if(g.allPaths.size()<=1) {
            System.out.println("No meeting point");
            return;
        }
        Set<Integer> intersects = new HashSet<>();
        Set<Integer> meetPoints = new HashSet<>();

        intersects.addAll(g.allPaths.get(0));

        for(int i=1; i<g.allPaths.size(); i++) {
            intersects.retainAll (g.allPaths.get(i));
        }

        for (Integer node: intersects) {
            if(g.adjList[node].size()==0)
                intersects.remove(node);
        }

        System.out.println(intersects);

    }
}

EDITTED 1 :
code which can handle cycles:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

// A directed graph using
// adjacency list representation
public class Graph {

    // No. of vertices in graph
    private int v;

    // adjacency list
    private ArrayList<Integer>[] adjList;

    // Constructor
    public Graph(int vertices)
    {

        // initialise vertex count
        this.v = vertices;

        // initialise adjacency list
        initAdjList();
    }

    // utility method to initialise
    // adjacency list
    @SuppressWarnings("unchecked")
    private void initAdjList()
    {
        adjList = new ArrayList[v];

        for (int i = 0; i < v; i++) {
            adjList[i] = new ArrayList<>();
        }
    }

    // add edge from u to v
    public void addEdge(int u, int v)
    {
        // Add v to u list.
        if(u != v)
            adjList[u].add(v);
    }

    // Prints all paths from
    // s to d
    public void printAllPaths(int s, int d)
    {
        boolean[] isVisited = new boolean[v];
        ArrayList<Integer> pathList = new ArrayList<>();

        // add source to path[]
        pathList.add(s);

        // Call recursive utility
        printAllPathsUtil(s, d, isVisited, pathList);
    }

    List<List<Integer>> allPaths = new ArrayList<>();

    private void printAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList)
    {

        if (u.equals(d)) {
            System.out.println(localPathList);
            allPaths.add(new ArrayList<>(localPathList));
            // if match found then no need to traverse more till depth
            return;
        }

        // Mark the current node
        isVisited[u] = true;

        // Recur for all the vertices adjacent to current vertex
        for (Integer i : adjList[u]) {
            if (!isVisited[i]) {
                // store current node in path[]
                localPathList.add(i);
                printAllPathsUtil(i, d, isVisited, localPathList);

                // remove current node in path[]
                localPathList.remove(i);
            }
        }

        // Mark the current node
        isVisited[u] = false;
    }

    // Driver program
    public static void main(String[] args)
    {
        // Create a sample graph
        Graph g = new Graph(5);
        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 1);
        g.addEdge(1, 3);
        g.addEdge(2, 3);
        g.addEdge(3, 4);

       /* g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 3);
        g.addEdge(1, 2);
        g.addEdge(2, 5);
        g.addEdge(3, 4);
        g.addEdge(4, 5);*/
        // arbitrary source
        int s = 0;

        // arbitrary destination
        int d = 4;
        System.out.println(
                "Following are all different paths from "
                        + s + " to " + d);
        g.printAllPaths(s, d);
        findMeetingPoint(g);

        //System.out.println(g.allPaths);

        /*for (int d=0; d<=4; d++) {
            System.out.println(
                    "Following are all different paths from "
                            + s + " to " + d);
            g.allPaths.clear();
            g.printAllPaths(s, d);
            findMeetingPoint(g);
        }*/
    }

    private static void findMeetingPoint(Graph g) {
        if(g.allPaths.size()<=1) {
            System.out.println("No meeting point");
            return;
        }
        Set<Integer> intersects = new HashSet<>();
        Set<Integer> meetPoints = new HashSet<>();

        intersects.addAll(g.allPaths.get(0));

        for(int i=1; i<g.allPaths.size(); i++) {
            intersects.retainAll (g.allPaths.get(i));
        }

        for (Integer node: intersects) {
            if(g.adjList[node].size()==0)
                intersects.remove(node);
        }

        System.out.println("Meeting points: " + intersects);

    }
}

EDITTED 2 :
code which can handle cycles and without a defined destination:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

// A directed graph using
// adjacency list representation
public class Graph {

    // No. of vertices in graph
    private int v;

    // adjacency list
    private ArrayList<Integer>[] adjList;

    // Constructor
    public Graph(int vertices)
    {

        // initialise vertex count
        this.v = vertices;

        // initialise adjacency list
        initAdjList();
    }

    // utility method to initialise
    // adjacency list
    @SuppressWarnings("unchecked")
    private void initAdjList()
    {
        adjList = new ArrayList[v];

        for (int i = 0; i < v; i++) {
            adjList[i] = new ArrayList<>();
        }
    }

    // add edge from u to v
    public void addEdge(int u, int v)
    {
        // Add v to u's list.
        if(u != v)
            adjList[u].add(v);
    }

    // Prints all paths from
    // 's' to 'd'
    public void printAllPaths(int s)
    {
        boolean[] isVisited = new boolean[v];
        ArrayList<Integer> pathList = new ArrayList<>();

        // add source to path[]
        pathList.add(s);

        // Call recursive utility
        printAllPathsUtil(s, isVisited, pathList);
    }

    List<List<Integer>> allPaths = new ArrayList<>();

    private void printAllPathsUtil(Integer u, boolean[] isVisited, List<Integer> localPathList)
    {

        if (adjList[u].isEmpty()) {
            System.out.println(localPathList);
            allPaths.add(new ArrayList<>(localPathList));
            // if match found then no need to traverse more till depth
            return;
        }

        // Mark the current node
        isVisited[u] = true;

        // Recur for all the vertices adjacent to current vertex
        for (Integer i : adjList[u]) {
            if (!isVisited[i]) {
                // store current node in path[]
                localPathList.add(i);
                printAllPathsUtil(i, isVisited, localPathList);

                // remove current node in path[]
                localPathList.remove(i);
            }
        }

        // Mark the current node
        isVisited[u] = false;
    }

    // Driver program
    public static void main(String[] args)
    {
        // Create a sample graph
        Graph g = new Graph(8);
        /*g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 1);
        g.addEdge(1, 3);
        g.addEdge(2, 3);
        g.addEdge(3, 4);*/

        /*g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 3);
        g.addEdge(1, 2);
        g.addEdge(2, 5);
        g.addEdge(3, 4);
        g.addEdge(4, 5);*/

        g.addEdge(0, 1);
        g.addEdge(0, 2);
        g.addEdge(1, 3);
        g.addEdge(1, 4);
        g.addEdge(2, 3);
        g.addEdge(2, 4);
        g.addEdge(3, 5);
        g.addEdge(4, 5);
        g.addEdge(5, 6);
        g.addEdge(5, 7);

        // arbitrary source
        int s = 0;

        // arbitrary destination
        System.out.println(
                "Following are all different paths from "
                        + s );
        g.printAllPaths(s);
        findMeetingPoint(g);
    }

    private static void findMeetingPoint(Graph g) {
        if(g.allPaths.size()<=1) {
            System.out.println("No meeting point");
            return;
        }
        Set<Integer> intersects = new HashSet<>();
        Set<Integer> meetPoints = new HashSet<>();

        intersects.addAll(g.allPaths.get(0));

        for(int i=1; i<g.allPaths.size(); i++) {
            intersects.retainAll (g.allPaths.get(i));
        }

        for (Integer node: intersects) {
            if(g.adjList[node].size()==0)
                intersects.remove(node);
        }

        System.out.println("Meeting points: " + intersects);

    }
}

input as:

g:{
 0: [1,2],
 1: [1,3,4],
 2: [3,4],
 3: [5],
 4: [5],
 5: [6,7],
 6: [],
 7: []
}
s=0

and output as:
Following are all different paths from 0
[0, 1, 3, 5, 6]
[0, 1, 3, 5, 7]
[0, 1, 4, 5, 6]
[0, 1, 4, 5, 7]
[0, 2, 3, 5, 6]
[0, 2, 3, 5, 7]
[0, 2, 4, 5, 6]
[0, 2, 4, 5, 7]
Meeting points: [0, 5]

You can use this link which provide Python code to find all paths, but need change like the proposed algorithm.


text:
Q: How to fix display automatic 2 digits the last phone number to second textfield? I've combined this script from http://jsbin.com/oleto5/5/edit?html,js,output and http://jsfiddle.net/AEMLoviji/tABDr/
But there is a little problem in code : $('#numbers').val($('#tt').val()+String.fromCharCode(event.keyCode));
If I remove +String.fromCharCode(event.keyCode)); and script be replaced to .substr(-2)); does not work.
If I use +String.fromCharCode(event.keyCode)); is not perfect when I remove digits.
Example :

<!doctype html>

<meta charset="utf-8">
<title>berkelilingkesemua.info</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" class="jsbin" />

<input id="txt" type="text" />

Second script is combined by me from first script becomes like below.

<input type="text" id="tt" />
<input type="text" id="numbers" />

Are there solution about this script ?.

A: I think you're after one of the following.
$('#output').text( $(this).val().slice(0, -2) );

$('#output').text( $(this).val().slice(-2) );

A demo using .slice():

$(function() {
    $('#txt').keyup(function() {
        var $this = $(this);
        $('#output1').val( $this.val().slice(0, -2) ); //Grab everything but the last 2 characters.
        $('#output2').val( $this.val().slice(-2) ); //Grab the last 2 characters.
    })
});

<input type="text" id="txt" />

<input type="text" id="output1">

<input type="text" id="output2">

A: Let's analyze it:
1. You're using HTML5, so why not to use the "input" event? It's more reliable then a "keyup"
2. To speed things up, always try to store a DOM element in a variable, so you won't have to navigate trough all the DOM tree every time, you press a button
3. Use slice() method, to get a proper string.

var source = $("#tt"),
    target = $("#numbers");
source.on('input', function() {
  target.val(source.val().slice(-2));
});

<input type="text" id="tt" />
<input type="text" id="numbers" />


text:
Q: SQL max last_Update column I am looking for help with the below update query. I am trying to update the provreg table with the latest updated contract from the contractinfo table but it doesn't seem right.  What is the best way to complete this update using the max(lastupdate) field on the contractinfo table?
UPDATE provreg
SET ContractName = ci.ContractID,
    ContractBegin = ci.ContractEff,
    ContractEnd = ci.contractterm
FROM provreg pr
INNER JOIN Provider P ON pr.npi = p.npi
INNER JOIN Affiliation A ON a.provid = p.provid
INNER JOIN contractinfo ci ON ci.affiliationid = a.affiliationid
WHERE CI.CONTRACTED = 'Y'
  AND ci.lastupdate = (SELECT MAX(lastupdate)
                       FROM PlanReport_QNXT_LA.dbo.contractinfo
                       WHERE contractid = ci.contractid)

A: Try below.
UPDATE PROVREG
   SET (CONTRACTNAME, CONTRACTBEGIN, CONTRACTEND) =
          (SELECT CI.CONTRACTID, CI.CONTRACTEFF, CI.CONTRACTTERM
             FROM PROVREG PR
                  INNER JOIN PROVIDER P ON PR.NPI = P.NPI
                  INNER JOIN AFFILIATION A ON A.PROVID = P.PROVID
                  INNER JOIN CONTRACTINFO CI
                     ON CI.AFFILIATIONID = A.AFFILIATIONID
            WHERE     CI.CONTRACTED = 'Y'
                  AND CI.LASTUPDATE = (SELECT MAX (LASTUPDATE)
                                         FROM PLANREPORT_QNXT_LA.DBO.CONTRACTINFO
                                        WHERE CONTRACTID = CI.CONTRACTID));

COMMIT;


text:
Q: SetValue Completion Block with Firebase 3.x In Firebase 2.5.1, this was working:
let post1Ref = sendRequestRef.childByAutoId()
post1Ref.setValue(request, withCompletionBlock: {( error:NSError?, ref:Firebase!) in

})

However, I couldn't figure out how to achieve it in 3.x (as the docs for completion doesn't really tell it)
let post1Ref = sendRequestRef.childByAutoId()
post1Ref.setValue(request, withCompletionBlock: {( error:NSError?, ref:Firebase!) in
    if (error != nil) {
       print("ERROR")
    } else {
       print("Success")
    }
})

This throws an error:

Use of unresolved Firebase

What is the proper way of handling completion block with Firebase 3.x?

A: Use
ref.setValue(object) { (error, ref) -> Void in

}

Here ref is FIRDatabaseReference


text:
Q: Bigquery Failed to Parse bq_parse_files with bq_table_download? I have bigquery some table. bq_table_download functions work for most of the table, however, it shows failed to parse errors with 1 table.
bigrquery::bq_auth()
sql_query=paste0("select * from `project_id.dataset.table_name`")
bq_table_ext=bq_table_download(bq_project_query(project_id, sql_query))

In order to solve this I have also used as suggested bq_table_download have download quota limit.
options(scipen = 20)

However, still, I am unable to figure what is an issue.
Here is snapshot of error code
Error in bq_parse_files(schema_path, c(path_first_chunk, chunk_plan$dat$path),  :
  Failed to parse '/tmp/Rtmpjd5eQN/bq-download-8650ad590.json'
Calls: ... master_table_base -> bq_table_download -> bq_parse_files
In addition: Warning messages:
1: In writeBin(result$content, con) : problem writing to connection
2: In writeBin(result$content, con) : problem writing to connection
Execution halted


text:
Q: No VC/inc folder in my MSVS 2013 directory I'm trying to add FLTK to MSVS 2013 and I'm copying the .lib files into vc/inc but I cannot find the folder anywhere. Under the Visual Studio 2013 folder all I have is
ArchitectureExplorer, Backup Files, Code Snippets,

Projects, Settings, StartPages, Templates, Visualizers

What am I missing here? I'm sure its something stupid.

A: Not exactly sure what you mean by holder.  Start VS, select Tools/Options/Projects & Solutions/VC++ directories.
On the right pane, select Include files from the top right box and add your FLTK include directory in the listbox below.
Then select Library files from the top right box and add your FLTK library directory to the listbox below.
That's basically it - there is no need to copy files anywhere.


text:
Q: Copying projection of existing defined raster file to define projection of feature class in ModelBuilder? For arcmap, can i copy the projection of an existing defined raster file to define a projection of feature class?
I'm planning on doing this inside ModelBuilder.

A: To do this you would use the Create Spatial Reference tool which:

Creates a spatial reference for use in ModelBuilder.

...

In ModelBuilder, the output of this tool can be used as input to tools
  with a spatial reference parameter (for example, Create Feature Class,
  Create Feature Dataset, and Make XY Event Layer).

...

spatial_reference_template (Optional) [is] The feature class or layer
  to be used as a template to set the value for the spatial reference.
  [and can be a] Feature Layer; Raster Catalog Layer; Raster Dataset


text:
Q: GeoCoordinate não contém um definição para GetDistanceTo Estou tentando fazer um algoritmo que calcula a distancia entre dois pontos a partir de suas coordenadas (Latitude e Longitude), nas minhas pesquisas acabei me deparando com GeoCoordinate (https://docs.microsoft.com/en-us/dotnet/api/system.device.location.geocoordinate?redirectedfrom=MSDN&view=netframework-4.8). Contudo não estou conseguindo utilizar a função GetDistanceTo.
Error :

"GeoCordinate" não contém uma definição para "GetDistanceTo" e não foi
  possível encontrar nenhum método de extensão "GetDistanceTo" que
  aceite um primeiro argumento do tipo "GeoCoordinate"

Código c#:
using Nest;
using System;

namespace Gps
{
    class Program
    {
        static void Main(string[] args)
        {
            double long1 = -38.527498;
            double lat1 = -3.734876;
            double long2 = -38.529240;
            double lat2 = -3.743198;

            var locA = new GeoCoordinate(lat1, long1);
            var locB = new GeoCoordinate(lat2, long2);

            double distance = locA.GetDistanceTo(locB);
        }
    }
}

Acho que deve ser besteira, mas já perdi um bom tempo tentando resolver este problema, agradeço desde já caso alguém possa me ajudar apontando a onde esta o erro.

A: Você criou uma solução console que utiliza o .NET Core, que o impede de adicionar referências a assemblies pois o objetivo desse tipo de aplicação é ser compatível com o Mono.
Quando tenta utilizar o tipo GeoCoordinate nesse tipo de aplicação o IntelliSense informa o erro e sugere que instale o pacote Nest que possui uma versão incompleta da classe GeoCoordinate.
Para utilizar a classe GeoCoordinate primeiro você tem que criar o projeto do tipo correto:

O correto é o projeto em que está escrito Console App(.NET Framework)
Criado esse projeto adicione a referência ao Assembly System.Device, que é onde se encontra o Namespace System.Device.Location, e faça a referencia ao namespace System.Device.Location em seu código.

Então seu código funcionará sem problemas.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Device.Location;

namespace Gps
{
    class Program
    {
        static void Main(string[] args)
        {
            double long1 = -38.527498;
            double lat1 = -3.734876;
            double long2 = -38.529240;
            double lat2 = -3.743198;

            var locA = new GeoCoordinate(lat1, long1);
            var locB = new GeoCoordinate(lat2, long2);

            double distance = locA.GetDistanceTo(locB);
            Console.WriteLine("A distancia é:" + distance);
            Console.ReadLine();
        }
    }
}


text:
Q: template-size array initialization in initializer list, C++ class Y; //not really relevant

class B
{
  B(Y*);
  //stuff
}

template<int SIZE> class X : public Y
{
  B array[SIZE];

  X();
}

I would like to call constructor of each element of array[] with this as parameter. How can I do that in pretty way? C++14 and even 17 are OK for me.

A: One of several approaches:
template <int SIZE>
class X : public Y
{
    B array[SIZE];

    template <std::size_t>
    X* that() { return this; } // don't abuse the comma operator

    template <std::size_t... Is>
    X(std::index_sequence<Is...>) : array{ that<Is>()... } {}

public:
    X() : X(std::make_index_sequence<SIZE>{}) {}
};

DEMO

A: There's no "nice" or simple way of doing it with C arrays (or even std::array).
You can to it very easily if you change to use a std::vector instead. It has a constructor that allows you to set the size and pass the default value for all elements:
template<int SIZE> class X : public Y
{
    std::vector<B> array;

    X()
        : array(SIZE, B(this))
    {}
};


text:
Q: Stub index points to a file without PSI: com.intellij.openapi.fileTypes.UnknownFileType@23713b43 Making app in Android Studio with Gradle I get this error:

Stub index points to a file without PSI: com.intellij.openapi.fileTypes.UnknownFileType@23713b43

A: Same problem here.
This link is a thread on JetBrain's community forum.
The comments suggest that you do the following:

*

*Go to File > Invalidate Caches/Restart
This worked for me.


text:
Q: JavaScript Error Element is null: while interacting ShadownDom element I am writing code in Javascript to automate the website https://www.fashionette.co.uk/. I have to use cookies when the user lands on the page for the first time
I am writing the following code to get cookies:
JavascriptExecutor js = (JavascriptExecutor)webdriver;
WebElement element= (WebElement) js.executeScript("return document.getElementById('usercentrics-root').shadowRoot.querySelector(\"[data-testid='uc-accept-all-button']\");");
            element.click()

it locate element in browser correctly:

But In Intellij it gives me error:
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebElement.click()" because "element" is null

A: If you are using Java create a browser instance and find elements:
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com/");
WebElement WE = driver.findElementByCss("YourCSSSelector");
WE.click();

If you are using JavaScript change your into:
WebElement element = (WebElement) js.executeScript
("document.getElementById('usercentrics-root').
shadowRoot.querySelector(\"[data-testid='uc-accept-all-button'])\");


text:
Q: Excel PowerQuery / C# WebAPI OData, Retrieving old Service Reference Having some strange behavior when trying to connect Excel Power Query to my OData web service.
When I started out building my web service my underlying data class (POCO) was called 'FilterSearchFacade'.  As development continued, I renamed the underlying data class to 'ReportSource'.
When I connect to the web service using a URL through a web browser, the correct 'ReportSource' object is returned.  However, when I connect with PowerQuery, it returns the following error:
It's as if there's some data cache in Excel that is holding on to the old class definition?
I have tried...
*In Excel going to "Power Query" > "Recent Sources", deleting them all and restarting excel.
*Searching the entirety of all code in my WebAPI project for the class name 'FilterSearchFacade', there are none.
*Deleting the bin/obj folders from the WebAPI project, cleaning and    rebuilding.
When I go to the $metadata root of the project from the web browser,    it shows the correct class definition:
Debugging locally: http://localhost:61023/api/PortlandDev/2/$metadata
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
<edmx:DataServices>
<Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="Sulzer.STAT.DataService">
<EntityType Name="ReportSource">
<Key>...

I'm stumped here.  The OData project has no references to the 'FilterSearchFacade' class but Excel is still trying to reference that type.  Any ideas as to additional items to look in to or how to proceed would be very much appreciated.


text:
Q: php pagination code is not working Can anyone point me out why my pagination is not working, What I am doing wrong here ? Working on it for a long time. my url generates like : http://localhost/medapp/admin/medorder.php?page=%209.
 <?php
   //pagination
    $perpage = 3;
    if (isset($_GET["page"])) {
        $page = $_GET["page"];
        }
        else {
          $page=1;
        }
    $start_from = ($page-1)*$perpage;
  //pagination

     $medorder = "SELECT * FROM `medorder` WHERE status='1'  order by ID desc";
     $result = $db->select($medorder);
      if($result){
         $i=0;
        while($row = $result->fetch_assoc()) {
        echo "
";
          echo "".$i++."	";
          echo "".$row["uid"]."	";
          echo "".$row["fullname"]."	";
          echo "
";
       }
// pagination
    $query  = "select * from medorder";
    $result = $db->select($query);
    $total_rows = mysqli_num_rows($result);
    $total_pages = ceil($total_rows/$perpage);
    echo "".'First Page'."";
    for ($i=1; $i <= $total_pages; $i++) {
    echo "".$i."";  }
    echo "".'Last Page'."";
                         //pagination
    }

  ?>

A: Change your query like this by using LIMIT and OFFSET
$medorder = "SELECT * FROM `medorder` WHERE status='1'  order by ID desc LIMIT $start_from,$perpage"; //

A: in this following line, you have a space before the $i variable:
echo "".$i."";

should be
echo "".$i."";


text:
Q: Maximum call stack size exceeded on trigger click I really want to do something simple. On click on a certain element, I trigger a click on another element but I get the below error on my console.

Uncaught RangeError: Maximum call stack size exceeded

My code is as below;
$('body').on('click', '.actual-click-element', function(event) {
    $('.trigger-click-element').trigger('click');
    event.preventDefault();
});

I wonder why am am getting this error and I don't see how this is recursive. Any ideas?

A: Surely because .trigger-click-element is descendant of .actual-click-element...
To avoid recursive call, you could use jq triggerHandler():

Events triggered with .triggerHandler() do not bubble up the DOM
  hierarchy; if they are not handled by the target element directly,
  they do nothing.

$('body').on('click', '.actual-click-element', function(event) {
    $('.trigger-click-element').triggerHandler('click');
    event.preventDefault();
});

Now if $('.trigger-click-element') returns more than one element, you could use:
$('.trigger-click-element').each(function(){$(this).triggerHandler('click');});


text:
Q: Make image and video upload optional I have a small app in codeigniter. There is a form that has 3 text fields, name,email,location. This is enough to submit. However there are two optional fields to all the user to submit either an image or video or both. I have it working until there is an error with the file uploaded. It will still submit the text data, when i want it to halt the whole submission until the error is fixed.
Here is the code from my controller. Any help would be great. Thanks!
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Form extends MY_Controller {

public function __construct()
{
    parent::__construct();
    $this->load->helper(array('form', 'url'));
}

function index()
    {
        $this->load->helper(array('form', 'url'));

        $this->load->library('form_validation');

        $this->form_validation->set_rules('nominee', 'Nominee', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        $this->form_validation->set_rules('location', 'Location', 'required');

        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('form');
        }
        else
        {
             // Load the library - no config specified here
                $this->load->library('upload');

                // Check if there was a file uploaded - there are other ways to
                // check this such as checking the 'error' for the file - if error
                // is 0, you are good to code
                if (!empty($_FILES['imageupload']['name']))
                {
                    // Specify configuration for File 1
                    $config['upload_path'] = 'uploads/images';
                    $config['allowed_types'] = 'gif|jpg|png';
                    $config['max_size'] = '100';
                    $config['max_width']  = '1024';
                    $config['max_height']  = '768';

                    // Initialize config for File 1
                    $this->upload->initialize($config);

                    // Upload file 1
                    if ($this->upload->do_upload('imageupload'))
                    {
                        $data = $this->upload->data();
                    }
                    else
                    {
                        echo $this->upload->display_errors();
                    }

                }

                // Do we have a second file?
                if (!empty($_FILES['videoupload']['name']))
                {
                    // Config for File 2 - can be completely different to file 1's config
                    // or if you want to stick with config for file 1, do nothing!
                    $config['upload_path'] = 'uploads/videos/';
                    $config['allowed_types'] = 'gif|jpg|png';
                    $config['max_size'] = '100';
                    $config['max_width']  = '1024';
                    $config['max_height']  = '768';

                    // Initialize the new config
                    $this->upload->initialize($config);

                    // Upload the second file
                    if ($this->upload->do_upload('videoupload'))
                    {
                        $data = $this->upload->data();
                    }
                    else
                    {
                        echo $this->upload->display_errors();
                    }

                }

            $this->load->view('thankyou');
            //Run code to add into the database
        }
    }

}

A: Place all the upload data logic into a custom validation callback.
Then if the validation fails (including the uploads), the page will return to the form, with the data pre-filled in - and your user can fix the file upload.
Then your controller logic is simplied as well;
    $this->load->library('form_validation');

    $this->form_validation->set_rules('nominee', 'Nominee', 'required');
    $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
    $this->form_validation->set_rules('location', 'Location', 'required');
    $this->form_validation->set_rules('imageupload', 'Image Upload', 'callback__image_upload');
    $this->form_validation->set_rules('videoupload', 'Video Upload', 'callback__video_upload');

    if ($this->form_validation->run() == FALSE)
    {
        $this->load->view('form');
    }
    else
    {
        //Run code to add into the database
        $this->load->view('thankyou');
    }

and
function _video_upload()
{
   //put upload logic here and check if its valid
}

function _image_upload()
{
   //put upload logic here and check if its valid
}


text:
Q: Laravel URL from comain.com/category/slug to domain.com/category I searched for answer and didn't find any that will works for me.
I have table 'articles' where I store articles with 'slug' column.
In my route files I have route:

Route::get('article/{slug}', 'ArticleController@viewArticle');

that works fine when I type for example /article/some-article-title and article will show, but I want to access from /some-article-title . I'v tried to change route like:

Route::get('{slug}', 'ArticleController@viewArticle');

And that works when i put this at the end of file, but after all for example WYSIWYG now works (uploading files), and some images stopts work (404 error). I'v tried modyfing .htaccess file and still not working.
Any ideas?
I want to create anchor like this
some-title-for-article

but now the link looks like this:
some-title-for-article

Routes file web.php
Route::get('/', 'HomeController@index');

/* DEPLOY BITBUCKET */
Route::get('/deploy/', 'DeployController@index');
Route::post('/deploy/update',
    ['as' => 'deploy_update', 'uses' => 'DeployController@update']);

/* ADMIN PANEL */

Auth::routes();
Route::get('/admin/', 'AdminController@index');

/* ADMIN USERS */
Route::get('/admin/users', 'UserController@index');
Route::get('/admin/users/add/', 'UserController@add');
Route::post('/admin/users/create/', 'UserController@create');
Route::get('/admin/users/edit/{id}', 'UserController@edit');
Route::post('/admin/users/update/', 'UserController@update');
Route::delete('/admin/users/delete/{id}', 'UserController@delete');

/* ADMIN CATEGORIES */
Route::get('/admin/categories', 'CategoryController@index');
Route::get('/admin/categories/add/', 'CategoryController@add');
Route::post('/admin/categories/create/', 'CategoryController@create');
Route::get('/admin/categories/edit/{id}', 'CategoryController@edit');
Route::post('/admin/categories/update/', 'CategoryController@update');
Route::delete('/admin/categories/delete/{id}', 'CategoryController@delete');

/* ADMIN COMMENTS */
Route::get('/admin/comments', 'CommentController@index');
Route::get('/admin/comments/view/{id}', 'CommentController@view');
Route::get('/admin/comments/add/', 'CommentController@add');
Route::post('/admin/comments/create/', 'CommentController@create');
Route::post('/admin/comments/approve/{id}', 'CommentController@approve');
Route::delete('/admin/comments/delete/{id}', 'CommentController@delete');

/* ADMIN ARTICLES */
Route::get('/admin/articles', 'ArticleController@index');
Route::get('/admin/articles/view/{id}', 'ArticleController@view');
Route::get('/admin/articles/edit/{id}', 'ArticleController@edit');
Route::get('/admin/articles/add/', 'ArticleController@add');
Route::post('/admin/articles/create/', 'ArticleController@create');
Route::post('/admin/articles/approve/{id}', 'ArticleController@approve');
Route::delete('/admin/articles/delete/{id}', 'ArticleController@delete');
Route::post('/admin/articles/update/', 'ArticleController@update');

Route::post('image-upload','ImageController@imageUploadPost');

/* GALLERIES */

Route::get('/admin/galleries', 'GalleryController@index');
Route::get('/admin/galleries/view/{id}', 'GalleryController@view');
Route::get('/admin/galleries/edit/{id}', 'GalleryController@edit');
Route::get('/admin/galleries/add/', 'GalleryController@add');
Route::post('/admin/galleries/create/', 'GalleryController@create');
Route::post('/admin/galleries/approve/{id}', 'GalleryController@approve');
Route::delete('/admin/galleries/delete/{id}', 'GalleryController@delete');
Route::post('/admin/galleries/update/', 'GalleryController@update');

/* IMAGE CONTROLLER */
Route::delete('/admin/images/delete/{id}', 'ImageController@delete');
Route::get('/admin/images/info/{id}', 'ImageController@info');
Route::post('/admin/images/update/', 'ImageController@update');

/* CONTACT FORM */
Route::get('/kontakt/', 'ContactController@index');
Route::post('/kontakt/',
    ['as' => 'contact_send', 'uses' => 'ContactController@send']);

/* GALLERY UPLOAD */
Route::post('/gallery_upload/', 'GalleryController@upload');

/* ARTICLE CONTROLLER */
Route::get('{slug}', 'ArticleController@viewArticle')->name('view.article');
//Route::get('artykuly/{slug}', 'ArticleController@viewArticle');

A: Please could you try to append a name to your route a call it with route name?
Like this:
Route::get('{slug}', 'ArticleController@viewArticle')->name('view.article');
and in your Blade file create the anchor with:
<a href="route('view.article')"

A: Since you're not using route names, just use url() helper:
{{ url('some-title-for-article') }}