text:
Q: How to pass data into a foreign key , while passing data i am getting null using postman? I am trying to pass data in foreign key but i am getting null value. See below my code:
This is the feature pojo class:
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "Feature", description = "This class is used to specify the Feature Property")
@Entity
public class Feature {
    @ApiModelProperty(notes = "unique feature id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long featureId;

    @NotNull
    @ApiModelProperty(notes = " feature name will define name of the feature")
    @Size(max = 50)
    private String name;
    @NotEmpty(message = "feature version should never be empty")
    @Size(max = 20)
    @ApiModelProperty(notes = "feature version will define version of the feature")
    @Column(unique = true)
    private String version;

    @NotBlank
    @Size(max = 500)
    @ApiModelProperty(notes = "feature description will describe the feature")
    private String description;

    @ManyToOne
    @JoinColumn(name = "plan_id")
    private Plan plan;
}

This is the plan pojo
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value = "PlanData", description = "Plan is a pojo class under plan management")
@Entity
public class Plan {

    @ApiModelProperty(notes = "unique plan id")
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Plan_Id")
    private Long planId;

    @ApiModelProperty(notes = "A plan name")
    private String planName;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    @DateTimeFormat
    @ApiModelProperty(notes = "plan start date will defines from what date the plan is active ")
    private Date planStartDate;

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy")
    @DateTimeFormat
    @ApiModelProperty(notes = "plan end date will define till what date the plan will active ")
    private Date planEndDate;
    @ApiModelProperty(notes = "planDescription defines about the plan in detail")
    private String planDescription;
    @ApiModelProperty(notes = "plan version specifies version sepecific knowledge")
    private String planVersion;
    @ApiModelProperty(notes = "planStatus defines the active/deactive status of plan")
    @JsonProperty
    @Column(nullable = false, columnDefinition = "BOOLEAN")
    private Boolean planStatus = true;

    @OneToMany(mappedBy = "plan", cascade = CascadeType.ALL)
    private Set<Feature> features=new HashSet<Feature>();;

    @OneToOne
    @JoinColumn(name = "templateId")
    @ApiModelProperty(notes = "This property is mainly use to bind with the template")
    private Template template;

    @OneToOne
    @JoinColumn(name = "termsId")
    @ApiModelProperty(notes = "This property is mainly use to bind with the terms")
    private TermsAndConditions terms;

This is post api for plan
@PostMapping(value = "/plan")
    public ResponseEntity<PlanDTO> createPlan(@RequestBody PlanDTO planDTO ) {
        PlanDTO plan = planImpl.createPlan(planDTO);
        return ResponseEntity.status(HttpStatus.CREATED).body(plan);
    }

This is post api for feature
    @ApiOperation("This api will use to create a feature data ")
    @PostMapping(value = "/feature")
    public ResponseEntity<FeatureDTO> createFeature(@RequestBody FeatureDTO featureDTO) {
        FeatureDTO feature = featureImpl.createFeature(featureDTO);
        return ResponseEntity.status(HttpStatus.CREATED).body(feature);
    }

This Iam sending through the postman request:
{
    "planName": "bnvn",
    "planStartDate": "2003-09-09",
    "planEndDate": "2003-09-09",
    "planDescription": "hvxncbvnc jfbvfd nbhnsdf cbc",
    "planVersion": "cvnm mxcnvbnc xncv",
    "planStatus": true,
    "features": [{"planId":1
    }],
  "template": {
    "templateId" :1
   },
  "terms": {
    "termsId" :1
   }
}

I am getting null values in all the foreign key field.
{
    "planId": 3,
    "planName": "bnvn",
    "planStartDate": "2003-09-09T00:00:00.000+0000",
    "planEndDate": "2003-09-09T00:00:00.000+0000",
    "planDescription": "hvxncbvnc jfbvfd nbhnsdf cbc",
    "planVersion": "cvnm mxcnvbnc xncv",
    "planStatus": true,
    "features": [],
    "template": null,
    "terms": null
}

This is the plan dto

@Data
public class PlanDTO {
    private Long planId;
    private String planName;
    private Date planStartDate;
    private Date planEndDate;
    private String planDescription;
    private String planVersion;
    private Boolean planStatus;
    private Set<Feature> features = new HashSet<Feature>();
    private Template template;
    private TermsAndConditions terms;

    public PlanDTO() {
    }

    public PlanDTO(Long planId, String planName, Date planStartDate, Date planEndDate, String planDescription,
            String planVersion, Boolean planStatus, Set<Feature> features, Template template,
            TermsAndConditions terms) {
        super();
        this.planId = planId;
        this.planName = planName;
        this.planStartDate = planStartDate;
        this.planEndDate = planEndDate;
        this.planDescription = planDescription;
        this.planVersion = planVersion;
        this.planStatus = planStatus;
        this.features = features;
        this.template = template;
        this.terms = terms;
    }
}

This is the feature dto:
@Data
public class FeatureDTO {
    private Long featureId;
    private String name;
    private String version;
    private String Description;
    private Plan plan;

    public FeatureDTO() {
    }

    public FeatureDTO(Long featureId, String name, String version, String description, Plan plan) {
        super();
        this.featureId = featureId;
        this.name = name;
        this.version = version;
        this.Description = description;
        this.plan = plan;
    }

}

This is the plan impl class
@Service
public class PlanImpl {

    private static final Logger logger = LoggerFactory.getLogger(PlanImpl.class);

    @Autowired
    private PlanRepo planRepo;

    @Autowired
    private PlanMapper planMapper;

    /**
     * createPlan will create a plan and will store it in repository
     *
     * @param plan
     * @return
     */
    public PlanDTO createPlan(PlanDTO planDTO) {
        Plan plan = planMapper.toPlan(planDTO);
        Plan planData = planRepo.save(plan);
        PlanDTO plans = planMapper.toPlanDTO(planData);
        return plans;

    }

    /**
     * update plan will update a plan using plan id and store it in database
     *
     * @param planId
     * @param plan
     */
    public PlanDTO updatePlan(Long planId, PlanDTO planDTO) {
        Plan plan = planMapper.toPlan(planDTO);
        Plan updatePlan;

        if (planRepo.findById(planId) == null) {
            throw new NullPointerException();

        } else {
            plan.setPlanId(planId);

            updatePlan = planRepo.getOne(plan.getPlanId());
            updatePlan.setPlanName(plan.getPlanName());
            updatePlan.setPlanStartDate(plan.getPlanStartDate());
            updatePlan.setPlanEndDate(plan.getPlanEndDate());
            updatePlan.setPlanDescription(plan.getPlanDescription());
            updatePlan.setPlanVersion(plan.getPlanVersion());
            updatePlan.setPlanStatus(plan.getPlanStatus());

            Plan planUpdateData = planRepo.save(updatePlan);
            PlanDTO Plans = planMapper.toPlanDTO(planUpdateData);
            return Plans;
        }
}

I want to show one plan with multiple features but it is returning null.
Thank you !

A: You need to add the features and the template to the plan. Something like this:
public class Plan {

   ...

   public void addFeature(Feature feature) {
       this.features.add(feature);
       feature.setPlan(this);
   }

   public void setTemplate(Template template) {
       this.template = template;
       template.setPlan(this);
   }
}

After adding, just call the addFeature and template setter before saving the plan. You could even adapt it to save all features at once.
Here is a good source on how to map with @OneToMany and @ManyToMany
https://vladmihalcea.com/the-best-way-to-map-a-onetomany-association-with-jpa-and-hibernate/ and
https://vladmihalcea.com/the-best-way-to-map-a-onetoone-relationship-with-jpa-and-hibernate/


text:
Q: Compress output of Hadoop Archive tool I'm using Hadoop Archive for reduce number of files in my Hadoop cluster, but for data retention, I want to keep my data as long as possible. Then the problem is Hadoop Archive not reduce folder size (my folder have multi-type of file, both small and large file, then not suitable for use Sequence File).
I used some option like -D mapreduce.compress.map.output=true -D mapred.map.ouput.compress.codec=org.apache.hadoop.io.compress.GzipCodec but it's not work.
Does anyone know a way for compress output of Hadoop Archive, or suggest me someway to get both goal (compress size and reduce number of file).
Any infomation is appreciate. Thanks so much.

A: You may use mapred compress and run har on the compressed directories

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular Node server returns You provided 'undefined' where a stream was expected I am using angular 9 + universal. No errors while i run ng serve , then I build the app with npm run build:ssr and try to run with node : node dist/app/server/main.js and get the following error in terminal :

Node Express server listening on http://localhost:4000 TypeError: You
  provided 'undefined' where a stream was expected. You can provide an
  Observable, Promise, Array, or Iterable.
      at subscribeTo (C:\Users\andri\OneDrive\Desktop\devfox\autorent\ng-videocms\dist\autorent\server\main.js:1:2547459)
      at subscribeToResult (C:\Users\andri\OneDrive\Desktop\devfox\autorent\ng-videocms\dist\autorent\server\main.js:1:2775326)
      at CatchSubscriber.error (C:\Users\andri\OneDrive\Desktop\devfox\autorent\ng-videocms\dist\autorent\server\main.js:1:1997435)
      at Observable_Observable._trySubscribe (C:\Users\andri\OneDrive\Desktop\devfox\autorent\ng-videocms\dist\autorent\server\main.js:1:1952954)
      at Observable_Observable.subscribe (C:\Users\andri\OneDrive\Desktop\devfox\autorent\ng-videocms\dist\autorent\server\main.js:1:1952574)
      at CatchOperator.call (C:\Users\andri\OneDrive\Desktop\devfox\autorent\ng-videocms\dist\autorent\server\main.js:1:1996823)
      at Observable_Observable.subscribe (C:\Users\andri\OneDrive\Desktop\devfox\autorent\ng-videocms\dist\autorent\server\main.js:1:1952428)
      at _task (C:\Users\andri\OneDrive\Desktop\devfox\autorent\ng-videocms\dist\autorent\server\main.js:1:1751796)
      at Observable_Observable.Observable.a.observer [as _subscribe] (C:\Users\andri\OneDrive\Desktop\devfox\autorent\ng-videocms\dist\autorent\server\main.js:1:1752141)
      at Observable_Observable._trySubscribe (C:\Users\andri\OneDrive\Desktop\devfox\autorent\ng-videocms\dist\autorent\server\main.js:1:1952792)

As I've explored, my app does 2 api calls on start :
app.component.ts  :
ngOnInit(){
get1();
get2();
}

  get1() {
    const loc = this.locationService.getPickupLocations().subscribe((data: Location[]) => {
      this.pickupLocations = data;
      this.formGroup.get(LocationFields.pickup).setValue(data[0].getId());
      this.pickupLocationsList = this.pickupLocations.map((data): ISelectOption => {
        return {
          label: data.getName(),
          value: data.getId(),
        };
      });
    },
    (error)=> {
      console.log(error)
    },
    () => {
      this.subs.add(loc);
      this.pickupDateChange(this.formGroup.get(this.LocationFields.pickupDate).value);
    });
  }

