text:
Q: Only Draw background where Children Views are not? I'm trying to prevent over-draw in my app, and in one of the root views I'd like to detect the location of my children views, and then draw a background for where they are not. From my understanding, clipping would clip outside of the path, but what I'd really like to do is not draw at certain locations on the screen where the children are. Is there a good way to do this?
EDIT:
So I haven't played with canvas in a while, but I'm looking to do something like this:
public class ContainerView extends FrameLayout {

    private final Paint mBackgroundPaint = new Paint();
    private final Path mPath = new Path();

    public ContainerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mBackgroundPaint.setColor(context.getResources().getColor(R.color.default_background));
    }

    @Override protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawPaint(mBackgroundPaint);

        mPath.reset();
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            mPath.addRect(child.getLeft(), child.getTop(), child.getRight(), child.getBottom(),
                    Path.Direction.CCW); // What direction do I want?
        }

        canvas.clipPath(mPath);
    }
}

clipPath just wont do what I want though, I don't think. I think that would clip outside the path, and I need to clip inside the path.

A: You'd probably want to do something like override onLayout and at the end of it:

*

*iterate over all your child views

*check if the child is visible/opaque

*build up a list of each child's position/size

*use that list to do your own background clipping


text:
Q: Why i am unable to mock the activated route? I am trying to mock my activated route but its throwing undefined error at get. I tried tweaking the code and stuffs but in vain. The error it shows is
TypeError: Cannot read properties of undefined (reading 'get')
at ViewEmployeesbyDeptComponent.call [as ngOnInit] (http://localhost:9877/karma_webpack/webpack:/src/app/components/departments/view-employeesby-dept/view-employeesby-dept.component.ts:19:51)
Here is my component.ts:
ngOnInit(): void {
    this.getId = Number(this.ar.snapshot.paramMap.get('id'));
    this.employeeService.getEmployeeById(this.getId).subscribe({
        next:(data) => {
          this.viewEmp = data;

        }

    })
  }

Here is my service.ts:
 getEmployeesByDepartment(id: number): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.baseApiUrl + "/department/" + id + "/employee");
  }

Here is my spec.ts:
describe('ViewEmployeesbyDeptComponent', () => {
  let component: ViewEmployeesbyDeptComponent;
  let fixture: ComponentFixture<ViewEmployeesbyDeptComponent>;
  let mockEmpService: DepartmentsService;
  let httpController: HttpTestingController;
  let mockActivatedRoute;

  let mockEmp: any = [{
    //dummy data
  }];

  beforeEach(async () => {

    mockActivatedRoute = {
      snapshot: { paraMap: { get: () => { return '1' } } }
    };

    await TestBed.configureTestingModule({
      declarations: [ViewEmployeesbyDeptComponent],
      imports: [ReactiveFormsModule, HttpClientTestingModule, HttpClientModule],
      providers: [
        { provide: DepartmentsService, useValue: mockEmpService },
        { provide: ActivatedRoute, useValue: mockActivatedRoute },
        { provide: HttpTestingController, useValue: httpController }
      ]
    })
      .compileComponents();

    mockEmpService = TestBed.inject(DepartmentsService);
    httpController = TestBed.inject(HttpTestingController);

    fixture = TestBed.createComponent(ViewEmployeesbyDeptComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('Should Get Employees By Department ID', () => {
   spyOn(mockEmpService, 'getEmployeesByDepartment')
   .and
   .callThrough();
   component.ngOnInit();
   expect(mockEmpService.getEmployeesByDepartment).toHaveBeenCalledWith(1);
   expect(component.getId).toBe(1);
   expect(component.employees).toEqual(mockEmp);
  });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Embedding Python to C++ Segmentation fault I am trying to track the execution of python scripts with C++ Threads (If anyone knows a better approach, feel free to mention it)
This is the code I have so far.
#define PY_SSIZE_T_CLEAN
#include </usr/include/python3.8/Python.h>
#include <iostream>
#include <thread>

void launchScript(const char *filename){
    Py_Initialize();
    FILE *fd = fopen(filename, "r");
    PyRun_SimpleFile(fd, filename);
    PyErr_Print();
    Py_Finalize();

}
int main(int argc, char const *argv[])
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");
    std::thread first (launchScript,"script.py");
    std::cout << "Thread 1 is running with thread ID: " << first.get_id() << std::endl;
    std::thread second (launchScript,"script2.py");
    std::cout << "Thread 2 is running with thread ID: " << second.get_id() << std::endl;

    first.join();
    second.join();
    Py_Finalize();
    return 0;

}

Script.py just has a print statement that prints "Hello World"
Script2.py has a print statement that prints "Goodbye World"
I build the application with the following commands
g++ -pthread -I/usr/include/python3.8/ main.cpp -L/usr/lib/python3.8/config-3.8-x86_64 linux-gnu -lpython3.8 -o output

When I run ./output, I receive the following on my terminal
Thread 1 is running with thread ID: 140594340370176
Thread 2 is running with thread ID: 140594331977472
GoodBye World
./build.sh: line 2:  7864 Segmentation fault      (core dumped) ./output

I am wondering why I am getting Segmentation Fault. I have tried to debug with PyErr_Print(); but that has not given me any clues.
Any feed back is appreciated.

A: After testing and debugging the program for about 20 minutes I found that the problem is caused because in your example you've created the second std::thread named second before calling join() on the first thread.
Thus, to solve this just make sure that you've used first.join() before creating the second thread as shown below:
int main(int argc, char const *argv[])
{
    Py_Initialize();
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append(\".\")");
    std::thread first (launchScript,"script.py");
    std::cout << "Thread 1 is running with thread ID: " << first.get_id() << std::endl;
//--vvvvvvvvvvvvv-------->call join on first thread before creating the second std::thread
    first.join();

    std::thread second (launchScript,"script2.py");
    std::cout << "Thread 2 is running with thread ID: " << second.get_id() << std::endl;

    second.join();

    Py_Finalize();
    return 0;

}


text:
Q: html required not working with onclick I have the following which I use for submitting forms on my site:
Register

I have inputs within the form with the required tag but this does not seem to fire them? Meaning doesn't stop empty inputs being submitted.
If I use a normal submit button it works fine by the way - is onclick not a recognised way to submit a form within html5?

A: The problem is the submit() method, not the use of onclick (although you can't avoid the former if you want to submit using JS instead of HTML).
Submitting using JS causes the form's validation steps to be skipped (although you can re-implement them in JS (with checkValidity()).

The submit() method, when invoked, must submit the form element from the form element itself, with the scripted-submit flag set.

— http://www.w3.org/TR/html5/forms.html#dom-form-submit

If the scripted-submit flag is not set, and the submitter element's no-validate state is false, then interactively validate the constraints of form and examine the result: if the result is negative (the constraint validation concluded that there were invalid fields and probably informed the user of this) then abort these steps.

— http://www.w3.org/TR/html5/association-of-controls-and-forms.html#form-submission-algorithm

A: Here is how you can do
Register

function CheckValidation()
{

    var isValidForm = document.forms['REGform'].checkValidity();
    if (isValidForm)
    {
        document.forms['REGform'].submit();
    }
    else
    {

        return false;
    }

}

A: Register

or
Register


text:
Q: Lucene Java opening too many files. Am I using IndexWriter properly? My Lucene Java implementation is eating up too many files.  I followed the instructions in the Lucene Wiki about too many open files, but that only helped slow the problem.  Here is my code to add objects (PTicket) to the index:
//This gets called when the bean is instantiated
public void initializeIndex() {
    analyzer = new WhitespaceAnalyzer(Version.LUCENE_32);
    config = new IndexWriterConfig(Version.LUCENE_32, analyzer);

}

public void addAllToIndex(Collection<PTicket> records) {
    IndexWriter indexWriter = null;
    config = new IndexWriterConfig(Version.LUCENE_32, analyzer);

    try{
        indexWriter = new IndexWriter(directory, config);
        for(PTicket record : records) {
            Document doc = new Document();
            StringBuffer documentText = new StringBuffer();
            doc.add(new Field("_id", record.getIdAsString(), Field.Store.YES, Field.Index.ANALYZED));
            doc.add(new Field("_type", record.getType(), Field.Store.YES, Field.Index.ANALYZED));

            for(String key : record.getProps().keySet()) {
                List<String> vals = record.getProps().get(key);

                for(String val : vals) {
                    addToDocument(doc, key, val);
                    documentText.append(val).append(" ");
                }
            }
            addToDocument(doc, DOC_TEXT, documentText.toString());
            indexWriter.addDocument(doc);
        }

        indexWriter.optimize();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cleanup(indexWriter);
    }
}

private void cleanup(IndexWriter iw) {
    if(iw == null) {
        return;
    }

    try{
        iw.close();
    } catch (IOException ioe) {
        logger.error("Error trying to close index writer");
        logger.error("{}", ioe.getClass().getName());
        logger.error("{}", ioe.getMessage());
    }
}

private void addToDocument(Document doc, String field, String value) {
    doc.add(new Field(field, value, Field.Store.YES, Field.Index.ANALYZED));
}

EDIT TO ADD code for searching
public Set<Object> searchIndex(AthenaSearch search) {

    try {
        Query q = new QueryParser(Version.LUCENE_32, DOC_TEXT, analyzer).parse(query);

        //search is actually instantiated in initialization.  Lucene recommends this.
        //IndexSearcher searcher = new IndexSearcher(directory, true);
        TopDocs topDocs = searcher.search(q, numResults);
        ScoreDoc[] hits = topDocs.scoreDocs;
        for(int i=start;i<hits.length;++i) {
            int docId = hits[i].doc;
            Document d = searcher.doc(docId);
            ids.add(d.get("_id"));
        }
        return ids;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

This code is in a web application.
1) Is this the advised way to use IndexWriter (instantiating a new one on each add to index)?
2) I've read that raising ulimit will help, but that just seems like a band-aid that won't address the actual problem.
3) Could the problem lie with IndexSearcher?

A:
1) Is this the advised way to use
  IndexWriter (instantiating a new one
  on each add to index)?

i advise No, there are constructors, which will check if exists or create a new writer, in the directory containing the index. problem 2 would be solved if you reuse the indexwriter.
EDIT:
Ok it seems in Lucene 3.2 the most but one constructors are deprecated,so the resue of Indexwriter can be achieved by using Enum IndexWriterConfig.OpenMode with value CREATE_OR_APPEND.
also, opening new writer and closing on each document add is not efficient,i suggest reuse, if you want to speed up indexing, set the setRamBufferSize default value is 16MB, so do it by trial and error method
from the docs:

Note that you can open an index with
  create=true even while readers are
  using the index. The old readers will
  continue to search the "point in time"
  snapshot they had opened, and won't
  see the newly created index until they
  re-open.

also reuse the IndexSearcher,i cannot see the code for searching, but Indexsearcher is threadsafe and can be used as Readonly as well
also i suggest you to use MergeFactor on writer, this is not necessary but will help on limiting the creation of inverted index files, do it by trial and error method

A: I think we'd need to see your search code to be sure, but I'd suspect that it is a problem with the index searcher.  More specifically, make sure that your index reader is being properly closed when you've finished with it.
Good luck,

A: The scientific correct answer would be: You can't really tell by this fragment of code.
The more constructive answer would be:
You have to make sure that there is only one IndexWriter is writing to the index at any given time and you therefor need some mechanism to make sure of that. So my answer depends of what you want to accomplish:

*

*do you want a deeper understanding of Lucene? or..

*do you just want to build and use an index?

If you answer is the latter, you probably want to look at projects like Solr, which hides all the index reading and writing.

A: This question is probably a duplicate of
Too many open files Error on Lucene
I am repeating here my answer for that.
Use compound index to reduce file count. When this flag is set, lucene will write a segment as single .cfs file instead of multiple files. This will reduce the number of files significantly.
IndexWriter.setUseCompoundFile(true)


text:
Q: Accessing User Application Settings in a WPF Prism 4 module I have developed a Microsoft Prism 4.0 application and I am struggling to understand how to make the user application setting functionality available to modules.
e.g. a Properties.Settings.Default.MyProperty.
I can define a simple class that gets populated via the bootloader (which does have a handle to the properties) and inject that into the modules but If I want to save a change of property, I need believe I need a handle to the Properties.Settings context which is not available to my modules (which are simple class libraries).

A: Your scenario sounds like the perfect reason to use a "Service" class.  Create an interface and class called IUserSettingsService and UserSettingsService that has the information (or can load and save it from where it is stored).
Read Chapter 3 of the Prism 4.0 help file, Managing Dependencies Between Components, Registering Types with (either Unity or MEF, depending on what you are using as your DI Container).
Then, in your ViewModel that needs the user settings, locate and use your service.  In MEF, it is as simple as adding a property of type IUserSettingsService with an [Import] attribute, or using [ImportingConstructor] and having a parameter of type IUserSettingsService.  With Unity, you access the service through the container.  See Chapter 10 of the Prism help file - Advanced MVVM Scenarios.
Added after comment discussion:
Because you need your service to be in the context of your main application, you can implement your service class there.  Create the interface for your service in a shared library that can be used by both the main project and your modules.  Finally, load the service in the bootloader class instead of in a module.


text:
Q: How to store sql server express in a different project from the UI? I have two projects in my solution:

*

*MyProject.UI (ASP.NET MVC 3)

*MyProject.Domain (class library)
I have added a sql server express database to my class library project as well as an entity framework edmx file. The model designer in entity framework has no problem finding and connecting to the database in that project. When I do so it generates an app.config file with the following connection string:
<add name="TestDBstuffEntities" connectionString="metadata=res://*/Test.csdl|res://*/Test.ssdl|res://*/Test.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDBstuff.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />

You'll notice that the connection string contains AttachDbFilename=|DataDirectory|\TestDBstuff.mdf;. When I copy this connection string to the UI web.config so that it can be used during runtime, I get an error. I assume that is because it is now referring to the UI project's data directory (App_Data). If I change the AttachDbFilename=|DataDirectory|\TestDBstuff.mdf; to the fully-qualified path where the .mdf file is stored, it works.
My question is what is the best practice to store a sql server express file in another project outside the UI project?

A: I know what the solution is supposed to be, since I had to look it up when I was creating an MVC solution for the first time and had the same problem.  I never had time to get it working fully, so there could be something wrong here.
Basically, you should set the value of DataDirectory.  In the Global.asax.cs file's Application_Start method, add
AppDomain.CurrentDomain.SetData("DataDirectory", "c:\Path\To\Your\Database\Directory");

making the obvious substitution.
Now, there are other potential issues -- the .mdf needs to be deployed somewhere, and SQL Server Express needs to have permissions to read and write the file where it gets deployed.  I don't recall the username for SQL Server Express, but I do recall it being quite long; double-check the permissions on a directory you know SQL Server Express can access to find the username.  Also, you may not want your database file to be overwritten each time you build the solution.  This MSDN blog post was written for Visual Studio 2005, but I think it still applies even in 2010.
I'm sorry if I'm missing something.  As I said, I haven't had time to get my own solution completely working, but I think this is the idea.

A: I think it depends on how you want to deploy.  For web based projects, I tend to use a Database projects that I deploy to SQL Server.  This obviously won't work for User Instanced databases however.
I guess I'm not a fan of user instances, and would rather use SQL CE if I wasn't using a permanently attached database.
But more to the point of answering your question, the DataDirectory for Web based apps I believe is the App_Data directory.  I'm going to assume that if you reference your class library, then the database and class files will end up in the Bin directory instead.  If I were to make a decision about how I go about deciding where the database lives, between the class library and the MVC project, it would highly depend on the data.  If the data is specific to the class library then my opinion would be to have it with the class library and your filename is bin\testDBstuff.mdf.  But more often then not this data is application specific and in my opinion should be stored with the application using it, in which case would be the app_data directory of the MVC project and the filename is correct..

A: Quite honestly: I've never liked this "just attach a MDF file on the fly" approach.
I would

*

*create my database on the SQL Server Express instance manually (e.g. in SQL Server Mgmt Studio Express)

*have a "real" connection string in the project that connects to that Express server and uses my database.

So your connection string would then be something like:
<add name="TestDBstuffEntities"
     connectionString="metadata=res://*/Test.csdl|res://*/Test.ssdl|res://*/Test.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.\SQLEXPRESS;Database=TestDBstuff;Integrated Security=True;MultipleActiveResultSets=True""
     providerName="System.Data.EntityClient" />

This way, you are not dependent on any physical location of the MDF file - you just talk to the SQL Server Express server process and the location of the actual file is totally transparent to you.

A: I reckon it is more of a deployment issue.  Where you store your physical mdf file shouldn't really matter.  When you deploy you could just update the relevant settings (probablt from some kind of installer).


text:
Q: Elastic Error: 500 - all shards failed I try to execute the following statement in R
elastic::Search("indexname", search_type = "scan")

and get the following error message

Error: 500 - all shards failed

Everything works if I use
elastic::Search("indexname")

Does anybody know what I have to do? I remember a similar error when I used ES v5
I'm using ES v2.4.3.


text:
Q: Bad state: field does not exist within the DocumentSnapshotPlatform . It shows the getter was called on null The relevant error-causing widget was
StreamBuilder. I've given the link of the project repo in github .
Widget build(BuildContext context) {
return StreamBuilder(
  stream: FirebaseFirestore.instance
      .collection("/chats/2DGQmBssJ4sU6MVJZYc0/messages")
      .orderBy('createdAt', descending: true)
      .snapshots(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting)
      Center(child: CircularProgressIndicator());
    final documents = snapshot.data.documents;
    return ListView.builder(
      reverse: true,
      itemCount: documents.length,
      itemBuilder: (context, index) {
        return MessageBubble(
            documents[index]['text'],
            documents[index]['userID'] == user.uid,
            documents[index]['userID'],
            documents[index]['imageurl']);
      },
    );
  },
);

}
}
Github link of the project

A: Try the following:
 if (snapshot.connectionState == ConnectionState.waiting)
      Center(child: CircularProgressIndicator());
 else if(snapshot.connectionState == ConnectionState.active){
    final documents = snapshot.data.documents;
    return ListView.builder(
      reverse: true,
      itemCount: docs.length,
      itemBuilder: (context, index) {
        return MessageBubble(
            docs[index]['text'],
            docs[index]['userID'] == user.uid,
            docs[index]['userID'],
            docs[index]['imageurl']);
       },
     );
   },
  },
);

