text:
Q: Specifying cursor options when returning a Stream in Spring Data MongoDB? I'm using Spring Data MongoDB (spring-boot-starter-data-mongodb from Spring Boot 1.5.2.RELEASE) and MongoDB 3.4.9 and have defined a repository defined that looks like this:
interface MyMongoDBRepository extends CrudRepository<MyDTO, String> {
    Stream<MyDTO> findAllByCategory(String category);
}

I then have a service, MyService that interacts with this repository:
@Service
class MyService {
    @Autowired
    MyMongoDBRepository repo;

    public void doStuff() {
        repo.findAllByCategory("category")
            .map(..)
            .filter(..)
            .forEach(..)
    }
}

There's quite a lot of data in the database and sometimes this error occur:
2018-01-01 18:16:56.631 ERROR 1 --- [ask-scheduler-6] o.s.integration.handler.LoggingHandler : org.springframework.dao.DataAccessResourceFailureException:
Query failed with error code -5 and error message 'Cursor 73973161000 not found on server <mongodb-server>' on server <mongodb-server>;
nested exception is com.mongodb.MongoCursorNotFoundException:
Query failed with error code -5 and error message 'Cursor 73973161000 not found on server <mongodb-server>' on server <mongodb-server>
at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:77)
at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2135)
at org.springframework.data.mongodb.core.MongoTemplate.access$1100(MongoTemplate.java:147)
at org.springframework.data.mongodb.core.MongoTemplate$CloseableIterableCursorAdapter.hasNext(MongoTemplate.java:2506)
at java.util.Iterator.forEachRemaining(Iterator.java:115)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at com.mycompany.MyService.doStuff(MyService.java:108)
at com.mycompany.AnotherService.doStuff(AnotherService.java:42)
at sun.reflect.GeneratedMethodAccessor2026.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:65)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748) Caused by: com.mongodb.MongoCursorNotFoundException: Query failed with error code -5 and error message 'Cursor 73973161000 not found on server <mongodb-server>' on server <mongodb-server>
at com.mongodb.operation.QueryHelper.translateCommandException(QueryHelper.java:27)
at com.mongodb.operation.QueryBatchCursor.getMore(QueryBatchCursor.java:213)
at com.mongodb.operation.QueryBatchCursor.hasNext(QueryBatchCursor.java:103)
at com.mongodb.MongoBatchCursorAdapter.hasNext(MongoBatchCursorAdapter.java:46)
at com.mongodb.DBCursor.hasNext(DBCursor.java:145)
at org.springframework.data.mongodb.core.MongoTemplate$CloseableIterableCursorAdapter.hasNext(MongoTemplate.java:2504) ... 24 more

I've read at various places that when using the vanilla MongoDB Java client you can configure the MongoDB cursor to either have no timeout or set a batch size to hopefully mitigate this.
If this is the way to go, then how can I supply cursor options when returning a Stream from Spring Data MongoDB?

A: Regarding the two options you mentioned.

*

*Batch size, You cannot set batch size using Repository class. You can do it using MongoTemplate. Something like this
final DBCursor cursor = mongoTemplate
        .getCollection(collectionName)
        .find(queryBuilder.get(), projection)
        .batchSize(readBatchSize);
   while (cursor.hasNext()) {
       ......
       ......
    }

But to use MongoTemplate you need to create a Custom Repository.

*Regarding Cursor timeout. You can do something like this
@Configuration
public class MongoDbSettings {

    @Bean
    public MongoClientOptions setmongoOptions() {
        return MongoClientOptions.builder().socketTimeout(5000).build();
    }
 }

There are many other options(heartbeat, connectiontimeout) you can set for Mongo. You can set those properties in your application.properties file, and then bind it using @Value in the above class and set(instead of hardcoding).
Unfortunately, spring-boot doesn't provide any way to specify these in application.properties file

A: Your error is occurring because you are processing the stream too slowly, so the cursor is timing out before you get to the next batch.
Batch size can be set on the Spring Data Query object, or on a Repository using the @Meta annotation. For example:
Query query = query(where("firstname").is("luke"))
    .batchSize(100);

Or when using repositories:
@Meta(batchSize = 100)
List<Person> findByFirstname(String firstname);

See Spring Data MongoDB documentation for more details.
The cursor timeout can also be disabled on a per query basis using the same configuration. e.g. @Meta(flags = {CursorOption.NO_TIMEOUT}).
The cursor timeout cannot be changed on a per-query basis. That is a server configuration. You need to use the cursorTimeoutMillis server parameter to change that server-wide.

A: You don't need to supply cursor options when returning a Stream from Spring Data MongoDB. The possible reason for this exception is how your service read data from Mongo. Possible reasons:

*

*You are sharing a single cursor across multiple threads

*You are requested too many elements at once

*Load balancer before Mongo server

See this Jira topic's comments for some ideas an direction applicable to your application.


text:
Q: Problem in reading XML Hello Guys can you help me solving my problem in reading xml.
I'm just new in xml. Here's the sample xml.
<Org>
    <Org ID="1">
        <OrgNum>1</OrgNum>
        <OrgName>sample1</OrgName>
    </Org>
    <Org ID="2">
        <OrgNum>2</OrgNum>
        <OrgName>sample2</OrgName>
    </Org>
</Org>

I want to get only the OrgName with an Org ID = 2.
Here's my sample code but it's read all the text.
Help me plz..Tnx
string xml = Application.StartupPath + "\\OrgName.xml";
XmlDocument xmlDoc = new XmlDocument();
if (System.IO.File.Exists(xml))
{
    XmlTextReader textReader = new XmlTextReader(xml);
    textReader.Read();
    while (textReader.Read())
    {
        XmlNodeType nType = textReader.NodeType;
        if (nType == XmlNodeType.Text)
        {
            MessageBox.Show(textReader.Value);
        }
    }
}

A: Maybe your life gets a lot easier if you start using tools like xdocument, xmldocument and xpath

A: If you want to use the classic .net Xml object model, you could try this:
    string xml = Application.StartupPath + "\\OrgName.xml";
    XmlDocument xmlDoc = new XmlDocument();
    if (System.IO.File.Exists(xml))
    {
       xmlDoc.Load(xml);
       XmlElement root = xmlDoc.DocumentElement;
       string orgName = root.SelectSingleNode(@"descendant::Org[@ID='1']/OrgName").InnerText;
       MessageBox.Show(orgName);
    }

A: A simple way to do it with linq:
 var doc = XDocument.Load(Application.StartupPath + "\\OrgName.xml");
 var result = doc.Root.Elements("Org").Where(x=>x.Attribute("id").ToString()=="2");

redpajama_set_name: RedPajamaStackExchange


text:
Q: MODX: sort by random selected ids I am new to modx revolution and I have pretty weird task. I have this:
 [[!getPage?
    &elementClass=`modSnippet`
    &element=`getResources`
    &parents=`127,106`
    &resources=`-831,-243`
    &depth=`2`
    &limit=`21`
    &pageVarKey=`page`
    &includeTVs=`1`
    &includeContent=`1`
    &tpl=`pageAllDoctors`
    &hideContainers=`true`
    &sortby=`FIELD(modResource.id, 456,331,390,491,2756,505,634,699,941,1044,1377,1436,1449,1678,1722,1711,1828,2007,2094,2184,2324,2487,2527)`
    &where=`[{"introtext:LIKE":"%[[!searchFieldClinic? &field=`spec`]]%", "AND:introtext:NOT LIKE":"%заведу%", "AND:template:=":104}]`]]

In the sortby I have a list of resources that are to be shown first and then the remaining resources. The only thing is that I need them not only to be first but also displayed random and not mix up with other resources that come after them.
Is there any way to do that?
Thanks in advance.

A: &sortby='RAND()'

http://modx.ws/getresources
Может так?

A: solved the issue with snippets:
&sortby=`FIELD(modResource.id, [[!shuffleVals?&vals=`456,331,390,491,2756,505,634,699,941,1044,1377,1436,1449,1678,1722,1711,1828,2007,2094,2184,2324,2487,2527`]])`

Snippet
<?php
/**
 * @package shuffleVals
 */
$output = '';

$properties =& $scriptProperties;

$properties['vals'] = explode(',', $properties['vals']);
shuffle($properties['vals']);
$properties['vals'] = implode(',', $properties['vals']);

return $properties['vals'];


text:
Q: polymer-cli - getting "Can't find variable: babelHelpers" when I set compile to true I use Polymer 2.0 and my build setting is:
"builds": [
{
  "name": "bundled",
  "bundle": true,
  "js": { "compile": true},
  "css": { "minify": true },
  "html": { "minify": true }
}]

I get "Can't find variable: babelHelpers" error after build.
The Polymer CLI version that I use is 1.1.0.
EDIT: I was using polymer-cli locally. After installing latest polymer-cli globally, now I get "Constructor requires 'new' operator" on safari and "Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function." on chrome.
EDIT2: used webcomponents-loader.js instead of webcomponents-lite.js and my problem solved.

A: I was getting same error.  Problem was that index.html is technically my entrypoint in my polymer.json config, but my actual served up entrypoint is another file that comes from my server (_Layout.cshtml since I'm using .NET on my backend).  What I needed to do was take the code in my compiled index.html file and move it over to my CSHTML file once I set "compile": true.  Problem solved.


text:
Q: LINQ to Entities Join on DateTime.DayOfWeek Imagine two tables: Shifts, RANK_S_DAY.  Shifts contains a ShiftDate column which is DateTime and RANK_S_DAY has a DayOfWeek column.  I need to join (int)ShiftDate.DayOfWeek equals DayOfWeek.  I understand why it won't work, but I'm not quite sure how I can change it.  The Exception is:

The specified type member 'DayOfWeek' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

As I understand it, LINQ can't translate (int)ShiftDate.DayOfWeek to something SQL understands,  Any ideas?
Here is the code:
Shifts = from s in en.Shifts
join j in en.RANK_S_JOB on s.kronos_JobPositions.JobID equals j.JOBNO
join d in en.RANK_S_DAY on (int)s.ShiftDate.DayOFWeek equals d.DAY_OF_WEEK
orderby
 d.RANK,
 j.RANK ascending
select s;

A: LINQ to SQL
var dayOfWeekCondition = (dt => dt.DayOfWeek == dayOfWeek);

LINQ to Entities
int dow = (int)dayOfWeek + 1; // SQL Day of week
var dayOfWeekCondition = (dt => SqlFunctions.DatePart("weekday", dt) == dow);

Source:
http://blog.abodit.com/2009/07/entity-framework-in-net-4-0/

A: It appears there isn't anything I can do at this level.  So what I've done is created a stored proc that joins the two tables and imported it into the Entity, created a function import that returned a Shifts entity.  Not sure if thats the best approach, but it works and is clean.

A: using System.Data.Objects.SqlClient; //Don't forget this!!

//You can access to SQL DatePart function using something like this:

YourTable.Select(t => new { DayOfWeek = SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 }); //Zero based in SQL

//You can compare to SQL DatePart function using something like this:

DateTime dateToCompare = DateTime.Today;
YourTable.Where(t => SqlFunctions.DatePart("weekday", t.dateTimeField) - 1 == dateToCompare }); //Zero based in SQL