  get2() {
    const drop = this.locationService.getDropOffLocations().subscribe((data: Location[]) => {
      this.dropoffLocations = data;
      this.formGroup.get(LocationFields.dropoff).setValue(data[1].getId());
      this.dropoffLocationsList = this.dropoffLocations.map((data): ISelectOption => {
        return {
          label: data.getName(),
          value: data.getId(),
        };
      });
    },(error)=> {
      console.log(error)
    },
    () => {
      this.subs.add(drop);
    });
  }

LocationService.ts :
  static locationsEndpoint = 'public/locations/rental';
  getPickupLocations(): Observable<Location[]> {
    const reqHeader = new HttpHeaders({ 'Content-Type': 'application/json', 'No-Auth': 'True' });
    return this.http.get(`${LocationsService.locationsEndpoint}/pickup`, { headers: reqHeader }).pipe(
     map((data: ILocationResponse) => this.hydrateCollectionData(data, LocationsHydrator))
    );
  }

  getDropOffLocations(): Observable<Location[]> {
    const reqHeader = new HttpHeaders({ 'Content-Type': 'application/json', 'No-Auth': 'True' });
    return this.http.get(`${LocationsService.locationsEndpoint}/dropoff`, { headers: reqHeader }).pipe(
     map((data: ILocationResponse) => this.hydrateCollectionData(data, LocationsHydrator))
    );
  }

And Interceptors :
 private static BASE_URL = environment.apiUrl;

  readonly HEADER_AUTHORIZATION = 'Authorization';
  readonly HEADER_ACCEPT = 'Accept';
  readonly HEADER_CONTENT_TYPE = 'Content-Type';
  readonly ACCEPT_LANGUAGE = 'Accept-Language';

  constructor(
    private authService: AuthService,
    private localeService: LocaleService
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (req.headers.get('skip')) {
          return next.handle(req);
    }
    if (req.url.startsWith('./assets')) {
      return next.handle(req);
    }
    req = req.clone({
      url: this._prefixUrl(req.url)
    });

    req = req.clone({
      headers: req.headers.set(this.HEADER_ACCEPT, 'application/json')
    });

    req = req.clone({
      headers: req.headers.set(this.HEADER_CONTENT_TYPE, 'application/json')
    });

    req = req.clone({
      headers: req.headers.set(this.ACCEPT_LANGUAGE, this.localeService.getLocale())
    });

    // Set token if exists
    const token = this.authService.getToken();

    if (token) {
      req = req.clone({
        headers: req.headers.set(this.HEADER_AUTHORIZATION, `Bearer ${token}`)
      });
    }

    return next.handle(req).pipe(
      catchError((httpErrorResponse: HttpErrorResponse) => {
        if(httpErrorResponse.error !== undefined){
          const customError: ApiErrors = {
            name: httpErrorResponse.error.name,
            message: httpErrorResponse.error.message,
            errors: httpErrorResponse.error.errors
          };
          return throwError(customError);
        }
      })
    );
  }

  private _prefixUrl(path: string): string {
    if (path.indexOf('/') === 0) {
      path = path.substr(1, path.length - 1);
    }

    return `${Interceptor.BASE_URL}/${path}`;
  }

I tried without these calls , tried to comment one of them.
When i disable those calls (comment them) , app works fine.
When i call them later, after i commented them, (onclick), app works fine.
When i disable interceptors , it works (SO the problem is in them, what to change ?? )
How to fix it ? And why it is happening ?

A: The trace seems to suggest the problem is related to CatchOperator.
I see only one place where catchError operator is used in your code
return next.handle(req).pipe(
      catchError((httpErrorResponse: HttpErrorResponse) => {
        if(httpErrorResponse.error !== undefined){
          const customError: ApiErrors = {
            name: httpErrorResponse.error.name,
            message: httpErrorResponse.error.message,
            errors: httpErrorResponse.error.errors
          };
          return throwError(customError);
        }
      })
    );

In your code you seem to assume that the function passed to catchError will receive always an instance of HttpErrorResponse which is not the case. catchError will be used for any error and so the function passed to it can receive any type of error.
What happens if httpErrorResponse.error is null but you still have an error in the upstream Observables somewhere? According to the code above you do not return anything, so this may be the reason why the log says You provided 'undefined' where a stream was expected.
Rather than not doing anything, you can throw an error, so that you should get the details of the error causing the fact that you enter catchError operator, so something like this
  catchError(err => {
    if(error instanceof HttpErrorResponse && httpErrorResponse.error !== undefined){
      const customError: ApiErrors = {
        name: httpErrorResponse.error.name,
        message: httpErrorResponse.error.message,
        errors: httpErrorResponse.error.errors
      };
      return throwError(customError);
    } else {
      throw err
    }
  })
);


text:
Q: How does the List has fast random access in Java? The RandomAccess interface identifies that a particular java.util.List implementation has fast random access. This interface tries to define an imprecise concept: how fast is fast? The documentation provides a simple guide:
if repeated access using the List.get() method is faster than repeated access
using the Iterator.next() method, then the List has fast random access.

The two types of access are shown in the following code examples:
Object o;
for (int i=0, n=list.size(); i < n; i++)
o = list.get(i);

Object o;
for (Iterator itr=list.iterator(); itr.hasNext(); )
o = itr.next();

How does the List has fast random access when its list.get() method is faster than repeated access
    using the Iterator.next() method.

A: The imprecise nature of what it means to be "fast" is the reason we have the concept of algorithmic complexity, a.k.a. "big O" notation.  Random access implies that get operations have an algorithmic complexity of O(1), which is true of ArrayList.  By contrast, a get operation on a LinkedList has an algorithmic complexity of O(n).

A:
How does the List has fast random access when its list.get() method is faster than repeated access using the Iterator.next() method.

It's only a suggestion that it's marked as having fast random access with the RandomAccess if the speed of list.get() is faster than the iterator.next(). The programmer programming the specific List implementation still has to choose to have their List implement RandomAccess.
It's understandable that since list.get(i) would directly query the data that such a method call would be faster than iterator.next() (for the List's that have good random access) because the next method may have some extra overhead of other method calls and other logic. If the iterator is faster, than you can probably safely bet it's because the List does not have good random access and that the iterator is faster because it's using some optimized method of going from node to node (such a List's iterator implementation probably has some access to underlying List data that would normally be private to other classes).

A: The example code is indeed a bit misleading, because the comparison to an iterator-based solution detracts from the actual point:
A list should implement the RandomAccess interface when the List#get(int) method has a constant asymptotic running time! (Written as O(1) in Big O Notation).
Consider an ArrayList: The data internally stored in an array. Calling arrayList.get(1) will take the same time as calling arrayList.get(100000).
In contrast to that: A LinkedList does not offer RandomAccess. While you can still call linkedList.get(1) and linkedList.get(100000), the latter will take much longer, because it has to traverse the whole list until it reaches the 100000th element.


text:
Q: Haskell - Calling a function defined in a typeclass Given a typeclass:
class AnimalTrainer animal food where
    getFood :: animal -> (food, Int) -- Returns the food and the quantity
    feed :: animal -> (food, Int) -- Returns the leftovers

    feed a = feed' (getFood a) -- Provide a default implementation
        where feed' (f, n) = (f, n - 1)

And an instance:
data Animal = Dog | Cat
data Food = Meat | Milk

instance AnimalTrainer Animal Food where
    getFood Dog = (Meat, 2)
    getFood Cat = (Milk, 3)

How can I write another function (somewhere else) that calls the feed function defined in the typeclass? Example:
feedEverything :: Bool
feedEverything = snd (feed Dog) == 0

Thanks

A: The problem is that Haskell can't figure out what type you want to use for food.  It sees one instance:
instance AnimalTrainer Animal Food

But maybe there is a second instance somewhere...
instance AnimalTrainer Animal Poison

So you need to tell Haskell that animals get food only, and not something else like poison.
Solution 1: You can use functional dependencies:
class AnimalTrainer animal food | animal -> food where
    ...

This tells Haskell that for each animal type, there is only one food type that it will eat.
Solution 2: You can also use type families.
class AnimalTrainer animal where
    type AnimalFood animal :: *
    getFood :: animal -> (AnimalFood animal, Int)
    feed :: animal -> (AnimalFood animal, Int)

    feed a = feed' (getFood a) -- Provide a default implementation
        where feed' (f, n) = (f, n - 1)

data Animal = Dog | Cat
data Food = Meat | Milk

instance AnimalTrainer Animal where
    type AnimalFood Animal = Food
    getFood Dog = (Meat, 2)
    getFood Cat = (Milk, 3)

I personally consider this solution a little more esoteric, and the syntax a little less natural.  But the example is contrived, so I include this for completeness.
Solution 3: You could add explicit type annotations whenever you call feed.
feedEverything = snd ((feed :: Animal -> (Food, Int)) Dog) == 0


text:
Q: jquery ui events I have some trouble with jquery ui-events: In my application, there are some sliders. I have to adjust the "min"-option from time to time, but I have the problem, that the change()-event is not triggered after that. I would expect that on every value-change, programmatically or manually, the change-event is called. How to treat that correctly?

A: Change event only triggered on value change (as you already know). But you can "fake" value change:
var value = $('#mySlider').slider('option', 'value');
$('#mySlider').slider('option', 'value', value);


text:
Q: asp.net mvc 4 async controller hanging on none TaskAsync methods I'm using Visual Studio 2011 Beta with 4.5 Beta. There seems to be a bug with ASP.Net MVC 4, where if the method returns a none "TaskAsync" task, it hangs the request.
public class HomeController : Controller
{
    //
    // GET: /Home/

    public async Task<ActionResult> Test1()
    {
        string s = await new WebClient().DownloadStringTaskAsync("http://google.com");
        return Content("asdf");
    }

    public async Task<ActionResult> Test2()
    {
        string MyConString = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
        MySqlConnection connection = new MySqlConnection(MyConString);
        await connection.OpenAsync();
        connection.Close();
        return Content("asdf");
    }
}

Test1 works fine.
Test2 hangs once the method returns. I am able to debug through the code with no errors.
Anyone know a fix/workaround for this?

A: Known issue with MVC 4 Beta.
In short, add the following to ~/Web.config:
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>

Then add await Task.Yield(); as the first line in your action method.  (Don't forget the await!)


text:
Q: Approximation by a polynomial degree 3 centered at a=2? Approximate $\:\mathbf{f(x) = 1/\sqrt{x^3 + 1}}\:$ by a polynomial of degree 3 centered at a = 2.
What exactly is this question asking when it says "approximate"? What is the end result supposed to be I'm so lost
I found the derivatives(up to the 3rd) and I substituted x with 2, but now what?
I'd appreciate any help!

A: The taylor polynomial of $f$ of dgree $3$ at $2$ is given by
$$f(2)+\frac{f'(2)}{1!}(x-2)+\frac{f''(2)}{2!}(x-2)^2+\frac{f'''(2)}{3!}(x-2)^3.$$

A: "Approximate" means: make use of some mathematical tool that you have mastered, or studied, that will give you a good approximation of a certain function. The most known method is Taylor series. So what you have to do is make use of Taylor Series. You know that
$$f(x) \approx \sum_{k = 0}^{+\infty} \dfrac{f^{(k)}(x_0)}{k!}(x-x_0)^k$$
Where $(k)$ stands for the derivative of $f$ of order $k$, evaluated in the given center $x_0$.
In your case, you find the three derivatives of $f$ as Fred wrote, centered at $x_0 = 2$ (your $a$ is my $x_0$).

A: To approximate a function usually means that you want to construct another function that 1) should be easier to compute and 2) takes values reasonably close to the original function. [The criterion 1) might be different, but this is rare.]
A method to obtain this is to start with a candidate expression (such as a polynomial) with adjustable parameters, and find the values of the parameters that minimize some measure of the average error. So you are trying a family of functions, and try to find the "best" of them.
Another method (probably the one meant to be used here) is to match the function closely in the neighborhood of a given $x$. This is done by ensuring that the value and derivatives (up to some order) of the function and its approximation are equal at the given $x$. This is the so-called Taylor approximation.
On the picture, the given function in blue, and Taylor approximations of increasing degree.