When the connectionState is active meaning with data being non-null, then retrieve the data. Also use docs since it seems you are using the new version of Firestore.
documents became docs

A: Edit
Now that I've become little better than before, so I must update this answer for better understanding.
Let's take this above example:
 return ListView.builder(
      reverse: true,
      itemCount: documents.length,
      itemBuilder: (context, index) {
        return MessageBubble(
            documents[index]['text'],
            documents[index]['userID'] == user.uid,
            documents[index]['userID'],
            documents[index]['imageurl']);
      },
    );
  },
);

Here, all the documents in that particular collection MUST contain these 3 fields, i.e, 'text', 'userID', and 'imageurl' to successfully build each child inside the listView.builder().
But, if any of these 3 fields is missing, or even miss-spelled in One or more documents, then it would throw an error like the above.
Will throw error:

Will throw error:

So, to solve that we need to find that particular document which has the field missing, or field miss-spelled and correct it.
Or, delete that document and keep only those documents which has correct fields.
(By the way, I'm using "Dark Reader" chrome extension for dark theme for firebase console, and every other website on internet.)
My Old Answer:
In my case I was using Firebase Firestore for my chat app, and while loading the chat screen, I was getting this error.
So in Firestore Database I had 15-20 messages, So I deleted most of them and leave just 2-3 messages. And then the Error disappeared.
I don't know happened here.

A: You create a widget and then don't use it and follow through with the rest of your logic:
if (snapshot.connectionState == ConnectionState.waiting)
     Center(child: CircularProgressIndicator());

You need to stop there and return that widget from your builder:
if (snapshot.connectionState == ConnectionState.waiting)
     return Center(child: CircularProgressIndicator());


text:
Q: Get all combinations of six players I have an array of six players. This means I have fifteen unique games:
players = [1, 2, 3, 4, 5, 6]
games = players.combination(2).to_a
# => [[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [2, 3], [2, 4], [2, 5],
#    [2, 6], [3, 4], [3, 5], [3, 6], [4, 5], [4, 6], [5, 6]]

I want to arrange these games randomly into 5 rounds of 3. Each player should play 1 game each round, and no pair should repeat from any previous round.
In each round, I have tried picking player1 and player2 randomly, using while loop coupled with each, but I always end up in infinite loop. Any suggestions?
So here is the code (sorry for not putting it in eariler). Problem is that sometimes it does work and gives me the result that I want but sometimes it just breaks down and it's caught in the loop.
def pick_pair(players)
    player1 = players[rand(players.length)]
    players.delete(player1)
    player2 = players[rand(players.length)]
    players.delete(player2)
    pair = [player1, player2]
    return pair.sort!
end

def check_round(all_rounds, current_round)
    repeat = false
    if all_rounds == []
        repeat = false
    else
        repeat = catch :repeat do
            k = 0
            all_rounds.each do |round|
                a_r_l = all_rounds.length
                round.each do |pair|
                    r_l = round.length
                    k += 1
                    z = 0
                    current_round.each do |new_pair|
                        #p "Comparing: #{pair} to #{new_pair}"
                        z += 1
                        if pair == new_pair
                            repeat = true
                            throw :repeat, repeat
                        elsif (k == a_r_l*r_l  and z == current_round.length and pair != new_pair)
                            repeat = false
                            throw :repeat, repeat
                        end
                    end
                end
            end
        end
     end
     return repeat
 end

players = [1,2,3,4,5,6]
all_rounds = []

for i in 1..(players.length-1)
    #p "Round: #{i}"
    players_d = players.dup
    current_round = catch :round do
        check = true
        while check
            current_round = []
            for j in 1..(players.length/2)
                #p "Game: #{j}"
                pair = pick_pair(players_d)
                current_round << pair
            end
            p "Previous rounds: #{all_rounds}"
            p "Current round: #{current_round}"
            repeat = check_round(all_rounds, current_round)
            if repeat == false
                throw :round, current_round
            else
                players_d = players.dup
            end
        end
    end
   all_rounds << current_round
 end

Hey,
thanks for the help. I rewrote the code and it seems to works. It's also much simpler:
players = [1,2,3,4,5,6]
possible_games = players.combination(2).to_a
all_games = []

for i in 1..(players.length - 1)
    round = catch :round do
            check = true
            while check
                round = []
                for i in 1..(players.length/2)
                    pair = possible_games[rand(possible_games.length)]
                    round << pair
                end
                if round.flatten.uniq == round.flatten
                    round.each do |game|
                        possible_games.delete(game)
                    end
                    throw :round, round
                else
                end
            end
        end
    all_games << round.sort!
end
p all_games

A: Basically you are trying for random combinations and retrying until the scheme is valid. It will succeed now and then, but it will get in a deadlock sometimes:
Round 1  2  3  4  5
      12 14 16 13
      34 36 32 5??
      56 52 54

In round 4, player 5 must play player 1 or 3, but that is not going to happen because 3 is already playing 1. Your script keeps retrying until the end of times.
Such a tournament is called a round-robin tournament; wikipedia has an algorithm.

A: Although, strictly speaking, the best (most efficient) solution here would be to use a "round-robin" algorithm as suggested by steenslang.
I would suggest a simpler approach which works great and is quite straight forward.
Basically, the program tries to make each round have each player playing once per round. It loops over a shuffled array of combinations and tries pairing them up. If the combination is not possible, it reshuffles the array and tries again.
It's simple and it works great.
Plus, you can change the number of players if you need to too and it just works.
Hope this helps:
players = [1, 2, 3, 4, 5, 6]
initial_games = players.combination(2).to_a.shuffle
players_sum = players.inject{|sum,x| sum + x }
all_rounds = []

games = initial_games
until games.empty?
  current_round = []
  games.each do |game|
    if (current_round.flatten & game).empty?
      current_round << game
    end
  end
  current_round_sum = current_round.flatten.inject{|sum,x| sum + x }
  if current_round_sum == players_sum
    all_rounds << current_round
    games = games - current_round
  else
    all_rounds = []
    games = initial_games.shuffle
  end
end

puts all_rounds.inspect  # this outputs 5 rounds of 3 games


text:
Q: google.maps.FusionTablesLayer: styles not applied I got a code snippet below to display the boundary of an area from google map FusionTablesLayer. The polygon got displayed but the expected style never applied. What's wrong with my code? Please help me. Thank you alot.
var FT_TableID=420419;
var ftoptions = {
        suppressInfoWindows:true,
        styles: [
            {polygonOptions: {fillColor:'#0040FF',fillOpacity:0.1,strokeColor:'#FF0000',strokeWeight:2,strokeOpacity:0.6}}
        ]
    };

var layer = new google.maps.FusionTablesLayer(FT_TableID,ftoptions);
layer.setQuery('SELECT \'kml_4326\' FROM 420419 WHERE \'name_0\' = \'Vietnam\';');

layer.setMap(theMap);

Thank you for the suggestion. Let me clarify my case further, why I had to write the code that way: I stored ftquery for each area in the database (in the raw format: SELECT ... FROM ...) and loaded it out to draw the area boundary.
var ftoptions = {...};
var layer = new google.maps.FusionTablesLayer(tableid);

//to load custom styles, but not work, same for setOptions or set('styles',styles);
layer.setValues(ftoptions);

var ftquery = '';//this is loaded from database
layer.setQuery(ftquery);
layer.setMap(theMap);

I tried your suggestion but the polygon did not show. I must be wrong somewhere. Thank you all for any further help.

A: You are using the "old" style syntax.  If you want to style the FusionTablesLayer, you need to use the documented syntax
var ftoptions = {
        query: {
          from: tableid,
          select: 'kml_4326',
          where: "name_0 = 'Vietnam'"
        },
        suppressInfoWindows:true,
        styles: [
            {polygonOptions: {fillColor:'#0040FF',fillOpacity:0.1,strokeColor:'#FF0000',strokeWeight:2,strokeOpacity:0.6    }}
        ]
    };

var layer = new google.maps.FusionTablesLayer(ftoptions);
layer.setMap(theMap);


text:
Q: How to save the output of printf() as a variable in c? I've code c for a very short time and have a problem, which I can't solve.
I want to save a string with variables
"order_%d: <button>ON</button>
", x, x    //x = 1,2,3,4...

into a variable named content. But all my attempts were useless. The code, which fits the most to my planned result is:
#include <stdio.h>
#include <stdbool.h>
bool order_state = false;

int orders_cond (int x, bool state){
    if (!state){
        printf("order_%d: <button>ON</button>
", x, x);
    }
    else {
        printf("Error");
    }
}
int main(){
    int x;
    printf("Enter a number:\n");
    scanf("%d", &x);
    orders_cond(x, order_state);
    return (0);
}

The output of this code is:
Enter a number:
8
order_8: <button>ON</button>

My idea was to save the last line of the output into a variable, but I don't know, how to do that.
Please explain me, how I can do this or if there's another method, how does this method work.

A: You could use sprintf to print the formatted string to your variable, then use printf to print the contents to the screen:
char contents[STRING_LEN] = {0};
sprintf(contents, "order_%d: <button>ON</button>
", x, x);
printf("%s", contents);

The sprintf statement puts the formatted string into array contents and printf prints the contents of contents to the screen.
You will have to make sure that the array contents is large enough to hold the entire string, otherwise you will have overflow.
If you want to avoid overflow, you could use snprintf and replace the sprintf statement with:
snprintf(contents, STRING_LEN, "order_%d: <button>ON</button>
", x, x);

An example may be found here:
https://www.educative.io/edpresso/storing-formatted-data-using-sprintf-in-c

A: You probably want something like this:
#include <stdio.h>
#include <stdbool.h>

bool order_state = false;

int orders_cond(int x, bool state, char *outputstring) {
  if (!state) {
    sprintf(outputstring, "order_%d: <button>ON</button>
", x, x);
  }
  else {
    sprintf(outputstring, "Error");
  }

  return 0;   // you probably need to return something meaningful here
              // or have   void orders_cond(...
}

int main() {
  int x;
  printf("Enter a number:\n");
  scanf("%d", &x);

  char outputstring[100];
  orders_cond(x, order_state, outputstring);

  printf("Content of outputstring: \"%s\"\n", outputstring);

  return 0;   // Bonus: don't put expressions after return between (), it's unusual and useless.
}

Disclaimer: there is still room for improvement, for example by using snprintf in order to prevent buffer overflows.


text:
Q: intellij artifacts not created I hope somebody can help me on this, I was given some sources to set the development environment but I cannot figure out what kind of project this is, the structure of the folders is like this:
TESTPROJECT
.idea
lib
META-INF
   application.xml
src
   classes
test-src
   testclasses
web
   faces
   resources
   WEB-INF
     faces-config.xml
     web.xml
here goes the iml

I am not sure what kind of project this is, I am opening as module in IntelliJ and as project but I am not sure how this has to be opened, but I am not able to build it or even generate any artifact, as they are not generated automatically, i would need the war or the ear but whenever i generate those manually they end up being corrupted or something is missing, I am not sure how to set up this environment so that I can make some changes and deploy back :S


text:
Q: Example of ring Let $R$ be a ring.
Let $A$ be the set of units of $R$. Let $B$ be the set of zero divisors of $R$ and let $C$ be the set of nonzero elements of $R$ which are not units or zero divisors.
Is there an example of a ring $R$ where $A$, $B$ and $C$ are non empty?

A: It's easy to find all three in $\mathbb Z\times \mathbb Z$.
Also $\mathbb Z[x]/(x^2)$ provides all types.
Another one would be the ring of continuous functions from the reals into the reals.

A: Take $R=\mathbb{Z}/n[X]$ where $n$ is the product of two odd primes.

A: Let me suggest some guiding principle: If a ring contains a field then there will be lot of units. If it is not contained any field there will be zero divisors.
Take the set of all real valued continuous functions defined on whole of the real line: This contains constant functions, that form a subring which is in fact a field, providing units.
Now  take a real number $b$: Construct three functions $f_b, g_b, h_b$  as below:
$f_b(x)= 0$ for $x\le b$ and $f_b(x)= x-b$  for $x\ge b $
$g_b(x) = x-b$ for $x\le b$ and $g_b(x) = 0$ for $x\ge b$
$h_b(x) = x-b$ for all $x$
ALl of them are continuous functions throughout the real line; and at any $x$ one of $f_b$ or $g_b$ vanishes, so $f_b(x) g_b(x)$ is the constant function zero.
They provide zero-divisors in this ring (one for each real number).
The function $h_b$ is neither a unit nor a zero divisor.
This provides an example where all the sets are non-empty (in fact all are uncountable)


text:
Q: min3D framework load .OBJ and .3DS. Resume redraw I've been using min3D framework for my last project and I'm stack with couple of problems.
First - it takes a lot of effort to get it load my car model from .OBJ file.
I've managed to do it only by converting .obj file to .3ds(this was the only way to reduce size from 5mb to 1mb which I can put and read from the assets folder) but I still have some issues like missing edges(some parts of the car just doesn't draw).
Second - I'm having a hard time to reload my OpenGL on the Resume.
I need to redraw the model again after hitting 'back' button but I can do it only if I parse the .3ds file again. It takes too much memory and time to do it over and over again and if I try to use already parsed ObjContainer it just doesn't draw(I got blank OpenGL view).
So to summarize my questions are:

*

*How to properly load huge(3-5mb) .OBJ or .3DS files via min3D framework and don't loose any parts of a model?

*How to redraw a model again onResume without parsing .OBJ file over and over again?


text:
Q: Why fatal error "LNK1104: cannot open file 'cryptlib.lib' occur when I compile a C++ project in Visual Studio? I am getting the error mentioned above when compiling a project on Visual Studio. What is strange and different about my situation is that this works on my personal laptop, but not at work.
I have the entire project saved in Dropbox, because I sometimes work on my projects from work and I like this automatic sync that way I don't worry about loosing anything. Having said that, I use relative paths for my libraries, that way the folder is the same for both computers, i.e. "..\cryptopp\x64\Output\Debug\cryptlib.lib"
My question is, why does it work at home, but not at work? I made sure the property sheet has the correct path as well. The linker and VC++ directories are both relative paths.
This cryptlib.lib has some namespaces like CryptoPP and variable types such as byte, it won't give me an error on this. It knows it exists (I get the correct font color)
Is there something that I am missing?
P.S. Added screenshots per request. Can't add more than 2 links, so I merged 2 screenshots into 1. That ECE427Projects is where the solution file is located. I don't want to go any further back than that.
Screenshot 1
Screenshot 2

A: You've put the directory for the library in the wrong field.
There's two places you could use to specify the directory where your libraries are supposed to be. I prefer to use the Library Directories section in Configuration Properties→VC++ Directories, but the alternate is Additional Library Directories in Configuration Properties→Linker→General. There's no need to specify it in both locations, though I doubt anything bad will happen if you do. Bear in mind that this is supposed to be a directory, not a file, so delete the trailing cryptlib.lib file name from this directory string.
If you haven't, in Configuration Properties→Linker→Input, for Additional Dependencies, you should be putting the name of the library object (cryptlib.lib), in your case.
For all of these, make sure the default values inherited by the project property pages are still there, after the stuff you add.
Let me know if this doesn't resolve the issue.


text:
Q: Thread safe method without using any type of lock how we can create a thread safe method without using any type of lock?Any Help will be highly appericiated. thanks

A: It depends on what you need to do inside the method, however usually a technique called CompareAndSwap can be used. The .NET framework uses the CompareExchange function. In any case you have to check if you can express your lock in a way that is suitable for CAS.

A: If you want to avoid locking you also want to avoid shared (mutable) state. Functional programming is a paradigm where you don't have any mutable state. You can do functional style programming in many programming languages and environments, but to give an example, a language like Erlang is particular suited to solve these kind of problems.

A: This is a very high-level question, so here a high-level answer:
http://en.wikipedia.org/wiki/Reentrancy_(computing)

A: Don't modify any shared state. i.e. for any piece of memory, there is at most one thread that can write to it. That's about your only choice if you want to avoid all locks.
Even "lockless" programming techniques (Interlocked class) use some kind of lock, even if it's a bit cheaper than normal locks.

A:
how we can create a thread safe method without using any type of lock?

Either: do not mdify any shared state. Basically this means that either (a) you CAN make the method static without breaknig it (as it is not using any instance ariables) or (b) all these variables are read only AND READONLY (so another thead can not change them) OR you can deal with the change.
Alternative:
OR: you wake up and realize that funny ishes may not come true. The moment yuo modify shares state you neded "a kind of locking". There are lock free mchanisms for that, but they are "lock free" in the strict term ("no lock") not in your term (i.e. they use a KIND OF LOCK). Spinlocks technically are lock free - a spinlock is a kind of lock, but not a real lock.


text:
Q: Cannot invoke 'SKSpriteNode.init' with an argument list of type '(texture: SKTexture, color: UIColor, size: CGSize, () -> ())' Can anyone help me solve this issue? The error shown is being generated even though I am using the designated initializer.
class OtherOrb: SKSpriteNode {

override init() {

    let texture = SKTexture(imageNamed: "Orb")

    super.init(texture: texture, color: UIColor.clear, size: texture.size()){
        self.position = CGPoint(x: 0.0, y: 500.0)
        self.physicsBody = SKPhysicsBody(circleOfRadius: 20)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

A: You are getting this error because of the closure you have trailing your initialiser.
In Swift, the compiler interprets a closure directly after a method call as the final argument to said method call, and hence the error you are getting effectively says that no initialiser that includes that closure argument exists.
Furthermore, your code looks very off, and I'm not convinced it's valid Swift. What are you trying to accomplish?
Based on my suspicions, I believe your code should resemble the following:
class OtherOrb: SKSpriteNode {

    init() {

        let texture = SKTexture(imageNamed: "Orb")
        super.init(texture: texture, color: UIColor.clear, size: texture.size())

        self.position = CGPoint(x: 0.0, y: 500.0)
        self.physicsBody = SKPhysicsBody(circleOfRadius: 20)
    }

    @available(*, unavailable)
    override init(texture: SKTexture?, color: UIColor, size: CGSize) {
        super.init(texture: texture, color: color, size: size)
    }

    @available(*, unavailable)
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

That is to say that you want an initialiser with no args to be your designated initialiser.


text:
Q: Content area takes 100% screen width I am trying to replicate the basic structure of the page which is base on theme https://themes.muffingroup.com/be/restaurant5/.
I tried to use bootstrap row & columns that seems to have created its own problem and when try to do it with Bootstrap using custom css it doesnt work as the theme.
In current case main content takes 100% and side menu is about 250px, since side nav has fixed position main content area has 100 % with of the screen, i want main content are to take on remain space Content Area - Side Nav
I can use .side-content {width:calc(100% - 250px) !important}  but i am curious how they are doing the sample theme as i could not see using calc function
https://codepen.io/KGuide/pen/oNXdgWz

body{font-family: 'Open Sans', sans-serif;}
.side-content{background-color:red; withd:100%; float:left;
 max-width: 100% !important;
 width: 100% !important;
 margin: 0 !important;
 overflow:hidden;
 background-color: #ccc;
}
.side-nav {
 text-align:center;
 background-color: #FCFCFC;
 position: fixed;
 width: 250px;
 height: 100%;
 top: 0;
 right:0;
 z-index: 9002;
 -webkit-box-shadow: 2px 0 4px 2px rgba(0,0,0,.15);
 box-shadow: 2px 0 4px 2px rgba(0,0,0,.15);

}
.img-logo {
 margin-top:50px;
 vertical-align: middle;
 max-height: 100%;
 width:100%;
 max-width:150px;
}
.nav-menu{
list-style: none outside;
padding-top:30px;
margin-top:30px;
padding-left:0px;
}
.nav-menu > li {

 margin: 0;
 z-index: 203;
 display: block;
 float: left;
  width: 100%;
 float: none;
 position: relative;
 font-size:15px;
 font-weight:600;
 text-transform:uppercase;
 padding:5px 15px;
}

.main-c{ background:yellow;}

.sone{position:relative;width:100%; height:100%; background:blue;}
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
 <link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet">
 <link rel="stylesheet"  href="assets/css/main.css">
    <title>Page Title HERE!</title>

Home

Abouts Us

Our Menu

Special Offers

Testimonials

Gallery

 SECTION ONE

 this is intro area

SECTION TWO - About us

SECTION THREE - Our menu


text:
Q: LoginStatus control in asp.net Any one help me out, how to work with LoginStatus control in asp.net...
the statu before login should be 'userlogin'
after logged in ,it automatically changes to 'userlogout'
any suggestions??

A: How about this
<asp:LoginView ID="ctlRightNavbar" runat="server">
   <AnonymousTemplate>
       userlogin
   </AnonymousTemplate>
   <LoggedInTemplate>
      userlogout
   </LoggedInTemplate>
</asp:LoginView>

This will make a more custom view for you if you do not wish to use LoginStatus. You can read more about the above code sample here.


text:
Q: Can't get refresh_token in callback with a 'full' scope I'm trying to get an access_token and a refresh token for a connected app.
I managed to get either the access_token and a full access to the API, or an access_token and a refresh_token, but without the ability to fetch opportunities and other data.
I'd like to get the full authorization, plus a refresh token.
Here is the POST request to get the full auth without a refresh token:
url = instance_url + '/services/oauth2/authorize?'

params = {
  redirect_uri: "http://example.com/salesforce/login",
  client_secret: secret_key,
  client_id: client_key,
  code: code,
  scope: "full",
  response_type: "token",
  grant_type: "refresh_token"
}

Here is the POST request to get the refresh token and the access_token without the full authorization:
url = instance_url + '/services/oauth2/authorize?'
params = {
  redirect_uri: "http://example.com/salesforce/login",
  client_secret: secret_key,
  client_id: client_key,
  code: code,
  scope: "refresh_token",
  response_type: "token",
  grant_type: "refresh_token"
}

How can I solve this ?

A: Specify both scopes:
  scope: "refresh_token full",

The scope parameter is a space-delimited list of scopes you would like to request. You can specify as many scopes as you need to be as granular as you'd like.
The parameter needs to be encoded using the method outlined in this help topic.


text:
Q: Mathmatically analizing different voltages in a phase changing circuit I am trying to understand a phase shift oscillator from a mathematical perspective, and to begin I simply took the phase-shifting part of the circuit and am now trying to analyze the voltages as a function of time. Essentially, I'm looking for a way to find the voltages across each component. Normally, something like this would be easy to find using basic equations and grouping, but in this specific application, I can't even find a way to group the components together. Here is the circuit:
My best guess on how to solve this is to find the impedance of each capacitor as a relation to time by working left to right. But in order to find this impedance, I also need to know the current through each capacitor as a relation of time. But in order to know that I would think that I would need to know the V-Out voltage. It seems that in whichever way I try to solve this, I end up going in a loop with all the equations. Also, just for informative purposes, I plan on graphing all the voltages on Desmos.
Is there anything that I am missing? I really am stumped here and any help would be appreciated. Also, I have only taken high school physics at this point and haven't had a chance to get into the calculus bits yet, so if its at all possible to answer the question without calculus, that would be appreciated.


text:
Q: User-friendly link to attached images for a certain post? I have set up a slideshow running on the front page of my site that runs on images attached to a page called 'Home'.
I would like to be able to adjust its contents and order from the admin area. And lo, I can do this, by going to the 'Home' page in pages, clicking on the Media Library, going to the 'Gallery' tab and reordering/editing each of the attached images.
But this is not very convenient for the person who will use the site.
Can anyone recommend a plugin that allows for very simple management of attachments for a given post? Even if it's just a link I can place it in a metabox on the Dashboard and they needn't follow the above tortuous route to get to where they need to be.
Thanks!

A: The Gallery tab of the Media Uploader for an individual post is located at this link:
http://example.com/wordpress/wp-admin/media-upload.php?post_id=999&tab=gallery
(change the post ID as needed.)
I have no idea how robust this is, but I did a quick test on my own site, and the changes I made were saved correctly.


text:
Q: Entering new data rows into SQL Server Express using C# I'm pretty sure I'm just being stupid here, but oh well.
My code is:
private void btnInsert_Click(object sender, EventArgs e)
{
        SqlConnection conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\LiftLog.mdf;Integrated Security=True;User Instance=True");
        conn.Open();

        SqlCommand cmdInsert = conn.CreateCommand();
        cmdInsert.CommandText = "INSERT INTO tblLog (Date, Time, Floor) VALUES (1011, 0011, 3)";
        cmdInsert.ExecuteNonQuery();
}

It's connecting to the table, since it complains if I put no data into a not-null field. However, when I click the button, the table doesn't update.
Why?
This worked to retrieve data:
    System.Data.SqlClient.SqlConnection con;
    System.Data.SqlClient.SqlDataAdapter da;
    DataSet ds1;

    // Connects to database.
    private void Form1_Load(object sender, EventArgs e)
    {
        con = new System.Data.SqlClient.SqlConnection();
        ds1 = new DataSet();
        con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\LiftLog.mdf;Integrated Security=True;User Instance=True";
        con.Open();
        string sql = "SELECT * From tblLog";
        da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
        da.Fill(ds1, "LogOutput");
        NavigateRecords();
        con.Close();
     }

As SSMS won't work for me, would it be possible to modify this somehow to insert?
Also, I know about sanitising inputs etc, I stripped it all away to try and pinpoint the problem.

A: This whole User Instance and AttachDbFileName= approach is flawed - at best! Visual Studio will be copying around the .mdf file (to your project's output directory where the app is run when inside Visual Studio), and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file (in your project's output directory) with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to

*

*install SQL Server Express (and you've already done that anyway)

*install SQL Server Management Studio Express

*create your database in SSMS Express, give it a logical name (e.g. LiftLog)

*connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=LiftLog;Integrated Security=True

and everything else is exactly the same as before...
Also, please note: I would strongly recommend always using parametrized queries to a) avoid SQL injection attacks, and b) significantly improve performance in SQL Server.
So instead of:
cmdInsert.CommandText = "INSERT INTO tblLog (Date, Time, Floor)
                         VALUES (1011, 0011, 3)";

you should use
cmdInsert.CommandText = "INSERT INTO tblLog (Date, Time, Floor)
                         VALUES (@Date, @Time, @Floor)";

and then define those parameters (@Date, @Time, @Floor) on your SqlCommand object and fill in their values that way.


text:
Q: Different answers for integral of $\sin^3x$ I was calculating an integral that I thought it'd be easy however it turned out very weird. I couldn't figure out so I'm looking for some help.
$$\int_{-\pi/2}^{\pi/2} \int_{2\cos\theta}^{2}2r{\sqrt{4-r^2}} \,dr\,d\vartheta$$
Then, I solved the inner integral with respect to r. I got the following by simplifying
$\int {2\over3}(4-(2\cos\theta)^2)^{3\over2} $
$\int {2\over3}(4-4\cos^2\theta)^{3\over2} $
$\int {2\over3}(4(1-\cos^2\theta))^{3\over2} $
$\int {2\over3}(4\sin^2\theta)^{3\over2} $
${16\over3}\int(\sin^3\theta) $
Then, with simple substitution, I got $\int(\sin^3\theta) d\theta $ = $1/3\cos^3\theta-\cos\theta+C$. When I plug in my end points $\pi/2$  and  $-\pi/2$, I get zero. However, it can't be zero because it's a legit solid piece. So, I tried to solve with wolphram alpha for $\sin^3\theta$ and my integrand before simplification, I got followings:

I also found this one for the integration of $\sin^3x$

 vs

So, I'm super confused how come $\sin^3x$ got two different answers???They seem the same but how come they are completely different functions? Where do I make mistake to solve the original problem?
thank you

A: There is no contradiction ...
If you use the substitution $y=\cos(x)$, you find that the primitives of $\sin^3$ are given by $x\mapsto\frac{1}{3}\cos^3(x)-\cos(x)+C$
On the other side, if you linearize first, you get $\sin^3(x)=\frac{1}{4}(3\sin(x)-\sin(3x))$, and hence the primitives of $\sin^3$ are given by $x\mapsto\frac{1}{12}\cos(3x)-\frac{3}{4}\cos(x)+C$
So, apparently, we get two different families of functions ... but only apparently because linearization of $\cos^3(x)$ leads to the formula :
$\cos^3(x)=\frac{1}{4}(\cos(3x)+3\cos(x))$
and so :
$\frac{1}{3}\cos^3(x)-\cos(x)=\frac{1}{12}(\cos(3x)+3\cos(x))-\cos(x)=\frac{1}{12}\cos(3x)-\frac{3}{4}\cos(x)$

A: $\int\sin^3xdx=\int(1-\cos^2x)\sin xdx=\int(\cos^2x-1)d(\cos x)=\frac{\cos^3x}{3}-\cos x+C$

A: There is actually no mistake. They are exactly the same since $\cos(3x)\equiv4\cos^3 x-3\cos x$. We demonstrate this as follows:
$$\cos(3x)=\cos(2x+x)$$
Using the double angle formula:
$$\cos(3x)=\cos(2x)\cdot\cos x-\sin(2x)\cdot \sin x$$
Using $\cos(2x)\equiv 2\cos^2 x-1$ and $\sin(2x)\equiv 2\sin x\cos x$, we obtain:
$$\cos(3x)=2\cos^3 x-\cos x-2\sin^2 x\cos x$$
Using the identity $\sin^2 x\equiv 1-\cos^2 x$, we obtain the correct identity:
$$\cos(3x)=2\cos^3 x-\cos x-2(1-\cos^2 x)\cos x$$
$$\boxed{\cos(3x)\equiv 4\cos^3 x-3\cos x}$$
Substituting this on your first solution gives the second solution.


text:
Q: SDL ld returned 1 exit status im writing a sample SDL program, and I just wrote the simplest program, but i get the following error because of my SDL_pollevent() function:
Test.cpp:(.text._ZN4CApp9OnExecuteEv[CApp::OnExecute()]+0x41): undefined reference to `SDL_PollEvent'
collect2: ld returned 1 exit status

and the code is:
int OnExecute()
{
    if(OnInit()==false)
        return -1;
    SDL_Event Event;
    while(Running)
    {
        while(SDL_PollEvent(&Event))
        {
            OnEvent(&Event);
        }
            OnLoop();
        OnRend();
    }
    OnClean();
    return 0;
}

A: This is a linker error. You are not correctly linking the SDL libraries to your project. Usually you would need to add -lSDL to your linker. If you are using Windows I believe you have to add -lSDLmain too. Make sure your compiler knows where to find these files (set your library path correctly). If you don't know how to do this, check the system and IDE specific installation instructions in this tutorial.
I assume that SDL_Init() is called within OnInit()? Otherwise your program will not run correctly.

A: First, make sure you are including SDL.h, which will look like this on most platforms:
#include "SDL.h"

If you're building on a Mac with Xcode, you'll want to use this instead:
#include <SDL/SDL.h>

Then make sure you've linked against the SDL framework:

*

*If you're using Visual Studio (Windows), right-click the project and bring up the Properties, then under Configuration Properties > Linker > Input, make sure Additional Dependencies is SDL.lib SDLmain.lib.

*If you're using Xcode (Mac), find SDL.framework (probably under /Library/Frameworks) and drag it to your project's Frameworks folder.

*If you're invoking GCC from the command-line, link to libSDL.a and libSDLmain.a by adding -lSDL -lSDLmain to your command-line.


text:
Q: Capistrano 3 version of on_rollback? Upgrading to capistrano 3, the following no longer seems to work:
namespace :project do
  desc "Prevents executing by creating lockfile"
  task :disable do
    on roles(:app) do
      execute "touch /tmp/proj_lockfile"
    end
    on_rollback do
      execute "rm /tmp/proj_lockfile"
    end
  end
end

...
NoMethodError: undefined method `on_rollback' for main:Object
config/deploy.rb:34:in `block (2 levels) in <top (required)>'
Tasks: TOP => deploy:starting => transformer:disable
(See full trace by running task with --trace)

Is there a new task etc to do this?

A: There is no Capistrano 3 equivalent of on_rollback.
In Capistrano 3, if any command fails, the deployment stops, and the release that was being deployed is left in place (possibly working and deployed, possibly not working and deployed, or not deployed - Capistrano no longer attempts to clean up at all).
Note that this also means that :on_error => :continue is unsupported with no replacement; you have to begin/rescue any exceptions yourself.
The rollbacks section of the documentation is completely empty.

A: Take a look at the "Rollback flow" documentation: http://capistranorb.com/documentation/getting-started/flow/
deploy:starting
deploy:started
deploy:reverting           - revert server(s) to previous release
deploy:reverted            - reverted hook
deploy:publishing
deploy:published
deploy:finishing_rollback  - finish the rollback, clean up everything
deploy:finished


text:
Q: Failed to download repository information Ubuntu 13.10 I know that this question has been asked many times but everything I've seen has not helped me.  I'm new to linux.  I'm on 13.10 and I get that message every time I try to update my software sources.  Let me know what other information you need.  Below is the detail under the "Failed to download repository information  Check your Internet connection." message.
W:Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/saucy/universe/source/Sources  404  Not Found [IP: 91.189.91.13 80]
W:Failed to fetch http://us.archive.ubuntu.com/ubuntu/dists/saucy/multiverse/source/Sources  404  Not Found [IP: 91.189.91.13 80]

E:Some index files failed to download. They have been ignored, or old ones used instead.

A: Ubuntu Sauncy (13.10) is already EOL. Upgrade it to a newer release. If I were you, I'd wait the release of 16.04 LTS, and upgrade to that.


text:
Q: How to convert Parametric equation to Cartesian form I need to convert a plane's equation from Parametric form to Cartesian form.
For example:
(1, 2, -1) + s(1, -2, 3) + t(1, 2, 3)

to:
ax+yb+cz+d=0

So basically, my question is: how do I find the a, b, c and d, and what's the logic behind the conversion.

A: Calculate normal vector to this plane :
N = s x t (vector product of two vectors belonging to plane)
Now you have coefficients a, b, c:
N = (a, b, c)

then substitute base point (in general - any point in the plane)
(1, 2, -1) to equation ax+yb+cz+d=0
a+2b-c+d=0

and find d


text:
Q: Concurrent.futures in AWS lambda function implementation I'm using AWS Lambda python functions for copying EBS/RDS snapshots to another region for disaster recovery.
The issue that I encountered is a copy limit of 5 snapshots at the time.
If I tried to copy more then 5 at the time I will get an error:
botocore.exceptions.ClientError: An error occurred (ResourceLimitExceeded) when calling the CopySnapshot operation: Too many snapshot copies in progress. The limit is 5 for this destination region.

To avoid this, I add a waiter function that is checking the status of the snapshot in the destination region and after a snapshot has completed status it continues a loop.
It works well, but in this case, it's coping only one snapshot at the time.
The question is, how to implement concurrent.futures module for a parallel task that will copy 5 snapshots at the time?
    waiter = client_ec2_dst.get_waiter('snapshot_completed')
    message = ""

    for i in ec2_snapshots_src:
            # snapshot_tags_filtered = ([item for item in i["Tags"] if item['Key'] != 'aws:backup:source-resource']
            # snapshot_tags_filtered.append({'Key': 'delete_On', 'Value': delete_on})
            # snapshot_tags_filtered.append({'Key': 'src_Id', 'Value': i["SnapshotId"]})
            try:
                response = client_ec2_dst.copy_snapshot(
                    Description='[Disaster Recovery] copied from us-east-1',
                    SourceRegion=region_src,
                    SourceSnapshotId=i["SnapshotId"],
                    DryRun=False,
                #           Encrypted=True,
                #           KmsKeyId='1e287363-89f6-4837-a619-b550ff28c211',
                )
                new_snapshot_id = response["SnapshotId"]
                waiter.wait(
                    SnapshotIds=[new_snapshot_id],
                    WaiterConfig={'Delay': 5, 'MaxAttempts': 120}
                )
                snapshot_src_name = ([dic['Value'] for dic in snapshot_tags_filtered if dic['Key'] == 'Name'])
                message += ("Started copying latest EBS snapshot: " + i["SnapshotId"] + " for EC2 instance: " + str(snapshot_src_name) + " from: " + region_src + " to: " + region_dst + " with new id: " + new_snapshot_id + ".\n")

                # Adding tags to snapshots in destination region
                tag_src = [new_snapshot_id]
                tag = client_ec2_dst.create_tags(
                    DryRun=False,
                    Resources=tag_src,
                    Tags=snapshot_tags_filtered
                )
            except Exception as e:
                raise e

A: You can use concurrent executor and max_workers parameter to limit how many jobs are run simutaneously. Like this:
import concurrent.futures

def copy_snapshot(snapshot_id):
    waiter = client_ec2_dst.get_waiter('snapshot_completed')
    response = client_ec2_dst.copy_snapshot(
        Description='[Disaster Recovery] copied from us-east-1',
        SourceRegion=region_src,
        SourceSnapshotId=snapshot_id,
        DryRun=False
    )
    new_snapshot_id = response["SnapshotId"]
    waiter.wait(
        SnapshotIds=[new_snapshot_id],
        WaiterConfig={'Delay': 5, 'MaxAttempts': 120}
    )

# Copy snapshots in parallel, but no more than 5 at a time:
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    futures = [
        executor.submit(copy_snapshot, s['SnapshotId'])
        for s in ec2_snapshots_src]
    for future in futures:
        future.result()


text:
Q: Configure Windows Firewall Server 2008 to allow access by only selected IP addresses I have a server running Windows Server 2008 and I need to configure the firewall if possible to only allow access from a few specified IP addresses, any other IP addresses will get rejected unless accessing via port 80, where any IP address can access a website.
It is because I am using NCH Broadcam streaming media server, and currently Port 86 streams the media from the servers IP address (e.g. 1.2.3.4:86) - so I want any access to the server at port 86 to only stream media to whitelisted IP address - any non whitelist IP's will get nothing on port 86.
thanks.

A: Setup an inbound firewall rule and set these settings:

*

*Protocols and Ports list the port(s) number

*Scope tab list the Remote IP addresses you will allow the
connection from

*Make sure the rule applies to the appropriate profiles: Domain,
Private, or Public

*Ensure you have permissions, if you need any, under the Users tab

*Restart the Firewall service after creating the rules

Inbound rules handle other machines accessing your computer. Since you are running a server you have to tell the Firewall that outsiders are allowed to connect to it.
Outbound rules determine which programs are allowed to use the Internet and it blocks others.

A: probably no one needs this anymore, but it seems that for it to work as slybloty described, it'll need to have Public profile enabled. Otherwise it won't work as intended.


text:
Q: Vbulletin Editor BBcodes JS Click event I want to pop up an alert when a user clicks on a BBcode icon in editor.
for example, I have a Spoiler BBcode and I want the event below for it :
onClick=alert("// Something Here")>

Where should I add this event ?! where are the codes for a BBcode which exists in editor ?
More explanation about the thing I need:
I have a Spoiler which makes  tag.
I want to add an option for it like .
"sth" is the string which users insert in a text input which has been alerted after they click on the BBcode icon in Editor. Then, the content will hide or show by clicking on "Sth"
This is my Spoiler code :

<span onClick=" if (this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display != '') {
this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = ''; this.innerHTML = 'Hide'; }
else { this.parentNode.parentNode.getElementsByTagName('div')[1].getElementsByTagName('div')[0].style.display = 'none'; this.innerHTML = 'Show'; }" />

Show

{param}

A: I think you mean this :
/clientscript/ckeplugins/bbcode/plugin.js
The Editor in VB vary widely from the original standalone one.
thus , it seems hard to work with it.


text:
Q: What is inline javascript? Me and my programmer has 2 different views for what "Inline JavaScript" is.

*

*I said inline JavaScript means JavaScript placed directly in the HTML file, without in a .JS file.

*My programmer means inline JavaScript is JavaScript on 1 line, and like <button onclick="alert('test')">
I give him right in, that inline JavaScript also is "onclick='alert(...)" because it again is like my solution #1, all JavaScript loaded in HTML and not in JS.
Who's right?
We have a HTML file, and there is <script>....</script> JavaScript in the bottom, that is inline javascript, right?

A: I've heard the term used for both of those, I don't think either of you is "wrong." I'd say I've heard it used more for #1 than for #2. Most terms I've heard for #2 are more clunky, like "onxyz event handler" or "inline event handler" (thank you Niet the Dark Absol for reminding me) or "DOM0 attribute event handler" or sometimes just "DOM0 handler."

A: A script tag without a src (ie. with code directly in the HTML document) is referred to as an inline script.
An onclick="..." attribute is called an inline event handler.


text:
Q: How do I post nested entity to Spring Data Rest without setting @RestResource(exported = false)? I've read this answer as a solution to POSTing an entity with nested entities. But I want to  make a RESTful POST request.
That is, I want nested entities to be represented with links.
As an example, suppose my client wants to POST a student:
class Student {
  String name;
  Address address;
}

RepresentationModel<Address> address = //feign call to get previously saved address from Spring Data Rest endpoint
Student student = new Student();
student.setName("name");
student.setAddress(address.getContent());
client.save(student); //feign call to save student

This last call fails because Spring Data Rest expects address to be represented as a URI instead of a nested object. How can I add the URI?
I've tried making the Student address field be of type RepresentationModel<Address> but this doesn't work. The server throws an error saying addressId can't be null.

A: So you have your Student:
public class Student {
    private String name;
    private Address address;
}

and Address:
public class Address {
    private String street;
    private String houseNumber;
    private String zipCode;
    ...
}

And because of the fact that Student has a relation to Address you either have to make the relation not required and you wouldn't need the Address in your POST request. Or it's required that the address is already persisted before you try to create the Student and therefore you need the Address in your POST call.

So the flow would look like this:

*

*Create the address with post -> Get the Id/URI back

*With the Id/URI create the Student.
And to implement this you have to adjust the object in the client to the required one. So create a Stundent that looks similar to the required json like this:
public class Student {
    private String name;
    private URI addressReference //probably need to rename this or use JsonProperty annotation
}


text:
Q: node.js cluster with https I'm using the cluster npm for my node app.
var cluster = require('cluster');
var app = express.createServer({
    key: fs.readFileSync('privatekey.pem'),
    cert: fs.readFileSync('certificate.pem')
});

cluster(app)
 .use(cluster.logger('logs'))
 .use(cluster.stats())
 .use(cluster.pidfiles('pids'))
 .use(cluster.cli())
 .listen(443);

But I got the Permission denied when I use port 443. It's working fine if I use another port . Obviously 443 is dedicated to https, so how can I use it for my app ?

A: By default node can't access lower ports (unless you're root). Don't be afraid though since any port will do.
The one usually used for development purposes is 8443:
 .listen(8443);


text:
Q: How to stop printing comma and space after last digit in c Here is the program I wrote:
int main(void)
{
    int d1, d2;

    d1 = 48;
    while (d1 < 58)
    {
        d2 = d1 + 1;
        while (d2 < 58)
        {
            putchar(d1);
            putchar(d2);
            putchar(',');
            putchar(' ');
            d2++;
        }
        d1++;
    }

    putchar(10);
    return (0);
}

Output of the program is as follows:
01, 02, 03, 04, 05, 06, 07, 08, 09, 12, 13, 14, 15, 16, 17, 18, 19, 23, 24, 25, 26, 27, 28, 29, 34, 35, 36, 37, 38, 39, 45, 46, 47, 48, 49, 56, 57, 58, 59, 67, 68, 69, 78, 79, 89, $

I want the output like this:
01, 02, 03, 04, 05, 06, 07, 08, 09, 12, 13, 14, 15, 16, 17, 18, 19, 23, 24, 25, 26, 27, 28, 29, 34, 35, 36, 37, 38, 39, 45, 46, 47, 48, 49, 56, 57, 58, 59, 67, 68, 69, 78, 79, 89$

How can I get the comma to stop before last digit?

A: A different way of doing what @chqrlie does i.e. to print separator before each character.
Before the first character the separators are null characters and for subsequent characters the separators are ',' and ' '.
Implementation:
int main(void)
{
    int d1, d2;
    int sep1 = 0;
    int sep2 = 0;

    d1 = 48;
    while (d1 < 58)
    {
        d2 = d1 + 1;
        while (d2 < 58)
        {
            putchar(sep1);
            putchar(sep2);
            putchar(d1);
            putchar(d2);
            d2++;
            sep1 = ',';
            sep2 = ' ';
        }
        d1++;
    }

    putchar(10);
    return (0);
}

A: There are many ways to solve your problem. You can print a separator before each of the outputs except the first one.
Note also that it would be much more readable to use '0' and '9' instead of hard coding ASCII values such as 48...
Here is a modified version:
#include <stdio.h>

int main() {
    int d1, d2, n = 0;

    for (d1 = '0'; d1 <= '9'; d1++) {
        for (d2 = d1 + 1; d2 <= '9'; d2++, n++) {
            if (n > 0) {
                putchar(',');
                putchar(' ');
            }
            putchar(d1);
            putchar(d2);
        }
    }
    putchar('\n');
    return 0;
}

Here is an alternative using a separator string:
#include <stdio.h>

int main() {
    int d1, d2;
    const char *sep = "";

    for (d1 = '0'; d1 <= '9'; d1++) {
        for (d2 = d1 + 1; d2 <= '9'; d2++) {
            fputs(sep, stdout);
            sep = ", ";
            putchar(d1);
            putchar(d2);
        }
    }
    putchar('\n');
    return 0;
}


text:
Q: How to disable the message "could not access file" in PHP mailer? I am using PHPMailer for sending mail from form with multiple attachments.
This is a part of the form:
 Attachment:<br />
<input type="file" name="attach1" id="attach1" />
<input type="file" name="attach2" id="attach2" />
<input type="file" name="attach3" id="attach3" />

When a user attaches only 1 or 2 files, I added some condition in my email.php:
if(!empty($_FILES['attach1'] ))
{
$mail->AddAttachment($_FILES['attach1']['tmp_name']); // bijlage 1
}
if(!empty($_FILES['attach2']))
{
$mail->AddAttachment($_FILES['attach2']['tmp_name']); // bijlage 2
}
if(!empty($_FILES['attach3']))
{
$mail->AddAttachment($_FILES['attach3']['tmp_name']); // bijlage 3
}

But I still got the message "could not access file" on the empty input fields.
The attachments are being sent correctly to the email address even with this message. But I want to get rid of it when I use only 1 or 2 attachments.

A: All right. This line :
if(!empty($_FILES['attach3']))..

isn't equal false ( array in $_FILES['attach3'] isn't empty: it has ,e.g, error code eq 4 (UPLOAD_ERR_NO_FILE) in $_FILES['attach3']['error'] and some another fields) when you send only 1 and 2 attachements => you see message with "could not access file" in third case. You need to change checks to:
if(!empty($_FILES['attach1']['name'] ))....

if(!empty($_FILES['attach2']['name'] ))....

if(!empty($_FILES['attach3']['name'] ))....

A: You're doing this wrong - you should use move_uploaded_file before accessing the files in $_FILES, as per the docs and the example code provided with PHPMailer.


text:
Q: how to make navigation bar slide from right slide

function openNav() {
     document.getElementsByClassName("menu-overlay").style.width = "50%";
}
function closeNav() {
     document.getElementsByClassName("menu-overlay").style.width = "0";
}
.menu-overlay {
 display: none;
 top: 0;
    height: 100%;
    width: 0%;
 position: absolute;
 z-index: 1;
 right: 0;
 background-color: #ef4f50;
 overflow-x: hidden;
 transition: 0.5s;
}

.menu-body{
 position: fixed;
    top: 0;
    z-index: 99999;
    right: 0;
    height: 100%;
 background-color: #ef4f51;
 width: 35%;
 float: right;
}

span.closer {
    font-size: 50px;
    float: right;
    color: white;
    padding: 30px;
}

.menu-pan{
    width: 100%;
    float: left;
    padding: 0 80px;
}
.menu-pan li {
 padding: 10px 0;
}
.menu-pan li a {
    color: white;
    text-decoration: none;
    font-size: 32px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.css" rel="stylesheet"/>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

        DONATE NOW

Home

About

Our Purpose

HOME

Contact

hello this is my menu bar code.i want my navigation bar to be open when i click on the hamburger icon from right side with transition (smooth) effect with width 50% & remaining part will be overlay.
"https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_overlay" this link has the same effect but from left right.

A: getElementsByClassName function returns an array so using getElementsByClassName("menu-overlay").style would be incorrect. Instead use it like so:
function openNav() {
     document.getElementsByClassName("menu-overlay")[0].style.width = "50%";
}
function closeNav() {
     document.getElementsByClassName("menu-overlay")[0].style.width = "0";
}


text:
Q: Desktop space reservation This might be a bit of a stretch, but is there some software or method available to reserve desktop space, but allow certain programs to use it? Sort of like dividing the desktop so that maximizing a program only takes up a certain amount of the screen?
EDIT: if at all possible I'd like to be able to maximize another window inside the reserved space.

A: I'm not sure I understand. Are you lookign for something like this: MaxTo
There is a few more of them here: Windows Split Desktop Utility

A: this CAN be done with JetToolBar, which is a freeware. This will install a sort of toolbar / launcher, which is what it is. What you need to do next is run this toolbar as NOT always-on-top (just see the program options), and use another program to run the program that you want to run (that I don't know of but any will do) as 'Always on top'. (See download.com, many program can make another one run on top of others).

A: On windows?  Not that I know of.
On Linux, Enlightenment can do this, with specially designated areas for icons etc.  I don't know if it was implemented or not, but I think there was talk of thinking these desktop layouts with wallpapers, so your icons could avoid the nice/complex parts of your background.
KDE can do it a little too, with plasma containers.  There is a windows port of KDE, but that's still quite new, so I wouldn't really recommend trying it yet.
OR, you could probably make a desktop file manager like nautilus run in non-root-window mode, so it's tiled beside other windows.  A tiling window manager would make this very easy to keep alongside other windows without them overlapping.

A: unless you're working with virtual machines, this is not possible in windows.
you can use Actual Window Manager, which will do the following:

placing windows exactly to the
  required place
sizing them exactly as they should be

Actual Window Manager is shareware, try before you buy.
a free alternative would be Eusing's Auto Window Manager. not as powerful though.


text:
Q: How does the distant neighbors factorial identity work? Wolfram has the following identity:
$$n! = \frac{(n+m)!}{(n+1)_m}$$
I'm not sure I'm parsing it correctly — I am assuming the denominator is supposed to be a falling factorial. No qualifications are given on the values of m and n, but I don't know how to evaluate the denominator if $m > n$.  Even if I assume $m \leq n$, it just doesn't appear to be true:
$$3! = 6 \neq \frac{(3+2)!}{(3+1)_2} = \frac{120}{12} = 10$$
What am I missing here?

A: The notation $(k)_m$ is called the Pochhammer's symbol, defined as
$$
(k)_m = k \cdot(k+1) \cdot \dots \cdot (k+m-1) , (k)_0 = 1
$$
Hence we have
$$
\frac{(n+m)!}{(n+1)_m} = \frac{(n+m)\dots(n+1)n!}{(n+1)\dots(n+1+m-1)} = \frac{(n+m)\dots(n+1)}{(n+1)\dots(n+m)}n! = n!
$$


text:
Q: Issue in periodically reading contents of stdout redirected to pipe using dup2 I have to periodically read contents of stdout which is redirected to file. please help me to resolve issue.
My problem in detail is that i have two thread in first thread , i have to execute a c file
 which is continously writing output to stdout(i.e writing hello world in infinite loop) and
 in second thread i have to retrieve line by line output periodically from stdout and store in buffer.
Below is the code for above requirement: please suggest me is my approach right?
 and how to implement entryOpThread() method so that it will read contents of stdout periodically
 whether should i use read() system call or getLine()or any other method to read line by line from
 pipe(stdout is redirected to this pipe).
 In this example exec thread is executing test.c which is continuouslly printing hello world on stdout,
 so according to my requirement i have to read this output line by line("Hello world") continuouslly in Outputthread from pipe and store it in buffer
//
#include<iostream>
#include<pthread>
#include<unistd.h>
#include<sys/wait.h>
const int MAX_LENGTH=100;
using namespace std;

//! file descriptor to duplicate the system standard input
int inputPIPE[2];

//! file descriptor to duplicate the system standard output
int OutputPipe[2];

//!Thread to retrieve output
//!
pthread_t OpThread;

//!Thread to execute script
//!
pthread_t ExecThread;

//! entry point of the exec thread
void *entryExecThread(void * obj)
{
    //create a child process to launch the script
    int lPid;
    lPid=fork();
    //connect read end of the pipe to the standard input
    if(dup2(inputPIPE[0],STDIN_FILENO)==-1)
    {
        //throw exception
    }

    //connect write end of the pipe to the standard output
    if(dup2(OutputPipe[1],STDOUT_FILENO)==-1)
    {
        //throw exception
    }
    if(lPid==0)
    {

        execvp("./test",NULL);
    }

    else
    {
        int mProcessId=lPid;
        waitpid(mProcessId,NULL,0);
    }
    return NULL;

}

//! entry point of the output thread
void *entryOpThread(void * obj)
{
    //read contents of stdout periodically
    char *lMssg=new char[MAX_LENGTH];
    read(OutputPipe[0],lMssg,MAX_LENGTH);

    FILE *fd=fdopen(OutputPipe[0],"r");
    int lBufferLength=MAX_LENGTH;
    /* while(true)
        {
            getline(&lMssg,(size_t * )&lBufferLength,fd);
            // push message to the output buffer
            if (lMssg !=NULL)
            {
                pthread_mutex_lock( &mOutputBufferMutex);
                mOutputBuffer.push(lMssg);
                pthread_mutex_unlock( &mOutputBufferMutex);
            }
        }
     */

}
int main() {

    //call to pipe system call
    if(pipe(inputPIPE)==-1)
    {
        printf("ERROR IN OPENING FILE \n");
    }
    if(pipe(OutputPipe)==-1)
    {
        printf("ERROR IN OPENING FILE\n ");
    }

    //CREATE OUTPUT THREAD TO RETRIEVE OUTPUT

    if (pthread_create(&OpThread,0,entryOpThread,NULL)!=0)
    {

        //throw exception
        printf("Creation of Output thread  failed for Script with ID\n");
    }

    //Create execution thread to launch script
    pthread_t execThread;
    if (pthread_create(&ExecThread,0,entryExecThread,NULL)!=0)
    {

        //Stop output thread
        pthread_cancel(OpThread);
        //throw exception
        printf("Creation of Execution thread  failed for Script with ID\n");
    }
}

test.c
#include <stdio.h>
#include "string.h"
//using namespace std;

int main() {
     int i=0;
     while(i<500)
    {
    printf("!!!Hello World!!! \n" ); // prints !!!Hello World!!!
    //extracting header and data from message
        sleep(5);
      i++;
    }
    return 0;
}

A: Data sent to a pipe is buffered so you don't need another buffer. Just read the data from a pipe whenever there is a need to. You can test whether there is a data to read using poll function. You don't need the reader thread.
Also you don't need exec thread because you are fork'ing anyway.
Besides your application would terminate almost immediately because the main thread would end up after firing secondary threads.
Other thing to point out is that you should close unneeded handles. pipe opens 2 handles, fork duplicates all opened handles, dup2 duplicate a handle. You didn't close any.
If you just want to read output of some process, run it using popen. Below short example.
main app:
int main()
{
    FILE *f = popen("./test", "r"); // open the process

    /* Your application is busy now, but the process runs and outputs */
    sleep(5);

    /* Now assume you need some data - just read it */
    int c;
    while (0 <= (c = fgetc(f))) putchar(c);
}

test app:
int main()
{
    int i;
    for (i = 0; i < 10; i++) {
        puts("Hello world!");
        fflush(stdout);
        sleep(1);
    }
}

If this solution doesn't fit your needs then write what's the problem.


text:
Q: How to send an email attachment with signature in excel I would like to know how to write a macro that would send an email with attachment in excel with user's signature.
The same macro would be used by different users. So it should dynamically read any one (out of multiple html, rtf and txt files) signature file from user's location C:\Documents and Settings\" & Environ("username") "\Application Data\Microsoft\Signatures\[user file]" OR Environ("APPDATA") & "\Microsoft\Signatures\" and send email with that particular user's signature.
Please guide me as how this could be achieved.

A: If you intend to use Outlook automation and Windows XP, it is possible to read the signature from:
C:\Documents and Settings\\Application Data\Microsoft\Signatures
You will find three files:
.htm (HTML)
   .rtf (Rich Text)
   .txt (Plain Text)
You can use Environment variables to get the current user and the FileSystemObject to read in the file.


text:
Q: how to find out which us states have bigger population in 2019 I'm very new to R. I would like to analyze the demographic pattern of Us States.
My dataset looks like these

US State
2020
2019

Hawaii
1,451,911
1,415,872

California
39,368,078
39,512,223

New Jersey
9,365,801
9,365,801

Rhode Island
1,097,379
1,087,379

Texas
29,145,505
28,986,794

Arkansas
3,216,598
3,512,223

My goal is to find out in which US States the population has decreased. Since I am very new I don't know how to code to find out the solution. How can I found out this problem?

A: In R, you can use several ways to achieve this.
First, create the data (next time it would be nicer if you gave your data as code, by pasting in the output of dput(data) or by giving some ready to use dummy-data):
data <- data.frame(
  "US State" = c("Hawaii", "California", "New Jersey", "Rhode Island", "Texas", "Arkansas"),
  "y2020" = c(1451911, 39368078, 9365801, 1097379, 29145505, 3216598),
  "y2019" = c(1415872, 39512223, 9365801, 1087379, 28986794, 3512223))

You can use a tidyverse approach:
library(tidyverse)
new <- data %>%
  filter(y2019 > y2020)

Or the base R approach:
new <- data[data$y2019 > data$y2020,]

Or you could add an additional column indicating whether the condition is TRUE or FALSE:
data$rising <- data$y2019 > data$y2020


text:
Q: Simple SQL query to LINQ I have the following query:
SELECT FROM tblMailToSend
WHERE (DateToSend < @dateToSend OR DateToSend IS NULL) AND DateSent IS NULL

@dateToSend is passed in as a param
I'm trying to convert this to linq to sql query.
I've got:
db.MailToSend.Where(m => m.DateToSend == null || m.DateToSend <= dateToSend)
                    .Where(m => m.DateSent == null)

But this is giving the following SQL:
SELECT *
FROM [dbo].[tblMailToSend] AS [t0]
WHERE ([t0].[DateSent] IS NULL) AND (([t0].[DateToSend] IS NULL) OR ([t0].[DateToSend] <= @p0))

Which is giving the wrong results...
What Linq query would I need to match the correct (first) sql?

A: Try this one:
db.MailToSend.Where(m => (m.DateToSend == null || m.DateToSend <= dateToSend) && m.DateSent == null);

A: The only different is that in your linq statement you are using m.DateToSend <= dateToSend instead of the strict less than in your first sql statement. So change that and everything should be right.

A: Might be a typo, but your SQL is using < whilst your Linq is using <=. Apart from that your queries look like they should produce the same results.

A: In the Linq-question you have DateToSend <= @DateToSend (Less or equal) but in the SQL-query you just check <


text:
Q: SQLAlchemy: Select records with same value in one column and different values in another column I have 4 tables such as Quiz, QuizCompletions, Quizset and Quizset_list(which has the quizzes for a quiz_Set). My requirement is to display Quizset-completions through a sqlalchemy query.
Below are my models for each table.
class Quiz(Base):

    id = Column(Integer(), primary_key=True)
    created = Column("created", DateTime(), default=datetime.utcnow)
    name = Column(String(200), nullable=False)
    quiz_in_quizset_list = orm.relation(
        QuizSetList, backref="quiz", cascade="all, delete-orphan"
    )

class QuizCompletion(Base):

    id = Column(Integer(), primary_key=True)
    created = Column("created", DateTime(), default=datetime.utcnow)

    person_id = Column(
        Integer(),
        ForeignKey("people.id", onupdate="CASCADE", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )

    quiz_id = Column(
        Integer(),
        ForeignKey("quiz.id", onupdate="CASCADE", ondelete="CASCADE"),
        index=True,
    )

class QuizSet(Base):

    id = Column(Integer(), primary_key=True)
    created = Column(DateTime(), default=datetime.utcnow)
    updated = Column(DateTime(), onupdate=datetime.utcnow)
    name = Column(String(200), nullable=False)

class QuizSetList(Base):

    id = Column(Integer(), primary_key=True)
    created = Column(DateTime(), default=datetime.utcnow)
    updated = Column(DateTime(), onupdate=datetime.utcnow)
    quiz_set_id = Column(
        Integer(),
        ForeignKey("quiz_sets.id", onupdate="CASCADE", ondelete="CASCADE"),
    )
    quiz_id = Column(
        Integer(),
        ForeignKey("quiz.id", onupdate="CASCADE", ondelete="CASCADE"),
    )

E.g. A scenario where Quiz1 and Quiz2 are in a quizset, I want to display the people who has completed both those quizzes.
Let's assume that below is the data in QuizCompletions table.

id
created
person_id
quiz_id

1
08.40
5
1

2
09.20
10
2

3
10.30
5
2

My query should identify that only user 5 has completed both quizzes and return the row with the latest time in created column.
Progress so far :
QuizCompletion.query.filter(QuizCompletion.quiz_id.in_([1,2])).all() this returns all the people who has completed either of the quizzes.


text:
Q: Ordinal scale specific selections dc charts I'm plotting a basic bar chart with ordinal x-axis and metric plotted in y-axis. Now, it works good using this post
However, now I want to select only specific data points to show.
Example : if my ordinal x-axis has - a, b & c. But, I need to show only - b & c.
Issue :
When I'm adding only b & c in the domain using the following code, even a is showing up in the background.
Code :
.x(d3.scale.ordinal().domain(["b", "c"])) // Need the empty val to offset the first value
.xUnits(dc.units.ordinal)

I have made a fiddle to show the issue here
Another place for more visibility would be the link here (Look for ordinal bar chart at the bottom - starting from California, London is excluded but still in background)
Is there a fix for this yet/or any workaround? Any approach/suggestions will be highly appreciated

A: I think this has been asked before but I couldn't find it in a quick search.
This is the kind of thing you want to use a fake group for, because it is changing the shape of the data. The crossfilter group will behave as normal but there will be an intervening object which will intercept the results and remove particular bins:
function remove_bins(source_group) { // (source_group, bins...}
    var bins = Array.prototype.slice.call(arguments, 1);
    return {
        all:function () {
            return source_group.all().filter(function(d) {
                return bins.indexOf(d.key) === -1;
            });
        }
    };
}

Add it to your usual crossfilter code like this:
var ndx = crossfilter(...)
var dim = ndx.dimension(...)
var group = dim.group(...) ...

var filtered_group = remove_bins(group, 'a');

chart.dimension(dim)
    .group(filtered_group)
    ...

https://github.com/dc-js/dc.js/wiki/FAQ#remove-particular-bins


text:
Q: Minified React error #130 after Deploy to Vercel on local everything working fine but after deploy /map not working.
full repo: https://github.com/selcukguler0/weather_app
live: https://weather-app-git-master-selcukguler0.vercel.app
stackblitz: https://stackblitz.com/github/selcukguler0/weather_app?file=src/Map.jsx
only map not working.
map.jsx
import TurkeyMap from "turkey-map-react";
import { GridLoader } from "react-spinners"; //Loading animation
import "antd/dist/antd.css";
import { Tooltip } from "antd";
import { useNavigate } from "react-router-dom";
import { Link } from "react-router-dom";

export default function Map() {
    console.log("Type of TurkeyMAp",typeof TurkeyMap);
    console.log("object" === typeof TurkeyMap);
    const navigate = useNavigate();

    return (

                <Link
                    className="text-[40px] text-center font-bold text-blue-500 hover:text-red-500"
                    to={"/"}>
                    Home
                </Link>

                    Map

                <Link
                    className="text-[40px] text-center font-bold text-blue-500 hover:text-red-500"
                    to={"/cities"}>
                    Cities
                </Link>

                <TurkeyMap
                    onClick={({ name }) => {
                        navigate(`/city/${name}`);
                    }}
                    cityWrapper={(cityComponent, cityData) => (
                        <Tooltip
                            title={`${cityData.plateNumber} - ${cityData.name}`}
                            key={cityData.id}>
                            {cityComponent}
                        </Tooltip>
                    )}
                />

    );
}

A: Navigating to /map and opening the console reveals the 130 error which redirects you to this link and shows you the following error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

According to this thread, the problem is in your imports: Element type is invalid: expected a string (for built-in components) or a class/function


text:
Q: How does React capture the props with `const props = this.props` I read the article written by Dan. In the example below
class ProfilePage extends React.Component {
  showMessage = (user) => {
    alert('Followed ' + user);
  };

  handleClick = () => {
    const props = this.props;
    setTimeout(() => this.showMessage(props.user), 3000);
  };

  render() {
    return <button onClick={this.handleClick}>Follow</button>;
  }
}

Why props does not change when this.props changed, since both point to the same reference?

A: props object is immutable, this.props reference may change with time in case new props are received.
It should be:
  handleClick = () => {
    setTimeout(() => {
      const { props } = this;
      this.showMessage(props.user);
    }, 3000);
  };

Also, timeouts should be tracked to be cancelled at component unmount in order to prevent leaks and exceptions.


text:
Q: Convert Firestore timestamp into a date format I have a service that obtains certain data from a BehaviorSubject.
this.myData.album$.value.album_date;

When console logging the returned date from firestore with:
console.log(this.myData.album$.value.album_date);

The console reads:
Timestamp {seconds: 1572263054, nanoseconds: 63000000}

What I need to do is convert this value inside one of my functions and manipulate it into any format, such as "Monday, 28th October 2019".
Unfortunately given my requirement i cannot use the toDate() | inside the HTML and this needs to be achieved within my function.
Any assistance here would be greatly appreciated.
Note: I have moment available to use within my Typescript file.
I am using Angular 8 and Firestore

A: A little bit late to the party, but I've encountered the same issue.
Here is my solution, although not pretty because of the use of any, but it worked for me:
(myAlbumDate as any).toDate()

Now TypeScript doesn't complain anymore and the production building passes without errors.
Update
Today I found myself in the same scenario and because the any type scratches my brain I tried to find a more elegant solution and I found it on another StackOverflow question and I applied it to my use case.
The solution is to extend the Date interface like so:
declare global {
  interface Date {
    toDate: () => Date;
  }
}

Now I have IntelliSense and no more any or errors in my Angular template.

A: https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp#to-date
You need to use Firebase to get the date within your function, and then pass the date to your html:
console.log(this.myData.album$.value.album_date.toDate());

I think may work


text:
Q: Oracle Query to Force results with default 2 years filter experts i want to force my reuslts with always 2 years default filter applied, regardless of user selects that date range or not
below is my approach. is there a better (optimal) way to write this
WITH forcedate as (
Select *
  From emp r
Where
   r.empdate >= to_date(20171019, 'YYYYMMDD')
  And r.empdate <= to_date(20181027, 'YYYYMMDD')
    )
  Select * From forcedate t
  where
  t.empid = 187
--below is the OPTIONAL bind variable for user input
AND t.empdate >= to_date(20171119, 'YYYYMMDD')
  And t.empdate <= to_date(20181227, 'YYYYMMDD');

A: You don't have to filter data twice, use functions greatest() and least():
with dates as (select date '2017-10-19' d1, date '2018-12-27' d2 from dual)
select *
  from emp
  join dates on empdate between greatest(d1, nvl(:input_1, d1)) and least(d2, nvl(:input_2, d2))
  where empid = 187