A: Interestingly, this works fine in Linq-to-Sql:
from o in Orders
join c in Categories on (int) o.OrderDate.Value.DayOfWeek equals c.CategoryID
where o.OrderDate != null
select c

That query is meaningless -- It's just some random joins with the proper datatypes.  (I was using Northwind)


text:
Q: How use custom object through website exactly like membership could you explain to me how can I store and use a custom object exactly like we use the asp.net MVC membership through a website ? I use very often the same one table from my database and I want to stop asking my server to retreive this same information on every page. I can't use cookie because I have some important information into this and I don't use session because I want this object accessible like the membership. After user login, I would like to set this information once and for all into this object until it disconnects.
Examples...

*

*The very normal membership :
MembershipUser UserAccount = Membership.GetUser(HttpContext.Current.User.Identity.Name);

*My custom data object I want to use
MyCustomData customData = Membership.GetCustomData(HttpContext.Current.User.Identity.Name);
Thank you very much!!

A: You can try to override something like here: ASP.NET MVC Custom Membership Provider - How to overload CreateUser? or create your custom membership provider and add extra methods: Custom Membership Providers (I prefer this)


text:
Q: numpy where takes at most 3 arguments - a way around this? Let's say I have this code:
import numpy as np

def myf(c):
    return c*11

def method_A(c):
    return c*999

def method_B(c):
    return c*55

minimum = 30
maximum = 100
the_method = 'A'

b = np.array([1, 20, 35, 3, 45, 52, 78, 101, 127, 135])

I want to use numpy where in order to fulfill some conditions.
Something like:
b = np.where( np.logical_or(b < minimum , b > maximum) , b,
             (if the_method == 'A': method_A(b)) ,
             (if the_method == 'B': method_B(b)))

If the conditions b < min or b > max are met, leave each element in b as it is, else, if the_method is A , call method A else if method is B, call method B
So , I tried :
b = np.where( np.logical_or(b < minimum , b > maximum) , b,
             (np.where(the_method == 'A',method_A(b),b)),
             (np.where(the_method == 'B',method_B(b),b))
            )

which gives me function takes at most 3 arguments (4 given) because np.where can't accept more than 3 arguments.
Is there a way to solve my problem?

A: the_method is a scalar not an array, so you don't need the inner np.wheres here:
if the_method == 'A':
    which_method = method_A
elif the_method == 'B':
    which_method = method_B
else:
    raise ValueError

b = np.where(
    (b < minimum) | (b > maximum),
     b,
     which_method(b)
)

In fact, if you insert a print in both methods, you'll see than when using np.where, they both run.
If you're really set on getting that in one expression:
def _raise(x): raise x

b = np.where(
    (b < minimum) | (b > maximum),
     b,
     (
         method_A if the_method == 'A' else
         method_B if the_method == 'B' else
         _raise(ValueError)
     )(b)
)

A: Your parentheses were not balanced, you needed additional parentheses in the inner condition:
In [33]:
b = np.where( np.logical_or(b < minimum , b > maximum) , b,
             ((np.where(apply_method == 'A',method_A(b),
             (np.where(apply_method == 'B',method_B(b),None))
            ))))
b

Out[33]:
array([1, 20, 35000, 3, 45000, 52000, 78000, 101, 127, 135], dtype=object)

Your initial attempt:
b = np.where( np.logical_or(b < minimum , b > maximum) , b,
             (np.where(the_method == 'A',method_A(b),b)),
             (np.where(the_method == 'B',method_B(b),b))
            )

needed parentheses on the other condition


text:
Q: How can I stop VS Code Intellisense from automatically appearing? When I'm not working in JavaScript, Intellisense is unfortunately not often terribly helpful.  How can I make it only appear when I hit controlspace, and not just appear automatically?
I don't want to turn it off completely.  I just want it to only appear when I explicitly ask it to.

A: Although the VS Code Intellisense documentation does not define "Quick Suggestions", apparently "quick suggestions" is Intellisense—or is the visible face of it. (Are there also slow suggestions?  I have no idea.  The name seems to suggest being just one aspect of Intellisense, but... it turns out that it seems to be pretty much the central thing.)
So to stop Intellisense from appearing uninvited, you have to turn off "quick suggestions".  Here's how I did that, in my user settings:
  "editor.quickSuggestions": {
    "other": false,
    "comments": false,
    "strings": false
  },


text:
Q: Connection to "process /usr/sbin/sendmail -bs" has been closed unexpectedly I have updated my Laravel version 5.4 to version 9. After that, the project is working fine, apart from sending emails.

Connection to "process /usr/bin/sendmail -bs" has been closed
unexpectedly

