text:
Q: preserve int64 values when parsing json in Go I'm processing a json POST in Go that contains an array of objects containing 64bit integers. When using json.Unmarshal these values seem to be converted to a float64 which isn't very helpful.
body := []byte(`{"tags":[{"id":4418489049307132905},{"id":4418489049307132906}]}`)

var dat map[string]interface{}
if err := json.Unmarshal(body, &dat); err != nil {
    panic(err)
}

tags := dat["tags"].([]interface{})

for i, tag := range tags {

    fmt.Println("tag: ", i, " id: ", tag.(map[string]interface{})["id"].(int64))

}

Is there any way to preserve the original int64 in the output of json.Unmarshal?
Go Playground of above code

A: Solution 1
You can use a Decoder and UseNumber to decode your numbers without loss :
The Number type is defined like this :
// A Number represents a JSON number literal.
type Number string

which means you can easily convert it :
package main

import (
    "encoding/json"
    "fmt"
    "bytes"
    "strconv"
)

func main() {
    body := []byte("{\"tags\":[{\"id\":4418489049307132905},{\"id\":4418489049307132906}]}")
    dat := make(map[string]interface{})
    d := json.NewDecoder(bytes.NewBuffer(body))
    d.UseNumber()
    if err := d.Decode(&dat); err != nil {
        panic(err)
    }
    tags := dat["tags"].([]interface{})
    n := tags[0].(map[string]interface{})["id"].(json.Number)
    i64, _ := strconv.ParseUint(string(n), 10, 64)
    fmt.Println(i64) // prints 4418489049307132905
}

Solution 2
You can also decode into a specific structure tailored to your needs :
package main

import (
    "encoding/json"
    "fmt"
)

type A struct {
    Tags []map[string]uint64 // "tags"
}

func main() {
    body := []byte("{\"tags\":[{\"id\":4418489049307132905},{\"id\":4418489049307132906}]}")
    var a A
    if err := json.Unmarshal(body, &a); err != nil {
        panic(err)
    }
    fmt.Println(a.Tags[0]["id"]) // logs 4418489049307132905
}

Personally I generally prefer this solution which feels more structured and easier to maintain.
Caution
A small note if you use JSON because your application is partly in JavaScript : JavaScript has no 64 bits integers but only one number type, which is the IEEE754 double precision float. So you wouldn't be able to parse this JSON in JavaScript without loss using the standard parsing function.

A: easier one:
body := []byte(`{"tags":[{"id":4418489049307132905},{"id":4418489049307132906}]}`)

var dat map[string]interface{}
if err := json.Unmarshal(body, &dat); err != nil {
    panic(err)
}

tags := dat["tags"].([]interface{})

for i, tag := range tags {
    fmt.Printf("tag: %v, id: %.0f", i, tag.(map[string]interface{})["id"].(float64))
}

A: I realize this is very old, but this is the solution I ended up using
/*
   skipping previous code, this is just converting the float
   to an int, if the value is the same with or without what's
   after the decimal points
*/

f := tag.(map[string]interface{})["id"].(float64)
if math.Floor(f) == f {
  fmt.Println("int tag: ", i, " id: ", int64(f))
} else {
  fmt.Println("tag: ", i, " id: ", f)
}


text:
Q: Why do some Flutter widget tests fail if executed together but pass individually? When having multiple tests in the same file, and running one test after the other. Some kinds of tests are failing, but the same tests pass when run individually.
This is my test file at the moment, it's kinda long though:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:rec/Components/Inputs/text_fields/DniTextField.dart';
import 'package:rec/Helpers/Validators.dart';

import '../../test_utils.dart';

void main() {
  testWidgets('DniTextField works with invalid DNI', (WidgetTester tester) async {
    var key = GlobalKey<DniTextFieldState>();
    var formKey = GlobalKey<FormState>();
    var onChangedResult;

    var widget = Form(
      key: formKey,
      child: DniTextField(
        key: key,
        onChange: (String value) {
          onChangedResult = value;
        },
        validator: (s) => Validators.verifyIdentityDocument(s),
      ),
    );
    await tester.pumpWidget(
      TestUtils.wrapPublicRoute(widget),
    );
    await tester.pumpAndSettle();

    // Test that widget has at least rendered
    TestUtils.widgetExists(widget);

    // Enter text into field with
    var widgetFinder = find.byWidget(widget);
    await tester.tap(widgetFinder);
    await tester.showKeyboard(widgetFinder);
    await tester.enterText(widgetFinder, 'invaliddni');

    await tester.pumpAndSettle();

    expect(onChangedResult, 'invaliddni');

    expect(formKey.currentState.validate(), false);
  });

  testWidgets('DniTextField works with valid DNI', (WidgetTester tester) async {
    var key = GlobalKey<DniTextFieldState>();
    var formKey = GlobalKey<FormState>();
    var onChangedResult;

    var widget = Form(
      key: formKey,
      child: DniTextField(
        key: key,
        onChange: (String value) {
          onChangedResult = value;
        },
        validator: (s) => Validators.verifyIdentityDocument(s),
      ),
    );
    await tester.pumpWidget(
      TestUtils.wrapPublicRoute(widget),
    );
    await tester.pumpAndSettle();

    // Enter text into field
    var widgetFinder = find.byType(DniTextField);
    await tester.tap(widgetFinder);
    await tester.showKeyboard(widgetFinder);
    await tester.enterText(widgetFinder, '80008000k');

    await tester.pumpAndSettle();

    expect(onChangedResult, '80008000k');

    expect(formKey.currentState.validate(), true);
  });

  testWidgets('DniTextField works with valid DNI with trailing space', (WidgetTester tester) async {
    var key = GlobalKey<DniTextFieldState>();
    var formKey = GlobalKey<FormState>();
    var onChangedResult;

    var widget = Form(
      key: formKey,
      child: DniTextField(
        key: key,
        onChange: (String value) {
          onChangedResult = value;
        },
        validator: (s) => Validators.verifyIdentityDocument(s),
      ),
    );
    await tester.pumpWidget(TestUtils.wrapPublicRoute(widget));
    await tester.pumpAndSettle();

    // Enter text into field
    var widgetFinder = find.byWidget(widget);
    await tester.tap(widgetFinder);
    await tester.showKeyboard(widgetFinder);
    await tester.enterText(widgetFinder, '80008000k ');

    await tester.pumpAndSettle();

    // The value emitted by the field, should be free of trailing whitespace
    expect(onChangedResult, '80008000k');

    expect(formKey.currentState.validate(), true);
  });
}

If I run this like this:
$ flutter test test/Components/inputs/dni_text_field_test.dart