text:
Q: I am using jquery to append additional form selections and inputs. If I come back to the form the appended inputs do not appear This is my append function:
function addMR() {
    //console.log('running addMR')
    //current keeps track of how many moving radar inputs there are
    current = parseInt(current) + 1;
    g_current = parseInt(g_current) + 1;
    var strToAdd = 'a select and 3 text inputs here - very long'
    $('#movingradarDiv').append(strToAdd)
}

and it works correctly.
Here is the form code that calls the append function:
 <input type="button" id="addMR" value="Add Moving Radar">

Appending the inputs works correctly, and the appended inputs are correctly posted with the form, but if I have to come back to the form to make changes the appended inputs no longer appear.
Can anyone tell me why this happens and how to prevent it?


text:
Q: ASP.Net Hyperlink navigation URL not including server name This might be a ridiculously easy question, but it has me stumped.  I have a web form where I'm trying to create a hyperlink in the code behind to a file server share, e.g. file://myServer/Shared/, but when the page is rendered, the link doesn't include the server name, i.e. file:///Shared/.  I don't know why this happens.  Any help or insight is appreciated.
UPDATE:
Sure, here is the snippet where the link is being set.
    //The link is embedded in a table
    HyperLink link = (HyperLink)e.Row.Cells[1].Controls[0];
    link.NavigateUrl = @"file://myServer/Shared/";

As a test, I assigned the link to a string value and the link prints the expected url.
string foo = link.NavigateUrl;

//Displays this
"file://myServer/Shared/"

I don't know why this doesn't appear when the link is rendered in the final page.
UPDATE 2:
Ok, so I know I have to set the absolute path in the code-behind, I thought that's what I was doing, but it still won't render correctly.
UPDATE 3:
I followed pjacobs suggestion about setting the test property and it was actually a step in the right direction.  I have the following:
link.Text = "link text";

Now the link gets rendered as follows: file:///myServer/Shared.  I'm almost there except it gives the extra '/' in front of the server name.  I'll keep playing with it, this seems like it should be so simple, I don't understand why ASP.Net renders the URL differently.

A: You have to set the Text property of the HyperLink...  link.Text = "whatever"

A: Are the resources inside the project? If so:
you need to use ResolveUrl to resolve the "web location" of the resource.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.resolveurl.aspx
if you're using an asp.net control you shouldn't need to use the resolve url, but you need to refer to the location of the file relative to the path of the project.
If not:
Did you give the proper read account to ASP.NET process?
Use a virtual directory?
http://www.dotnetspider.com/tutorials/AspNet-Tutorial-86.aspx


text:
Q: How do I read the soap response from UPS web services? I am trying to parse the UPS sample code for the Rating service and while I get the response from UPS, I cannot seem to do anything with it. How do I read through and find the data I want? eg
<rate:RatedShipment><rate:Service><rate:Code>03</rate:Code>

and
<rate:TotalCharges>
   <rate:CurrencyCode>USD</rate:CurrencyCode>
   <rate:MonetaryValue>126.72</rate:MonetaryValue>
</rate:TotalCharges>

I need that code and the total charges.
My code so far looks like this:
        $result = $client->__soapCall($operation ,array($this->processRate()));
        $resp = $client->__getLastResponse() ;
        echo $resp ;

output:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header />
  <soapenv:Body>
    <rate:RateResponse xmlns:rate="http://www.ups.com/XMLSchema/XOLTWS/Rate/v1.1">
      <common:Response xmlns:common="http://www.ups.com/XMLSchema/XOLTWS/Common/v1.0">
        <common:ResponseStatus>
          <common:Code>1</common:Code>
          <common:Description>Success</common:Description>
        </common:ResponseStatus>
        <common:Alert>
          <common:Code>110971</common:Code>
          <common:Description>Your invoice may vary from the displayed reference rates</common:Description>
        </common:Alert>
        <common:Alert>
          <common:Code>110920</common:Code>
          <common:Description>Ship To Address Classification is changed from Residential to Commercial</common:Description>
        </common:Alert>
        <common:TransactionReference />
      </common:Response>
      <rate:RatedShipment>
        <rate:Service>
          <rate:Code>03</rate:Code>
          <rate:Description />
        </rate:Service>
        <rate:RatedShipmentAlert>
          <rate:Code>110971</rate:Code>
          <rate:Description>Your invoice may vary from the displayed reference rates</rate:Description>
        </rate:RatedShipmentAlert>
        <rate:RatedShipmentAlert>
          <rate:Code>110920</rate:Code>
          <rate:Description>Ship To Address Classification is changed from Residential to Commercial</rate:Description>
        </rate:RatedShipmentAlert>
        <rate:BillingWeight>
          <rate:UnitOfMeasurement>
            <rate:Code>LBS</rate:Code>
            <rate:Description>Pounds</rate:Description>
          </rate:UnitOfMeasurement>
          <rate:Weight>3.0</rate:Weight>
        </rate:BillingWeight>
        <rate:TransportationCharges>
          <rate:CurrencyCode>USD</rate:CurrencyCode>
          <rate:MonetaryValue>17.76</rate:MonetaryValue>
        </rate:TransportationCharges>
        <rate:ServiceOptionsCharges>
          <rate:CurrencyCode>USD</rate:CurrencyCode>
          <rate:MonetaryValue>0.00</rate:MonetaryValue>
        </rate:ServiceOptionsCharges>
        <rate:TotalCharges>
          <rate:CurrencyCode>USD</rate:CurrencyCode>
          <rate:MonetaryValue>17.76</rate:MonetaryValue>
        </rate:TotalCharges>
      </rate:RatedShipment>
      ......
    </rate:RateResponse>
  </soapenv:Body>
</soapenv:Envelope>

I then run this code on it:
$xml = simplexml_load_string($resp);
\TYPO3\Flow\var_dump($xml  );

$json = json_encode($xml);
$xmlarray = json_decode($json,TRUE);

echo "\n".__FILE__.' '.__LINE__."   xmlarray   \n";
\TYPO3\Flow\var_dump($xmlarray);
die;

This outputs

                Flow Variable Dump

SimpleXMLElementprototypeobject

/home/me/domains/shop.me.com/public_html/releases/20131219160416/Data/Temporary/Development/Cache/Code/Flow_Object_Classes/Shop_Shipping_UPSShippingHandler.php 336   xmlarray

                Flow Variable Dump

array(empty)

Seems my simplexml_load_string($resp) call is not working.
UPDATE:
Thanks alien. This is what my code looks like now - it is not perfect yet but you get the idea - :
                $result = $client->__soapCall($operation ,array($this->processRate()));
                $resp =   $client->__getLastResponse() ;
                $sxe = simplexml_load_string($resp);
                $sxe->registerXPathNamespace('r', "http://www.ups.com/XMLSchema/XOLTWS/Rate/v1.1");
                $codes = $sxe->xpath('//r:RatedShipment/r:Service/r:Code');

                $mv = $sxe->xpath('//r:TotalCharges/r:MonetaryValue');
                $indx=0;
                $estimates = array();
                foreach ($codes as $c) {
                    $temporaryEstimate = array();
                    $temporaryEstimate['estimateId'] = $this->getServiceTitleByCode($c->__toString());
                    $temporaryEstimate['estimatePrice'] = '$' .$mv[$indx];
                    $estimates[] = $temporaryEstimate;
                    $indx++;
                }
                return $estimates;

A: There is no real need to do the conversion to JSON and back again (unless you like making your computer work!); I loaded the XML you posted directly into a SimpleXMLElement and then queried it using XPath:
$sxe = new SimpleXMLElement($resp);

The elements that you are interested in are all in the rate namespace, so you need to register the namespace to be able to query it:
$sxe->registerXPathNamespace('r', "http://www.ups.com/XMLSchema/XOLTWS/Rate/v1.1");

We can now refer to all the rate: nodes in the XML using the shorthand r:.
Query for all the Code elements under RatedShipment/Service in the r namespace:
$codes = $sxe->xpath('//r:RatedShipment/r:Service/r:Code');
foreach ($codes as $c) {
    echo "code: $c" . PHP_EOL;
}

Output:
code: 03

Find the total cost of the shipment, which is under r:TotalCharges as r:MonetaryValue and r:CurrencyCode:
# xpath returns an array; we want the first element of that array for both these
$curr = $sxe->xpath('//r:TotalCharges/r:CurrencyCode')[0];
$mv = $sxe->xpath('//r:TotalCharges/r:MonetaryValue')[0];
echo "total charges: $mv $curr ". PHP_EOL;

Output:
total charges: 17.76 USD

If you aren't familiar with XPath, see the PHP documentation for more information on SimpleXML's XPath implementation.