A: Please look at https://talk.plesk.com/threads/removal-of-bs-option-from-plesk-sendmail-wrapper.365077/
As long as the plesk guys aren't able to deliver a stable interface to their  sendmail binary, you can fiddle around with command line options that will stop working without any notice. Or probably you'll better use native PHP transport (https://symfony.com/doc/5.4/mailer.html#using-built-in-transports).


text:
Q: Stabilize image sequence using FIR Filter instead of Kalman Filter I need help implimenting FIR Filter on a video sequence, in hope to stabilized the video.
There's a Kelman filter algorithm that uses a prediction and update stage on a prev and current pixels, with something called kalman gain looks like that:
     for i = 2:frames
         for j = 1:height
             for k = 1:width
             %predict:
             Xp = F*[X(j,k,i-1);0];
             Pp = F*(P(j,k,i-1))*F'+Q;

             %update:
             y = vid(j,k,i) - H*X(j,k,i-1);
             S = H*Pp*H'+R;
             K = Pp*H'*(S^-1);
             Xp = Xp+K*y;
             X(j,k,i) = Xp(1,1);
             Pp = (eye(2)-K*H)*Pp;
             P(j,k,i) = Pp(1,2);
             end
         end

which i'm not fully understand.
So I created the h coefficient vector, I want to apply the h an image such that I'll get a filtered input. I also tried to use the state space model but I'm not sure using it correctly.
%MATLAB
function [filtered] = firFilter(vid, dt, M)
% This function applies an FIR filter to a video using the state space model approach.
% Input arguments:
% vid - the video to filter in a form of a 3-D matrix
% dt - the sampling interval
% N - the number of samples in the sliding window
% M - the number of filter taps
% Output arguments:
% filtered - the filtered video

I = eye(1);
Z = zeros(1);
% Define the state space model
A = [I, I; Z, I];
B = [I Z;Z I];
C = [I, Z];
D = I;

%Horizontal and vertical absolute frame
Xpx = 0; Xpy = 0;
Xp = [ Xpx ;Xpy ];

% velocity frame
Xvx = Xpx/dt; Xvy = Xpy/dt;
Xv = [Xvx; Xvy];

X = [Xp; Xv]; %[Xpx; Xpy; Xvx; Xvy]

% Define the system noise and measurement noise covariance matrices
Q = 0.01;
R = 100;

% Initialize the filter coefficients
h = hCoafCalc(A,B,C,R,Q,M);

H = h'; %[Hp,Hv]
H{end+1} = [0,0];
Hp = [];
Hv = [];
for i = 1:M
    Hp(end+1) = H{i}(1);
    Hv(end+1) = H{i}(2);
end

% Loop over the frames
for i = M:size(vid, 3)
    % Get the current frame
    frame = vid(:, :, i);

    % Loop over the pixels
    for j = 1:size(frame, 1)
        for k = 1:size(frame, 2)

            % Construct the observation matrix over the sliding window
            Zm = zeros(M, 1);
            for l = 1:M
                Xp(l,1) = vid(j, k, in-l+1);
            end

            % Predict Stage

            % Update Stage

            % consturcting the filtered image
        end
    end

    % Display the progress
    disp(['Filtering frame ' num2str(i) ' out of ' num2str(size(vid, 3))]);
end

% Convert the filtered video to uint8 format
filtered = uint8(filtered);

end

function [h] = hCoafCalc(A,B,C,R,Q,M)

    I = eye(1);
    OmegaInt = I;
    TetaInt = C'*(R^-1)*C;
    Omege = {OmegaInt};
    Teta  = {TetaInt};
    N = M-1;
    %Constract Coefficients h(j) according to algorithm for filter gain coe
    %obtain from the article.
    for l = 1:N %[0:M-1]
        Teta{end+1} = (I+(A'^-1)*Teta{l}*(A^-1)*B*Q*B')^-1*A'^-1*Teta{l}*A^-1+C'*(R^-1)*C;
    end

    for l = 1:N %[0:M-1]
        Omege{end+1} = Omege{l}*(I+(A'^-1)*Teta{N-l+1}*(A^-1)*B*Q*B')^-1*A'^-1;
    end

    h = {Teta{M-1}^-1*Omege{1}*C'*(R^-1)};
    for l = 1:M %[1:M]
        h{end+1} = (Teta{M}^-1)*(Omege{l})*(C')*(R^-1);
    end

end

Can someone help me somehow apply the FIR Filter in the same way the kalman filter works ?
Thanks alot


text:
Q: Adding FB share button to pages behind sign-in I have web page which needs users to sign-in (not FB signin though), and need to add share button to it. Issue is when I share that page, it only posts link to the wall. og image and og:description tags are ignored.
btw i am using iframe to show fb:like
Can you please let me know how to solve this issue?

A: You need to generate open graph tags even when user is not logged in.


text:
Q: Dynamically Linking GLEW with CMake I've looked over Stack Overflow and Google to try to figure this out, but everything I've seen regarding a dynamic linking either doesn't work or they end up static linking.
E:/CLion/GLEW-Test/main.cpp:8: undefined reference to `_imp__glewInit@0'
E:/CLion/GLEW-Test/main.cpp:12: undefined reference to `_imp__glewGetErrorString@4'
E:/CLion/GLEW-Test/main.cpp:14: undefined reference to `_imp__glewGetString@4'

I am trying to dynamically link GLEW using CLion. The problem is, I've grown up with Visual Studio so I've never really had to think much about it. I'm trying to teach myself CMake and OpenGL, so this would have been a perfect exercise.
I downloaded the source for GLEW and built it with CMake and MinGW. I placed the resulting glew32.dll in C:/Windows/System32/, and I placed the libglew32.a in C:/MinGW/lib, and I placed glew.h, glxew.h, and wglew.h into C:/MinGW/include/GL.
Currently, I also have the libraries glew32.dll, libglu32.a, and libopengl32.a in my build directory.
Here is my CMakeLists.txt:
cmake_minimum_required(VERSION 3.8)
project(GLEW_Test)

set(CMAKE_CXX_STANDARD 11)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra")
set( CMAKE_VERBOSE_MAKEFILE on )

set(SOURCE_FILES main.cpp)
add_executable(GLEW_Test ${SOURCE_FILES})
target_link_libraries(GLEW_Test glew32 glu32 opengl32)

and this is my main.cpp:
#include <iostream>
#include <GL/glew.h>

int main()
{
    std::cout << "Hello, World!" << std::endl;

    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

    return 0;
}

Now, if I #define GLEW_STATIC before I #include <GL/glew.h>, the program compiles and outputs the expected output (An error for having no GLContext).    However, to my knowledge, that is static linking, and I want to dynamically link GLEW.  This is what I see when I compile without #define GLEW_STATIC:
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" --build E:\CLion\GLEW-Test\cmake-build-debug --target GLEW_Test -- -j 2
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -HE:\CLion\GLEW-Test -BE:\CLion\GLEW-Test\cmake-build-debug --check-build-system CMakeFiles\Makefile.cmake 0
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\Makefile2 GLEW_Test
mingw32-make.exe[1]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -HE:\CLion\GLEW-Test -BE:\CLion\GLEW-Test\cmake-build-debug --check-build-system CMakeFiles\Makefile.cmake 0
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_progress_start E:\CLion\GLEW-Test\cmake-build-debug\CMakeFiles 2
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\Makefile2 CMakeFiles/GLEW_Test.dir/all
mingw32-make.exe[2]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\GLEW_Test.dir\build.make CMakeFiles/GLEW_Test.dir/depend
mingw32-make.exe[3]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_depends "MinGW Makefiles" E:\CLion\GLEW-Test E:\CLion\GLEW-Test E:\CLion\GLEW-Test\cmake-build-debug E:\CLion\GLEW-Test\cmake-build-debug E:\CLion\GLEW-Test\cmake-build-debug\CMakeFiles\GLEW_Test.dir\DependInfo.cmake --color=
mingw32-make.exe[3]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\GLEW_Test.dir\build.make CMakeFiles/GLEW_Test.dir/build
mingw32-make.exe[3]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
[ 50%] Linking CXX executable GLEW_Test.exe
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_link_script CMakeFiles\GLEW_Test.dir\link.txt --verbose=1
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E remove -f CMakeFiles\GLEW_Test.dir/objects.a
C:\MinGW\bin\ar.exe cr CMakeFiles\GLEW_Test.dir/objects.a @CMakeFiles\GLEW_Test.dir\objects1.rsp
C:\MinGW\bin\g++.exe  -Wall -Wextra -g   -Wl,--whole-archive CMakeFiles\GLEW_Test.dir/objects.a -Wl,--no-whole-archive  -o GLEW_Test.exe -Wl,--out-implib,libGLEW_Test.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\GLEW_Test.dir\linklibs.rsp
CMakeFiles\GLEW_Test.dir/objects.a(main.cpp.obj): In function `main':
E:/CLion/GLEW-Test/main.cpp:8: undefined reference to `_imp__glewInit@0'
E:/CLion/GLEW-Test/main.cpp:12: undefined reference to `_imp__glewGetErrorString@4'
E:/CLion/GLEW-Test/main.cpp:14: undefined reference to `_imp__glewGetString@4'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [GLEW_Test.exe] Error 1
CMakeFiles\GLEW_Test.dir\build.make:98: recipe for target 'GLEW_Test.exe' failed
mingw32-make.exe[2]: *** [CMakeFiles/GLEW_Test.dir/all] Error 2
mingw32-make.exe[3]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
mingw32-make.exe[1]: *** [CMakeFiles/GLEW_Test.dir/rule] Error 2
CMakeFiles\Makefile2:69: recipe for target 'CMakeFiles/GLEW_Test.dir/all' failed
mingw32-make.exe[2]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
CMakeFiles\Makefile2:81: recipe for target 'CMakeFiles/GLEW_Test.dir/rule' failed
mingw32-make.exe[1]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
Makefile:120: recipe for target 'GLEW_Test' failed
mingw32-make.exe: *** [GLEW_Test] Error 2

What am I doing wrong? I followed the guide at glew's sourceforge, and placed the .dll in my System32 folder. Since I built with CMake and MinGW, I have .a files instead of .lib files, and I stuck those in my MinGW/lib directory.
The only thing I didn't do (because I wasn't sure), was do nothing with my libglew32.dll.a
Is this the culprit? I'm not sure what to do with it, and googling for information on a .dll.a file turned up nothing.

A: target_link_libraries(GLEW_Test libglew32.a libglu32.a libopengl32.a)

You should never include "lib" prefix and the file extension of a library in your target_link_libraries. Instead you should do it like this
target_link_libraries(GLEW_Test glew32 glu32 opengl32)

as cmake already will search for e.g. glew32.dll, libglew32.a by itself then. This way, you also stay platform/compiler independent.
For testing/bughunt purpose, I would recommend that you put the required libraries in the directory of your executable first and check if the error still occurs, since the windows linker searches the executable's directory first for libraries.
If it does not occur anymore but does when the libraries are located in the other locations, be sure that those locations are part of the PATH environmental variable.

A: Alright, so after googling around a bit and trying to understand what a .dll.a file is, I've got it figured out!
This is what I did to dynamically link glew using CMake:

*

*I deleted glew32.a from my C:\MinGW\lib directory, and replaced it with glew32.dll.a

*I placed glew32.dll into my build folder. However, you can also have it in your SysWOW64 folder and it should work.

And that's all! My CMakeLists.txt is still the same.


text:
Q: Duplicate (and empty) user is created using regular account signup I set up django-allauth in my project and social accounts work great. However, when I create user using regular acoounts it saves the user twice: One with username and another without username (this is empty username). Thus, next time I try to create a user it raises an Exception because username must be unique and it is duplicated, the empty username.
It set receivers for every signal and print logs when each of them are handled. However, I could only fence the problem between the populate_username signal and the email_confirmation_sent signal

A: After diving into the source code, and sprinkle logs everywhere I found the problem was caused by the custom Signup Model Form I use (I could have figured it out but it wasn't easy).
django-allauth manually saves the user, so in my case the form model default save method does it again and causes the bug.
As pointed out in the docs:

This class (the ACCOUNT_SIGNUP_FORM_CLASS) should implement a def signup(self, request, user) method, where user represents the newly signed up user.

However, the appreciation is quite vague and (at least in my case) it is easy to think that the ACCOUNT_SIGNUP_FORM_CLASS could be a form (whatever the kind).
So, I found two solutions:

*

*Replace the model form with a regular form. However, it is not clearly explained in the docs.

*Override the ModelForm's save method and skip the call to parent's save method

I implemented the second one, and the form end up as follows:
class SignupForm(UserCreationForm):

    class Meta:
        model = get_user_model()
        fields = ('first_name', 'last_name', 'email')

    def save(self, commit=True):
        return None


text:
Q: Sending email from codeigniter I am trying to implement contact form in my codeigniter application. But I get couldn't get it working. I have tried many tutorials, but couldn't find the bug.
My view file.

Contact Us

1234 Street Name, City Name

+(123) 456-7890

                        contact@humanity.com

                    <form id="contact-form" class="contact-form" name="contact-form" method="post" action="contactform/index">

                                <input type="text" name="name" class="form-control" required="required" placeholder="Name">

                                <input type="email" name="email" class="form-control" required="required" placeholder="Email Address">

                                <textarea name="message" id="message" required="required" class="form-control" rows="8" placeholder="Message"></textarea>

                            <button type="submit" class="btn btn-primary">Send Your Message</button>

                    </form>

My controller class.
<?php
class ContactForm extends CI_Controller {
public function __construct() {
    parent::__construct ();
}

// Custom validation function to accept only alphabets and space input
function alpha_space_only($str) {
    if (! preg_match ( "/^[a-zA-Z ]+$/", $str )) {
        $this->form_validation->set_message ( 'alpha_space_only', 'The %s field must contain only alphabets and space!' );
        return FALSE;
    } else {
        return TRUE;
    }
}
function index() {
    // set validation rules
    $this->form_validation->set_rules ( 'name', 'Name', 'trim|required|callback_alpha_space_only' );
    $this->form_validation->set_rules ( 'email', 'Emaid ID', 'trim|required|valid_email' );
    $this->form_validation->set_rules ( 'message', 'Message', 'trim|required' );

    // run validation on form input
    if ($this->form_validation->run () == FALSE) {
        // validation fails
        $this->load->view('_main_layout');
    } else {
        // get the form data
        $name = $this->input->post ( 'name' );
        $from_email = $this->input->post ( 'email' );
        $message = $this->input->post ( 'message' );

        // set to_email id to which you want to receive mails
        $to_email = 'proisuru@outlook.com';

        // send mail
        $this->email->from ( $from_email, $name );
        $this->email->to ( $to_email );
        $this->email->message ( $message );
        if ($this->email->send ()) {
            // mail sent
            print "";
        } else {
            // error
            print "";
        }
    }
 }
}

And email.php file
<?php
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.gmail.com'; //change this
$config['smtp_port'] = '465';
$config['smtp_user'] = 'proisuru@gmail.com'; //change this
$config['smtp_pass'] = 'password'; //change this
$config['mailtype'] = 'html';
$config['charset'] = 'UTF-8';
$config['wordwrap'] = TRUE;
$config['newline'] = "\r\n"; //use double quotes to comply with RFC 822 standard
?>

I have spent like three hours on this. But still couldn't find a solution.

A: In your email config file you specify that you want your emails to be html: $config[mailtype] = 'html' but when you are sending your email you set the $this->email->message to the forms message input. When your sending html emails in Codeigniter (at least the version I am on) you need to send in a complete web page.
For example:
 $data['message'] = $this->input->post ( 'message' );
 $this->email->message($this->load->view('path/to/email/message_view',$data, true ));

Then in your view you can do any html you want or just echo out your message:
echo $message;

Here is the documentation


text:
Q: wikipedia page view statistcs I need the page view statistics for any wikipedia page over certain time period. At least for one year. And they have to be in a certain format so that I can process them as json, xml or csv. I know that there are the page statistics by Domas Mituzas but they are too big. I only need page view statistics for some pages and not for all. Furthermore I have seen certain tools like http://stats.grok.se/ but here the period is not long enough (only 90 days).
Are there any other tools that provide the page view statistic in a format that can be processed?

A: The stats.grok.se site contains data about more than just the last 90 days. You can get information about every month of a single page in JSON using a query like:
http://stats.grok.se/json/en/201106/Stack%20Overflow

A: *

*Open wiki page

*In a navigation menu to the left click "Page information" (Tools)

*For some pages you may find page view statistics graphs here

*If not, scroll down to External Tools section

*Click "Page view statistics"

*You'll be taken to an external tool https://tools.wmflabs.org/pageviews where you can view statistics and download it as CSV, JSON, PNG.

A: The previous answer is now out of date.
In 2016, responding to urging via the "Community Wishlist" process, the old stats.grok.se tool was replaced with the vastly improved Pageview Statistics tool. (I'd post a direct link, but I don't have a high enough rep yet!) It's based on the same data as stats.grok was, as far as I know, but much more configurable -- arbitrary duration, multiple articles in one chart, etc.

*

*The tool may be found on the "view history" tab of any Wikipedia or Wikimedia article (in any language).

*Actual page views may be 50% higher than what's reported from the earlier days (Signpost coverage)


text:
Q: Can't get chrome to use the specified proxy settings I'm trying to make my chrome browser use the proxy settings 10.23.201.11:3128 .
When I run the command google-chrome --proxy-server=http://10.23.201.11:3128 I get the following errors:
MESA-INTEL: warning: Performance support disabled, consider sysctl dev.i915.perf_stream_paranoid=0

libva error: vaGetDriverNameByIndex() failed with unknown libva error, driver_name = (null)

How can I solve this?
UPDATE:
I've run the command consider sysctl dev.i915.perf_stream_paranoid=0 as instructed in the first error message and got the following response:
dev.i915.perf_stream_paranoid = 0

After this, I tried to run the command google-chrome --proxy-server=http://10.23.201.11:3128 once again but the second error message (libva) re-appeared again.


text:
Q: VSCode: How to programmatically set a handler on editor's language change event in my extension? I make an extension for VS Code. My task is to add an element to the status bar when working with a specific language, for example, SQL. For other languages, the element does not need to be displayed.
I have created a command:
    envStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 80);
    envStatusBarItem.command = aseChangeEnvironmentCommand;
    context.subscriptions.push(envStatusBarItem);

and set the listener:
context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(updateEnvStatusBarItemFn));

In addition, in package.json added the condition "onLanguage: sql" to activationEvents.
I show and hide the status bar element as follows:
    const updateEnvStatusBarItemFn = () => {
        const editor = vscode.window.activeTextEditor;
        if (editor) {
            if (editor.document.languageId === 'sql') {
                let aseCurrentServer = context.globalState.get('aseCurrentServer', '');
                envStatusBarItem.text = `ASE[${aseCurrentServer}]`;
                envStatusBarItem.show();
            }
            else {
                envStatusBarItem.hide();
            }
        }
        else {
            envStatusBarItem.hide();
        }
    };

The problem is that the extension is activated when you change the language in the editor to SQL or open the * .sql file (as per the condition in package.json). The status bar element is shown, but then the extension is considered active and the function of displaying / hiding the status bar element only works on the software-installed onDidChangeActiveTextEditor handler when switching tabs. I could not find a listener related to changing the language in which I could hang my handler.
Is there such a way, or should I write feature-request?

A: I received the answer from VSCode team on github:

When the language of a document changes the onDidCloseTextDocument
  and onDidOpenTextDocument events are fired:

github comment
Description is in VSCode sourcecode.


text:
Q: jQuery DataTables on live tables from PHP script I'm having a problem with the implementation of DataTables, I simple can't make it work in a returned table from a PHP script. Suppose this simple PHP script named simple_table.php:
<?php
    echo '

                Column 1
                Column 2

                Row 1 Data 1
                Row 1 Data 2

                Row 2 Data 1
                Row 2 Data 2

';
?>

Now I also have the next very simple jQuery script declared after the  tag in the hipotetic html file:
$(document).ready( function () {
    $('table.table_type').dataTable();
} );

$('div.push_button li').click(function() {
    var content = $(this).closest('div').children('div.content');
    $.get('simple_table.php', {}, function(html_table) {
            content.html(html_table);
    } );
} );

What is needed to be made for this simple example to work and keeping in it simple? The problem is that there is no solution for this useful scenario of a dynamic table made by a so simple script!
Well, maybe you have to have a preexisting
 and only yhen be able to filled up the respective
...

A: The problem is because you are running .dataTable() before the page has the element table.table_type. Instead of calling .dataTable() when the page loads, you need to run it once the table has been added to your
.
$('div.push_button li').click(function() {
    var content = $(this).closest('div').children('div.content');
    $.get('simple_table.php', {}, function(html_table) {
            content.html(html_table);
            content.find('table').dataTable();
    } );
} );


text:
Q: Searching similar products sku with sphinxsearch I have search form in my e-commerce site. Search engine is Sphinxsearch.
I have products with sku like (04078, PS04078, DS04078, 04078-1, 04078-2, 4078-3).

The problem I cannot figure out how to configure sphinx to get results I need:
Searching by '04078' gives me only item with sku 04078, but not all 6 items.
How to get all 6 items in result set?
My conf:
source products
{
        type                    = mysql
        sql_host                = #
        sql_user                = #
        sql_pass                = #
        sql_db                  = #
        sql_port                = #
        sql_query_pre = SET CHARACTER SET utf8
        sql_query               = \
                SELECT id,price,name,sku,producer_name \
                                        FROM products
        #sql_attr_string         = post_title
        #sql_field_string        = post_content
        sql_query_info          = SELECT * FROM products WHERE id=$id

}

index products
{
        source                  = products
        path                    = /var/data/products
        docinfo                 = extern
        mlock                   = 0
        charset_type = utf-8
        html_strip = 1
        html_remove_elements = style, script
        enable_star = 1
        min_word_len = 1
        min_infix_len = 3
}

A: The new regex filter in 2.1.1 beta sounds just the ticket to munge the product codes into a consistant form...
http://sphinxsearch.googlecode.com/svn/trunk/doc/sphinx.html#conf-regexp-filter


text:
Q: HTTP redirect not working My website: https://www.louiswebsdale.co.uk/ keeps giving the "400 bad request invalid header" error when trying to visit it without the https. So www.louiswebsdale.co.uk or http://www.louiswebsdale.co.uk give the "400 bad request invalid header" error.
Is there some code I need to change in the .htaccess file?
It currently is the following:
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Thank you very much.


text:
Q: transaction flow with roll back strategy mule Input:-
<balanceInquiry>
    <request>
      <amount>
        <amount>5.0</amount>
        <currency/>
      </amount>
    </request>
  </balanceInquiry>
<balanceInquiry>
    <request>
      <amount>
        <amount>10.0</amount>
        <currency/>
      </amount>
    </request>
  </balanceInquiry>
<balanceInquiry>
    <request>
      <amount>
        <amount>57.0</amount>
        <currency/>
      </amount>
    </request>
  </balanceInquiry>

I am trying to hit a SOAP webservice using the above input, but the webservice can only accept one balanceInquiry request at once. So I am spliting the request into different balanceInquiry using splitter. but if the status of 1st request is success then I have to go for 2nd and so on. If anyone of them fails then I need to rollback all the previous transaction. there is a attribute  which can be "success" or "fail" depending on the request.
So I want to know if there is any component to achieve this in mule? Please suggest.

A: I believe you should take a look at the foreach documentation.   https://docs.mulesoft.com/mule-user-guide/v/3.7/foreach and the exception handling strategy ; https://docs.mulesoft.com/mule-user-guide/v/3.7/error-handling.
If your 3 inquiries are in the same message and that you are using the default exception strategy, it will rollback the previous transactions... assuming you are writing the SOAP responses in a database using a DB connector.
Since I don't know exactly what you wish to do in your transaction, here's another interesting link : https://docs.mulesoft.com/mule-user-guide/v/3.7/rollback-exception-strategy


text:
Q: Is accepting a json directly from the client insecure/bad practice in a Golang app with a json file datastore? I have a simple Golang application with a HTTP API that controls the app, the api has a frontend over it powered by a React.js app. The frontend allows users to change settings and  POSTS a json object called settings directly to the API /api/settings endpoint (which has simple JWT authentication builtin). I take that object unmarshal it into a struct for the application to use, in case of an error the application uses the default struct and sends an error to the client. My question is; am I doing this correctly or is this insecure; sending the json directly to the app, without any server side validation, but a simple json.unmarshal?
PS:I come from a PHP+MySQL web apps background, where accepting client input for the DB without escaping it was a very dangerous thing to do.

A: In principle, yes it is bad, however you would need to decide whether the risks outweigh the cost in your specific case as the work required can be quite extensive.
No matter the language used employing the model 'Never trust the client' tends to provide the best security. In this model you assume all requests are malicious therefore should be validated and sanitized. This allows you to gain confidence in the data you are storing, and in principle protects against changing requirements. For example; if you are presenting this stored data back to the users then you can have some trust that nothing malicious is stored, however this should not mean output encoding is not also used.
The final point to consider is how you are accessing the DB and creating the inserts. Assuming this is a SQL DB then ensure your query uses named parameters rather than string concatenation.


text:
Q: Encode URL in JavaScript How do you safely encode a URL using JavaScript such that it can be put into a GET string?
var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;

I assume that you need to encode the myUrl variable on that second line?

A: The best answer is to use encodeURIComponent on values in the query string (and nowhere else).
However, I find that many APIs want to replace " " with "+" so I've had to use the following:
const value = encodeURIComponent(value).replace('%20','+');
const url = 'http://example.com?lang=en&key=' + value

escape is implemented differently in different browsers and encodeURI doesn't encode many characters (like # and even /) -- it's made to be used on a full URI/URL without breaking it – which isn't super helpful or secure.
And as @Jochem points out below, you may want to use encodeURIComponent() on a (each) folder name, but for whatever reason these APIs don't seem to want + in folder names so plain old encodeURIComponent works great.
Example:
const escapedValue = encodeURIComponent(value).replace('%20','+');
const escapedFolder = encodeURIComponent('My Folder'); // no replace
const url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`;

A: To prevent double encoding, it's a good idea to decode the URL before encoding (if you are dealing with user entered URLs for example, which might be already encoded).
Let's say we have abc%20xyz 123 as input (one space is already encoded):
encodeURI("abc%20xyz 123")            //   Wrong: "abc%2520xyz%20123"
encodeURI(decodeURI("abc%20xyz 123")) // Correct: "abc%20xyz%20123"

A: A similar kind of thing I tried with normal JavaScript:
function fixedEncodeURIComponent(str){
    return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

A: You should not use encodeURIComponent() directly.
Take a look at RFC3986: Uniform Resource Identifier (URI): Generic Syntax

sub-delims  = "!" / "$" / "&" / "'" / "(" / ")"
/ "*" / "+" / "," / ";" / "="
The purpose of reserved characters is to provide a set of delimiting characters that are distinguishable from other data within a URI.

These reserved characters from the URI definition in RFC3986 ARE NOT escaped by encodeURIComponent().
MDN Web Docs: encodeURIComponent()

To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

Use the MDN Web Docs function...
function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

A: I would suggest to use the qs npm package:
qs.stringify({a:"1=2", b:"Test 1"}); // gets a=1%3D2&b=Test+1

It is easier to use with a JavaScript object and it gives you the proper URL encoding for all parameters.
If you are using jQuery, I would go for the $.param method. It URL encodes an object, mapping fields to values, which is easier to read than calling an escape method on each value.
$.param({a:"1=2", b:"Test 1"}) // Gets a=1%3D2&b=Test+1

A: Performance
Today (2020.06.12) I performed a speed test for chosen solutions on macOS v10.13.6 (High Sierra) on browsers Chrome 83.0, Safari 13.1, and Firefox 77.0. This results can be useful for massive URLs encoding.
Conclusions

*

*encodeURI (B) seems to be fastest, but it is not recommended for URLs

*escape (A) is a fast cross-browser solution

*solution F recommended by MDN is medium fast

*solution D is slowest

Details
For solutions
A
B
C
D
E
F
I perform two tests

*

*for short URL - 50 characters - you can run it HERE

*for long URL - 1M characters - you can run it HERE

function A(url) {
    return escape(url);
}

function B(url) {
    return encodeURI(url);
}

function C(url) {
    return encodeURIComponent(url);
}

function D(url) {
    return new URLSearchParams({url}).toString();
}

function E(url){
     return encodeURIComponent(url).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

function F(url) {
  return encodeURIComponent(url).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

// ----------
// TEST
// ----------

var myUrl = "http://example.com/index.html?param=1&anotherParam=2";

[A,B,C,D,E,F]
  .forEach(f=> console.log(`${f.name} ?url=${f(myUrl).replace(/^url=/,'')}`));
This snippet only presents code of chosen solutions

Example results for Chrome

A: Check out the built-in function encodeURIComponent(str) and encodeURI(str).
In your case, this should work:
var myOtherUrl =
       "http://example.com/index.html?url=" + encodeURIComponent(myUrl);

A: Modern solution (2021)
Since the other answers were written, the URLSearchParams API has been introduced. It can be used like this:
const queryParams = { param1: 'value1', param2: 'value2' }
const queryString = new URLSearchParams(queryParams).toString()
// 'param1=value1&param2=value2'

It also encodes non-URL characters.
For your specific example, you would use it like this:

const myUrl = "http://example.com/index.html?param=1&anotherParam=2";
const myOtherUrl = new URL("http://example.com/index.html");
myOtherUrl.search = new URLSearchParams({url: myUrl});
console.log(myOtherUrl.toString());

This solution is also mentioned here and here.

A: Nothing worked for me. All I was seeing was the HTML of the login page, coming back to the client side with code 200. (302 at first but the same Ajax request loading login page inside another Ajax request, which was supposed to be a redirect rather than loading plain text of the login page).
In the login controller, I added this line:
Response.Headers["land"] = "login";

And in the global Ajax handler, I did this:
$(function () {
    var $document = $(document);
    $document.ajaxSuccess(function (e, response, request) {
        var land = response.getResponseHeader('land');
        var redrUrl = '/login?ReturnUrl=' + encodeURIComponent(window.location);
        if(land) {
            if (land.toString() === 'login') {
                window.location = redrUrl;
            }
        }
    });
});

Now I don't have any issue, and it works like a charm.

A: Encode URL String
var url = $(location).attr('href'); // Get the current URL

// Or
var url = 'folder/index.html?param=#23dd&noob=yes'; // Or specify one

var encodedUrl = encodeURIComponent(url);
console.log(encodedUrl);
// Outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes

For more information, go to, jQuery Encode/Decode URL String.

A: Here is a live demo of encodeURIComponent() and decodeURIComponent() JavaScript built-in functions:
<!DOCTYPE html>

      <textarea id="txt1">Some text to decode
      </textarea>

      <input type="button" id="btnencode" value="Encode" onClick="encode()"/>

      <textarea id="txt2">
      </textarea>

      <textarea id="txt3">U29tZSB0ZXh0IHRvIGRlY29kZQ==
      </textarea>

      <input type="button" id="btndecode" value="Decode" onClick="decode()"/>

      <textarea id="txt4">
      </textarea>

A: Stick with encodeURIComponent(). The function encodeURI() does not bother to encode many characters that have semantic importance in URLs (e.g. "#", "?", and "&"). escape() is deprecated, and does not bother to encode "+" characters, which will be interpreted as encoded spaces on the server (and, as pointed out by others here, does not properly URL-encode non-ASCII characters).
There is a nice explanation of the difference between encodeURI() and encodeURIComponent() elsewhere. If you want to encode something so that it can safely be included as a component of a URI (e.g. as a query string parameter), you want to use encodeURIComponent().

A: You can use ESAPI library and encode your URL using the below function. The function ensures that '/'s are not lost to encoding while the remainder of the text contents are encoded:
function encodeUrl(url)
{
    String arr[] = url.split("/");
    String encodedUrl = "";
    for(int i = 0; i<arr.length; i++)
    {
        encodedUrl = encodedUrl + ESAPI.encoder().encodeForHTML(ESAPI.encoder().encodeForURL(arr[i]));
        if(i<arr.length-1) encodedUrl = encodedUrl + "/";
    }
    return url;
}

A: Use fixedEncodeURIComponent function to strictly comply with RFC 3986:
function fixedEncodeURIComponent(str) {
  return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
    return '%' + c.charCodeAt(0).toString(16);
  });
}

A: You have three options:

*

*escape() will not encode: @*/+

*encodeURI() will not encode: ~!@#$&*()=:/,;?+'

*encodeURIComponent() will not encode: ~!*()'
But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.
See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.

A: encodeURIComponent() is the way to go.
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);

But you should keep in mind that there are small differences from PHP version urlencode() and as @CMS mentioned, it will not encode every character. Guys at http://phpjs.org/functions/urlencode/ made JavaScript equivalent to phpencode():
function urlencode(str) {
  str = (str + '').toString();

  // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
  // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
  return encodeURIComponent(str)
    .replace('!', '%21')
    .replace('\'', '%27')
    .replace('(', '%28')
    .replace(')', '%29')
    .replace('*', '%2A')
    .replace('%20', '+');
}

A: I think now in 2022 to be really safe, you should always consider constructing your URLs using the URL() interface. It'll do most of the job for you. So coming to your code,

const baseURL = 'http://example.com/index.html';

const myUrl = new URL(baseURL);
myUrl.searchParams.append('param', '1');
myUrl.searchParams.append('anotherParam', '2');

const myOtherUrl = new URL(baseURL);
myOtherUrl.searchParams.append('url', myUrl.href);

console.log(myUrl.href);
// Outputs: http://example.com/index.html?param=1&anotherParam=2
console.log(myOtherUrl.href);
// Outputs: http://example.com/index.html?url=http%3A%2F%2Fexample.com%2Findex.html%3Fparam%3D1%26anotherParam%3D2
console.log(myOtherUrl.searchParams.get('url'));
// Outputs: http://example.com/index.html?param=1&anotherParam=2

Or...
const params = new URLSearchParams(myOtherUrl.search);

console.log(params.get('url'));
// Outputs: http://example.com/index.html?param=1&anotherParam=2

Something like this is assured not to fail.

A: To encode a URL, as has been said before, you have two functions:
encodeURI()

and
encodeURIComponent()

The reason both exist is that the first preserves the URL with the risk of leaving too many things unescaped, while the second encodes everything needed.
With the first, you could copy the newly escaped URL into address bar (for example) and it would work.  However your unescaped '&'s would interfere with field delimiters, the '='s would interfere with field names and values, and the '+'s would look like spaces.  But for simple data when you want to preserve the URL nature of what you are escaping, this works.
The second is everything you need to do to make sure nothing in your string interfers with a URL.  It leaves various unimportant characters unescaped so that the URL remains as human readable as possible without interference.  A URL encoded this way will no longer work as a URL without unescaping it.
So if you can take the time, you always want to use encodeURIComponent() -- before adding on name/value pairs encode both the name and the value using this function before adding it to the query string.
I'm having a tough time coming up with reasons to use the encodeURI() -- I'll leave that to the smarter people.

A: What is URL encoding:
A URL should be encoded when there are special characters located inside the URL. For example:

console.log(encodeURIComponent('?notEncoded=&+'));

We can observe in this example that all characters except the string notEncoded are encoded with % signs. URL encoding is also known as percentage encoding because it escapes all special characters with a %. Then after this % sign every special character has a unique code
Why do we need URL encoding:
Certain characters have a special value in a URL string. For example, the ? character denotes the beginning of a query string. In order to successfully locate a resource on the web, it is necessary to distinguish between when a character is meant as a part of string or part of the URL structure.
How can we achieve URL encoding in JavaScript:
JavaScript offers a bunch of built-in utility functions which we can use to easily encode URLs. These are two convenient options:

*

*encodeURIComponent(): Takes a component of a URI as an argument and returns the encoded URI string.

*encodeURI():  Takes a  URI as an argument and returns the encoded URI string.

Example and caveats:
Be aware of not passing in the whole URL (including scheme, e.g., https://) into encodeURIComponent(). This can actually transform it into a not functional URL. For example:

// for a whole URI don't use encodeURIComponent it will transform
// the / characters and the URL won't fucntion properly
console.log(encodeURIComponent("http://www.random.com/specials&char.html"));

// instead use encodeURI for whole URL's
console.log(encodeURI("http://www.random.com/specials&char.html"));

We can observe f we put the whole URL in encodeURIComponent that the forward slashes (/) are also converted to special characters. This will cause the URL to not function properly anymore.
Therefore (as the name implies) use:

*

*encodeURIComponent on a certain part of a URL which you want to encode.

*encodeURI on a whole URL which you want to encode.

A: Don't forget the /g flag to replace all encoded ' '
var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl).replace(/%20/g,'+');

A: I always use this to encode stuff for URLs. This is completely safe because it will encode every single character even if it doesn't have to be encoded.
function urlEncode(text) {
    let encoded = '';
    for (let char of text) {
        encoded += '%' + char.charCodeAt(0).toString(16);
    }
    return encoded;
}

A:

let name = `bbb`;
params = `name=${name}`;
var myOtherUrl = `http://example.com/index.html?url=${encodeURIComponent(params)}`;
console.log(myOtherUrl);

Use backtick now in ES6 to encode urls
try this - https://bbbootstrap.com/code/encode-url-javascript-26885283


text:
Q: MVC - Loading screen / disable button before and after downloading a file So i have a button to download a csv file. The button simple does:
$("#btnExportToContactList").click(function (e) {
    window.location.href = '/Home/ExportList';
});

My action simply returns a
File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", filename);

Everything is working fine. Now since I'm building a csv when pressing the button and since the process can take some time, I want to put up a loading screen or simply disable the button while they wait. My problem is how to disable/enable the button?
I have tried the following but it doesn't work because the browser is being redirected to another page and it will stop executing my Javascript.
$("#btnExportToContactList").click(function (e) {
    $("#btnExportToContactList").attr("disabled", true);
    window.location.href = '/Home/ExportList';
    $("#btnExportToContactList").attr("disabled", false);
});

but its not working. Anybody have a solution for this?

A: You can set disabled property to false each time page is ready or loaded.
$(function(){
   $("#btnExportToContactList").attr("disabled", false);

  $("#btnExportToContactList").click(function (e) {
    $("#btnExportToContactList").attr("disabled", true);
    window.location.href = '/Home/ExportList';
  });
});

Update: If above isnt working, you can try workaround like this. Rather than calling window.location.href you can call action of controller using ajax request and returning json resullt containing url of file created on server  and then on success of ajax call you can download this file using some javscript code and then changing desired element's disabled property.
Check this for more


text:
Q: Getting error array to string conversation I want to insert multiple data using add button and the data of dynamically added button doesn't inserted sometimes get 0 and sometimes just no change...
include 'config.php';

if(isset($_POST['submit1'])) {
    $bill_no = isset($_REQUEST['bill_no']) ? $_REQUEST['bill_no'] : '';
    $bill_date = isset($_REQUEST['bill_date']) ? $_REQUEST['bill_date'] : '';

    $proselect = isset($_REQUEST['proselect']) ? $_REQUEST['proselect'] : '';

    $price = isset($_REQUEST['price']) ? $_REQUEST['price'] : '';

    $addItem = isset($_REQUEST['Add1']) ? $_REQUEST['Add1'] : '';
    $check  = "SELECT bill_no from bill_p where bill_no = '$bill_no'";
    $result = mysqli_query($conn,$check);
    $count1 = mysqli_fetch_array($result);

    if ($count1 > 0) {
        echo '<script text="javascript/text">alert("Bill Exist")</script';
    }
    else
    {
        $count = count($REQUEST['price']);

        for($i = 0; $i <= $count; $i++)
        {
            $bill_no = $REQUEST['bill_no'][$i];
            $bill_date = $REQUEST['bill_date'][$i];
            $proselect = $REQUEST['proselect'][$i];
            $price = $REQUEST['price'][$i];

            $query = "INSERT INTO bill_p(p_id,bill_no,b_date,amount) VALUES ('$proselect','$bill_no','$bill_date','$price')";

            $exe = mysqli_query($conn, $query);


text:
Q: How can I display the contents of a folder in a JTree? What I am trying to accomplish is to take a pre-defined file path and display every folder and file within that file path inside of a JTree.
Simply;
Folder1
Folder2
    Folder3a
        ->File3a
    ->File2a
    ->File2b

What I have so far is the following:
public class GUI extends JPanel {

public GUI() {

    super(new GridLayout(1, 2, 20, 0));
    setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10));

    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (final Exception ignored) {
    }

    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

    frame.setContentPane(this);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

}

I would love some direction on how to proceed. Everything this far has been a compilation of a ton of readings I have gone through, and I'm not really sure how to accomplish what I want.

A: public class FileTree extends JPanel {
/** Construct a FileTree */
public FileTree(File dir) {
setLayout(new BorderLayout());

// Make a tree list with all the nodes, and make it a JTree
JTree tree = new JTree(addNodes(null, dir));

// Add a listener
tree.addTreeSelectionListener(new TreeSelectionListener() {
  public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) e
        .getPath().getLastPathComponent();
    System.out.println("You selected " + node);
  }
});

// Lastly, put the JTree into a JScrollPane.
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
add(BorderLayout.CENTER, scrollpane);
 }

 /** Add nodes from under "dir" into curTop. Highly recursive. */
 DefaultMutableTreeNode addNodes(DefaultMutableTreeNode curTop, File dir) {
 String curPath = dir.getPath();
DefaultMutableTreeNode curDir = new DefaultMutableTreeNode(curPath);
if (curTop != null) { // should only be null at root
  curTop.add(curDir);
}
Vector ol = new Vector();
String[] tmp = dir.list();
for (int i = 0; i < tmp.length; i++)
  ol.addElement(tmp[i]);
Collections.sort(ol, String.CASE_INSENSITIVE_ORDER);
File f;
Vector files = new Vector();
// Make two passes, one for Dirs and one for Files. This is #1.
  for (int i = 0; i < ol.size(); i++) {
  String thisObject = (String) ol.elementAt(i);
    String newPath;
    if (curPath.equals("."))
    newPath = thisObject;
  else
    newPath = curPath + File.separator + thisObject;
  if ((f = new File(newPath)).isDirectory())
    addNodes(curDir, f);
  else
    files.addElement(thisObject);
}
// Pass two: for files.
for (int fnum = 0; fnum < files.size(); fnum++)
  curDir.add(new DefaultMutableTreeNode(files.elementAt(fnum)));
return curDir;
}

 public Dimension getMinimumSize() {
   return new Dimension(200, 400);
 }

 public Dimension getPreferredSize() {
  return new Dimension(200, 400);
}

/** Main: make a Frame, add a FileTree */
 public static void main(String[] av) {

JFrame frame = new JFrame("FileTree");
frame.setForeground(Color.black);
frame.setBackground(Color.lightGray);
Container cp = frame.getContentPane();

if (av.length == 0) {
  cp.add(new FileTree(new File(".")));
} else {
  cp.setLayout(new BoxLayout(cp, BoxLayout.X_AXIS));
  for (int i = 0; i < av.length; i++)
    cp.add(new FileTree(new File(av[i])));
}

frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


text:
Q: Detecting CPU architecture (32bit / 64bit ) in scons? Are there any 'standard' plugins for detecting the CPU architecture in scons?
BTW, this question was asked already here in a more general form... just wondering if anyone has already taken the time to incorporate this information into scons.

A: Using i386 is rather compiler dependant, and won't detect non x86 32 bits archs. Assuming the python interpreter used by scons runs on the CPU you are interested in (not always the case - think cross compilation), you can just use python itself.
import platform
print platform.machine()
print platform.architecture()

If you need something more sophisticated, then maybe you will have to write your own configure function - but it may be better to deal with it in your code directly.

A: Something like this?
env = Environment()
conf = Configure(env)
if conf.CheckDeclaration("__i386__"):
    conf.Define("MY_ARCH", "blahblablah")
env = conf.Finish()


text:
Q: Why STL implementation is so unreadable? How C++ could have been improved here? For instance why does most members in STL implementation have _M_ or _ or __ prefix?
Why there is so much boilerplate code ?
What features C++ is lacking that would allow make vector (for instance) implementation clear and more concise?

A: Lots of STL implementations also include checking for debug builds, such as verifying that two iterators are from the same container when comparing them, and watching for iterators going out of bounds.  This involves fairly complex code to track the container and validity of every iterator created, but is invaluable for finding bugs.  This code is also all interwoven with the standard release code with #ifdefs - even in the STL algorithms.  So it's never going to be as clear as their most basic operation.  Sites like this one show the most basic functionality of STL algorithms, stating their functionality is "equivalent to" the code they show.  You won't see that in your header files though.

A: Implementations use names starting with an underscore followed by an uppercase letter or two underscores to avoid conflicts with user-defined macros. Such names are reserved in C++.
For example, one could define a macro called Type and then #include <vector>. If vector implementations used Type as a template parameter name, it would break.
However, one is not allowed to define macros called _Type (or __type, type__ etc.). Therefore, vector can safely use such names.

A: In addition to the good reasons robson and AshleysBrain have already given, one reason that C++ standard library implementations have such terse names and compact code is that virtually every C++ program (compilation unit, really) includes a large number of the standard library headers, and they are thus repeatedly recompiled (remember that they're largely inlined and template-based, whereas the C standard library headers only contain a handful of function declarations).  A standard library written to "industry standard" style guidelines would take longer to compile and thus lead to the perception that a particular compiler was "slow".  By minimizing whitespace and using short identifier names, the lexer and parser have less work to do, and the whole compilation process completes a little bit faster.
Another reason worth mentioning is that many standard library implementations (e.g. Dinkumware, Rogue Wave (old), etc.) can be used with several different compilers with widely different standards compliance and quirks.  There's frequently a lot of macro hackery aimed at satisfying each supported platform.


text:
Q: Angular 6 : Renderer 2 - rendering custom components using Renderer2 is not working I have one custom angular component <sample-cmp></sample-cmp>
Its content is not rendering in the browser, when it is appended into DOM via Renderer2.
Please find the following code that I am using to render the custom angular 6 component via Renderer2
@ViewChild('formParent')
public elmRef: ElementRef;

constructor(public renderer: Renderer2) {

}

const domElm = renderer.createElement('sample-cmp');

renderer.appendChild(elmRef.nativeElement, domElm);

The above code will generate the below tag in UI.
<sample-cmp></sample-cmp>

But this 'sample-cmp' template contains 'Hello World' text and that is not rendered.
My issue is, When we render one custom component using Renderer 2 the content in the custom components template is not getting rendered.


text:
Q: Kubernetes scaling pods using custom algorithm Our cloud application consists of 3 tightly coupled Docker containers, Nginx, Web and Mongo. Currently we run these containers on a single machine. However as our users are increasing we are looking for a solution to scale. Using Kubernetes we would form a multi container pod. If we are to replicate we need to replicate all 3 containers as a unit. Our cloud application is consumed by mobile app users. Our app can only handle approx 30000 users per Worker node and we intend to place a single pod on a single worker node. Once a mobile device is connected to worker node it must continue to only use that machine ( unique IP address )
We plan on using Kubernetes to manage the containers. Load balancing doesn't work for our use case as a mobile device needs to be tied to a single machine once assigned and each Pod works independently with its own persistent volume.  However we need a way of spinning up new Pods on worker nodes if the number of users goes over 30000 and so on.
The idea is we have some sort of custom scheduler which assigns a mobile device a Worker Node ( domain/ IPaddress) depending on the number of users on that node.
Is Kubernetes a good fit for this design and how could we implement a custom pod scale algorithm.
Thanks

A: Piggy-Backing on the answer of Jonah Benton:
While this is technically possible - your problem is not with Kubernetes it's with your Application! Let me point you the problem:

Our cloud application consists of 3 tightly coupled Docker containers, Nginx, Web, and Mongo.

Here is your first problem: Is you can only deploy these three containers together and not independently - you cannot scale one or the other!
While MongoDB can be scaled to insane loads - if it's bundled with your web server and web application it won't be able to...
So the first step for you is to break up these three components so they can be managed independently of each other. Next:

Currently we run these containers on a single machine.

While not strictly a problem - I have serious doubt's what it would mean to scale your application and what the challenges that come with scalability!

Once a mobile device is connected to worker node it must continue to only use that machine ( unique IP address )

Now, this IS a problem. You're looking to run an application on Kubernetes but I do not think you understand the consequences of doing that: Kubernetes orchestrates your resources. This means it will move pods (by killing and recreating) between nodes (and if necessary to the same node). It does this fully autonomous (which is awesome and gives you a good night sleep) If you're relying on clients sticking to a single nodes IP, you're going to get up in the middle of the night because Kubernetes tried to correct for a node failure and moved your pod which is now gone and your users can't connect anymore. You need to leverage the load-balancing features (services) in Kubernetes. Only they are able to handle the dynamic changes that happen in Kubernetes clusters.

Using Kubernetes we would form a multi container pod.

And we have another winner - No! You're trying to treat Kubernetes as if it were your on-premise infrastructure! If you keep doing so you're going to fail and curse Kubernetes in the process!
Now that I told you some of the things you're thinking wrong - what a person would I be if I did not offer some advice on how to make this work:
In Kubernetes your three applications should not run in one pod! They should run in separate pods:

*

*your webservers work should be done by Ingress and since you're already familiar with nginx, this is probably the ingress you are looking for!

*Your web application should be a simple Deployment and be exposed to ingress through a Service

*your database should be a separate deployment which you can either do manually through a statefullset or (more advanced) through an operator and also exposed to the web application trough a Service

Feel free to ask if you have any more questions!

A: Building a custom scheduler and running multiple schedulers at the same time is supported:
https://kubernetes.io/docs/tasks/administer-cluster/configure-multiple-schedulers/
That said, to the question of whether kubernetes is a good fit for this design- my answer is: not really.
K8s can be difficult to operate, with the payoff being the level of automation and resiliency that it provides out of the box for whole classes of workloads.
This workload is not one of those. In order to gain any benefit you would have to write a scheduler to handle the edge failure and error cases this application has (what happens when you lose a node for a short period of time...) in a way that makes sense for k8s. And you would have to come up to speed with normal k8s operations.
With the information provided, hard pressed to see why one would use k8s for this workload over just running docker on some VMs and scripting some of the automation.


text:
Q: Integration of django authentication system with Facebook API I am integrating Django authentication and login system with Facebook Login API. The problem is that once Facebook username will be the same as existing in my project's database so the only solution to the problem is to catch Facebook username and add numbers or something to the string to make it unique ? Is it correct ? How is it normally handled ?

A: You have several options, I'm sure I won't think of them all.

*

*If you have an unique constraint on the field for 'username', you can add numbers to remain unique.

*Remove the unique constraint on the 'username' field. Add a boolean to the user table, to identify users logging in with facebook. You are probably able to determine when a user logins with a facebook account. After logging in you can crossmatch the information with the user you have in the database. Facebook probably has some kind of 'unique' data about a specific user which you can place in your database to differentiate between unique users with the same name.


text:
Q: Low-pA TIA Design and Noise Floor I am currently an EE/Physics undergrad doing scanning tunneling microscopy research at my local university. For future experiments, it would be helpful to employ a higher gain preamp than we currently have, and given that other groups have built them, I was looking into doing the same.
We're hoping to measure current signals from about 0.05-10pA from DC to a few kHz (though more bandwidth with a low noise floor is certainly welcome), requiring a transimpedance gain on the order of 0.1-1 teraohm. This certainly seems possible as it was done at the University of Florence (circuit below), as well as in a number of other papers. A few other topologies are presented here.

simulate this circuit – Schematic created using CircuitLab
I was able to perform a noise analysis of the circuit in LTspice, but I'm a little uncertain of how to translate the spectrum of uV/rtHz vs frequency into a average value for noise floor as it seems to blow up at low frequency with 1/f noise.
Additionally, the LTC6268 seems to have a very low input bias and reasonable noise characteristics, so I was considering using it in place of the above for the first stage.

A: Looking at the low frequency voltage noise (0.1 to 10 Hz) from the AD549J and the LTC6268 I would say the AD549 is superior at 4 uVp-p. The LTC6268 has a noise of 13 uVp-p. So this is something to be wary of if you are considering a change.
For the input current noise at low frequencies, nothing appears to be stated that is much below 10 MHz for the LTC6268 and that would be a concern. The AD549 is 0.7 fA RMS from 0.1 to 10 Hz by comparison.
I think the LTC6268 is better suited for high speed photodiode applications and not low frequency applications like ion beam measurement.

A: 1/f Noise is a real problem in low frequency applications, at around 10Hz it increases until around 0.01Hz or 0.001Hz and accounts for the majority of noise in amplifiers and electronics.
This is tough because it's in your frequency of interest and it can't be filtered out.
If 1/f noise is a problem, then use a chopping amplifier. However, they may not have the open loop gain characteristics and input bias current characteristics you need. I don't think any from the major manufacturers have an input bias current characteristic that meets your low requirements.
However, There is a company that makes high gain low input impedance low noise amplifiers called Nanovolt EM Amplifiers with no 1/f noise and TΩ input impedance. But they are expensive.


text:
Q: How can I reference a C# class from a different file? I'm new to programming, and am trying to learn C# using a Mono compiler for BBEdit's "TextWrangler" program (something like NotePad++, but for Mac). My question, however, is pretty straightforward: I am trying to code a very simple program in C# that uses a class from a different .cs file.
And I am struggling with it. If the classes were in the same .cs file, I have no issues; otherwise, the bash terminal keeps giving me errors. Here's my code:
Program.cs:
//  Client class, where Main method calls the Car method

using System;
using Auto;

namespace Auto
{
    class Program
    {
        public static void Main(string[] args)
        {
            //Instantiate car class
            Car car = new Car("Toyota", "Corolla", "Sedan", 2014, 25000);
            Console.WriteLine(car.Maintenance());
            Console.Read();
        }
    }
}

Car.cs:
//  "Car" class (does NOT include the Main method)

using System;

namespace Auto
{
    public class Car
    {
        //Create various attributes for Car Class with getters and setters
        public string Make { get; set; }
        public int Year { get; set; }
        public string Model { get; set; }
        public string Type { get; set; }
        public int Millage { get; set; }
        public DateTime PurchaseDate { get; set; }

        //Constructor to instantiate Car object that pass all the necessary attribute values
        public Car(string make, string model, string _type, int year, int millage)
        {
            Make = make;
            Model = model;
            Type = _type;
            Millage = millage;
        }

        //Maintenance method will check all the inspection that the mechanic has to do     based on the millage of the car
        public string Maintenance()
        {
            int index = 1;
            string maintenanceList = string.Empty;
            if (Millage > 5000)
                maintenanceList += (index++).ToString() + ". Oil Change " +Environment.NewLine;
            if (Millage > 10000)
            {
                maintenanceList += (index++).ToString() + ". Check Brakes " +     Environment.NewLine;
                maintenanceList += (index++).ToString() + ". Rotate Tires " + Environment.NewLine;
                maintenanceList += (index++).ToString() + ". Lube Hinges, Lock, and Latches" + Environment.NewLine;
            }

            if (Millage > 15000)
                maintenanceList += (index++).ToString() + ". Replace air Cleaner element" + Environment.NewLine;

            if (Millage > 30000)
                maintenanceList += (index++).ToString() + ". Replace Dust and Pollen Filter" + Environment.NewLine;

            return maintenanceList;
        }
    }
}

So there you go. The code's simpler than it seems- but whenever I try to compile these files, both saved under the same folder in my Finder, I get these results:
Program.cs:
Compilation failed: 1 error(s), 0 warnings

Program.cs(14,13): error CS0246: The type or namespace name `Car' could not be found.      Are you missing an assembly reference?
Program.cs(15,31): error CS0841: A local variable `car' cannot be used before it is declared

Car.cs:
error CS5001: Program `Car.exe' does not contain a static `Main' method suitable for an entry point

So yeah, I'm stuck. I've poured over many sources on introductory class building in C#, but my luck has yielded nothing. Any help would be very much appreciated.

A: Your errors in the "Program.cs" file are not relevant here. They will disappear as soon as you've fixed the one in the "Car.cs" file.

*

*there is an error in "Car.cs"

*it does not compile

*there is no DLL generated

*it cannot be found when compiling the "Program.cs" file

Fix one, the other will be fixed too.
The question remains: how to fix the error in "Car.cs". This is certainly a problem in the file attributes in your project file.
Some possible answers can be found here be most certainly here when pixaloop wrote:

Change the Output Type under the Project > Properties to that of a "Class Library". By default, this setting may have been set to a "Console Application".

As a side note, you should try MonoDevelop for your C# development in MacOS. It will ease your project/files/dll management.


text:
Q: Android Java - Date EditText validation is not working I replicate how to show datepicker popup from edittext from a question here(i use the accepted answer):
Datepicker: How to popup datepicker when click on edittext
but when im trying to validate if the EditText is not empty, it didnt work. Here is my attempt:
final Calendar myCalendar= Calendar.getInstance();
EditText tStart;
EditText tEnd;
TextInputLayout desc;
Editable tDesc;
Button btnSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_timeoff);

    tStart = (EditText) findViewById(R.id.startDate);
    tEnd = (EditText) findViewById(R.id.endDate);
    Button btnSubmit = (Button) findViewById(R.id.btnSubmit);

    DatePickerDialog.OnDateSetListener dateStart =new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int day) {
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH,month);
            myCalendar.set(Calendar.DAY_OF_MONTH,day);
            startupdateLabel();
        }
    };

    DatePickerDialog.OnDateSetListener dateEnd =new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int month, int day) {
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH,month);
            myCalendar.set(Calendar.DAY_OF_MONTH,day);
            endupdateLabel();
        }
    };

    tStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            new DatePickerDialog(TimeoffActivity.this,dateStart,myCalendar.get(Calendar.YEAR),myCalendar.get(Calendar.MONTH),myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

    tEnd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new DatePickerDialog(TimeoffActivity.this,dateEnd,myCalendar.get(Calendar.YEAR),myCalendar.get(Calendar.MONTH),myCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(tStart.toString().isEmpty() || TextUtils.isEmpty(tEnd.toString()) ){
                Toast.makeText(TimeoffActivity.this, "Please fill all field before submitting", Toast.LENGTH_LONG).show();
            } else{
                saveTimeoffRequest();
            }
        }
    });
}