The first test passes, but the next 2 don't, spitting out the following error:
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown running a test:
The finder "zero widgets with the given widget
(DniTextField-[LabeledGlobalKey<DniTextFieldState>#0fb86]) (ignoring offstage widgets)" (used in a
call to "tap()") could not find any matching widgets.

When the exception was thrown, this was the stack:
#0      WidgetController._getElementPoint (package:flutter_test/src/controller.dart:902:7)
#1      WidgetController.getCenter (package:flutter_test/src/controller.dart:841:12)
#2      WidgetController.tap (package:flutter_test/src/controller.dart:273:18)
#3      main.<anonymous closure> (file:///[masked]/test/Components/inputs/dni_text_field_test.dart:99:18)
<asynchronous suspension>
<asynchronous suspension>
(elided one frame from package:stack_trace)

If I then comment out the first test, then the second one passes but the third one does not. As I said the test pass if I run them individually.
I can't find any information about this, not even one thing. Maybe there is someone here that can guide me in the right direction. I'm a bit of a noob with Flutter widget testing, so I might be missing some important things.
The only solution I've found for now is having each test in a separate file. It's not ideal though, would be much better to contain related tests in the same file. Flutter has examples showing that multiple tests per file is allowed as it should be.
Flutter Version: 2.4.0-5.0.pre.87

A: Okay I found the solution and reason, fixed thanks to this issue and this SO question.
The main issue was the use of Localizations that loaded from JSON files. The solution was to wrap each test with tester.runAsync()
testWidgets('widget test 2', (WidgetTester tester) async {
  await tester.runAsync(() async {
    // tests
  });
});

A: I suppose this trouble occure when different test are not craeting different instances of widgets (or they are conflicting in some other way), but there is a turnaround that might help you.
If you want to create a single button running all your tests - you can create a bash (or cmd on windows) file, that is running all your tests sequentially.
Example all_tests.cmd
dart test_1.dart
dart test_2.dart
dart test_3.dart

It is not the clearest solution, but it might work for first time.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to design following dialog How is following dialog box designed, sorry But I am no gui developer but with some initial help I can do this. What I want is tree view is attached to right pane and how it change with selection in the tree view and the lower text also change with each selection.

Any starting point would be helpful.

A: Pure guessing so maybe it's not entirely correct:

Pardon the cheesy colors, I don't know why I did this...


text:
Q: Git push/pull between team members local repositories Lets say there is a team with 4 developers.
We also have a central repository for our project.
Developers push and pull from central repository. Here(in Decentralized but centralized section) it says that its possible to push/pull between team members local repositories.

Each developer pulls and pushes to origin. But besides the centralized
  push-pull relationships, each developer may also pull changes from
  other peers to form sub teams...Technically, this means nothing more
  than that Alice has defined a Git remote, named bob, pointing to Bob's
  repository, and vice versa

Now question is how to define remote name bob which is pointing to Bob's repository.
If it matters developers possibly use different operation systems.

A: If you establish a user account on the host and access permission on the repo, someone else can push/fetch over SSH with or without establishing a named "remote".
git push user@host:/path/to/repo branch

If you share code frequently, you can setup a named remote to remember the server path:
git remote add remotename user@host:/path/to/repo

If it's OK that sharing involve close coordination (and probably very loose security), you can fire up a short-lived git daemon on the "master" as needed: git equivalent of 'hg serve'?  In this case, the above sharing commands still apply, but the user@host:/path will be replaced by git://host/.  See also git daemon documentation.
Alternatively, you could setup a separate dedicated repository to use for intermediate sharing: How do I setup a staging repository in git?

A: It's a very common thing like Alice and Bob need to work on some functionality together. In the mean time, the development should be carried on different branches by different developers.
Simple approach would be:

*

*Create a new branch sprint_1, Alice and bob checkout to sprint_1

*All the changes related to functionality should be done here

*Push and pull operations should be performed using
git pull origin sprint_1  and git push origin sprint_1

When the changes are done and sprint_1 has a stable code, it could be merged with other branch. If the code on sprint_1 has come a long way, it is advised to rebase the branch than merge to avoid conflicts or cherry picking.

A: Similar to GIT clone repo across local file system in windows
Per J.F.Sebastian reply:

$ git clone --no-hardlinks /path/to/repo

The above command uses POSIX path notation for the directory with your
  git repository. For Windows it is (directory C:/path/to/repo contains
  .git directory):
C:\some\dir\> git clone --local file:///C:/path/to/repo my_project

The repository will be clone to C:\some\dir\my_project. If you omit
  file:/// part then --local option is implied.

A: If the two repos share a filesystem namespace you can just use the filesystem paths directly.  Otherwise the developers can easily run local git servers, on e.g. a VPN where access is already workably private the git daemon command will serve fetches just fine, otherwise you can set up ssh access on a dedicated port to achieve the same effect with a bit more work.

A: I wanted to do a similar thing, in my case I was looking for an easy way to synchronise a project on an embedded system (running Linux). Previously I just setup a shared internet connection and pulled from the centralised repository. But I didn't find it easy to work like this, and sometimes my internet connection is just poor.
In the following article the use of git daemon is explained very nicely to solve this problem. I'll just put a brief copy of the contents here:
http://railsware.com/blog/2013/09/19/taming-the-git-daemon-to-quickly-share-git-repository/
Setup the following aliases for read access (serve) or read/write access (hub) to your repositories:
$ git config --global alias.serve "!git daemon --base-path=. --export-all --reuseaddr --informative-errors --verbose"
$ git config --global alias.hub "!git daemon --base-path=. --export-all --enable=receive-pack --reuseaddr --informative-errors --verbose"

Then on the host just execute git serve or git hub from the directory where the repositories you want to share reside. Now on the client one can execute git clone git://x.x.x.x/path/to/repo to access the local repository on the host!
For windows users:

*

*Use double quotes in the commands to setup the aliases

*Be sure to 'hang' the command-prompt for it to not output any line by right clicking on the title bar and choosing Edit->Mark. Otherwise connections to clients might be interrupted due to a bug in git (according to a comment in the blog post).

A: TL;DR - You want to perform the steps in chapter 4.4 for each machine serving as a remote.
Getting a true distributed workflow is not all that difficult if you have the freedom between your machine and the machines you want to share with. Essentially you need each machine serving a repo to act as an SSH git server.
A few answers here state that you can simply add users between the machines and use the user password to establish SSH. Chapter 4.1 and 4.4 of the git book also detail the creation of a single user that grants access to remote requests by a list of SSH keys in the ~/.ssh/authorized_keys file. This seems like a nice consolidated approach to managing the access given to your colleagues, but still requires managing user keys in the authorized_keys file for the consolidation account. Something to consider since this is "your" dev box and not a proper "server".
Having never used git daemon I can't exactly say how much better or not it is, but it does seem like a viable option if you're willing to use the git protocol, and have a good understanding of running it on each machine that should serve a repository from a secure position in your network. It might also be helpful here to state that the documentation mentions the following when referring to firewall settings:

If you're running a firewall, you'll also need to punch a hole in it at port 9418 on the box you're setting this up on


text:
Q: Extending polyfit line in MatLab I am trying to extend my polyfit line of best fit in Matlab. I want it to extend to y = 200 and x = 64. What would be the best way of doing this?
Cheers Tom
Link to image of polyfit through data

A: Plot your polyval over a different range. Something like that should work:
% Make up data
x = 1:100;
y = -0.03.*x.^2 + 2*x + 10*randn(size(x));
x2 = -50:150;

P = polyfit(x,y,2);

plot(x,y,'o',x2,polyval(P,x2),'--');
grid on;


text:
Q: how to get people picker text using javascript I want to compare text of 2 people picker which are on same form.how to do it using JavaScript or Jquery. I have already gone through so many blogs but they are not providing the exact solution that i want.

A: You can use a Sharepoint function to do it that is called GetPickerControlValue. You'll need to known the HTML ID of the both fields. Then just use GetPickerControlValue("ID_of_the_UserField", false, false) to get the value.

A: SPUtility.js is free javascript library which does this very well.
Example
You need to add the js reference in your master page.
// Get the field
var peopleField = SPUtility.GetSPField('Assigned To');
//here "assigned to" is field name

spservices.js also supports this.
Example
var salesRep = $().SPFindPeoplePicker({
    peoplePickerDisplayName: "Column Display Name"
});

Let me know if you need more help.


text:
Q: Read CSV file from FTP and update records in salesforce I want to read a csv file from SFTP server and using that i need to update records or mark checkbox field true in Salesforce. This needs to be scheduled to run everyday. Can you please suggest a better approach for this? Don't want to use informatica cloud/ Jitterbit Data Loader.
Few method i thinked use Command line data loader inside FTP server to push the data into salesforce?

A: You can't access files(either upload or download) from FTP in Apex Code or other from Salesforce.
Your best bet would be to use an external application. CastIron, Dell Boomi is the go to application for FTP interactions with salesforce.
Also you can create your own webservice outside of the salesforce platform and call it from Apex.


text:
Q: Is it possible to solve recursive percent equations? I'm working on a program that calculates the skill level of a sports teams based on how well its done against other teams. Something along the lines of, your skill is +20% of the average skill of the teams you beat.
This quickly becomes a math problem where:
x = (y+z)/2
AND
y = (x+z)/2
AND
z = (x+y)/2
Obviously, this is not good, at least in my understanding of math. Is there a way around this? Or am I trying to do something impossible and will have to figure out some way of doing this that does not result in a potential loop?
Thank you in advance.


text:
Q: Clipping raster to multiple rasters for each parcel using ArcGIS Desktop? I have a raster aerial photo.  I have county wide parcel data.
I want to clip/screen shot the raster at each individual parcel.
Think of this application - a post card with an image of your house --here is your house--
I want to have each parcel attribute to contain information + hyperlink of the aerial photo.
Any other solutions welcome, but this is the only method I could think of. Although I am unsure of how to achieve it efficiently.
Using ArcInfo 10.

A: Check out this ArcGIS Forum Posting - it sounds a lot like what you are wanting to do.
I found it by thinking along the lines of a map book with a page for each property and the need to apply a graphic clip or mask to leave just the property image showing.
Your map pages would need to be exported to the format of your choice and those locations written using an ArcPy update cursor into the attribute table.
From @Thad as a comment:

But it is simpler. Here is the workflow. Use Data Driven Pages, but
  instead of using a grid use the parcel polygons as the map extents.
  Then Layer properties - dataframe - clip to current data driven pages
  extent.

A: You could try to subset your raster via Image Analysis Window - Clip Tool.
This tool is fine to cut any parts of your image. http://goo.gl/E3ivO


text:
Q: SQL most commonly occurring I want to find out, which actors are mostly playing in comedy movies.
The majority of their filmography have to be comedy.
So when a actor has 7 movies and 4 of them are comedy.
(And also all actors who only have played comedies.)
Table "actor":
|id_actor| name |
|--------|------|
|  12    |franco|
|  13    |rogen |
|  14    |hill  |
|  15    |teller|
|  16    |john  |

Table "genre"
|id_genre|    name    |
|--------|------------|
|  22    |comedy      |
|  23    |thriller    |
|  24    |documentary |

Table "plays_in":
|id_actor|    id_film |
|--------|------------|
|  12    |      5001  |
|  12    |      5002  |
|  12    |      5003  |
|  13    |      5004  |
|  13    |      5005  |
|  13    |      5006  |
|  14    |      5007  |
|  14    |      5008  |

Table is_in_genre
|id_genre|    id_film |
|--------|------------|
|  22    |      5001  |
|  22    |      5002  |
|  22    |      5003  |
|  23    |      5004  |
|  23    |      5005  |
|  24    |      5006  |
|  24    |      5007  |
|  24    |      5008  |

This is what I have, but it doesn't show actors, that only played comedies.
select      id_actor, name
from        actor x where
(
    select      count(id_film)
    from        actor y
    natural join plays_in
    natural join movie
    natural join is_in_genre
    where       id_genre = 4001 and x.id_actor = y.id_actor
    group by    id_actor
)
<=
(
    select      count(id_film)
    from        actor y
    natural join plays_in
    natural join movie
    natural join is_in_genre
    where       id_genre != 4001 and x.id_actor = y.id_actor
    group by    id_actor
)

A: Join all 4 tables and group by actor.
To get only actors who only played more than 50% comedies the condition after grouping is:
having (1.0 * sum(case when genrename = 'comedy' then 1 else 0 end ) / count(genrename)) > 0.5.
select
  t.actorname
from (
select
  actor.name actorname, genre.name genrename
from actor
inner join plays_in
on plays_in.id_actor = actor.id_actor
inner join is_in_genre
on is_in_genre.id_film = plays_in.id_film
inner join genre
on genre.id_genre = is_in_genre.id_genre
) t
group by t.actorname
having (1.0 * sum(case when genrename = 'comedy' then 1 else 0 end ) / count(genrename)) > 0.5

See the demo

A: A movie is a comedy when one of its genres is comedy. The actors you are looking for are those whose movies are mainly comedies.
with comedies as
(
  select id_film
  from is_in_genre
  group by id_film
  having count(case when id_genre = (select id_genre from genre where name = 'comedy') then 1 end) > 0
)
, comedy_actors as
(
  select id_actor
  from plays_in
  group by id_actor
  having avg(case when id_film in (select id_film from comedies) then 1 else 0 end) > 0.5
)
select *
from actor
where id_actor in (select id_actor from comedy_actors);


text:
Q: HTML5 and peripherals I have done a search on this and I think I actually came away more confused.  We are looking for a solution where we supply a card swiper for a mobile device. Just a swiper, we do not need a gateway solution.
We want to be able to have someone swipe a card and then have the card information auto-populate in an HTML form.
Simple question:  Is this possible and if so, any suggestions on how to go about it?  I cant seem to find much out there on this.
Thanks,

A: Pretty sure you need a activex or similar installed in the brower, to get hold of the PC's comport. I used Silverlight for the same reason. Wanted the input from a barcode scanner to act different that the operators input.
Hope it helps :)


text:
Q: Using 64 bit integer iterator for 32 bit address space? I'm writing some code (that runs on an FPGA) that writes a pattern to a block of memory specified by it's base address and highest address. The data width is 64 bits and the address space is 32 bits. On my system longs are 32 bits and long longs are 64 bits. The code looks something like this:
unsigned long base_addr = 0xC0000000;
unsigned long high_addr = 0xFFFFFFFF;
unsigned long long i;

for(i = base_addr; i <= high_addr; i += 4){
    *((unsigned long *) i) = some_pattern;
}

Everything works fine but I get a "cast to pointer from integer of different size" warning from the compiler. If I use a 32 bit iterator variable the code loops infinitely since the iterator hits 0xFFFFFFFC and then overflows back to 0 again.
Is there a better way to do this? I know there are lots of ways to use a 32 bit iterator without problems (detect/predict the overflow, subtract 3 from the high_addr) but I think this code is the simplest and most readable. Is it considered bad style to write code with known compiler errors?