text:
Q: Cake bake don't generate auto rules I'm newbie in cakephp and i'm generating model's code with bake. But the code generated dont give with a array with auto validations. why not? My fields are not null, an id, an title and an content fields. Sorry for my bad english, and thanks very much.
My table:
CREATE TABLE `pages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(500) NOT NULL,
  `content` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB;

A: Automatically the cakephp bake doesn't create validation rules for your models. However it provides an interactive shell to create the models and also the validation rules and/or relationships.
More info in the docs


text:
Q: Axis2 error: The addressing-1.5.1.mar module, which is not valid, caused null anyone have any idea what could be the cause of the following error and how to resolve it?
org.apache.axis2.deployment.ModuleDeployer 2010-09-23 11:42:40,689 -- ERROR -- The addressing-1.5.1.mar module, which is not valid, caused null
java.lang.ExceptionInInitializerError
        at org.apache.axis2.deployment.util.Utils.createTempFile(Utils.java:224)

        at org.apache.axis2.deployment.util.Utils.getURLsForAllJars(Utils.java:165)

        at org.apache.axis2.deployment.util.Utils.createClassLoader(Utils.java:899)

        at org.apache.axis2.deployment.repository.util.DeploymentFileData.setClassLoader(DeploymentFileData.java:115)

        at org.apache.axis2.deployment.ModuleDeployer.deploy(ModuleDeployer.java:65)

        at org.apache.axis2.deployment.repository.util.DeploymentFileData.deploy(DeploymentFileData.java:136)

        at org.apache.axis2.deployment.DeploymentEngine.doDeploy(DeploymentEngine.java:659)

        at org.apache.axis2.deployment.RepositoryListener.init(RepositoryListener.java:251)

        at org.apache.axis2.deployment.RepositoryListener.init2(RepositoryListener.java:68)

        at org.apache.axis2.deployment.RepositoryListener.<init>(RepositoryListener.java:63)

        at org.apache.axis2.deployment.DeploymentEngine.loadRepository(DeploymentEngine.java:147)

        at org.apache.axis2.deployment.FileSystemConfigurator.getAxisConfiguration(FileSystemConfigurator.java:133)

        at org.apache.axis2.context.ConfigurationContextFactory.createConfigurationContext(ConfigurationContextFactory.java:64)

        at org.apache.axis2.context.ConfigurationContextFactory.createConfigurationContextFromFileSystem(ConfigurationContextFactory.java:206)

Caused by: java.lang.NullPointerException
        at org.apache.axis2.deployment.util.TempFileManager.recursiveDelete(TempFileManager.java:138)

        at org.apache.axis2.deployment.util.TempFileManager.<clinit>(TempFileManager.java:202)

        ... 22 more

A: When this happened to me, I solved the problem by setting java's java.io.tmpdir property to a directory that my Linux user acct could surely write to.  I used "mkdir" while logged into my Linux user account to create the tmpdir before running my application.
java -Djava.io.tmpdir=[writable directory] [other options] [class to run]


text:
Q: How to add location in ACM-Reference-Format.bst ? also related: How to order by citation the bibliography with ACM-Reference-Format.bst? ACM-Reference-Format.bst order alphabetically .
i want to use this ".bst" and ordering by appearance in the final document. Also i want to add the location. Examples:
[3] Fröhlich, B. and Plate, J. 2000. The cubic mouse: a new device for three-dimensional input. In Proceedings of the SIGCHI Conference on Human Factors in Computing Systems (The Hague, The Netherlands, April 01 - 06, 2000). CHI '00. ACM, New York, NY, 526-531. DOI= http://doi.acm.org/10.1145/332040.332491.
the new format shows without location
[3] Fröhlich, B. and Plate, J. 2000. The cubic mouse: a new device for three-dimensional input. In Proceedings of the SIGCHI Conference on Human Factors in Computing Systems . CHI '00. ACM, New York, NY, 526-531. DOI= http://doi.acm.org/10.1145/332040.332491.

A: *

*The location is a part of the book title,
booktitle={Proceedings of the SIGCHI Conference on Human Factors in
Computing Systems (The Hague, The Netherlands, April 01 - 06, 2000).
 CHI'00}

*Currently alphabetic sorting is required for all ACM citations.


text:
Q: No overload for method '(Function Name)' takes '0' arguments while debugging i got this error : "No overload for method 'STUDENTCOURSEDETAILS_Load' takes '0' arguments"
The STUDENTCOURSEDETAILS is a Winform and STUDENTCOURSEDETAILS_Load is the OnLoad event for the form.i tried to call this event in another function and got the above said error.How can i call an Event in another function ? How  can I Pass parameter's while calling this Event ?I Don't Know what kind of Parameter's sholud I have to Pass. Need Help...
private void STUDENTCOURSEDETAILS_Load(object sender, EventArgs e)
        {
            txtregno.Enabled        = false;
            txtstudentname.Enabled  = false;
            txtcoursid.Enabled      = false;
            txtcoursname.Enabled    = false;
            dtpdoj.Enabled          = false;
            txtfee.Enabled          = false;
            txtdiscountper.Enabled  = false;
            txtnarration.Enabled    = false;
            btnSave.Text            = "&Add";

        }

private void btnAdd_Click(object sender, EventArgs e)
        {
            switch (btnSave.Text)
            {
                case "&Add":
                    txtregno.Enabled        = true;
                    txtstudentname.Enabled  = true;
                    txtcoursid.Enabled      = true;
                    txtcoursname.Enabled    = true;
                    dtpdoj.Enabled          = true;
                    txtfee.Enabled          = true;
                    txtdiscountper.Enabled  = true;
                    txtnarration.Enabled    = true;
                    btnSave.Text            = "&Save";
                    break;
                case "&Save":
                    if (validation())
                    {
                        if (MessageBox.Show("sure to save?", CPublic.messagename, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            selectstudentid();
                            cmd.Connection = CPublic.Comm_con;
                            cmd.Parameters.Clear();
                            cmd.Parameters.AddWithValue("@regno", txtregno.Text);
                            cmd.Parameters.AddWithValue("@studentid", id);
                            cmd.Parameters.AddWithValue("@studentname", txtstudentname.Text);
                            cmd.Parameters.AddWithValue("@courseid", txtcoursid.Text);
                            cmd.Parameters.AddWithValue("@coursename", txtcoursname.Text);
                            cmd.Parameters.AddWithValue("@doj", dtpdoj.Value.ToString(CGeneral.ServeDateFmt));
                            cmd.Parameters.AddWithValue("@fee", txtfee.Text);
                            cmd.Parameters.AddWithValue("@discount", txtdiscountper.Text);
                            cmd.Parameters.AddWithValue("@narration", txtnarration.Text);
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.CommandText = "SP_INSERT_studentcoursedetails" + CPublic.g_firmcode;
                            cmd.ExecuteNonQuery();
                            MessageBox.Show("COURSE ADDED SUCCESSFULLY...", CPublic.messagename, MessageBoxButtons.OK, MessageBoxIcon.Information);
                            clearall();
                            btnSave.Enabled         = true;
                            btnSave.Text            = "&Add";
                            STUDENTCOURSEDETAILS_Load();
                         }
                    }
                            break;
            }
        }

A: That is because of the line
btnSave.Text            = "&Add";
STUDENTCOURSEDETAILS_Load();

You should rather use
STUDENTCOURSEDETAILS_Load(null, null);

Obviously there can be further error which you may face at runtime.

A: You can call the method like this:
STUDENTCOURSEDETAILS_Load(null, null);


text:
Q: Combine two RDDs in Scala The first RDD, user_person, is a Hive table which records every person's information:
+---------+---+----+
|person_id|age| bmi|
+---------+---+----+
|     -100|  1|null|
|        3|  4|null|
...

Below is my second RDD, a Hive table that only has 40 row and only includes basic information:
| id|startage|endage|energy|
|  1|       0|   0.2|     1|
|  1|       2|    10|     3|
|  1|      10|    20|     5|

I want to compute every person's energy requirement by age scope for each row.
For example,a person's age is 4, so it require 3 energy. I want to add that info into RDD user_person.
How can I do this?

A: First, initialize the spark session with enableHiveSupport() and copy Hive config files (hive-site.xml, core-site.xml, and hdfs-site.xml) to Spark/conf/ directory, to enable Spark to read from Hive.
val sparkSession = SparkSession.builder()
  .appName("spark-scala-read-and-write-from-hive")
  .config("hive.metastore.warehouse.dir", params.hiveHost + "user/hive/warehouse")
  .enableHiveSupport()
  .getOrCreate()

Read the Hive tables as Dataframes as below:
val personDF= spark.sql("SELECT * from user_person")
val infoDF = spark.sql("SELECT * from person_info")

Join these two dataframes using below expression:
val outputDF = personDF.join(infoDF, $"age" >= $"startage" && $"age" < $"endage")

The outputDF dataframe contains all the columns of input dataframes.


text:
Q: How to get an input value of input type number? I've got a number field in my form which one can input a score here:
<input type="number" min="0" max="100" class="form-control" name="total_score" id='total_score' value="<?php echo $total_score;?>" >(Please enter a score from 0-100)

And before the form is submit, I need to check whether this field is filled. I'd not like to use the required since I don't want to block the user when they need more time to decide the input score.
I tried to catch the value of total score with:
                var score  = document.getElementsById("total_score").value;
                if(score==null){
                    alert("no score");
                }

But seems not working. Any Ideas? Thanks.

A: value will never be null because it's always a string. You could use
var score  = document.getElementsById("total_score").value.trim();
if (!score) {
    alert("no score");
}

...since any non-blank string (including "0") will be truthy.
Once you'e determined there's a value there, you can either convert it to number yourself (my answer here has several options) or use the valueAsNumber property of the input.
Note: String#trim was added in ES2015 so it won't exist in obsolete browsers like IE8 unless you polyfill it.

Side note: I assume the getElementsById in your question is a typo, and your real code has getElementById (no s).

A: Lets describe this problem in details. We always need to understand problem the under the hood that we can solve all similar problems.

    (Please enter a score from 0-100)
    <input
      type="number"
      id="total_score"
      name="total_score"
      min="0"
      max="100"
      value="<?php echo $total_score;?>">

If we want to grab the value document.getElementById('total_score').value. It return a String type of value.
let value = document.getElementById('total_score').value;
console.log(typeof value) //'String'

So a String type of value never be null
let value = '';
console.log(value == null) //false

Enough discussion, Right?
Lets solve the problem.
const score = parseFloat(document.getElementById('total_score').value);

Its convert the value String to Number.
Suppose
parseFloat("100"); // 100
parseFloat(''); //NaN

We can check is value really a number or not.
isNaN(value); // return true or false

I think, here is your problem solve.
Full solve:
HTML:

        (Please enter a score from 0-100
        <input
          type="number"
          id="total_score"
          name="total_score"
          min="0"
          max="100">

JS:
const score = parseFloat(document.getElementById("total_score").value);

if(isNaN(score)){
   alert("no score");
}

A: Does this work:
            if(isNaN(parseInt(score))){
                alert("no score");
            }

A: This should work:

// first get the element
let element = document.getElementById('myInput');

// get the value property of the element
console.log(element.value);

//we could do a check the following way:

function change() {
  if (element.value > 100) {
    console.log('value too big');
  }

  if (element.value < 5) {
    console.log('value too small');
  }
}
<input type="number" value=5 id="myInput" oninput="change()"/>


text:
Q: Adding to local variables (integers) in Python I'm trying to make a function where if the user chooses an option more than twice the output of the option will change, so when they choose the 'bench' option more than twice it will change and give them a different answer. Btw - delayedPrint() is a function I made which prints the characters one by one.
def menuChoice():
    notepad = 1
    delayedPrint('\n')
    choice = input('> ')
    if choice == "bench" and notepad < 2:
        moreDelayedPrint("You grab the notepad off the bench." + '\n')
        moreDelayedPrint("You flick through the pages, but don't notice anything written down." + '\n')
        notepad + 1
        optionMenu()
    elif choice == "bench" and notepad > 2:
        moreDelayedPrint("You grab the notepad off the bench." + '\n')
        moreDelayedPrint("Aha! This time you notice a small scribble near the back of the     notepad." + '\n')
        moreDelayedPrint("It reads "3472" + '\n')
        optionMenu()

No matter how many times I choose my 'bench' option, It reads 'you flick through the pages, but don't notice anything written down' - my 'notepad + 1' seems not to be working. Any ideas?
Thanks!

A: notepad + 1 returns the new value. Assign it back to notepad to replace the old:
notepad = notepad + 1

You'll also need to add a loop to your function; you are just asking the user once:
def menuChoice():
    notepad = 1
    delayedPrint('\n')
    while True:
        choice = input('> ')
        if choice == "bench" and notepad < 2:
            moreDelayedPrint("You grab the notepad off the bench." + '\n')
            moreDelayedPrint("You flick through the pages, but don't notice anything written down." + '\n')
            notepad = notepad + 1
            optionMenu()
        elif choice == "bench" and notepad >= 2:
            moreDelayedPrint("You grab the notepad off the bench." + '\n')
            moreDelayedPrint("Aha! This time you notice a small scribble near the back of the     notepad." + '\n')
            moreDelayedPrint('It reads "3472\n')
            optionMenu()

Now when optionMenu() returns the loop brings you back to the choice prompt.


text:
Q: How Do I Update Two Models in Rails Simultaneously? Let's say I have an app that matches two People against each other, kind of like "hot or not."
I have my matchup view pulling random users out of the database and matching them up against each other. When a user votes for one of the people I would like to increase their :wins and :matches_played by 1 but I would also like to increase the losers :matches_played by 1 so that I can calculate rankings.
Is there is a way to use a form for each person to accomplish this or do I need a model in between, something like Match that has two columns for the winner and loser, and if so how would this work.

A: Doing it only using a People model (the "easy" way):

*

*Pro's: It's easy

*Con's: It's easy for people to inflate their "wins" by forging the form's parameters using Firebug or Chrome's Inspection tool

Assuming you have these routes:
new_person  GET     /people/new(.:format)        {:action=>"new", :controller=>"people"}
edit_person GET     /people/:id/edit(.:format)   {:action=>"edit", :controller=>"people"}
person      GET     /people/:id(.:format)        {:action=>"show", :controller=>"people"}
            PUT     /people/:id(.:format)        {:action=>"update", :controller=>"people"}
            DELETE  /people/:id(.:format)        {:action=>"destroy", :controller=>"people"}

HAML Version of the view code:
- # Person A form
= form_tag(person_path(@personA, :loser_id => @personB), :method => :put) do
  = submit_tag "Vote for Person A"

- # Person B form
= form_tag(person_path(@personB, :loser_id => @personA), :method => :put) do
  = submit_tag "Vote for Person B"

ERB Version:
<%# Person A form %>
<% form_tag(person_path(@personA, :loser_id => @personB), :method => :put) do %>
  <%= submit_tag "Vote for Person A" %>
<% end %>

<%# Person B form %>
<% form_tag(person_path(@personB, :loser_id => @personA), :method => :put) do %>
  <%= submit_tag "Vote for Person B" %>
<% end %>

Then in your controller for the update action you could do:
def update
  People.transaction do
    winner = People.find(params[:id])
    loser = People.find(params[:loser_id])

    # Increment the winner
    winner.increment! :matches_played
    winner.increment! :wins

    # Increment the loser
    loser.increment! :matches_played
  end

  respond_to do |format|
    format.html { redirect_to new_match_path }
  end
end

As someone pointed out in the comments, you should probably wrap this in what is called a transaction so that it's only permanently in the database if everything within the transaction saves successfully.

Even though I'm showing you the method above, I'd still recommend using a Match model.  Ultimately, using that extra model will help you validate the following things so people can't game your system.

*

*User's can only vote once per match

*User can't vote on a match involving them

*User can't forge a form to inflate their wins

*Separate's concerns as far as Models go and keeps your data more organized and clear for analytics purposes

Yes, this all requires more work (which is why I'm not showing code for it), but it may be something you want to do if you're concerned about any of the above.

A: You should write your form submission to submit both user ids to your controller, with an indication of the winning user. Then you can operate on both and save them to the db.
winner = People.find(params[:winner_id])
loser  = People.find(params[:loser_id])
winner.matches_played += 1
winner.wins += 1
loser.matches_played += 1
winner.save!
loser.save!


text:
Q: StackExchange inbox tab shows only older messages The StackExchange Inbox tab (not the top left inbox link but the dedicated page) has been stuck on older messages for  around 2 around 4 days now.
Scroll down from top left Inbox to the bottom to "See All". This link sometimes shows as "more inbox messages …"

which takes you to the page below. Note: you can get to this Inbox page from Network Profile > Inbox as well
Mine is out of sync by about 40 messages or 12 days. In case that helps.

A: There was an ordering issue here, your new items were actually on page 2, 3, 4, or 5 (depending on how many you had).  This is now fixed.

In-depth why, because we care <3:
We actually store your inbox in 2 places, your most recent items are in redis, and your older ones are in SQL.  After a small delay a background process culls them from redis to SQL.
Actually after a minute or two usually, all your items are in both places...but since redis may still be changing, or have a deletion that's not yet persisted, etc...we need to construct the overall inbox that stackexchange.com shows from both sources.
To do this, we take the items from redis (observing the earliest date) and the items from SQL (any before the minimum redis date), then combine them in code via .Union(), this was happening backwards in some cases.
In addition to that, the API on the backend for has a page size 5x larger than what is shown on stackexchange.com (meaning se.com loads 5 pages at once when fetching)...combine these two and you see how your new items were appearing at the end of the first API page, which translated to anywhere from page 1-5 on stackexchange.com, depending on how many new items you had.


text:
Q: OpenCV YAML parser does not recognize "true"/"false" values OpenCV's YAML parser does not recognize "true"/"false" values.
According to the YAML definition of bool, these values should be interpreted as boolean values.
Example code:
bool b(false);
cv::FileStorage fs("/tmp/test.yaml", cv::FileStorage::READ);
if(!fs["b"].empty())  fs["b"] >> b;
fs.release();

"/tmp/test.yaml":
b: false
b: False
b: off
b: 0

Only when b:0, b becomes false.  Otherwise, b==true as the values (false/False/off) are translated as an integer value (cf. the OpenCV source code-persistence.hpp).

A: My solution is overwriting the behavior of operator>> for bool by specializing the template.
More concretely:
namespace cv
{
// Define a new bool reader in order to accept "true/false"-like values.
void read_bool(const cv::FileNode &node, bool &value, const bool &default_value)
{
  std::string s(static_cast<std::string>(node));
  if(s=="y"||s=="Y"||s=="yes"||s=="Yes"||s=="YES"||s=="true"||s=="True"||s=="TRUE"||s=="on"||s=="On"||s=="ON")
    {value=true; return;}
  if(s=="n"||s=="N"||s=="no"||s=="No"||s=="NO"||s=="false"||s=="False"||s=="FALSE"||s=="off"||s=="Off"||s=="OFF")
    {value=false; return;}
  value= static_cast<int>(node);
}
// Specialize cv::operator>> for bool.
template<> inline void operator >> (const cv::FileNode& n, bool& value)
{
  read_bool(n, value, false);
}
} // cv


text:
Q: I want to use LGPL htmltopdf library in a commercial project, I'm I free to use? I'm working on a project where I need to use some htmltopdf library.Now their licence is LGPL, I don't know whether I'm free to use this one. My project is a commercial one.Please explain LGPL and what are the consequences if use it in a commercial project!

A: LGPL is GNU Lesser Public License and it allows you to use and distribute your application without revealing the source code. LGPL does not put restrictions on whether your software is commercial or not.
Actually both GPL and LGPL do not care if your software is commercial or not. GPL license mandates that you should open-source the software in which it is used. LGPL does not.
When using LGPL, if you modify the LGPL source then you still have to link and open-source your changes to the LGPL versioned part of your application (in your case HTMLToPDF). However you can link the LGPL-ed software to a commerical/proprietary software which is closed source.
Read this as well.


text:
Q: AS3 Should i removeEventListener I have a pretty complex game with many views and many controllers, and it works really well but periodically lags. I am trying to fix up my code so it's as efficient as i can make it, but i have some questions as to who AS3 handles events.
Now here is a very basic example:
AppController loads 5 different OverlayControllers. Each one of those OverlayControllers dispatch an Event.COMPLETE when they are done that my AppController listens to. I have a constant EventListener listening to those OverlayControlllers no matter where I am in the game.
Should i only have those listeners there when the Overlay is open? And Remove them when they close?
Should i bypass the event listener period and just pass the AppController to the OverlayControllers so it can just call a public function instead of requiring an EventListener?
Just to be clear these aren't objects that i'm removing from the stage. They are just being hidden. If i ever remove an object i always remove its event listeners before destroying them.

A: First of all download Adobe Scout (http://www.adobe.com/devnet/scout/articles/adobe-scout-getting-started.html) and see what's causing the "lags" - probably garbage collection ...then fix the issue. Removing as many listeners as possible is always a good thing but make sure that those are causing the issue. Profile memory usage and try to keep object creation/destruction to a minimum to avoid garbage collection (during the main game loop).


text:
Q: SQL Server geography latitude longitude error I'm using geography data type for calculating shortest distance.
CREATE TABLE Landmark (
    Id int,
    Latitude FLOAT,
    Longitude FLOAT
)

INSERT Landmark VALUES
(1, 49.242458, -123.153465),
(2, 49.249381, -122.866683)

WITH GeographyLandmark AS
(
    SELECT Id, geography::STPointFromText('POINT(' + CAST(Latitude AS VARCHAR(20)) + ' ' + CAST(Longitude AS VARCHAR(20)) + ')', 4326) Location
    FROM Landmark
)

--this query calculates distance between point and localizations in meters
SELECT Id, geography::STPointFromText('POINT(' + CAST(49.2424566 AS VARCHAR(20)) + ' ' + CAST(-123.1534623 AS VARCHAR(20)) + ')', 4326).STDistance(Location) Distance
FROM GeographyLandmark

But I am getting this error:

A .NET Framework error occurred during execution of user-defined routine or aggregate "geography":
    System.FormatException: 24201: Latitude values must be between -90 and 90 degrees.
    System.FormatException:
       at Microsoft.SqlServer.Types.GeographyValidator.ValidatePoint(Double x, Double y, Nullable1 z, Nullable1 m)
       at Microsoft.SqlServer.Types.Validator.BeginFigure(Double x, Double y, Nullable1 z, Nullable1 m)
       at Microsoft.SqlServer.Types.ForwardingGeoDataSink.BeginFigure(Double x, Double y, Nullable1 z, Nullable1 m)
       at Microsoft.SqlServer.Types.CoordinateReversingGeoDataSink.BeginFigure(Double x, Double y, Nullable1 z, Nullable1 m)
       at Microsoft.SqlServer.Types.WellKnownTextReader.ParsePointText(Boolean parseParentheses)
       at Microsoft.SqlServer.Types.WellKnownTextReader.ParseTaggedText(OpenGisType type)
       at Microsoft.SqlServer.Types.WellKnownTextReader.Read(OpenGisType type, Int32 srid)
       at Microsoft.SqlServer.Types.SqlGeography.ParseText(OpenGisType type, SqlChars taggedText, Int32 srid)
       at Microsoft.SqlServer.Types.SqlGeography.GeographyFromText(OpenGisType type, SqlChars taggedText, Int32 srid)
    .

What's the problem here?

A: It looks like you've got the latitude and longitude switched. A couple of things:

*

*An easy sanity check is to use the Lat and/or Long extended properties. Here is the doc for Long.

*Another extension that Microsoft's implementation provides is the Point static method for creating points. So instead of having to create the WKT for a point to pass to STPointFromText, you can just do geography::Point(Latitude, Longitude, SRID). Here is the doc for that.


text:
Q: how to get return value from the the subroutine functrion to the main function? I would like to ask very simple question that sometime make me confuse.
I want to get a value from the subroutine function, but I tried many ways still don't get it out,
Here is my code:
void Read_line (string filename)
{
    int number_of_lines = 0;
    std::string line1;
    std::ifstream myfile(filename.c_str());

    while (std::getline(myfile, line1))
    {
        ++number_of_lines;
    }
    cout << "Number of lines in text file: " << number_of_lines;

//  return number_of_lines;
}

int main ()
{

    string name = "gbm";
    double WEEK = 1930;
    double DAY = 0;

    string week = boost::lexical_cast<string>(WEEK);  // convert number to string
    string day  = boost::lexical_cast<string>(DAY) ;  // convert number to string

    string filename = name + week + day + ".sp3";
    int number_of_lines = Read_line(filename);

   // my expectation to have "number_of_lines" value in here

   cout << "Number of lines in text file: " << number_of_lines;

}

Thank you for helps.

A: Change the function to return int instead of void. Then you'll be able to uncomment the return statement.
int Read_line (string filename)
{
    ...
    return number_of_lines;
}


text:
Q: singular or plural: objects following "sometimes" I would like to ask a question to native English speakers.  Could you tell which sentense is right and its reason?
a) I sometimes go to a museum.
b) I sometimes go to museums.
My question is whether we should take plural or singular object when we use "sometimes."
Thank you.

A:
a) I sometimes go to a museum.

You would say this when you often go to one particular museum (e.g., the Museum of Modern Art). You can also say this when you go to any museum on a particular occasion.

When I am depressed, I sometimes go to a museum or an empty theater.

The other one

b) I sometimes go to museums.

can be said when you visit multiple museums, both in a single occasion and in different ones.
When I go to NYC, I sometimes go to museums, parks, and libraries.


text:
Q: Testing means and proportions I've worked with survey researchers, and we used to collect a lot of categorical data. So for significance testing of a 5 point scale, we would do something like recode the original variable into a binary variable where 4/5=1 and 1/2/3=0.
Then we would use a Z test of means of the binary variable and use that proportion to test for significant differences.
I guess my question is, why not use the test of proportions? Would the two yield the same results? In other words, can I take any categorical variable and recode it to 0/1 variable and use a mean test, or conversely use a proportion test?
Why do two different tests exist anyways? Does the means test exist to accommodate truly continuous data?

A: A couple of things here:
To your general question about the difference between the test of means and the test of proportions the answer comes into the variance (and therefore the standard deviation) of the estimator.
For means, we either take the variance as given, or we compute it from the sample using the estimator
$$\frac{1}{n-1}\sum_{i=1}^n(X_i-\bar{X})^2$$
and for proportions we use the estimator
$$n\hat{p}(1-\hat{p})$$
where $\hat{p}$ is the sample estiamtor of the proportion of successes. Okay so we see that these are two different estimators.
Now for your original problem, neither of these estimators are really appropriate for categorical analysis. The most basic test is that of the chi-squared significance test. You could also look at other non-parametric tests.


text:
Q: ODI Log and Error files are empty Hi I am trying to load data using ODI where my source is flat files and target is Hyperion Essbase but it is getting failed and if I try to see the ODI Log and Error files they are empty.
Can anyone help me regarding this issue.
Thanks in advance.

A: The best way to debug an ODI job is to go in the Operator navigator in ODI Studio. There you will see the result of the execution, with more or less details depending on the log level you choose at execution time. The higher the log level is, the more information you will have.
The log files in ODI Studio only contains errors encountered by the GUI while designing your jobs, it doesn't give much information about the runtime.


text:
Q: Why does this sum converge to $0$? In Van der Poorten's "A Proof that Euler Missed...", which outlines Apéry's proof that $\zeta(3)$ is irrational, the following sum appears:
$$
S=\sum_{k=1}^{N} \frac{(-1)^k}{(2k^3) \binom{N+k}{k} \binom {N}{k}}.
$$
Van der Poorten remarks further on that $\displaystyle \lim_{N\to\infty} S = 0$ without giving a proof. This does not seem immediately obvious to me, how can I prove it?

A: Every term is less than $1/N^2$, so the total is less than $1/N$


text:
Q: Failing to close connection after running sql query, how detrimental? When manually running an sql query from an app server, if a user just clicks the X to close the window instead of using F12 or the menu to close the connection to the DB, what kind of negative impact can there be?
.
Is there an automatic timeout for connections?

A: The timeout of a MySQL connection is defined in the /etc/my.cnf file in the wait_timeout server system variable. It's defaulted to 28800 (seconds) - we usually set it for our clients to a very low value - ranging from 10 seconds to 60 seconds. So, if you leave a connection unclosed, then it'll close, by default, after 28800 seconds (that's very high if you have a large number of clients using the app).
In your case, interactive_timeout doesn't apply, since you are not really using the console.


text:
Q: Submit form with an anchor tag without refreshing page I am trying to use basicModal to make a modal popup after my anchor tag is clicked on to submit a form. I originally had a button tag, but it seems to me that basicModal only works with anchor tags so I switched to that. The problem is that when I submit the form by clicking on the button, the page refreshes without the modal actually popping up. That being said, I'd like for me to be able to submit the form using the anchor tag and not refresh the page so the modal can popup.
I tried doing:
Submit!
To submit the form but do nothing onclick with return false but that is not working.
The code looks like this:
    <form method="POST" action="" class="form">

          <select name="city">
            <option value="" disabled selected>Select a City</option>
            <option value="nyc">NYC</option>
            <option value="philly">Phladelphia</option>
            <option value="rot">Rotchester</option>
            <option value="sf">San Francisco</option>
            <option value="boston">Boston</option>
            <option value="la">Los Angeles</option>
          </select>

          <select name="category">
            <option value="" disabled selected>Select a Category</option>
            <option value="cs">Computer Science</option>
            <option value="math">Mathematics</option>
            <option value="bio">Biology</option>
            <option value="chem">Chemistry</option>
            <option value="physics">Physics</option>
            <option value="art">Art</option>
            <option value="lang">Linguistics</option>
            <option value="astro">Astrology</option>
          </select>

                <input type="text" class="span2" name="get-date" value="Select a Date" id="dp1">

              Submit!

    </form>

A: If i understand right, you want submit form to the server and then show response with modal popup, without page refresh. Then you need ajax request:
var submitForm = function()
{
    $.ajax({
        type: 'post',
        url: '',
        data: $('form').serialize(),
        success: function(response){
            //open your modal here
        }
    })
}

and button:
Submit!

A: Consider the following example:
Submit!

function submitForm(){
    $.ajax({
        type: 'POST',
        url: '<url>',  // change to your url
        data: $('.form').serialize(),
        success: function(response){
            basicModal.show({    // just for example
                body: '
This is a dead-simple alert modal!
The message can be filled with anything you want.
',
                buttons: {
                     action: {
                         title: 'Dismiss',
                         fn: basicModal.close
                     }
                }
            });
        }
    });
}


text:
Q: A Variable in JS is not deleted but here is no error? I have a variable. var variable; It is variable="Hello World";. Now, without using var and deleting it:

document.write(myVar);
delete myVar;
console.log("This should be an error because myVar has been deleted: ");
console.log(myVar);
<!--This is my module-->
<script>
  myVar = "Hello";
</script>

But with 'use strict';, there is no error with delete, and no error even though it cannot delete a var?

console.log("My Code Is Running");
delete myVar;
if (!myVar){
document.write("Var Has Been Deleted");
}
console.log("My Code Is Done");

// Why does it not write "Var Has Been Deleted"?
// There is no 'use strict' to stop the delete.
<script>
'use strict';
var myVar = "Hello World";
</script>

What is happening?
Thanks in advance


text:
Q: Clarification on the Onion architecture's Domain Service and Application Service I am studying Onion Architeture but i got some doubts:
All the samples (github) I found over internet are too simple, or are implemented under DDD (which I have not studied at the moment) so I can not get a clear concept.
About Domain.Services I have some doubts:

*

*It has to define implementations?  For all Services interfaces declared?

*It has to define domain logic, can you give a detailed example? (avoid tipical GetUser() example ). I can imagine this service as for example
 public interface IMarketKartService
 {
    double AddItemToKart(Kart kart, ShopItem item);
    double CalculateBill(Kart kart);
 }

*This layer is able to use repositories or not?

Later is Application.Services layer. As i read it should be an API, and implement user cases that get consumed by the User (for example from a WinForms app)

*Am I right?

*Is this layer able to use repositories? (I suposse that yes but please clarify) So repositories in which layers are eligible to use?

I don't get the sense of many DDD terms, so please avoid them in your explanations.


text:
Q: Passing array elements between different classes in Java I am having trouble passing the elements in an array that holds names and numbers to another class where calculations will be done. This is what I have for the classes.
public class Employee {
    private int sales;
    private String name;

    public Employee(String name, int sales){
        this.name = name;
        this.sales = sales;
    }
    public String getName(){
        return this.name;
    }
    public int getSales(){
        return this.sales;
    }
}

That class is to help store the name and sales for the array. Here is the array in its separate class.
import java.util.Scanner;

public class EmployeeArray {

    public static int employee() {

        Scanner input = new Scanner(System.in);

        int numEmp;
        System.out.println("Enter how may employees to be compared: ");
        numEmp = input.nextInt();
        input.nextLine();
        Employee[] employees = new Employee[numEmp];

        for (int i = 0; i < numEmp; i++) {
            System.out.print("Enter your name: ");
            String employeeName = input.nextLine();
            System.out.println();
            System.out.print("Enter your annual sales: ");
            int employeeSales = input.nextInt();
            input.nextLine();
            System.out.println();

            Employee employee = new Employee(employeeName, employeeSales);
            employees[i] = employee;
        }
        Employee maxSeller = employees[0];
        for (int i = 0; i < employees.length; i++) {

            System.out.println("Employee Name: " + employees[i].getName());
            System.out.println("Total sales: $" + employees[i].getSales());
            System.out.println();

            if (maxSeller.getSales() < employees[i].getSales()) {
                maxSeller = employees[i];
            }
        }
        System.out.println();
        System.out.println("Top Seller is: " + maxSeller.getName());
        System.out.println("Top Sales are: $" + maxSeller.getSales());

        return maxSeller.getSales();

    }
}

The array holds the values and returns a top seller called maxSeller and gets the name and sales amount for them. Now the problem I am running into is that in a separate class I need to get the values stored in this array to do some calculations. I have to get sales of maxSeller and compare them to the sales of the other sellers in the array. Form there I am trying to display how much more sales the others need to get to equal or surpass the top seller. That is the problem I am running into. I don't know how to pass the values from this array to the next class so I can do the calculations. Any thoughts?

A: Instead of creating the array inside a static method you can make it a member of EmployeeArray you can then reuse the the array in a static context (not recommended) or create different EmployeeArrays to hold different arrays of employees, this makes more sense in OOP. A rough sketch:
import java.util.Scanner;

public class EmployeeArray {
private Employee[] employees;

public Employee[] getEmployees() {
    return employees;
}

public void setUpArray() {
    Scanner input = new Scanner(System.in);

    int numEmp;
    System.out.println("Enter how may employees to be compared: ");
    numEmp = input.nextInt();
    input.nextLine();
    employees = new Employee[numEmp];

    for (int i = 0; i < numEmp; i++) {
        System.out.print("Enter your name: ");
        String employeeName = input.nextLine();
        System.out.println();
        System.out.print("Enter your annual sales: ");
        int employeeSales = input.nextInt();
        input.nextLine();
        System.out.println();

        Employee employee = new Employee(employeeName, employeeSales);
        employees[i] = employee;
    }
}

public int getMaxSellerEmployeeSales() {
    Employee maxSeller = employees[0];
    for (int i = 0; i < employees.length; i++) {

        System.out.println("Employee Name: " + employees[i].getName());
        System.out.println("Total sales: $" + employees[i].getSales());
        System.out.println();

        if (maxSeller.getSales() < employees[i].getSales()) {
            maxSeller = employees[i];
        }
    }
    System.out.println();
    System.out.println("Top Seller is: " + maxSeller.getName());
    System.out.println("Top Sales are: $" + maxSeller.getSales());
    return maxSeller.getSales();
}

public static void main(String[] args) {
    EmployeeArray google = new EmployeeArray();
    google.setUpArray();

    EmployeeArray ms = new EmployeeArray();
    ms.setUpArray();

    EmployeeArrayCalculatorAndManipulator eGoogle = new EmployeeArrayCalculatorAndManipulator();
    EmployeeArrayCalculatorAndManipulator eMS = new EmployeeArrayCalculatorAndManipulator();
    eGoogle.doSomethingWithArray(google.getEmployees());
    eMS.doSomethingWithArray(ms.getEmployees());
}

}

A: It worked out for me:-
package EmployeePackage;
public class Employee {
private int sales;
private String name;

public Employee(String employeeName, int employeeSales){
    this.name = employeeName;
    this.sales = employeeSales;

}
public String getName(){
    return this.name;
}
public int getSales(){
    return this.sales;
}

}

package EmployeePackage;
import java.util.Scanner;
public class EmployeeArray {
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    int numEmp;

    System.out.println("Enter how may employees to be compared: ");
    numEmp = input.nextInt();
    input.nextLine();
    Employee[] employees = new Employee[numEmp];

    for (int i = 0; i < numEmp; i++) {
        System.out.print("Enter your name: ");
        String employeeName = input.nextLine();
        System.out.println();
        System.out.print("Enter your annual sales: ");
        int employeeSales = input.nextInt();
        input.nextLine();
        System.out.println();

 employees[i] = new Employee(employeeName , employeeSales); //calling constructor

    }
    Employee maxSeller = employees[0];
    for (int i = 0; i < employees.length; i++) {

        System.out.println("Employee Name: " + employees[i].getName());
        System.out.println("Total sales: $" + employees[i].getSales());
        System.out.println();

        if (maxSeller.getSales() < employees[i].getSales()) {
            maxSeller = employees[i];
        }
    }
    System.out.println();
    System.out.println("Top Seller is: " + maxSeller.getName());
    System.out.println("Top Sales are: $" + maxSeller.getSales());

}

}


text:
Q: What is the right way to initialize a constant in Ruby? I have a simple class that defines some constants, e.g.:
module Foo
  class Bar
    BAZ = "bof"
    ...

Everything is puppies and rainbows until I tell Rake to run all my Test::Unit tests. When it does, I get warnings:
bar.rb:3: warning: already initialized constant BAZ

My habit has been to avoid these warnings by making the constant initialization conditional, e.g.:
...
BAZ = "bof" unless const_defined? :BAZ
...

This seems to solve the problem, but it is a little tedious, and I don't ever see anyone else initializing constants this way. This makes me think I might be Doing It Wrong. Is there a better way to initialize constants that won't generate warnings?
Update: By way of a little more detail on how I'm using these constants, let's say I've defined a Token class that has constants for all the characters that are part of the syntax of some artificial language. I also have a Scanner class that reads a stream of characters, generating a Token instance for each one.
module Foo
  class Token
    LPAREN = "("
    RPAREN = ")"
    ...
  end

  class Scanner
    def next_token
      case read_char()
        when Token::LPAREN: # Generate a new LPAREN token
        ...

That is, when checking to see what kind of token should be generated for the given character, I want to use the constants defined in Token.
Update 2: Jörg's answer revealed that the problem was probably in how I was constructing paths in my require statements, not in how I was initializing or using the constants. I rewrote my require statements to eliminate any manual path creation, e.g.:
# File: $PROJECT_ROOT/lib/foo.rb; trying to load $PROJECT_ROOT/lib/foo/bar.rb
require File.expand_path(File.dirname(__FILE__)) + "foo/bar"

is now written to rely on $LOAD_PATH:
# File: $PROJECT_ROOT/lib/foo.rb; trying to load $PROJECT_ROOT/lib/foo/bar.rb
require 'lib/foo/bar'

I removed the conditional checks from my constant initialization statements, and rake now runs unit tests without throwing any warnings.

A: There's a good discussion on this in the comments on this post. I think the following one puts it nicely:

This irked me somewhat when I first
  walked up to Ruby. It was a remnant of
  my static type brainwashing. Three
  things mitigate against this being a
  real problem. 1. The warning. You
  could argue it should be an exception,
  but in reality, how would that be any
  different in the case where some other
  programmer silently caught the
  exception? Which brings me to number
  2) Don't work with morons. Only morons
  silently catch exceptions and continue
  and only morons change constant values
  used in that way. Which brings me to
  3) Neither of us is a moron, so you'll
  be happy to know that anecdotally this
  has never happened to me. It's really
  because constants stand out in Ruby
  anyway, what with their upcase, and
  how often are you likely to have a
  constant as an L-value in your code?

To directly answer your question, I wouldn't do anything to get rid of the warning. Just take the warning as just that, a warning, and move on.

A: The only way this can happen, is when bar.rb is required multiple times. Which shouldn't happen, since require doesn't load files that have already been loaded once.
It does, however, only use the path you pass to it to determine whether a file has already been loaded, at least in Ruby 1.8:
require 'bar'   # => true, file was loaded

require 'bar'   # => false, file had already been loaded

require './bar' # => true, OOPS, I DID IT AGAIN
# bar.rb:3: warning: already initialized constant BAZ

So, you are right: this could very well be an indication that there is something wrong with your dependency management.
Typical warning signs are

*

*manually constructing file paths instead of just relying on $LOAD_PATH
require "File.expand_path('../lib/bar', File.dirname(__FILE__))"

*manipulating $LOAD_PATH anywhere except maybe the main entry point to your library:
path = File.expand_path(File.dirname(__FILE__))
$LOAD_PATH << path unless $LOAD_PATH.include?(path)

In general, my philosophy is that it's not my job as a library writer to figure out how to put my library on the $LOAD_PATH. It's the system administrator's job. If the sysadmin uses RubyGems to install my library, then RubyGems will take care of it, otherwise whatever other package management system he uses should take care of it, and if he uses setup.rb, then it will be installed in site_ruby, which is already on the $LOAD_PATH anyway.


text:
Q: Способы позиционирования и их разумное применение Вопрос банальный, но надеюсь простите новичку;)
Теорию и значение свойств position (в вопросе интересует только мнение об absolute и relative) и отступов я конечно знаю, но дабы впоследствии не наступать на грабли и избежать возникновения недопониманий объясните, пожалуйста, в каких случаях какой способ позиционирования

*

*абсолютное

*относительное

*margin,padding
предпочтительнее использовать. Я конечно понимаю, что теоретически можно сайт и на only absolute'е сверстать но я хотел бы услышать примеры, где определенное свойство было бы более уместно (или даже незаменимо) относительно других.
Заранее спасибо за помощь начинающему верстальщику;)

A: Позиционирование отделяет элемент от общей картины и позволяет сдвигать его по всем векторам: x, y и z. Можно представить, что позиционированный элемент отрывается и подлетает над плоскостью (которой является страница), ну как летающий юнит в Warcraft 3, например, и затем его можно смещать в любую сторону, указывая координаты свойствами left и right, а также z-index.
При этом абсолютный элемент теряет свою позицию и его координаты отсчитываются от краёв контейнера (контейнером для такого элемента становится первый родительский элемент с НЕ статичным позиционированием или вся страница). Потеря позиции также значит, что его игнорируют все прочие элементы на странице. При left и right равным auto, абсолютный элемент встаёт туда, где он должен бы был быть, если бы он не потерял своей позиции.
Относительно позиционированный элемент своей позиции не теряет, с ним всё также считаются все остальные НЕ абсолютные элементы, а его смещение по координатам происходит относительно его текущей позиции. Важно знать, что смещение относительного элемента свойствами left и top не меняет его фактической позиции, а только визуально смещает в сторону, все прочие элементы будут думать, что он так и стоит, где стоял.
Маргин же просто двигает элемент в определённую сторону, тоесть меняет его фактическое местоположение.
Паддинг не из этой оперы, он добавляет пустого пространства внутрь элемента, но иногда и его можно использовать для позиционирования.
P.S. Только написав всё это вспомнил, что ТСу нужны были примеры использования, а не объяснения что к чему, но такой талмуд удалять жалко. Только не кидайте камнями, считайте я просто релаксируя написать что-то по теме захотел.

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

absolute
Может использоваться для попапов, плавающих декоративных элементов, контролов (например, выпадающего меню).
Такой способ позиционирования вынимает элемент из контекста, соответственно, его можно использовать, когда другие элементы никак не завязаны на абсолютно позиционируемый элемент.
Также top и left этого элемента
Также absolute удобно использовать для вертикального и/или горизонтального центрирования блока в блоке. При этом нужно учитывать, что внешний блок может уменьшиться и центрированный блок уже не влезет:

.wrapper {
  width: 100vw;
  height: 100vh;
  background: #ccc;
}

.inner {
  background: #000;
  width: 50px;
  height: 50px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

relative
Способ позиционируется относительно других элементов, вынимает его из контекста, но не двигает другие элементы. Его удобно использовать, когда нужно подвинуть какой-то элемент и не "зацепить" находящиеся рядом.
Также его удобно использовать для выносных элементов — степени, индексы в химических формулах, т. к. он ведёт себя более предсказуемо, чем vertical-align.

.jump {
  position: relative;
  top: -10px;
}

span {
  position: relative;
  top: 10px;
}

The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog

Важно помнить, relative задаёт, условно, нулевую точку для абсолютно позиционированных элементов, которые находятся внутри него.
Также relative удобно использовать в таких случаях (не смог вспомнить ни одного примера из реальной жизни, но точно помню что применял такой подход):

span {
  position: relative;
  z-index: 100;
}

.text {
  position: relative;
}

.over {
  width: 500px;
  height: 100px;
  top: 0;
  left: 10%;
  background: red;
  position: absolute;
}

  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean tellus dui, accumsan sed odio in, dictum ornare risus. Donec viverra ipsum vitae nisi ornare vehicula. Proin tempus et ipsum eu porta. Duis vitae luctus mi, sit amet aliquet mauris. Nulla facilisi. Sed suscipit nunc ac augue volutpat congue. Donec sollicitudin venenatis est sed feugiat. Vestibulum at risus metus.

margin
Margin не вынимает элемент из контекста и при изменении положения влияет на другие элементы.
Основное использование в качестве позиционирования — это margin с отрицательными значениями.
Это можно использовать, например, для того чтобы "подтянуть" блок на странице повыше к другому блоку, если у него задан слишком большой отступ снизу (это не совсем хорошо, но иногда другого выхода нет), при этом остальные элементы, находящиеся ниже, также подтянутся выше:

.relative-jump {
  position: relative;
  top: -10px;
}

.margin-jump {
  margin-top: -10px;
}

The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog

The quick brown fox jumps over the lazy dog

Отрицательный margin часто использовался для задания порядка колонок (без изменения html) в мультиколоночных дизайнах.
Также отрицательный margin можно использовать в качестве костыля с абсолютно позиционированными элементами чтобы задать им дополнительный отступ, не ломая уже созданный код.
Ещё одно применение — это горизонтальное центрирование блока внутри другого блока с использованием margin: 0 auto (эдакий text-align: center для блочных элементов):

.wrapper {
  background: #ccc;
  height: 200px;
}

.inner {
  margin: 0 auto;
  width: 100px;
  background: #000;
  color: #fff;
}

inner text

padding
Padding я бы не рассматривал как способ позиционирования: он применяется для отступов с разных сторон. Важно помнить что это внутренний отступ до border.
Единственный приём относительно позиционирования который бы я привёл — это отступы элемента + box-sizing:

.wrapper {
  padding: 20px;
  box-sizing: border-box;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pulvinar, arcu sit amet fringilla iaculis, augue ipsum vulputate augue, posuere mattis sem massa et urna. Mauris aliquam quam id mollis tempus. Donec eu tempus quam. Donec tincidunt imperdiet purus, quis aliquet massa convallis sit amet. Maecenas sollicitudin tempor justo nec cursus. Proin luctus sapien a lobortis suscipit. Nulla vitae tristique velit. Etiam luctus leo sit amet rutrum pellentesque.

Этот приём удобно использовать чтобы задать отступы элементам внутри блока, при этом не меняя их css, то есть внутри этого блока может оказаться что угодно и оно будет с едиными правильными отступами от краёв блока.

A: Как можете видеть, ниже 2 картинки и одна находится под другой
Это не сверстаешь без позиционирования одними margin'ами и padding'ами

.about-us {
  background-color: #000;
  min-width: 1200px;
  min-height: 600px;
}

.about-us .wrapper {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  width: 1200px;
  margin: 0 auto;
}

.about-us__images {
  position: relative;
}

.about-us__images img:first-child {
  position: absolute;
  top: 175px;
  z-index: 5;
  width: 302px;
}

.about-us__images img:last-child {
  margin-left: 65px;
  z-index: 2;
  width: 419px;
}

.about-us__text {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -ms-flex-direction: column;
  flex-direction: column;
  -webkit-box-align: start;
  -ms-flex-align: start;
  align-items: flex-start;
  -webkit-box-pack: end;
  -ms-flex-pack: end;
  justify-content: flex-end;
  margin-left: 152px;
}

.about-us__theme {
  color: #95a7ff;
  font-family: "Fightspirit";
  font-size: 20px;
  font-weight: 400;
  line-height: 30px;
}

.about-us__paragraph {
  margin-top: 35px;
  color: #ffffff;
  font-family: "Fightspirit";
  font-size: 50px;
  font-weight: 400;
  line-height: 30px;
}

.about-us__article {
  margin-top: 63px;
  color: #ffffff;
  font-family: Montserrat;
  font-size: 13px;
  font-weight: 400;
  line-height: 36px;
  letter-spacing: 0.35px;
}

      About us
      Lorem Ipsum
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur sollicitudin aliquam suscipit. Vestibulum ligula dolor, vehicula ac metus lobortis, lobortis maximus mauris


text:
Q: Punjabi Text not shown properly on Mobile i have used many punjabi fonts as like bulara_f.ttf , anmollipi , Akaash and many more but every time prolem with one word of punjabi  "sihari"
Sihari : Sihari is equivalent to i in pin or thin. Hence forth in this module we will denote sihari vowel with /i/.
in my application only this one word is not shown properly as like in following snapshot... please help...
EDIT
    i am using this method
Typeface myfont;
        myfont=Typeface.createFromAsset(getAssets(),"font.ttf");
    TextView textview = (TextView)findViewById(R.id.TextView01);
    //textview.setText("punjabi Text");
    textview.setTypeface(myfont);
}

A: Use bulara_5.ttf and run the code on device it will show correct punjabi words
mTvAbout = (TextView) findViewById(R.id.tv_about);
        font = Typeface.createFromAsset(this.getAssets(), "bulara_5.ttf");
        mTvAbout.setTypeface(font);
        mTvAbout.setText(" ਜਾਣਕਾਰੀ");


text:
Q: How does contextService work in flink internally? Currently, I am using flink with kafka consumer. I listen task event changes(task creation event, task updation event, task close event) from kafka consumer stream. I have a use case where I need to check no task updation happened within 135 minutes of task creation.
For this use case, I am using contextService.setTimer(....).
Now, I am confused about the limitation of number of timer can be set.
i.e. if 100000 new task get created, then, 100000 timer will be set with different - different timestamp.
is it feasible?
is it the best way to solve my use case?
So Basically I want to know.

*

*How does contextService work internally?

*How many timer can be set(number of timers)?

Code
   private static class MatchFunction extends KeyedProcessFunction<String, Tuple5<String, String, String, String, Long>, Object> {
        private ValueState<Tuple5<String, String, String, String, Long>> taskState;

        public MatchFunction() {}

        @Override
        public void open(Configuration config) {
            ValueStateDescriptor<Tuple5<String, String, String, String, Long>> stateDescriptor =
                    new ValueStateDescriptor<>("SLA Breach task event", TupleTypeInfo.getBasicTupleTypeInfo(String.class, String.class, String.class, String.class, Long.class));
            taskState = getRuntimeContext().getState(stateDescriptor);
        }

        @Override
        public void processElement(Tuple5<String, String, String, String, Long> event, Context context, Collector<Object> out) throws Exception {
            Tuple5<String, String, String, String, Long> previousEvent = taskState.value();
            String taskStatus = event.f1;
            String taskId = event.f0;
            long createdAt = event.f4;

            if(previousEvent != null && previousEvent.f1.equalsIgnoreCase(taskStatus)) {
                // might be duplicate event
                return;
            }

            if (previousEvent == null) {
                if (isNewEvent(event)) {
                    taskState.update(event);
                    long scheduleTime = Utils.getTimerTime(createdAt, Time.minutes(INT_135));
                    context.timerService().registerEventTimeTimer(scheduleTime);
                    logger.info("Adding event -> {} in taskState, Schedule time -> {}", event, new Date(scheduleTime));
                }
            } else {
                if (isUpdatedEvent(event)) {
                    // it's an UPDATE event, so event saved was the START event and has a timer
                    // the timer hasn't fired yet, and we can safely kill the timer

                    context.timerService().deleteEventTimeTimer(Utils.getTimerTime(createdAt, Time.minutes(INT_135)));

                    logger.info("Cancelled timer as Updation event was received for event - {} ", event);
                    // Update events have now been seen, we can clear the state
                    taskState.clear();
                }
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext context, Collector<Object> out) throws Exception {
            // no UPDATE event is received from past 135 minutes.

            Tuple5<String, String, String, String, Long> event = taskState.value();
            String taskId = event.f0;

            long createdAt = event.f4;
                // do something here after timer is received...

                }
            }
        }
    }

A: A few key facts about Flink's timers:

*

*Timers are always keyed.

*Timers are inexpensive: you can have millions or billions of them.

*Timers can either live on the heap or in RocksDB.

*Timers are checkpointed, and will be restored after a failure.

*Timers are deduplicated at the level of (key, timestamp). In other words, for a specific key and timestamp, there will be at most one timer. Sometimes you can reduce the number of timers being created by leveraging this deduplication to coalesce timers.


text:
Q: GCP instances disappear after account/billing upgrade I have four projects running in my GCP, each with a compute instance. When the free credits ran out, I was asked to upgrade my account and billing info. I took me few months to do that. But now that I did the upgrade, all instances have disappeared.
Is there a time frame required by GCP to upgrade, otherwise the instances are deleted?
Thanks,
Sherjeel

A:
Is there a time frame required by GCP to upgrade, otherwise the instances are deleted?

When you run out of free credits, in other words, your trial ends, the resources you created during the trial are stopped.
As stated here, when your trial ends, the following conditions apply:

*

*You must upgrade to a paid account to continue using Google Cloud.

*All resources you created during the trial are stopped.

*Any data you stored in Compute Engine is lost.

*Your account enters a 30-day grace period, during which you can recover resources and
data you stored in any Google Cloud services during the trial period.

You might receive a message stating that your account has been canceled, which only indicates that your account has been suspended to prevent charges.
Furthermore, as shown here:

Within that 30-day period, you can also contact Google Billing Support to export any data you stored in Google GCP services (other than on Compute Engine). After 30 days, your data and resources are not available, even if you upgrade.

If you would like to know more details, you can find it at this link.
I hope this helps.


text:
Q: compare datetime currentdate javascript I've txtStartDate control like that format : 09.03.2012
I want to compare txtStartDate value CurrentDate. if txtStartDate bigger than CurrentDate, i want to return true. how to to this?

A: Dates in javascript suck. I recommend using this library FWIW, http://www.datejs.com/
Specifically http://code.google.com/p/datejs/wiki/APIDocumentation#compare
and related
Also see
http://code.google.com/p/datejs/wiki/APIDocumentation#parse for actually converting the text to a date object.

A: Reverse your dates: 20120309, comparing is easy.
function chgDate(dte){
    var pm=new String(dte.getMonth()+1);if(pm.length<2) pm='0'+pm;
    var pd=new String(dte.getDate());if(pd.length<2) pd='0'+pd;
    var py=dte.getFullYear();
    return new Number(py+pm+pd);
}

function chgControl(dte){
    dte=dte.split('.');
    return new Number(dte[2]+dte[1]+dte[0]);
}

bool=(chgControl('09.03.2012')>chgDate(new Date()));

A: You'll want to create a Date object from the text you have. This will probably involve taking the string and splitting it up and passing it to the Date(year, month, day) constructor. I can't tell which way round your days and months are though so I can't give you example code.
Once you've created a Date object you can compare it to the current date, which you can get using new Date().