I tried using 2 way but still didnt work:
tStart.toString().isEmpty() || TextUtils.isEmpty(tEnd.toString())

how to validate those 2 date EditText if its not empty?
thanks in advance.

A: Try This
Change
btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(tStart.toString().isEmpty() || TextUtils.isEmpty(tEnd.toString()) ){
                Toast.makeText(TimeoffActivity.this, "Please fill all field before submitting", Toast.LENGTH_LONG).show();
            } else{
                saveTimeoffRequest();
            }
        }
    });

To
btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(tStart.getText().toString().trim().length() <= 0 || tEnd.getText().toString().trim().length() <= 0){
                    Toast.makeText(MainActivity.this, "Please fill all field before submitting", Toast.LENGTH_LONG).show();
                } else{
                    Log.e("check", "do something....");
                }
            }
        });


text:
Q: Is it possible to connect a reed switch to two separate arduino boards? I'd like to add a bit of redundancy to a security system. I use reed switches for doors. How can i safely connect the same reed switch to two separate arduino boards? (the boards are not connected between them in any way, they use separate adapters).

A:
... How can i safely connect the same reed switch to two separate Arduino boards?
  (the boards are not connected between them in any way, they use separate adapters).

If they are not electrically connected and if you wish to maintain the isolation you could use an optoisolator or similar. The reed switch could provide current via the LED in the opto isolator or voltage switched by the reed switch could apply voltage to a resistor connected to the LED. A reed could drive 2 x LEDs in two optoisolators this way this way if it had its own power supply or using the power supply from one Arduino.
Placing the LED from an optoisolator in series with the reed switch adds a reliability hazrad - if the LED fails then the input fails on both Arduinos. Placing a few diodes or a zener across the LED such that Vdiode_string is slightly higher than V_LED_on will protect against LED failure as long as there is enough drive voltage.
There are other isolating means available but an opt-oisolator is about as easy and cheap as any.
If you do not wish to maintain isolation then by connecting the two systems' grounds together you could share a sensor. But, isolated systems seem with having in the context. One mode of attacking a security system is to use a TASER or electric cattle prod or similar. This tends to be poorly tolerated [tm] in most cases. If you wish half your system to live long enough to report the other half's death when under TASER attack you will need to rate the cross coupling isolators accordingly. One method I've heard of is to use a dummy video camera which is presented as first line target. It's health is monitored by the system proper. It's role is to act as a honey-pot TASER-attack sensor. [I won't tell you what country I heard about this from :-) ].