A: Why are you declaring i as unsigned long long? What is the point of that?
As you said yourself, addresses on your platform are 32 bit. Declare i as unsigned long, just like base_addr and high_addr. The warning should disappear.
Meanwhile, what is the meaning of "data width is 64 bits"? If the data (and the pattern) is actually 64 bits, then you should be doing
for (i = base_addr; i <= high_addr; i += 8){ /* or i += sizeof(unsigned long long) */
    *((unsigned long long *) i) = some_pattern;
}

Also, note that if, for example, i becomes equal to high_addr during iterations, your cycle body will still execute, accessing 7 extra bytes beyond high_addr. Was that the intent?

A: My idea of a better way to do it:
unsigned long long *base_addr = (unsigned long long *)0xC0000000;
unsigned long long *high_addr = (unsigned long long *)0xFFFFFFFF;
unsigned long long *i;

for (i = base_addr; i < high_addr; ++i) {
    *i = some_pattern;
}

May need to be careful of pointer (i) wrap-around, by aborting the for loop if i < base_addr too.


text:
Q: printing 2 characters and keeping them through dynamically allocated 2d array Hello I am trying to print something like this with 2d array.
Note that when user enters the same number, character should be printed above existing char.
EXPECTED RESULTS:
Input 1: 3  //user1 inputs 3

****
****
**x*

Input 2: 1 //user2 inputs 1

****
****
y*x*

Input 3: 1 //user1 inputs 1

****
x***
y*x*

current results:
enter first: 3
3***
***
**x
enter second: 1
1******
******
xx****
enter first: 2
2*********
*********
***xxx***

But keeping printed values on its previous places.
The problem is that they don't get printed in right order. And also it seems that I haven't done the best job with 2d array which is dynamically allocated.
Here is something what I've tried:
#include <stdio.h>
#include <stdlib.h>

int num(int term)
{
  int number1;
  int number2;
  if(term==1)
  {
    scanf("%d", &number1);
    return number1;
  }
  if (term==2)
  {
     scanf("%d", &number2);
    return number2;
  }
  return 0;
}

void function(int a, int b, int result[], int size)
{

  int i = 0;
  int j = 0;
  int desired_num = 0;
  int count = 0;
  int *arr[a];

  for (i = 0; i < a; i++)
    arr[i] = (int *)malloc(a * sizeof(int));

  for (i = 0; i < a; i++)
    for (j = 0; j < b; j++)
      arr[i][j] = ++count;

  for (i = 0; i < a; i++)
  {
    for (j = 0; j < b; j++)
    {
      for (int counter = 0; counter < size; counter++)
      {
        if (arr[i][j] == arr[a - 1][result[counter] - 1])
        {
          arr[i][j] = desired_num;
        }

        if (arr[i][j] == desired_num)
        {
          printf("%s", "x");
        }
        else
        {
          printf("*");
        }
      }
    }
    printf("\n");
  }
}

int main()
{
  int counter = 1;
  int i = 0;
  int given_number;
  int array[20];
  for (;;)
  {
    if (counter % 2 != 0)
    {
      printf("enter first: ");
      given_number = num(1);
      printf("%d", given_number);
    }
    else
    {
      printf("enter second: ");
      given_number = num(2);
      printf("%d", given_number);
    }
    array[i] = given_number;
    function(3, 3, array, counter);
    counter++;
  }

  return 0;
}

A: array[i] = given_number;

i is never changed from the value of 0. You are only ever overwriting the first element of array each iteration. The other 19 elements remain in an indeterminate state.
counter and array are passed to function, as size and result respectively:
This means as size is incremented, it is used as a bounds for accessing elements of result; elements that contain indeterminate values.
for (int counter = 0; counter < size; counter++)
{
    if (arr[i][j] == arr[a - 1][result[counter] - 1])

This will surely lead to Undefined Behaviour as those indeterminate values are used to index arr, effectively accessing random memory offsets. This fact alone makes it hard to reason about the output you are seeing, as really anything is valid.

While perfectly valid, the variable-length array of dynamic allocations is a somewhat perplexing choice, especially considering you fail to free the memory allocated by malloc when you are done with it.
int *arr[a];

for (i = 0; i < a; i++)
    arr[i] = (int *)malloc(a * sizeof(int));

int arr[a][b]; would work, given a and b are not stack-crushingly large values (or non-positive). You are, or would be, bounded by the size of array in main anyway.

The triply nested loop is confused at best. There is only logic for printing the x and * characters, so you obviously will never see a y.
For each element of arr, you iterate through each element of result. If the current element of arr equals the value of the column selected by the current value of result ([result[counter] - 1]) in the last row (arr[a - 1]) you print x, otherwise *.
Again UB from utilizing indeterminate values of result, but you can see you are printing a * b * size characters, plus newlines, each iteration.
This is severely flawed.

Some other things of note:
The two branches of the if .. else statement in the num function do the exact same thing, just with different identifiers.
The two branches of the if .. else statement in main are identical, other than the first printf in each, and the integer value passed to num, which have the same effect.
This means the only thing that needs to branch is the printf argument.
A generic function for getting an integer would work fine
int get_num(void)
{
    int n;

    if (1 != scanf("%d", &n)) {
        fprintf(stderr, "Could not read input.\n");
        exit(EXIT_FAILURE);
    }

    return n;
}

for use inside main
if (counter % 2 == 0)
    printf("enter first: ");
else
    printf("enter second: ");

given_number = get_num();

A small issue: printf("%d", given_number); is muddling the output slightly.

There is no reason to repeatedly generate the array. Initialize an array in main to serve as the state of the program. Over time, fill it with the users' selections, and simply print the array each iteration.
Make sure to always check the return value of scanf is the expected number of conversions, and ensure the integers provided by the users will not access invalid memory.
Here is a cursory example.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define EMPTY '*'
#define PLAYER_ONE 'X'
#define PLAYER_TWO 'O'

int get_num(void)
{
    int n;

    if (1 != scanf("%d", &n)) {
        fprintf(stderr, "Could not read input.\n");
        exit(EXIT_FAILURE);
    }

    return n;
}

int main(void)
{
    const size_t rows = 6;
    const size_t cols = 7;

    char board[rows][cols + 1];

    memset(board, EMPTY, sizeof board);

    /* our rows are now strings */
    for (size_t i = 0; i < rows; i++) {
        board[i][cols] = '\0';
        puts(board[i]);
    }

    unsigned char turn = 1;

    while (1) {
        printf("Player %s, Enter column #(1-%zu): ",
                turn & 1 ? "One" : "Two", rows);

        int input = get_num();

        if (1 > input || input > cols) {
            printf("Invalid column [%d]. Try again...\n", input);
            continue;
        }

        size_t sel = input - 1;

        if (board[0][sel] != EMPTY) {
            printf("Column [%d] is full! Try again...\n", input);
            continue;
        }

        size_t n = rows;

        while (n--) {
            if (board[n][sel] == EMPTY) {
                board[n][sel] = turn & 1 ? PLAYER_ONE : PLAYER_TWO;
                break;
            }
        }

        for (size_t i = 0; i < rows; i++)
            puts(board[i]);

        turn ^= 1
    }
}


text:
Q: How do you add environment variables to your django project I'm trying to set up my project so that it can use environment variables locally
Ive tried adding it to the end of my activate file and a list of other things. I'm trying to use this
from .base import *

    if os.environ['DJANGO_SERVER_TYPE'] == 'local':
        try:
            from .local import *
        except:
            pass

    if os.environ['DJANGO_SERVER_TYPE'] == 'production':
        try:
            from .production import *
        except:
            pass

I am a real novice and often things are explained brief and matter of factly. So a thorough explanation would really be beneficial to me in how to implement this thanks. I've NEVER done anything n Bash. Ive tried doing this
export KEY=VALUE

in the activate file, only for it not to be recognized by the system, and I had to remove it in order to use my local server

A: I have a settings module that contains something like the following:
…
import os
from django.core.exceptions import ImproperlyConfigured
…

def _require_env(name):
    """Raise an error if the environment variable isn't defined"""
    value = os.getenv(name)
    if value is None:
        raise ImproperlyConfigured('Required environment variable "{}" is not set.'.format(name))
    return value

…

SECRET_KEY = _require_env('SOMETHING_SECRET_KEY')

_db_host = os.getenv('SOMETHING_MYSQL_HOST', 'mysql')
_db_port = os.getenv('SOMETHING_MYSQL_PORT', 3306)
_db_name = _require_env('SOMETHING_MYSQL_DATABASE')
_db_user = _require_env('SOMETHING_MYSQL_USER')
_db_password = _require_env('SOMETHING_MYSQL_PASSWORD')

DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql',
                     'NAME': _db_name,
                     'HOST': _db_host,
                     'PORT': _db_port,
                     'USER': _db_user,
                     'PASSWORD': _db_password,
    … } }

and so on.
_require_env is for environment variables that must be set. If those environment values are not found, Django immediately raises an ImproperlyConfigured error. In other cases I just use os.getenv with a default value.

A: If you're running it through the Django web server, you can pass environment variables the same way you would to any other command:
DJANGO_SERVER_TYPE="local" ./manage.py runserver

If you're running it through a web server like Apache, you can set environment variables through your virtual host configuration:
SetEnv DJANGO_SERVER_TYPE local

A: Install the environ library and add the following code to your settings file:
root_path = environ.Path(__file__) - 2
env = environ.Env(DEBUG=(bool, False), DJANGO_ENV=(str, 'dev')) # set default    values and casting
environ.Env.read_env(root_path('.env'))

Add a file called .env on the root of your project folder with variables formatted like:
DEBUG=on


text:
Q: How do gulp pattern recursive work **/* i started to use gulp, i have a little difficulty understand how globs work in gulp.
Why do **/* copy all directory structure(how it work)

A: Gulp uses the glob module. Rules for globbing can be found in its repo.

*

** Matches 0 or more characters in a single path portion

*** If a "globstar" is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories.

** means "recursively descend through subdirectories" while * means "match any path".

A: Extending your folder structure  css/**/*.css
** means recursive.
This means your telling gulp to go inside css folder and all it's subdirectories and  compile all files that has an extension .css


text:
Q: Changing value of global javascript variable I'm attempting to change the value of a global variable inside a javascript function, however, the value does not seem to be taken, and I'm not sure why. (Admittedly, I am not an experienced javascript person.) Here is my code:
var title_chart = "";

google.load("visualization", "1", {packages:["corechart"]});

google.setOnLoadCallback(drawChart);

function drawChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Country');
  data.addColumn('number', 'Number of Entries');

  jQuery.getJSON('/data/stats.json', function(chart_data) {
    title_chart = chart_data.chart_title;
    jQuery.each(chart_data.stats, function(index, value){
      data.addRows(1);
      data.setValue(index, 0, value.chart_label);
    });
  });

  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 450, height: 300, title: title_chart});

}

Thanks!