text:
Q: Размер APK файла в Android Studio намного больше, чем в AIDE. Как уменьшить размер пакета? Один и тот же код. Простейшее приложение с двумя TextView и Button и Activity классом.
Собираю release в Android Studio, в AIDE и Codenvy (Eclipse Che). Proguard minify включен.
В итоге в AIDE и Codenvy размер APK файла 15 - 30 Кб, а в Android Studio - 1.5 Мб.
После установки соответственно 56 Кб и 3-4 Мб.
Вопрос: возможно ли и как уменьшить размер APK компилируемого с Android Studio?


text:
Q: Difference between sw600dp and w600dp? Please elaborate on the difference between sw<N>dp and w<N>dp, in a simple way. I have studied the complete documentation of screen sizes but am confused between these two qualifiers sw<> and w<>.

A: Android device screens are rectangles. Rectangles have two sides, one shorter than the other. Let's call the short one A and the long one B.
-swNNNdp indicates "use these resources if A is greater than or equal to NNN dp in length"
-wNNNdp indicates "use these resources if the width of the device, as presently held, is greater than or equal to NNN dp"
When the user rotates the device between portrait and landscape, the width will change (to be A or B), but A (the shortest width) is always the same.

A: Please take a look at Screen Support
According to the documentations :
SW : The fundamental size of a screen, as indicated by the shortest dimension of the available screen area. Specifically, the device's smallestWidth is the shortest of the screen's available height and width (you may also think of it as the "smallest possible width" for the screen). You can use this qualifier to ensure that, regardless of the screen's current orientation, your application's has at least  dps of width available for it UI.
while W : Specifies a minimum available width in dp units at which the resources should be used—defined by the  value. The system's corresponding value for the width changes when the screen's orientation switches between landscape and portrait to reflect the current actual width that's available for your UI.
In my words :
SW : minimum distance between screen edges in dps your layout will run on, so if you use layout-sw600dp/ folder then all layouts inside it will only work on devices that has at least 600dp (width or height)
W : means your layout will work on any device with n dp width regardless of the height or maybe the device currently in landscape mode (in this case w would refer to the height .. since orientation differs between landscape and portrait)


text:
Q: How to read files from HDFS using Spark? I have built a recommendation system using Apache Spark with datasets stored locally in my project folder, now i need to access these files from HDFS.
How can i read files from HDFS using Spark ?
This is how i initialize my Spark session:
SparkContext context = new SparkContext(new SparkConf().setAppName("spark-ml").setMaster("local")
                .set("fs.default.name", "hdfs://localhost:54310").set("fs.defaultFS", "hdfs://localhost:54310"));
        Configuration conf = context.hadoopConfiguration();
        conf.addResource(new Path("/usr/local/hadoop-3.1.2/etc/hadoop/core-site.xml"));
        conf.addResource(new Path("/usr/local/hadoop-3.1.2/etc/hadoop/hdfs-site.xml"));
        conf.set("fs.hdfs.impl", "org.apache.hadoop.hdfs.DistributedFileSystem");
        conf.set("fs.hdfs.impl", "org.apache.hadoop.fs.LocalFileSystem");
        this.session = SparkSession.builder().sparkContext(context).getOrCreate();
        System.out.println(conf.getRaw("fs.default.name"));
        System.out.println(context.getConf().get("fs.defaultFS"));

All the outputs return hdfs://localhost:54310 which is the correct uri for my HDFS.
When trying to read a file from HDFS:
session.read().option("header", true).option("inferSchema", true).csv("hdfs://localhost:54310/recommendation_system/movies/ratings.csv").cache();