A: getJSON is asynchronous.  Do this instead:
jQuery.getJSON('/data/stats.json', function(chart_data) {
  var title_chart = chart_data.chart_title;
  jQuery.each(chart_data.stats, function(index, value){
    data.addRows(1);
    data.setValue(index, 0, value.chart_label);
  });

  var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
  chart.draw(data, {width: 450, height: 300, title: title_chart});
});

The issue is that getJSON returns immediately.  Only later, when the request completes, is your callback called.  In the meantime, chart.draw may have already run.  By moving this code into the callback function, we ensure it runs at the right time.  Also note that we can eliminate the global.


text:
Q: Class not being built using Scala Eclipse plug-in I'm trying to use the Scala Eclipse plug-in (version 1.1.0, which appears to be the most current) with version 3.7 of Eclipse on Mac OS X 10.6.8. I've copied the "Hello, World" program from a tutorial website. I was able to build the program successfully using the command-line scalac compiler. However, when I attempt to run the project as a Scala application from within Eclipse, I get an error like so:
Exception in thread "main" java.lang.NoClassDefFoundError: de/vogella/scala/first/Hello

with a bunch more stuff following. Looking in the relevant directory structure in my Eclipse workspace directory shows that the associated bin directory is completely empty. However, there are no errors (and indeed no messages of any sort) when I select "Build Project" from the menu.
As far as I can tell, my Eclipse installation is otherwise functional. I can, for instance, successfully build and run Java projects.
Any tips on where to start with troubleshooting would be greatly appreciated. Trying the suggested solutions in the most relevant-seeming existing question didn't work.
EDIT to add: There isn't anything in the Error Log window except this:
System property http.nonProxyHosts has been set to
local|*.local|169.254/16|*.169.254/16 by an external source. This value will be
overwritten using the values from the preferences

which doesn't strike me as terribly relevant. The full text, as copied from the tutorial, of the Hello.scala file, is
package de.vogella.scala.first

object Hello {
  def main (args: Array[String]) {
    println("Hello, world!")
  }
}

and the package the file is a part of is called de.vogella.scala.first.

A: I followed Kipton Barros' suggestion from the comments, and installed the 2.0.0 beta of the Scala IDE plug-in for Eclipse. While I find it slightly strange that switching from a final release to a beta release resolved the issue, resolve the issue it did.
(Too bad I can't accept a comment as the answer.)

A: Check if the package declaration in your scala file match the packages in eclipse.


text:
Q: sending a url to another page I wrote the following javascript code for prompting the user to enter a password before he can access a page. Also, I want to send a url to the page which is going to load if the password is correct. Is it the correct way of sending the url of another html page to that page
function pagePassword(url)
{
var password;
var pass1="xxxxxx";
password=prompt('Please enter the page password:',' ');
if (password==pass1)
{
//code to send a url of another html page to the page which is going to load if the password entered by the user is correct
window.location="http://nano.uark.edu/nanophpscripts/xxxxxxx.php?pageurl="+url;
}
else {
alert('Wrong password!');

}
}

This is the code for the edit_backend.php page. The page gets the url of another html page and opens it's source code in a text  box
$url=$_GET["pageurl"];
echo "<textarea name=\"content\" id= \"content\" cols=\"90\" rows=\"40\">";
$handle = fopen("$url","r");
while(!feof($handle))
{
$text = fgets($handle);
echo $text;
}
fclose($handle);
?>

 echo "</textarea><br>";

A: Do password-handling server-side, not with javascript. Anyone could just look at the javascript and see the password, or which page they are going to.

A: well, you have to escape the url in javascript - probably :
"http://........?pageurl="+escape(url);

And inside the php script:
$prevpagename=htmlspecialchars(urldecode($_GET["pageurl"]));

Probably that should work.
Of course as guys suggested above, comparing your password at the clientside is not quite a smart thing to do.

A: First, you shouldn't keep any sensitive data whatsoever in Javascript where anyone can simply view the source code. You need to handle the login with your PHP.
Second, just for fun, I cut and pasted your window.location link into my browser and within 3 minutes was able to view all the source code from your php files, including you database login details, right there in your little app.
You might not want to let that happen...


text:
Q: Storing a reference to an object from inside another class in Java? So I am making a class that performs an action when a specific event happens. Basically, a variable gets changed to a different value. What I need to do is store a reference to this object from inside the constructor. Here is the code that I am working with to give everyone a better picture:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Created by iJason on 8/26/2016.
 */
class ClickListener implements ActionListener {
    JLabel label;

    public void actionPerformed(ActionEvent event) {
        label.setText("I was clicked.");
    }

    public ClickListener(JLabel label) {
        this.label = label;
    }
}

So whenever the "actionPerformed" method is called, I want the "label" that is getting passed in to the constructor to actually change. So I need to set a reference to it from the constructor but I am not sure how to do that in Java. Thanks in advance for all the help!

A: Java uses pass by value. But in the case of objects, the value passed is a reference to the actual object. Which means that the text of the label that is getting passed to the constructor will change. Long story short, your code already does what you want.

A: Java is always pass by value. It is never pass by reference.
Please refer to proper explanation which explains above statement  with examples here.
In your example,
public ClickListener(JLabel label) {
    this.label = label;
}

actually, the value( i.e. instance of JLabel) is passed to the constructor method, in which it is assigned to a member variable(i.e reference) of the class ClickListener. Hence the variable ClickListener.label refers to the object being passed. Therefore any modifications done to through ClickListener.label reference variable will be reflected in the original object until it is assigned with new instance of an object.


text:
Q: How to fix:Parse error: syntax error, unexpected ',' in /home/monkeybu/public_html/index.php on line 2 Can some one help me fix this?
Parse error: syntax error, unexpected ',' in /home/monkeybu/public_html/index.php on line 2
I am using x10hosting for my host.
Here's my code:
  <?php
    require_once "lib/steam-condenser.php",
    require_once "config.php";
    $id = $_GET['sid'];
    $getData = SteamId::create($id);
    ?>
    <!DOCTYPE HTML>

        <meta charset="UTF-8">
        <link rel="stylesheet" href="css/main.css" type="text/css" media="screen">
        <link rel="stylesheet" href="css/jquery.maximage.css" type="text/css"      media="screen" title="CSS" charset="utf-8" />

filename.vmt 0%

    <?php
    echo '
        getFullAvatarUrl().'" width="299">

serverName

'.$getData->getNickname().'['.SteamId::convertCommunityIdToSteamId($id).']

mapName

';
    ?>

    <?php
        if($loadingScreen['backgroundMusic'] != "")
        {
            $ytLink = explode("v=", $loadingScreen['backgroundMusic']);
            echo '';
        }
    ?>

        <?php
        $imgDir = scandir("images/backgrounds/");
        $picNum = 0;
        foreach($imgDir as &$files)
        {
            $picNum++;
            if($picNum >= 3)
            {
                echo "\n";
            }
        }
        ?>

config:
<?php
$loadingScreen['backgroundMusic'] = "http://www.youtube.com/watch?v=0UjsXo9l6I8";     //Only youtube links.. (for now). (if you dont want to play music leave it blank)
?>

steam:
<?php
/**
 * This code is free software; you can redistribute it and/or modify it under
 * the terms of the new BSD License.
 *
 * Copyright (c) 2010-2013, Sebastian Staudt
 *
 * @author  Sebastian Staudt
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 * @package steam-condenser
 */

define('STEAM_CONDENSER_PATH', dirname(__FILE__) . '/');
define('STEAM_CONDENSER_VERSION', '1.3.6');

require_once STEAM_CONDENSER_PATH . 'steam/community/SteamId.php';

A: This line:
require_once "lib/steam-condenser.php",
                                //-   ^ should be a semi-colon

should have a semi-colon and not a comma
require_once "lib/steam-condenser.php";

Dagon, sorry I saw your comment after I posted this.


text:
Q: Already display the player card value but have an error range() integer end argument expected, got list Whenever I display the playerscards I get an error saying

range() integer end argument expected
  But list.below is in my code. Any help would be much appreciated.

def cards(self, handsize):
    global playerscards
    playerscards = []
    for i in range(handsize):
        playerscards.append(str(self.cards[randrange(52)]))
        print playerscards
    return playerscards

def main():
  n=Deck()
  n.cards(playerscards)
main()

Output:
 for i in range(handsize):
 TypeError: range() integer end argument expected, got list.

A: The error is telling you exactly what is wrong. The range() function's first positional argument has to be an integer, but you are passing it a list. Where are you passing in handsize? Make sure that you are actually passing in what you think you are.


text:
Q: Difficulty connecting Mysql to Spring Boot I am new to Spring Boot and have been attempting to connect it to my MySql workbench. I started a new Spring Boot project with web, jdbc, jpa, and hibernate, but have been stuck.
There are a number of tutorials on this subject, but they all start by indicating that it's necessary to go into the application.properties file and add a configuration similar to the below:
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/mysqltutorial?useSSL=false
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

However, none of the tutorials I have found discusses how to find the spring.datasource.url or even the username or password.
How can I find update these application properties so my Mysql workbench will connect to my Spring Boot application?

A: In your case,
spring.datasource.url is equal to jdbc:mysql://localhost:3306/mysqltutorial?useSSL=false
Breaking it up:
jdbc:mysql://localhost:3306 is a reference to MySQL that is running locally on your machine. By default, MySQL runs on port 3306, though it can be changed if you so desire. Additionally, the address can be changed from localhost if you want to connect to a database that is running elsewhere.
mysqltutorial is the name of your database created in MySQL.
?useSSL=false is an additional property of connecting to the database.
Next,
spring.datasource.username and spring.datasource.password are the password and username you use for the database in MySQL. For a small project, you can use root, though that is not recommended for more serious projects and another user should be created with varying permissions.

A: Springboot is autotool to generate Java Config Object, like DataSource etc 's instance.
For most springboot application, if you added annotation @EnableAutoConfiguration or @SpringBootApplication on you springboot main class, it will auto load a lot of SpringBoot's config Java class.

For your question , springboot will auto load DataSourceAutoConfiguration.

next @EnableConfigurationProperties({DataSourceProperties.class}) will load properties from metadata class DataSourceProperties.class .
so the metadata class DataSourceProperties.class solve your problem.


text:
Q: Better search in emacs with expand region Suppose we have the following text:
(print "thIis-is-a-text")

and the cursor is in the word "this" which between char 'h' and 'i'.
In emacs, if I type C-s C-w, the text to search is 'is',
again C-w is 'is-is',
again C-w is 'is-is-a',
again C-w is 'is-is-a-text',
again C-w is 'is-is-a-text"'...
And there is a emacs plugin expand region: "Expand region increases the selected region by semantic units. Just keep pressing the key until it selects what you want."
So I want to make C-s C-w to be more intelligent: to combine with expand region.
Cursor between char 'h' and 'i' in the word 'this' again, my goal is:
when I type C-s C-w, the word 'this' will be the text to search,
again will be 'this-is-a-text',
again will be '"this-is-a-text"',
again will be 'print "this-is-a-text"',
again will be '(print "this-is-a-text")',
....(behaves like expand region, maybe this is not a good example...)
As I find sometimes expand region is quite useful in searching texts, I hope someone can write some codes to achieve this for me since I am new to emacs and elisp. Thanks and please forgive my broken English! :)