I get this error:
Exception in thread "main" java.lang.IllegalArgumentException: Wrong FS: hdfs://localhost:54310/recommendation_system/movies/ratings.csv, expected: file:///
    at org.apache.hadoop.fs.FileSystem.checkPath(FileSystem.java:730)
    at org.apache.hadoop.fs.RawLocalFileSystem.pathToFile(RawLocalFileSystem.java:86)
    at org.apache.hadoop.fs.RawLocalFileSystem.deprecatedGetFileStatus(RawLocalFileSystem.java:636)
    at org.apache.hadoop.fs.RawLocalFileSystem.getFileLinkStatusInternal(RawLocalFileSystem.java:930)
    at org.apache.hadoop.fs.RawLocalFileSystem.getFileStatus(RawLocalFileSystem.java:631)
    at org.apache.hadoop.fs.FilterFileSystem.getFileStatus(FilterFileSystem.java:454)
    at org.apache.hadoop.fs.Globber.getFileStatus(Globber.java:65)
    at org.apache.hadoop.fs.Globber.doGlob(Globber.java:281)
    at org.apache.hadoop.fs.Globber.glob(Globber.java:149)
    at org.apache.hadoop.fs.FileSystem.globStatus(FileSystem.java:2034)
    at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:257)
    at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:228)
    at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:313)
    at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:204)
    at org.apache.spark.rdd.RDD.$anonfun$partitions$2(RDD.scala:253)
    at scala.Option.getOrElse(Option.scala:138)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:251)
    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:49)
    at org.apache.spark.rdd.RDD.$anonfun$partitions$2(RDD.scala:253)
    at scala.Option.getOrElse(Option.scala:138)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:251)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:2126)
    at org.apache.spark.rdd.RDD.$anonfun$collect$1(RDD.scala:945)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
    at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
    at org.apache.spark.rdd.RDD.collect(RDD.scala:944)
    at org.apache.spark.api.java.JavaRDDLike.collect(JavaRDDLike.scala:361)
    at org.apache.spark.api.java.JavaRDDLike.collect$(JavaRDDLike.scala:360)
    at org.apache.spark.api.java.AbstractJavaRDDLike.collect(JavaRDDLike.scala:45)
    at com.dastamn.sparkml.analytics.SparkManager.<init>(SparkManager.java:36)
    at com.dastamn.sparkml.Main.main(Main.java:22)

What can i do to solve this issue ?

A: A couple of things from the code snippet pasted:
1. When a hadoop property has to be set as part of using SparkConf, it has to be prefixed with spark.hadoop., in this case key fs.default.name needs to be set as spark.hadoop.fs.default.name and likewise for the other properties.
2. The argument to the csv function does not have to tell about the HDFS endpoint, Spark will figure it out from default properties, since it is already set.

session.read().option("header", true).option("inferSchema",
  true).csv("/recommendation_system/movies/ratings.csv").cache();

If the default filesystem properties are not set part of HadoopConfiguration, the complete URI isrequired for Spark/Hadoop to figure out the filesystem to use.
(Also the object name conf is not used)
3. In the above case, looks like Hadoop not was able to find a FileSystem for hdfs:// URI prefix and resorted to use the default filesystem which is local in this case(since it is using RawLocalFileSystemto process the path).
Make sure that hadoop-hdfs.jar is present in class path which has DistributedFileSystem,to instatntiate the FS objects for HDFS.

A: Here's the configuration that solved the problem:
SparkContext context = new SparkContext(new SparkConf().setAppName("spark-ml").setMaster("local[*]")
                .set("spark.hadoop.fs.default.name", "hdfs://localhost:54310").set("spark.hadoop.fs.defaultFS", "hdfs://localhost:54310")
                .set("spark.hadoop.fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName())
                .set("spark.hadoop.fs.hdfs.server", org.apache.hadoop.hdfs.server.namenode.NameNode.class.getName())
                .set("spark.hadoop.conf", org.apache.hadoop.hdfs.HdfsConfiguration.class.getName()));
        this.session = SparkSession.builder().sparkContext(context).getOrCreate();