A: There's a very simple package called thingopt that uses thingatpt to do something similar to expand-region.  I've been using a modified version for quite a while now, which adds isearch support.  This question reminded me to fork and put up a pull request.  I have the following in my init.el:
(define-key isearch-mode-map (kbd "C-S-s") 'upward-isearch-thing)
(define-key isearch-mode-map (kbd "M-3") 'upward-isearch-thing)

(global-set-key (kbd "C-S-s") 'upward-mark-thing)
(global-set-key (kbd "M-3") 'upward-mark-thing)

(setq upward-mark-thing-list
      '(email
        url
        word
        symbol
        string
        (up-list . *)
        paragraph
        ))

I've tried expand-region, and I think I'd like it better, but it looks much more complicated, and I'd have to add isearch support before I'd start using it.  Hopefully I'll (or someone else will) get around to it someday.

A: (defadvice isearch-yank-word-or-char (before move-to-beginning-of-word)
  (unless (eq last-command this-command)
    (goto-char (car (bounds-of-thing-at-point 'word)))))
(ad-activate 'isearch-yank-word-or-char)


text:
Q: Using Python to wait for a specific Serial Input before sending a serial output Here's a little background on this project. Im trying to write a script that will run at the startup of the raspberry pi and run continuously as long as the pi is on. The script needs to output a text file over the rs232 port, but only when it receives chr17 (ascii) from a cnc machine. chr17 is also the xon code for software flow control I believe.
So as soon as the machine requests an input, the raspberry pi will output whatever file the script is pointed to. When the machine requests an input it outputs chr17. And when it gets the last line of the file it outputs chr18 to signal it is finished.
As far as the memory on the pi, I don't know the most efficient way of executing this script, I think a while loop might take up too much memory on the pi. I'm not sure though.
If anyone can help me come up with this script that would be very much appreciated.
As of now this code works if i execute it after the machine has requested an input. But i need it to run continuously and then as soon as it sees the machine request an input, it should output the file.
Here's what I have, feel free to modify whatever you need or completely start over if its not helpful, lol.
import serial
port = serial.Serial("/dev/ttyAMA0", baudrate=4800, bytesize=7, parity='E')
machinenumber = "BND-2"
cncfile = "/home/pi/myNAS/myShare/e-matix/Machines/%s/Upload/9937.cnc" % machinenumber

try:
    port.open()
except Exception, e:
print "error opening serial port:" + str(e)
if port.isOpen():
    port.write(open(cncfile, "rb").read())
    print ("worked")
    print (open(cncfile, "rb").read())
else:
    print ("cannot open port")
    time.sleep(5)
port.close()

A: 1) put script in crontab, set so it starts at boot time:
@reboot  python /path/to/script.py

http://www.cyberciti.biz/faq/linux-execute-cron-job-after-system-reboot/
2) put above script in a while loop, so it runs then starts again


text:
Q: Why do I have to press the "Update" button twice to save my meta box values? I'm having a problem with updating the post_date in a custom function I've written.
I'm trying to change the post_date to my custom meta_date value.
Here is the function:
function cfc_reset_postdate( $data, $postarr ) {
 // If it is our form has not been submitted, so we dont want to do anything
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

if($data['post_type'] == 'scripture-memory') {
$date = get_post_meta( get_the_ID(), 'cfc_date', true );
$date = DateTime::createFromFormat('D - M j, Y', $date);
$date = $date->format('Y-m-d');

$data['post_date'] = $date;
return $data;
}
add_filter( 'wp_insert_post_data', 'cfc_reset_postdate', '10', 2);

It works, except I have to press the Update button twice to change the post_date to match my new meta date.
I read something in wp-includes on line 2380:

If the $postarr parameter has 'ID' set to a value, then post will be
  updated.

Not sure what that means, but I think it may help me solve this problem.
What am I doing wrong?
EDIT:
Here is the code I'm sending into the meta-box plugin:
$prefix = 'cfc_';

global $meta_boxes;

$meta_boxes = array();

// 1st meta box
$meta_boxes[] = array(
// Meta box id, UNIQUE per meta box
'id' => 'scripture_memory_verse',

// Meta box title - Will appear at the drag and drop handle bar
'title' => 'Scripture Memory Verse',

// Post types, accept custom post types as well - DEFAULT is array('post'); (optional)
'pages' => array( 'scripture-memory' ),

// Where the meta box appear: normal (default), advanced, side; optional
'context' => 'normal',

// Order of meta box: high (default), low; optional
'priority' => 'high',

// List of meta fields
'fields' => array(
    array(
        // Field name - Will be used as label
        'name'      => 'Reference',
        // Field ID, i.e. the meta key
        'id'        => $prefix . 'reference',
        // Field description (optional)
        'desc'      => 'If you don\'t spell the book correctly, the verse won\'t show up!',
        // CLONES: Add to make the field cloneable (i.e. have multiple value)
        'clone'     => true,
        'type'      => 'text'
    ),
    array(
        'name'      => 'Day',
        'id'        => "{$prefix}date",
        'type'      => 'date',
        'desc'      => '(What Sunday are we saying this verse)',
        // Date format, default yy-mm-dd. Optional. See: http://goo.gl/po8vf
        'format'    => 'DD - M d, yy'
    )
)

);

A: The issue is that you are using get_post_meta(), but since you're hooking wp_insert_post_data you have not set the post meta yet (because the hook fires before the post is inserted into the database. You should be pulling from the metadata submission, and running through any filters you use for update_post_meta(). If you post the code where you set the postmeta and comment back, I'll try to write out some sample code (assuming you need it)

A: Try to see if you can grab the $_POST data and add it when update:
//see what is being pass...
print_r($postarr);
die();

Then add the field info to your function
function update_post_from_meta($data,$postarr) {

//see what is being pass...
//print_r($postarr);
//die();

if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

if($data['post_type'] == 'scripture-memory') {

$date = $_POST['you_field_name'];
//OR
//$date = $postarr['your_field_name'];

$date = DateTime::createFromFormat('D - M j, Y', $date);
$date = $date->format('Y-m-d H:i:s');

$data['post_date'] = $date;
return $data;

}
add_filter('wp_insert_post_data','update_post_from_meta',99,2);


text:
Q: Python operator precedence - and vs greater than I have a line of code in my script that has both these operators chained together. From the documentation reference BOOLEAN AND has a lower precedence than COMPARISON GREATER THAN. I am getting unexpected results here in this code:
>>> def test(msg, value):
...     print(msg)
...     return value

>>> test("First", 10) and test("Second", 15) > test("Third", 5)
First
Second
Third
True

I was expecting Second or Third test to happen before the fist one, since > operator has a higher precedence. What am I doing wrong here?
https://docs.python.org/3/reference/expressions.html#operator-precedence

A: Because you are looking at the wrong thing. call (or function call) takes higher precendence over both and as well as > (greater than) . So first function calls occur from left to right.
Python will get the results for all function calls before either comparison happens. The only thing that takes precendence over here would be short circuiting , so if test("First",10) returned False, it would short circuit and return False.
The comparisons and and still occur in the same precendence , that is first the result of test("Second", 15) is compared against test("Third", 5) (please note only the return values (the function call already occured before)) . Then the result of test("Second", 15) > test("Third", 5) is used in the and operation.
From the documentation on operator precedence -

A: One way to see what's happening is to look at exactly how Python is interpreting this result:
>>> x = lambda: test("First", 10) and test("Second", 15) > test("Third", 5)
>>> dis.dis(x)
  1           0 LOAD_GLOBAL              0 (test)
              3 LOAD_CONST               1 ('First')
              6 LOAD_CONST               2 (10)
              9 CALL_FUNCTION            2
             12 JUMP_IF_FALSE_OR_POP    42
             15 LOAD_GLOBAL              0 (test)
             18 LOAD_CONST               3 ('Second')
             21 LOAD_CONST               4 (15)
             24 CALL_FUNCTION            2
             27 LOAD_GLOBAL              0 (test)
             30 LOAD_CONST               5 ('Third')
             33 LOAD_CONST               6 (5)
             36 CALL_FUNCTION            2
             39 COMPARE_OP               4 (>)
        >>   42 RETURN_VALUE

If you do the same for 10 and 15 > 5, you get:
>>> x = lambda: 10 and 15 > 5
>>> dis.dis(x)
  1           0 LOAD_CONST               1 (10)
              3 JUMP_IF_FALSE_OR_POP    15
              6 LOAD_CONST               2 (15)
              9 LOAD_CONST               3 (5)
             12 COMPARE_OP               4 (>)
        >>   15 RETURN_VALUE


text:
Q: Iterating through two lists and return indices I created a habit tracker app and one of the functions is to return the longest uninterrupted streak of done habits. If there are two or more habits with the same streak length, I want to return all of them. Therefore I saved the habit IDs in an id_list and the respective streak lengths in the streak_length_list.
Let me give you an example:
id_list = [1, 2, 3, 4, 5, 6]
streak_length_list = [2, 5, 6, 6, 6, 1]
longest_streak = max(streak_length_list)
longest_streak_ids = []

How can I iterate through the id_list and the streak_length_list simultaneously and append the respective ID to the longest_streak_id list if its length equals the longest_streak value?

A: You don't need to iterate over both lists, only over streak_length_list and use enumerate to get the value and index of all items. If the value equals to longest_streak use the index to get the id from id_list
longest_streak_ids = [id_list[i] for i, x in enumerate(streak_length_list) if x == longest_streak]

A: You can zip the lists:
longest_streak_ids = [i for i, x in zip(id_list, streak_length_list) if x == longest_streak]

Out[15]: [3, 4, 5]


text:
Q: How can I prevent developers from pushing a particular file? I have a repo, used by developers working on my project. In this repo, there is a file ".your_local_variable.php", where there are paths that have to be filled by the developer, relative to their machines, before starting working on the project. I want the developers to pull the "template" of this file only once when they first clone the repo on their machines, but I want to prevent them to send this file on a merge request.
I tried to put it in the .gitignore, and push .gitignore remotely, so they can retrieve it, but the file ".your_local_variable.php" is still showing up on command "git status" as "changes not staged for commit".
Is there any way to prevent pushing this file, and to hide it from git status, while keeping a "template version" of this file on the remote repo?

A: If the file was already checked into git, just adding it to .gitignore won't resolve the problem.
You will need to delete the file from git with git rm + add the file to .gitignore, then push this commit - which contains the delete + ignore. Everyone will need to pull this change so that it stops showing up in your git status.
You can also keep the template version on git, and just tell everyone to copy + rename the file into the one ignored. This is what it should look like on git :

*

*template-for-everyone.file (checked into git so people can retrieve, no one should change this file, unless you want to change the template)

*my-local-template.file (add this file into .gitignore, everyone should copy the template and edit it with this name)

*.gitignore (which contains my-local-template.file)

A: I think the most common solution for that is to create a template file, commit it and ignore the actual file.
Let's say your file name is foo.bar, you may commit a file called foo.bar.example with your template, then in your .gitignore file you add foo.bar.
To remove your file from your repo you just run git rm --cached foo.bar and commit it.
Then your collaborators will copy the foo.bar.example file on their local environment to a new foo.bar file.

A: Another solution would be for the file to pick values from environment variables, sometimes with default values:
<?php
// This variable represents the path for blablabla
$somePath = getenv("PROJECT_SOME_PATH");
// This variable represents the time to wait before contacting the customer (in hours)
$timeToAnswer = getenv("PROJECT_TIME_TO_ANSWER", 42);
// .....

This way, the developers define their own values in their environment, container, other, without touching the file (which is then here for reference).
The first step towards that would be first to update your file with environment variables, push it and communicate to the other devs that they need to set up their env.

A: This is typically handed outside of version control. You'd describe the needed file in a Readme (or provide a template with a .txt extension, for example) and have the developer add it manually. It should be in .gitignore, however.

A: In one commit:

*

*Delete the file.

*Add it to .gitignore.

*Add a non-working version of the file to the repo.  For example:
.your_local_variable.phpREMOVEME
Then each developer has the a template file which won't cause any problems until they interact with it.


text:
Q: How can I mix optional keyword arguments with the & rest stuff? I have a macro that takes a body:
(defmacro blah [& body] (dostuffwithbody))

But I'd like to add an optional keyword argument to it as well, so when called it could look like either of these:
(blah :specialthingy 0 body morebody lotsofbody)
(blah body morebody lotsofboy)

How can I do that? Note that I'm using Clojure 1.2, so I'm also using the new optional keyword argument destructuring stuff. I naively tried to do this:
(defmacro blah [& {specialthingy :specialthingy} & body])

But obviously that didn't work out well. How can I accomplish this or something similar?

A: Something like the following perhaps (also see how defn and some other macros in clojure.core are defined):
(defmacro blah [& maybe-option-and-body]
  (let [has-option (= :specialthingy (first maybe-option-and-body))
        option-val (if has-option (second maybe-option-and-body)) ; nil otherwise
        body (if has-option (nnext maybe-option-and-body) maybe-option-and-body)]
    ...))

Alternatively you could be more sophisticated; it might be worthwhile if you think you might want to have multiple possible options at some point:
(defn foo [& args]
  (let [aps (partition-all 2 args)
        [opts-and-vals ps] (split-with #(keyword? (first %)) aps)
        options (into {} (map vec opts-and-vals))
        positionals (reduce into [] ps)]
    [options positionals]))

(foo :a 1 :b 2 3 4 5)
; => [{:a 1, :b 2} [3 4 5]]

A: Michał Marczyk answered your question nicely, but if you're willing to accept (foo {} rest of the args), so a map with the optional keywords as the first argument (empty in this example), then this more simple code will work fine:
(defn foo [{:keys [a b]} & rest] (list a b rest))
(foo {} 2 3)
=> (nil nil (2 3))
(foo {:a 1} 2 3)
=> (1 nil (2 3))

Works the same for defmacro. The advantage of this is that you don't have to remember a special syntax for optional keyword parameters, and implement code to handle the special syntax (maybe other people who are going to call your macro are more used to specifying key-value pairs in a map than outside of it). The disadvantage is of course that you always have to provide a map, even when you don't want to provide any keyword arguments.
A small improvement when you want to get rid of this disadvantage is checking if you provided a map as the first element of your argument list:
(defn foo [& rest]
  (letfn [(inner-foo [{:keys [a b]} & rest] (list a b rest))]
    (if (map? (first rest))
      (apply inner-foo rest)
      (apply inner-foo {} rest))))

(foo 1 2 3)
=> (nil nil (1 2 3))
(foo {:a 2 :b 3} 4 5 6)
=> (2 3 (4 5 6))


text: Q: SharePoint online specify who can change issue status in a issue tracking list I have an issue tracking list set up on SharePoint Online with the 3 state workflow running for email notifications. Is it possible to configure the list/set up a workflow so that, dynamically, only the person who is assigned the issue can change the item status from active to resolved and only the person who created the issue can change item status from resolved to closed. I have looked at the approval workflow but it doesn't fit requirements (issues need to be visible to all from the point on creation) and item level permissions seem to refer to visible to users and not controlling who can take what action on list items. I am fairly new to SharePoint so any help/advice would be great! Thanks.


text:
Q: Terminal client which allows sending raw bytes? Is there an application like putty, that would allow me to type in raw bytes to send over serial?

A: try RealTerm: under the Send tab, you can send either ASCII or raw bytes, the latter either decimal, hex, or escape sequences.


text:
Q: Can't get ID to insert into database from HTML Form (using PHP) Right now I am trying to create a edit form for my forum, and while I CAN get it to edit, it does not insert an ID to the database (rendering it 0 and thus faulty), the ID field have Auto increment and I've double checked it is the primary field. Tried looking over it many times, but there's got to be something I am missing.
The DB connection:
<?php
error_reporting(E_ALL);
session_start();

$host = 'HOSTNAME';
$dbusername = 'USERNAME';
$dbpassword = 'PASSWORD';

$anslutning = mysqli_connect($host, $dbusername, $dbpassword) or die("Could not connect to database server");

$anslutning->select_db('DATABASE NAME') or die("Could not connect to the specified database");

?>

The form where you edit the post ($edit in this scenario is the ID it grabs when clicking "edit" on a post), as well as where I try to update the database field.
<?php

            if(isset($_GET['edit'])) {
            // If click on "edit"

                $edit = $_GET['edit'];
                // The post-editing ID

                $getEditData = $anslutning->prepare("SELECT postId, title, content FROM tblPosts WHERE postid='$edit' LIMIT 1");
                $getEditData->bind_result($postId, $title, $content);
                $getEditData->store_result();
                $getEditData->execute();

                while($row = $getEditData->fetch()) {

                    echo '

                        <form action="index.php" method="POST">
                            <input type="hidden" name="author" value="'.$_SESSION['loggedIn'].'">
                            <input type="hidden" name="edit" value="'.$edit.'">
                            Title: <input type="text" name="new_title" value="'.$title.'">

                            Content: <textarea name="new_content"> '.$content.' </textarea>

                            <input type="submit" name="editPost">
                        </form>

                    ';
            }
            }

            // Issue(s): Editing a post does not send postId/edit(id) to database

            if(isset($_POST['editPost'])) {

                $edit = $_GET['edit'];
                $author = $_POST['author'];
                $new_title = $_POST['new_title'];
                $new_content = $_POST['new_content'];

                $updatePost = $anslutning->prepare("UPDATE tblPosts SET postId=?, author=?, title=?, content=?");
                $updatePost->bind_param("isss", $edit, $author, $new_title, $new_content);
                $updatePost->execute();
                echo 'Post updated. Redirecting..';
                sleep(1);
                echo '';
            }

        ?>

A: Change
$edit = $_GET['edit'];

to
$edit = $_POST['edit'];


text:
Q: Only remove commas embedded within quotes in a comma delimited file I have a input file delimited with commas (,). There are some fields enclosed in double quotes that are having a comma in them. Here is the sample row
123,"ABC, DEV 23",345,534.202,NAME

I need to remove all the comma's occuring within inside the double quotes and the double quotes as well. So the above line should get parsed into as shown below
123,ABC DEV 23,345,534.202,NAME

I tried the following using sed but not giving expected results.
sed -e 's/\(".*\),\(".*\)/\1 \2/g'

Any quick tricks with sed, awk or any other unix utility please?

A: There is a good response, using sed simply one time with a loop:
echo '123,"ABC, DEV 23",345,534,"some more, comma-separated, words",202,NAME'|
  sed ':a;s/^\(\([^"]*,\?\|"[^",]*",\?\)*"[^",]*\),/\1 /;ta'
123,"ABC  DEV 23",345,534,"some more  comma-separated  words",202,NAME

Explanation:

*

*:a; is a label for furter branch

*s/^\(\([^"]*,\?\|"[^",]*",\?\)*"[^",]*\),/\1 / could contain 3 enclosed parts

*

*first the 2nd: [^"]*,\?\|"[^",]*",\? match for a string containing no double quote, maybe followed by a coma or a string enclosed by two double quote, without coma and maybe followed by a coma.

*than the first RE part is composed by as many repetition of previously described part 2, followed by 1 double quote and some caracteres, but no double-quote, nor comas.

*The first RE part as to be followed by a coma.

*Nota, the rest of the line don't need to be touched

*ta will loop to :a if previous s/ command did some change.

Once loop done, you could even add s/  */ /g:
echo '123,"ABC, DEV 23",345,534,"some more, comma-separated, words",202,NAME'|
    sed ':a;s/^\(\([^"]*,\?\|"[^",]*",\?\)*"[^",]*\),/\1 /;ta;s/  */ /g'

will suppress double spaces:
123,"ABC DEV 23",345,534,"some more comma-separated words",202,NAME

A: A general solution that can also handle several commas between balanced quotes needs a nested substitution. I implement a solution in perl, which process every line of a given input and only substitute commas in every other pair of quotes:
perl -pe 's/ "  (.+?  [^\\])  "               # find all non escaped
                                              # quoting pairs
                                              # in a non-greedy way

           / ($ret = $1) =~ (s#,##g);         # remove all commas within quotes
             $ret                             # substitute the substitution :)
           /gex'

or in short
perl -pe 's/"(.+?[^\\])"/($ret = $1) =~ (s#,##g); $ret/ge'

You can either pipe the text you want to process to the command or specify the textfile to be processed as last command line argument.

A: If the quotes are balanced, you will want to remove commas between every other quote, this can be expressed in awk like this:
awk -F'"' -v OFS='' '{ for (i=2; i<=NF; i+=2) gsub(",", "", $i) } 1' infile

Output:
123,ABC DEV 23,345,534.202,NAME

Explanation
The -F" makes awk separate the line at the double-quote signs, which means every other field will be the inter-quote text. The for-loop runs gsub, short for globally substitute, on every other field, replacing comma (",") with nothing (""). The 1 at the end invokes the default code-block: { print $0 }.

A: Your second quotes are misplaced:
sed -e 's/\(".*\),\(.*"\)/\1 \2/g'

In addition, using regular expressions tend to match the longest possible part of the text, meaning this will not work if you have more than one quoted field in the string.
A way that handles multiple quoted fields in sed
sed -e 's/\(\"[^",]\+\),\([^",]*\)/\1 \2/g' -e 's/\"//g'

This is also a way to solve this, however, with input that may contain more than one comma per quoted field the first expression in the sed would have to be repeated as many times as the maximum comma content in a single field, or until it does not change the output at all.
Running sed with the more than one expression should be more efficient than several sed processes running and a "tr" all running with open pipes.
However, this may have undesired consequences if the input is not properly formatted.
i.e. nested quotes, unterminated quotes.
Using the running example:
echo '123,"ABC, DEV 23",345,534,"some more, comma-separated, words",202,NAME' \
| sed -e 's/\(\"[^",]\+\),\([^",]*\)/\1 \2/g' \
-e 's/\(\"[^",]\+\),\([^",]*\)/\1 \2/g' -e 's/\"//g'

Output:
123,ABC  DEV 23,345,534,some more  comma-separated  words,202,NAME

A: I would use a language with a proper CSV parser. For example:
ruby -r csv -ne '
  CSV.parse($_) do |row|
    newrow = CSV::Row.new [], []
    row.each {|field| newrow << field.delete(",")}
    puts newrow.to_csv
  end
' < input_file

A: Consider csvkit:
< file csvformat -D ^ | tr -d , | tr ^ ,
Explanation

*

*-D ^ set the delimiter to a character not present in the file, such as carat

*tr -d , now that commas are no longer the delimiting character, delete commas

*tr ^ , convert carat back to comma

A: In perl - you can use Text::CSV to parse this, and do it trivially:
#!/usr/bin/env perl
use strict;
use warnings;

use Text::CSV;

my $csv = Text::CSV -> new();

while ( my $row = $csv -> getline ( \*STDIN ) ) {
    #remove commas in each field in the row
    $_ =~ s/,//g for @$row;
    #print it - use print and join, rather than csv output because quotes.
    print join ( ",", @$row ),"\n";
}

You can print with Text::CSV but it tends to preserve quotes if you do. (Although, I'd suggest - rather than stripping quotes for your output, you could just parse using Text::CSV in the first place).

A: I created a function to loop thru every character in the string.
If the character is a quotation then the check (b_in_qt) is marked true.
While b_in_qt is true, all commas are replaced with a space.
b_in_qt is set to false when the next comma is found.
FUNCTION f_replace_c (str_in  VARCHAR2) RETURN VARCHAR2 IS
str_out     varchar2(1000)  := null;
str_chr     varchar2(1)     := null;
b_in_qt     boolean         := false;

BEGIN
    FOR x IN 1..length(str_in) LOOP
      str_chr := substr(str_in,x,1);
      IF str_chr = '"' THEN
        if b_in_qt then
            b_in_qt := false;
        else
            b_in_qt := true;
        end if;
      END IF;
      IF b_in_qt THEN
        if str_chr = ',' then
            str_chr := ' ';
        end if;
      END IF;
    str_out := str_out || str_chr;
    END LOOP;
RETURN str_out;
END;

str_in := f_replace_c ("blue","cat,dog,horse","",yellow,"green")

RESULTS
  "blue","cat dog horse","",yellow,"green"

A: GoCSV makes quick and obvious work of this:
sample.csv:
Col1,Col2,Col3,Col4
01299,"ABC,DEV 23",1,0
26528,"ABC,DEV 03",0,0
38080,"DEF,STG 35",0,0
38081,"GHI,STG 19",0,0

Use its replace command to substitute all , with   only in Col2:
gocsv replace -c 'Col2' -regex ',' -repl ' ' sample.csv

yields:
Col1,Col2,Col3,Col4
01299,ABC DEV 23,1,0
26528,ABC DEV 03,0,0
38080,DEF STG 35,0,0
38081,GHI STG 19,0,0

A: Using Python
''.join([item if index % 2 == 0 else re.sub(',', '', item) for index, item in enumerate(row.split('"')) ])

A: Using the CSV-aware utility Miller (mlr) to remove all commas from the second field of the header-less CSV data in the file called file:
$ cat file
123,"ABC, DEV 23",345,534.202,NAME

$ mlr --csv -N put '$2 = gsub($2,",","")' file
123,ABC DEV 23,345,534.202,NAME

If you want to retain the original quotes:
$ mlr --csv -N --quote-original put '$2 = gsub($2,",","")' file
123,"ABC DEV 23",345,534.202,NAME

If you have named fields (i.e. a header line), then use the name of the field instead of the 2, and drop the -N option:
mlr --csv --quote-original put '$departement = gsub($departement,",","")' file

Would you want to process all fields, then do something like
$ mlr --csv -N --quote-original put 'for (k,v in $*) { is_string(v) { $[k] = gsub(v,",","") } }' file
123,"ABC DEV 23",345,534.202,NAME

A: Using Raku (formerly known as Perl_6)
~$ raku -pe 's:g/ \" ~ \" (<-[",]>+) ** 2..* % "," /{$0.join}/;'  file

Raku is a programming language in the Perl-family. Raku's regex notation has been significantly reworked over the approximately fifteen years of Perl6/Raku development, and many people find it easier to learn.
Above we see the familiar -pe autoprinting linewise flags, as in Perl. We also see the familiar s/// substution notation. One point of interest: substitution modifiers are denoted with a : colon and go at the head of the notation , so s:g/// stands for "substitute-global".
Within the recognition half of the s/// notation, we see two important improvements within the Raku Regex "dialect":

*

*First of all, nested structures can be denoted with Raku's new ~ tilde (nested) notation, such that \" ~ \" [.+] means "one-or-more characters surrounded by " double-quotes".

*Second of all, repeated structures can be denoted with Raku's new % modified quantifier for repeated structures. The notation [.+] ** 2..* % "," means "one-or-more characters separated by , commas with this pattern repeated ** 2..* two or more times. [If there happens to be a trailing separator (e.g. comma), use a %% instead of % in the syntax].
So, knowing Perl or PCRE syntax, at becomes much easier to read the regex notation above. To enhance this point, the syntax <-[",]> simply denotes a custom character class that does not contain either , comma or " doublequote.
Sample Input:
123,"ABC, DEV 23",345,534.202,NAME

Sample Output:
123,ABC DEV 23,345,534.202,NAME

Example Captures:
~$ raku -ne 'say $<> if m:g/ \" ~ \" (<-[",]>+)** 2..* % "," /;'  file
(「"ABC, DEV 23"」
 0 => 「ABC」
 0 => 「 DEV 23」)

Note: the replacement half uses {$0.join} to concatenate captured values. If you want a space inserted where the comma has been removed, simply use $0 in the replacement. Finally, for anything complex, consider using a CSV-parser like Raku's Text::CSV module. URLs below.
https://docs.raku.org/language/regexes#Tilde_for_nesting_structures
https://docs.raku.org/language/regexes#Modified_quantifier:_%,_%%
https://raku.land/github:Tux/Text::CSV
https://github.com/Tux/CSV
https://raku.org


text:
Q: Как объединить интервалы по заданной длине перекрытия Здравствуйте, я совсем запутался. Помогите.
Задача следующая: есть интервалы
from interval import interval

d = {
    'a': interval([0, 10]),
    'b': interval([5, 40]),
    'c': interval([30, 50]),
    'd': interval([55, 70])
}

мне нужно получить объединенные группы интервалов по заданному значению минимального перекрытия N
Например если N >= 10, получается
{
    interval([0, 10]):['a'],
    interval([5.0, 50.0]):['b','c'],
    interval([55.0, 70.0]):['d']
}

N >= 5,
{
    interval([0, 50]):['a','b','c'],
    interval([55.0, 70.0]):['d']
}

Заранее спасибо за любую помощь!

A: Я попробовал решить свою же задачу. Код не оптимальный так как я не занимаюсь программированием профессионально. Может кому-нибудь пригодится.
def merge_intervals(interval_list,overlap):

    #Дан словарь интервалов
    #data = [(24231, 24894, 1), (26358, 27018, 2), (24231, 24894, 3), ... ]
    #Результат
    #{interval([24231.0, 24894.0]): [1, 3, 5, 8, 9, 11, 14, 16], interval([26358.0, 27018.0]): [2, 4, 6, 7, 10, 12, 13, 15]}

    def length(interval_):
        """
        Определение длины перекрытия интервала
        """
        try:
            return abs(interval_[0][1] - interval_[0][0])
        except:
            return -1

    # Подготавливаем список тьюполов (конвертируем их в интервалы) и сортируем
    c = list(set([interval[i[0],i[1]]for i in interval_list]))
    c.sort()

    # Объединяем все интервалы в перекрываемые
    merged = interval(c[0])
    for i in c[1:]:
        current = interval(merged[-1])
        # если перекрытие интервалов по заданному условию
        if length(i&current) > overlap:
           # то объединяем интервал из списка с предыдущим
           mer = i | current
           # заменяем предыдущий сохраненный интервал на полученный
           merged = tuple(list(merged)[:-1] + list(interval(mer)))
        else:
            # если условие не выполняется, то просто добавляем к списку
            merged = tuple(list(merged) + list(interval(i)))

    dict_ = {}
    # для каждого из исходных интервалов
    for i in interval_list:
        # для каждого из полученных объединенных интервалов
        for r_i in merged:
            if interval([i[0],i[1]]) in interval(r_i):
               if interval(r_i) in dict_:
                  dict_[interval(r_i)].append(i[-1])
               else:
                  dict_[interval(r_i)] = []
                  dict_[interval(r_i)].append(i[-1])

    return dict_

if __name__ == '__main__':

    data = [(100,500,1),(50,600,2),(550,700,3),(800,900,4),(850,1000,5)]
    print 'BEFORE', data
    data = merge_intervals(data, 1000)
    print 'AFTER', data


text:
Q: Why the line bundle associated to the hyperplane is tautoloical line bundle Let $X = \Bbb{CP}^n$ , consider the hyperplane $H = \{z_0 = 0\}\subset\Bbb{CP}^n$ , we can define it as Weil divisor , then since the isomorphism between $$\text{Div}(X) \cong H^0(X,\mathcal{K}_X^*/\mathcal{O}_X^*)$$
we can associate this Divisor $H\in \text{Div}(X)$ as a set of $\{f_i\} \in H^0(X,\mathcal{K}_X^*/\mathcal{O}_X^*)$ ,this set of $\{f_i\}$ define a cocycle $\{\psi_{ij} = f_if^{-1}_j\}$ hence we have a canonical map from $$\text{Div} (X) \to \text{Pic}(X)$$via the cocycle above.

Now I want to check that via this map $$\text{Div}(X) \to H^0(X,\mathcal{K}_X^*/\mathcal{O}_X^*)\to \text{Pic}(X)$$
we maps $H\in \text{Div}(X)$ to tautogical line bunle $\mathcal{O}(1)$
the key is to find the cocycle if it has the form $$\psi_{ij} = z_i/z_j$$ then we can deduce it, however I don't know how to find such $\{f_i\}$?

My solution(if don't think about it too carefully this solution is sufficient):
Given the Weil divisor $H$ the corresponding Cartier divisor is:
$$\{(U_0,1),(U_1,z_0/z_1),...(U_n,z_0/z_n)\}
$$
where $U_i = \{(z_0:...:z_{n})\mid z_i \ne 0\}$
Therefore the cocycle is:
$$\psi_{ij} =f_if_j^{-1} = z_j/z_i$$
which is the same as the tautological line bundle $\mathcal{O}(1)$


text:
Q: Responsividade no Bootstrap Estou iniciando com o framework Bootstrap. Minha dúvida é: Quando eu específico um valor para a propriedade width na classe container, eu perco o modo responsivo de tela? porque eu fiz esse procedimento, e meu responsivo não funcionava mais. Existe alguma coisa a se fazer diante disso? Ou o container tem que ter somente uma única largura?

A: Para manter o layout responsivo utilize a propriedade max-width: ?px; pois o width deve ficar com o valor 100%;

A: Andrew, você subscreveu a regra daquela class... dependendo do contexto você sim pode perder a responsividade já que, se seu codigo vem depois da chamada da biblioteca, as regras que escreveu vão subescrever todas as anteriores. Recomendo usar a grid para ser seu wrap e desenvolver o modulo dentro dela, ou o inverso. Não é muito legal colocar nas suas divs, ou tags de blocos, as classes das grids e containers, isso te limita ao comportamento do framework.


text:
Q: Verify if the database is empty in neo4j I'm working on neo4j in java and I have one question. When I create a node, how can I verify that the database is empty?
Here's my code to create a node:
br = new BufferedReader(new FileReader(csvFile));

        while (br.ready()==true) {
            transaction = graphDb.beginTx();
            int cont = 0;//limitador de tuplas por query
            while ((line = br.readLine()) != null && cont < 10000) {

                String[] dado = line.split(cvsSplitBy);

                // inserir comando para criar o nós com a data
                Node no = graphDb.createNode();
                no.setProperty("data", dado[0]);
                no.setProperty("temperatura", dado[1]);
                no.setProperty("latitude", dado[2]);
                no.setProperty("longitude", dado[3]);
                no.setProperty("variação", dado[4]);

                System.out.println(cont);
                cont++;
            }
            transaction.success();
            transaction.close();
        }

A: Execute a cypher query from java.
Use this query:
MATCH (n) RETURN count(n);

If the answer is zero, the database is empty.  If it's anything else, it's not.

A: UPDATED ANSWER
Here is an efficient Cypher query that returns a boolean isEmpty result.
OPTIONAL MATCH (n)
RETURN n IS NULL AS isEmpty
LIMIT 1;

A: match (n)
return 1
limit 1

I hope Neo4J would bother less processing this query, knowing it doesnt has to bother counting or bother filtering as suggested in previous answers


text:
Q: White Space Between SVG Background Repeats I cannot seem to get rid of this white space between SVG element repeats (as CSS backgrounds) exported by Illustrator CS5.
I am using a simple CSS background-image and background-repeat: repeat-x but there is always this white space between each repeat. I am not using background-size at all.
Here is what I am seeing (tested on Safari/Chrome):

If I open the SVG to check for any whitespace on the side, nothing is there (see window on the right) and it goes all the way to the side of the window:

I've tried saving the image in Illustrator by File -> Scripts -> SaveDocsAsSVG and Save as.. -> SVG.
HTML

CSS
.outer {
  background-color: #7fcefb;
  height: 700px;
  background-image: url('/wp-content/themes/grizzly/assets/img/trees.png');
  background-position: center 95%;
  background-repeat: repeat-x;
}

.inner {
  background-image: url('/wp-content/themes/grizzly/assets/svg/treeshill.svg');
  height: 700px;
  background-position: center bottom;
  background-repeat: repeat-x;
}

A: preserveAspectRatio="none" didn't work for me because it makes the svg to take the full width of its parent container.
Instead a take the parameters: preserveAspectRatio="xMinYMax meet" which in return I was able to use with background-repeat: repeat-x;
For more info here is an exellent article: A Look At preserveAspectRatio in SVG

A: If it's what I think it is, open up your SVG file and change the root <svg> element so that it includes the following attribute:
<svg ... preserveAspectRatio="none">

If it already has a preserveAspectRatio attribute, just change it to "none" and reload.

A: I can't guarantee this will always work or even work in your situation, but you might try specifying the css background-size in pixels not as a percentage. This has worked for me in the past with chrome. i.e. background-size: 50px 100px;


text:
Q: Chat Program: Client to Client Chat Currently I'm working on this mini chat program in Java where multiple users should be able to log into the chat program and chat. Right now what my program does is log in users (Clients) to the Server, and what ever they say gets echoed back by the Server. What I want to do is be able to send a request to chat with another client directly.
My idea was to create a Hash map that holds the username of the client and its socket. When a client requests to chat with another client it looks for that user's username in the HashMap and if the other client agrees to chat then it connects the sockets.
I'm not sure how to implement this and also my program only takes one input from the user and returns it from the Server and after that it stops I have no idea why. I've been trying to get this working for a while now, starting to give me headaches.
Here's the code:
Client Class:
package source;

import java.io.*;
import java.util.*;
import java.net.*;

public class Client implements Runnable {
    private Socket socket;
    private DataOutputStream dout;
    private DataInputStream din;
    // Constructor

    public Client() {
        // Code
    }

    public Client(String host, int port) {

        try {
            socket = new Socket(host, port);
            System.out.println("connected to " + socket);
            din = new DataInputStream(socket.getInputStream());
            dout = new DataOutputStream(socket.getOutputStream());
            new Thread(this).start();
        } catch (IOException ie) {
            System.out.println(ie);
        }
    }

    private void processMessage(String message) {
        try {
            dout.writeUTF(message);
        } catch (IOException ie) {
            System.out.println(ie);
        }
    }

    public void run() {
        try {
            while (true) {
                String message = din.readUTF();
                System.out.println(message);
            }
        } catch (IOException ie) {
            System.out.println(ie);
        }
    }

    public static void main(String[] args) throws IOException {
        while (true) {
            String prompt;
            Scanner clientPrompt = new Scanner(System.in);
            System.out.println("client> ");
            prompt = clientPrompt.next();
            if (prompt.equals("Emmanuel"))
                System.out.println("God With Us");
            else if (prompt.equals("goOnline")) {
                // Enter a host name
                // Enter a portNumber
                // Enter a userName
                String h, p, u;
                System.out.println("Enter hostname: ");
                h = clientPrompt.next();
                System.out.println("Enter portNumber: ");
                p = clientPrompt.next();
                System.out.println("Enter userName: ");
                u = clientPrompt.next();
                goOnline(h, p, u);
            } else if (prompt.equals("Exit")) {
                clientPrompt.close();
                System.exit(1);
            } else {
                System.out.println("Invalid Input, Try Again");
            }
        }
    }

    public static void goOnline(String host, String port, String userName) {
        int portNumber = Integer.parseInt(port);
        Client c = new Client(host, portNumber);
        c.processMessage("Username: " + userName);
        String prompt;
        Scanner clientPrompt = new Scanner(System.in);
        while (true) {

            prompt = clientPrompt.next();
            c.processMessage(prompt);
            c.run();
            if (prompt.equals("Exit")) {
                System.out.println("Bye Bye");
                clientPrompt.close();
            }
        }
    }
}

Server Class:
package source;

import java.io.*;
import java.net.*;
import java.util.*;

public class Server { // The ServerSocket we'll use for accepting new
                        // connections
    private ServerSocket ss;

    private HashMap<String, Socket> userInfo = new HashMap<String, Socket>();

    // A mapping from sockets to DataOutputStreams.
    private Hashtable<Socket, DataOutputStream> outputStreams = new Hashtable<Socket, DataOutputStream>();

    // Constructor and while-accept loop all in one.
    public Server(int port) throws IOException {
        // All we have to do is listen
        listen(port);
    }

    private void listen(int port) throws IOException {
        // ServerSocket
        ss = new ServerSocket(port);
        System.out.println("Listening on " + ss);
        while (true) {
            Socket s = ss.accept();
            System.out.println("Connection from " + s);
            DataOutputStream dout = new DataOutputStream(s.getOutputStream());
            DataOutputStream userInfo = new DataOutputStream(s.getOutputStream());
            outputStreams.put(s, dout);
            outputStreams.put(s, userInfo);
            new ServerThread(this, s);
        }
    }

    Enumeration<DataOutputStream> getOutputStreams() {
        return outputStreams.elements();
    }

    void sendToAll(String message) {
        for (Enumeration<DataOutputStream> e = getOutputStreams(); e.hasMoreElements();) {
            // Output Stream
            DataOutputStream dout = (DataOutputStream) e.nextElement();
            // Send Message
            try {
                dout.writeUTF(message);
            } catch (IOException ie) {
                System.out.println(ie);
            }
        }
    }

    // Remove socket,
    void removeConnection(Socket s) {
        // Synchronize
        synchronized (outputStreams) {
            // Tell the world
            System.out.println("Removing connection to " + s);
            // Remove it from hashtable
            outputStreams.remove(s);
            try {
                s.close();
            } catch (IOException ie) {
                System.out.println("Error closing " + s);
                ie.printStackTrace();
            }
        }
    }

    void addInfo(String user, Socket s) {
        userInfo.put(user, s);
    }

    // Main
    static public void main(String args[]) throws Exception {
        // Get port
        int port = Integer.parseInt(args[0]);
        // Create Server object
        new Server(port);
    }
}

ServerThread:
package source;

import java.io.*;
import java.util.*;
import java.net.*;

public class ServerThread extends Thread { // The Server that spawned us
    private Server server;
    private Socket socket;

    public ServerThread(Server server, Socket socket) {
        this.server = server;
        this.socket = socket;
        start();
    }

    public void run() {
        try {
            DataInputStream din = new DataInputStream(socket.getInputStream());
            while (true) {
                String message = din.readUTF();
                StringTokenizer stt = new StringTokenizer(message, " ");
                while (stt.hasMoreTokens()) {
                    String token = stt.nextToken();
                    if (token.equals("Username:")) {
                        String username = stt.nextToken();
                        server.addInfo(username, socket);
                    }
                }
                System.out.println("Sending " + message);

                server.sendToAll(message);
                if (message.equals("Exit")) {
                    System.out.println("Bye Bye");
                    server.removeConnection(socket);
                    System.exit(1);
                }
            }
        } catch (EOFException ie) {
        } catch (IOException ie) {
            ie.printStackTrace();
        } finally {
            server.removeConnection(socket);
        }
    }
}

A: my program only takes one input from the user and returns it from the Server and after that it stops I have no idea why?
Just do one change as mentioned below at client side to resolve above issue.
public void run() {
    try {
        // while (true) { // remove an infinite loop that will block
                          // the client thread to accept next message
        String message = din.readUTF();
        System.out.println(message);
        // }
    } catch (IOException ie) {
        System.out.println(ie);
    }
}

Doubt: (client side)

*

*You have started a thread then why are you calling run() method directly.