text:
Q: Struct member [ array vs pointer ] What is the benefit of declaring a C structure member as in array of size 1 instead of a pointer :
struct {
  a_struct_t a_member[1];
  ...
}b_struct;

Thanks in advance

A: In a typical case, a structure with a member that's declared as an array of one item will have that member as the last item in the struct. The intent is that the struct will be allocated dynamically. When it is allocated, the code will allocate space for as many items as you really want/need in that array:
struct X {
    time_t birthday;
    char name[1];
};

struct X *x = malloc(sizeof(*x) + 35);
x->birthday = mktime(&t);
strcpy(x->name, "no more than 35 characters");

This works particularly well for strings -- the character you've allocated in the struct gives you space for the NUL terminator, so when you do the allocation, the number of characters you allocate is exactly the strlen() of the string you're going to put there. For most other kinds of items, you normally want to subtract one from the allocation size (or just live with the allocated space being one item larger than is strictly necessary).
You can do (sort of) the same thing with a pointer, but it results in allocating the body of the struct separately from the item you refer to via the pointer. The good point is that (unlike the method above) more than one item can be allocated dynamically, where the method above only works for the last member of the struct.

A: What you describe are two different things entirely.  If you have a pointer as a member:
a_struct_t* a_member;

then it is simply a pointer.  There is no memory allocated inside of the struct to hold an a_struct_t.  If, on the other hand, you have an array of size 1:
a_struct_t a_member[1];

then your struct actually has an object of type a_struct_t inside of it.  From a memory standpoint, it isn't much different from just putting an object of that type inside the struct:
a_struct_t a_member;

From a usage standpoint, an array requires indirection to access the one element (i.e., you need to use *a_member instead of a_member).

A: "Array of size 1 instead of a pointer"? Sorry, but I don't see how this quiestion can possibly make sense. I would understand if you asked about "array of size 1 instead of an ordinary member (non-array)". But "instead of a pointer"? What does pointer have to do with this? How is it interchangeable with an array, to justify the question?
If what you really wanted to ask is why it is declared as an array of size 1 instead of non-array as in
struct {
  a_struct_t a_member;
} b_struct;

then one possible explanation is the well-known idiom called "struct hack". You might see a declaration like
struct {
  ...
  a_struct_t a_member[1];
} b_struct;

used to implement an array of flexible size as the last member of the struct object. The actual struct object is later created within a memory block that is large enough to accomodate as many array elements as necessary. But in this case the array has to be the last member of the struct, not the first one as in your example.
P.S. From time to time you might see "struct hack" implemented through an array of size 0, which is actually a constraint violation in C (i.e. a compile error).

A: These are different things.
Such member's name is an address of allocated memory, allocated inside the struct instance itself.

A: So I think it's been stated that the main difference between pointers and arrays is that you have to allocate memory for pointers.
The tricky part about your question is that even as you allocate space for your struct, if your struct contains a pointer you have to allocate a SECOND time for the pointer, but the pointer itself would be allocated as part of the struct's allocaiton.
If your struct contained an array of 1 you would not have to allocate any additional memory, it would be stored in the struct (which you still have to allocate).


text:
Q: How could I add Link with jQuery.eraser? I am trying the jQuery.eraser plugin .
After user scratched the first picture , they will see one girl .
I want that picture link to URL (example : www.google.com).
But it doesn't work . How could I add  into thr HTML . And get it work .
here is my JDfiddle
Thank sooooo much !

Patty

A: Since the eraser is rendering in Canvas, and the image is not clickable in the top, you won't be able to link the image. Even if you link it, it will not be above for the user to click on it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find the solution of the initial value problem $y' = 2x / (1 + 2y)$, $y(2) = 0$ in explicit form. This is what I've done so far:

The answer given is $y = \sqrt{x^2 - \frac{15}{4}} - \frac{1}{2}$ so that would mean I'll have to reject $y = -\sqrt{x^2 - \frac{15}{4}} - \frac{1}{2}$ but how do I go about doing that?
Can someone give me a hint or two on how to reject $y = -\sqrt{x^2 - \frac{15}{4}} - \frac{1}{2}$?

A: The negative root does not satisfy the initial condition.


text:
Q: react-google-charts with react-create-app not being properly installed through npm I am currently developing a react app taking advantage of the create-react-app command as I am not familiar at all with the node stack. Everything has gone well so far but I am stuck with the fact that I am unable to have react-google-charts added properly to my project.
No error appears when executing the command:
npm i -s react-google-charts

But nothing has happened. There is no node_module added and there is no edition of package.json file neither.
So whenever I place the quick samples given in:
https://github.com/RakanNimer/react-google-charts
(I mean any inclusion of any react-google-chart element)
I got the error:

Error in .... Module not found: 'react-google-charts' in /....

Could it be that this library is not compatible with create-react-app? Or it does not make any sense...
Thank you for any light or guide with this issue.
PS:
Node is v6.2.2, npm is 3.9.5, Create React App "react-scripts": "0.9.5"

A: Finally I installed yarn (npm install -g yarn) and executed the command: yarn add react-google-charts.
This way it worked as expected (I do not know the reason of the different behaviour).

A: According to npm install documentation there is no such flag as -s. There is, however, --save or its alias -S. Note that it is a capital letter.


text:
Q: I have some problems with xpath in python I'm trying to get distinct values with xpath query and lxml module.
So my code seems to work fine but i have two problems which i can't solve.
Xml
<?xml version='1.0' encoding='UTF-8'?>
<osm version="0.6" generator="osmconvert 0.8.5">
        <node id="429459476" lat="55.6091243" lon="37.7270414" version="2" timestamp="2012-02-20T18:13:50Z" changeset="10743203" uid="210173" user="osmmaker">
        <tag k="amenity" v="library"/>
        <tag k="name" v="Детская библиотека №101"/>
        <tag k="opening_hours" v="Mo-Fr 12:00-18:00; Sa 12:00-17:00"/>
        <tag k="phone" v="+7-495-3995297"/>
    </node>
    <node id="448176571" lat="55.6098905" lon="37.7317767" version="2" timestamp="2009-11-03T16:02:27Z" changeset="3025778" uid="75496" user="navigARTor">
        <tag k="highway" v="bus_stop"/>
        <tag k="name" v="Воронежская улица"/>
    </node>
    <node id="448176571" lat="55.6098905" lon="37.7317767" version="2" timestamp="2009-11-03T16:02:27Z" changeset="3025778" uid="75496" user="navigARTor">
        <tag k="highway" v="bus_stop"/>
        <tag k="name" v="Воронежская улица"/>
    </node>
</osm>

Python code
from lxml import etree
tree = etree.parse('out.xml')
tags = tree.xpath('./node[tag[not(@k = preceding::tag/@k)]]')
with open('10.xml','w') as f:
    for tag in tags:
          f.write(etree.tostring(tag,pretty_print=True).decode())

Xml after xpath query
<node id="429459476" lat="55.6091243" lon="37.7270414" version="2" timestamp="2012-02-20T18:13:50Z" changeset="10743203" uid="210173" user="osmmaker">
        <tag k="amenity" v="library"/>
        <tag k="name" v="Детская библиотека №101"/>
        <tag k="opening_hours" v="Mo-Fr 12:00-18:00; Sa 12:00-17:00"/>
        <tag k="phone" v="+7-495-3995297"/>
    </node>

<node id="448176571" lat="55.6098905" lon="37.7317767" version="2" timestamp="2009-11-03T16:02:27Z" changeset="3025778" uid="75496" user="navigARTor">
        <tag k="highway" v="bus_stop"/>
        <tag k="name" v="Воронежская улица"/>
    </node>

Problem #1
How to get full xml document like:
<?xml version='1.0' encoding='UTF-8'?>
<osm version="0.6" generator="osmconvert 0.8.5">
        <node id="429459476" lat="55.6091243" lon="37.7270414" version="2" timestamp="2012-02-20T18:13:50Z" changeset="10743203" uid="210173" user="osmmaker">
        <tag k="amenity" v="library"/>
        <tag k="name" v="Детская библиотека №101"/>
        <tag k="opening_hours" v="Mo-Fr 12:00-18:00; Sa 12:00-17:00"/>
        <tag k="phone" v="+7-495-3995297"/>
    </node>
<node id="448176571" lat="55.6098905" lon="37.7317767" version="2" timestamp="2009-11-03T16:02:27Z" changeset="3025778" uid="75496" user="navigARTor">
        <tag k="highway" v="bus_stop"/>
        <tag k="name" v="Воронежская улица"/>
    </node>
</osm>

Problem #2
And how to get rid from this abracadabra
v="Воронежская улиц&#1072

P.S. Sorry for my bad english i hope you'll understand

A: Consider XPath's sibling XSLT to manipulate your source XML. Whereas XPath is great for parsing select areas of a document, XSLT is a special-purpose language designed to transform documents. And specifically what you need is more the Muenchian Method where you index the document by an element/attribute value (using xsl:key) for grouping to return distinct values. Here we use node/@id.
Python's lxml module can process XSLT 1.0 scripts. Since such scripts are well-formed XML files, they can be parsed from file or as embedded string. One other reason to go this route is preserving unicode, the challenge of your original output, as the etree.tostring() method is rendering character entities for the special cyrillic characters.
XSLT Script (save as .xsl)
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
 <xsl:output version="1.0" encoding="UTF-8" indent="yes" />
 <xsl:strip-space elements="*"/>

 <xsl:key name="nodekey" match="node" use="@id" />

  <xsl:template match="/osm">
   <xsl:copy>
     <xsl:copy-of select="@*"/>
     <xsl:for-each select="node[count(. | key('nodekey', @id))]">
      <xsl:copy>
        <xsl:copy-of select="@*|*"/>
      </xsl:copy>
    </xsl:for-each>
   </xsl:copy>
  </xsl:template>

</xsl:transform>

Python Script
from lxml import etree

xml = etree.parse('Input.xml')
xsl = etree.parse('XSLTScript.xsl')

transform = etree.XSLT(xsl)
newdom = transform(xml)

with open('Output.xml', 'wb') as f:
    f.write(newdom)

XML Output
<?xml version="1.0" encoding="UTF-8"?>
<osm version="0.6" generator="osmconvert 0.8.5">
  <node id="429459476" lat="55.6091243" lon="37.7270414" version="2" timestamp="2012-02-20T18:13:50Z" changeset="10743203" uid="210173" user="osmmaker">
    <tag k="amenity" v="library"/>
    <tag k="name" v="Детская библиотека №101"/>
    <tag k="opening_hours" v="Mo-Fr 12:00-18:00; Sa 12:00-17:00"/>
    <tag k="phone" v="+7-495-3995297"/>
  </node>
  <node id="448176571" lat="55.6098905" lon="37.7317767" version="2" timestamp="2009-11-03T16:02:27Z" changeset="3025778" uid="75496" user="navigARTor">
    <tag k="highway" v="bus_stop"/>
    <tag k="name" v="Воронежская улица"/>
  </node>
</osm>


text:
Q: Windows RDP: which options to remotely kill a process which prevents rdp connection I have windows machine (running w7x64) executing since months a given job. I don't have any sort of physical access to it and I usually control things via RDP (remote desktop protocol).
Currently the machine is doing the usual job, although, probably by virtue of some memory leaking process, I cannot access to it via RDP.
Specifically, when trying to connect it remains stuck in the process of "configuring remote session" (Login information are typed already).
Which options do I have to see which processes are running and to kill them?
Can I do some sort of console connection?
or can I issue a force-reboot command?
any help appreciated

A: There are quite a few options that may vary depending the version of Windows you're using.  Since you didn't specify a version, I'll show a dos version and a Powershell version.  These both assume you have the requisite permissions to the computer.

*

*cmd.exe (works with just about any version of Windows):
Tasklist /s YourComputer
Note the PID of the process you want to kill
Taskkill /s YourComputer /fi "pid eq ####"  (replace #### with your PID)
Or to reboot, use this command:
shutdown /r /c "Comment about shutdown" /m \YourComputerName /t 0

*PowerShell (The computer you're rebooting must have Powershell installed):
Get-Process -computername YourComputer
Stop-Process -computername YourComputer -name ProcessName
Or to reboot, use this command:
Restart-computer -computername YourComputerName -force


text:
Q: How to Prevent Users From Taking Screenshots in React-Js Website How to Prevent Users From Taking Screenshots in React-Js Website
Can we block windows +print screen in reactjs

A: As far as I know, there's no way you're going to code something into your webpage that will prevent the user from using their OS to take a screenshot of their screen.  You will need to think of better security measures.


text:
Q: How do I display most recent week items by default with WeekArchiveView? I'm astonished by how little documentation on class-based generic views there is.
Anything slightly more complex than a trivial sample has to get done through guesswork, trial and error.
I want to use WeekArchiveView to display a week's item list.
There's my urls.py entry:
url(r'^items/(?P<year>\d{4})/week/(?P<week>\d{1,2})/$', ItemWeekArchiveView.as_view())

When no year or week is specified, I get an error page.
I want them to equal today's year and week by default.
What is the right place for tweak here? Should I introduce another mixing and override a method?

A: Urls like /items/ or /items/2011/ wouldn't match your regexp because \d{4} means exactly 4 digits.
You probably should specify two another url entries for both cases:
url(r'^items/$', AchievementListView.as_view(
    year=str(date.today().year), week=str(date.today().isocalendar()[1])
    )),
url(r'^items/(?P<year>\d{4})/week/(?P<week>\d{1,2})/$', ItemWeekArchiveView.as_view()),

(Using isocalendar to get the week number).


text:
Q: Request work at Postman but Fail with Ruby I had tried so many options here and I really don't understand what is going one.
I try this request at Postman, and all works fine:
https://api.airbnb.com/v1/authorize?client_id=d306zoyjsyarp7ifhu67rjxn52tv0t20&username=someemail@test.com&password=secret
But if I try the same with ruby I get:

<title>503 Service Temporarily Unavailable</title>

503 Service Temporarily Unavailable

nginx

My Ruby request is:
require 'openssl'
require 'uri'
require 'net/http'

url = URI("https://api.airbnb.com/v1/authorize?client_id=d306zoyjsyarp7ifhu67rjxn52tv0t20&username=someemail@test.com&password=secret")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

request = Net::HTTP::Post.new(url)
request["cache-control"] = 'no-cache'
request["postman-token"] = 'f7cd129c-f7f5-b79a-e829-0ad7f7ebf81f'
request['content-type'] = 'application/x-www-form-urlencoded'

response = http.request(request)
puts response.read_body


text:
Q: ANTLR v4 dynamic grammar I have this grammar:
grammar ProcedureHeaderLanguage ;

@header
{
  package com.company.generated.antlr.atr;
}

fragment DIGIT
  : '0'..'9'
  ;

fragment A
  : [aA]
  ;

fragment B
  : [bB]
  ;

fragment C
  : [cC]
  ;

fragment D
  : [dD]
  ;

fragment E
  : [eE]
  ;

fragment F
  : [fF]
  ;

fragment G
  : [gG]
  ;

fragment H
  : [hH]
  ;

fragment I
  : [iI]
  ;

fragment J
  : [jJ]
  ;

fragment K
  : [kK]
  ;

fragment L
  : [lL]
  ;

fragment M
  : [mM]
  ;

fragment N
  : [nN]
  ;

fragment O
  : [oO]
  ;

fragment P
  : [pP]
  ;

fragment Q
  : [qQ]
  ;

fragment R
  : [rR]
  ;

fragment S
  : [sS]
  ;

fragment T
  : [tT]
  ;

fragment U
  : [uU]
  ;

fragment V
  : [vV]
  ;

fragment W
  : [wW]
  ;

fragment X
  : [xX]
  ;

fragment Y
  : [yY]
  ;

fragment Z
  : [zZ]
  ;

fragment DIGIT_PAIR
  : DIGIT DIGIT
  ;

fragment ALPHA
  : 'a'..'z'
  | 'A'..'Z'
  ;

SEMICOLON
  : ';'
  ;

HYPHEN
  : '-'
  ;

PROCEDURE_IDENTIFIER
  : P R O C E D U R E
  ;

COMMA
  : ','
  ;

LEFT_PARENTHESIS
  : '('
  ;

RIGHT_PARENTHESIS
  : ')'
  ;

dataField
  : IDENTIFIER
  ;

nameField
  : dataField
  ;

parameterNameField
  : dataField
  ;

dataTypeField
  : dataField
  ;

IN
  : I N
  ;

WS
  : (' ' | '\t' | '\r' | '\n')+ -> skip
  ;

IDENTIFIER
  : (ALPHA | '_') (ALPHA | DIGIT | '_')*
  ;

COMMENT
  : HYPHEN HYPHEN
  ;

parameterPair
  : parameterNameField IN dataTypeField
  ;

procedureName
  : PROCEDURE_IDENTIFIER nameField
  ;

procedureParameter
  : LEFT_PARENTHESIS parameterPair (COMMA parameterPair)* RIGHT_PARENTHESIS
  ;

procedure
  : procedureName procedureParameter SEMICOLON
  ;

procedures
  : procedure (procedure)*
  ;

which is able to parse the following example:
sorten_COBB_SEK in number,
sorten_COBB_VORG in number,

However the parsing files will not only contain such data.
It will also store some informations which are optional and not mandatory.
I know I could simply tell them to be optional with ? but it's not that simple.
I additionally have this example:
sorten_FEUCHTE_MIN in number,
sorten_FEUCHTE_MAX in number,
sorten_FEUCHTE_SPERR in number,
sorten_LEIMUNG in varchar2, -- J or N
sorten_BEMERKUNG in varchar2

where -- J or N is in association with the entry sorten_LEIMUNG and I want to get that information for that entry. The problem is that the delimitier COMMA is before the comment which I want to parse.
so some grammar like this will not work:
parameterPair
  : parameterNameField IN dataTypeField COMMA? COMMENT? dataField?
  ;

procedureParameter
  : LEFT_PARENTHESIS parameterPair (parameterPair)* RIGHT_PARENTHESIS
  ;

How can I achieve the goal to also register the comment for the same entry (same line)?
EDIT: as said the above grammar will parse the first example correctly. However the second one will be broken. It will detect or as new parameterName.
With the second grammar change I am able to parse -- J while the rest will be detected as a new parameterName.
How can I tell antlr to parse how I wish, or is this a limitation where I am better of telling the user to not use spaces in his comments?

A: Without your whole grammar I cannot do real testing, but I'll try to make a suggestion for you.  Since your comment identifier -- must be consecutive, I'd code that rule as:
TEXT: ALPHA | DIGIT;
TEXTS : TEXT*;

COMMENT
  : '--' TEXTS
  ;

Something like that to ensure that your -- comment + mixed text gets lexed as a comment.

A: Your COMMENT rule is incomplete. It contains only the comment introducer, but nothing that should match the rest of the line. A typical approach is:
SINGLE_LINE_COMMENT: '--' ~([\r\n] | EOF)*;

A: Since I just started using ANTLR I don't know if this is the best solution but with the grammar rule:
SINGLE_LINE_COMMENT
  : '--' (.)*? '\r'? '\n'
  ;

parameterPair
  : parameterNameField IN dataTypeField COMMA? SINGLE_LINE_COMMENT?
  ;

I am then able to do this in a custom visitor:
/**
     * Filters out the needed informations of the antlr parser context and
     * creates the POJO {@link SqlParameter} with it.
     *
     * @param parameterPair the parameter pair
     * @return the sql parameter
     */
    private SqlParameter createParameter( ParameterPairContext parameterPair )
    {
      final String parameterName = parameterPair.parameterNameField().getText();
      final String dataType = parameterPair.dataTypeField().getText();
      Optional<String> comment = Optional.empty();
      if ( parameterPair.SINGLE_LINE_COMMENT() != null )
      {
        comment = Optional.ofNullable( parameterPair.SINGLE_LINE_COMMENT().getText().trim() );
      }

      return new SqlParameter( parameterName, dataType, comment );
    }

Which is not really practical in all cases but should do the trick for now. logging it out will result in what I needed:
StringBuilder log = new StringBuilder();
log.append( "Parameter: " );
log.append( parameter.getParameterName() );
log.append( " with type: " );
log.append( parameter.getParameterType() );
parameter.getComment().ifPresent( comment -> log.append( " with comment: " ).append( comment ) );
>>>>>>>>>>>>>>>>>>>>>>>>>>>
Parameter: sorten_FEUCHTE_SPERR with type: number
Parameter: sorten_LEIMUNG with type: varchar2 with comment: -- J or N
Parameter: sorten_BEMERKUNG with type: varchar2


text:
Q: do I need Windows 10 for Xamarin On the Xamarin website, it says:

"The minimum operating system version is Windows 7. Xamarin.Forms Windows support requires Windows 8.1, and Xamarin.Forms UWP support requires Windows 10."

Does this mean if I want to use the UI controls and XAML in the Xamarin.Forms API for Android and iOS apps, I will need to have Windows 10? Or Windows 10 is needed only if I want to deploy my app on to Windows phone?
Update: Sorry I didn't make it clear on my question. So basically, I want to write an app that:

*

*Can share the same source code for both Android and iOS.

*Can debug on my Android phone, similar to the way I can do with Android on Eclipse (i.e. no need for Emulation, just load the app directly onto the phone and then debug through the Eclipse IDE).

*Can take advantage of all the Xamarin.Forms control and XAML syntax.

Would I need Windows 10 for all 3 above? If not, which # does and which does not need Windows 10?
Thanks.

A: Windows 10 is needed only if you would like to create Universal Windows Platform (UWP) projects.

A: If you want to make cross-platform Android and iOS Apps with Xamarin, than No, you don't need to have Windows 10. Windows 10 is required in case that you are developing UWP App with Xamarin.Forms so that you can test it on your PC.


text:
Q: Can I create a git hook that runs a script based on the tags for the commits being pushed? I am trying to create a git hook such that when a user pushes it will take information about the tags attached to the commits and create an archive with the same name as the tag. I really only need to know if it is possible to use a pre-push hook for this and how to determine the information I need for the script specifically how to reference individual commits and their tags. Thanks!

A: For those curious, I had finally learned that the references to commits and tags are passed through the stdin rather than the program arguments as I had previously thought, so when you read from stdin you get something like:
refs/heads/main SHA-1 refs/heads/main SHA-1 refs/tags/v4.0 SHA-1 refs/tags/v4.0 0000000000000000000000000000000000000000


text:
Q: Customization for Visual Studio 2008 that opens MSDN Help in a browser when hitting F1 The MSDN help isn't very helpful in that its startup time is long and that it quite often doesn't get you to the correct help file. I always end up opening MSDN in a browser instead. Is there some customization for Visual Studio 2008 that opens MSDN Help in a browser when hitting F1?

A: Two suggestions:
1: Remove the default key-binding for F1, via Tools > Options > Environment > Keyboard > Help.F1Help
Then write a little macro (different ways to do this of course), to start your browser with a default URL e.g.
Sub OpenChromeWithURL()
Dim url As String = "http://msdn.microsoft.com"

'launch browser
System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\Google\Chrome\Application\chrome.exe", url)
End Sub

To this macro you can now assign a keyboard shortcut as described before. Go to Tools > Options > Evnironment >Keyboard. Look for Macro.OpenChromeWithURL and assign a shortcut key to your Macro. An explanation on how to assign a shortcut key you can find here: How to map a Visual Studio macro to a keyboard shortcut?

2: Download the MSDN Library for Visual Studio 2008 SP1


text:
Q: How to find a field of an object using a Generic method? I have a Cube object with a public 'x' field. I have a toString method in my Cube class which prints out the x,y,z fields, but when I directly access it, I get an error where: field cannot be resolved or is not a field.
public <T> void setPosition(T object){
   System.out.println(object);
   System.out.println(object.x); // error here
}

A: I would recommend defining an interface that declares the method that your multiple different types will expose. Something like:
public interface ValueProducer {
  public String getValue();
}

Then, your Cube type would look like this:
public <T extends ValueProducer> void setPosition (T obj) {
   System.out.println(obj);
   System.out.println(obj.getValue());
}

Then any type with which you wish to use this method need only implement the interface ValueProducer, and can still extend or implement whatever other types are appropriate for their use cases.
Or, you could omit generics altogether, and just pass obj in as a ValueProducer.

A: your method does not know what is the type T.
But we can say T is some class which extends
public class GenericCube {
    public String value;
    }

So, now we able to access the value because we know about it
public <T extends GenericCube> void setPosition(T obj){
    System.out.println(obj);
    System.out.println(obj.value);
}

A: I found that I could access the field utilizing Reflection methods and cast to the object I needed. This is supported using an abstract class with this field so that all objects  inheriting from this object can utilize this function.
public <T> void setPosition(T object) {
   Field xField = object.getClass().getField("x");
   Field boxField = object.getClass().getField("boundBox");
   float xpos = (float)xField.get(object);
   BoundingBox box = (BoundingBox)boxField.get(object);
}

I'm open to critique, but this has been working very well with my multiple classes inheriting from my abstract base class. The reason for this method, is for another class to work with these other classes without creating multiple functions, thus giving flexibility for a user who wants to create their own classes inheriting from the abstract class.


text:
Q: when to carefully use free() to free up malloc() used memory? I read from many question here in SO and some other articles regarding free() function in c that frees the memory of unused variables. In my case,  I have the following code block.
char *injectStrAt(char *str, char *strToIn, int pos)
{
    char *strC = malloc(strlen(str) + strlen(strToIn) + 1);
    strncpy(strC, str, pos);
    strC[pos] = '\0';
    strcat(strC, strToIn);
    strcat(strC, str + pos);
    return strC;
}

The above function I use to inject a string block in to an array. I am using malloc to create a new char*. In the above case do I need to do free(strC) ? advice pls.

A: strC is the return value of this function, so you don't call free(strC) inside the function itself. You need to free it outside the function, the time when this string is not used anymore.

A: Since your function is returning strC, one presumes it must remain valid after the return of this function, thus this function must not free() that buffer. Once it's freed, the buffer is no longer valid so must not be used.
Your caller is responsible for freeing it in this case.

A: No you shouldn't free strC inside this function because it is the return value of this function. If you do so the statement:
return strC;

will return some unexpected or garbage value.
char* stringA = injectStrAt(str, strToIn, pos);
printf("StringA: %s"); // unexpected value.

So when should you free up the memory? Well, you should do it after the value of strC is returned from the function injectStrAt() to stringA, in this particular case. Although generally memory is freed when the string or the variable to which the memory was allocated is no longer required.
char* stringA = injectStrAt(str, strToIn, pos);
/... use the string

free(stringA);


text:
Q: Bootstrap dropdown menu same functionality as Highcharts navigation button I would like to link the functionality (print, export to excel etc) of the navigation button of highcharts to a bootstrap dropdown menu. This drop-down panel is in the panel-heading separate from the graph in the panel. I have made this example. The intention is that if you click on the bootstrap dropdown icon and for example on "Download CSV" you will receive pop-up to download, which now applies to the navigation button of highcharts.
HTML
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">

Panel title

              <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
     </button>

Print chart

Download PNG image

Download JPEG image

Download PDF document

Download SVG vector image

Download CSV

Download XLS

View data table

Open in Highcharts Cloud

JavaScript
Highcharts.chart('container', {

title: {
  text: 'Solar Employment Growth by Sector, 2010-2016'
},

subtitle: {
  text: 'Source: thesolarfoundation.com'
},

yAxis: {
  title: {
    text: 'Number of Employees'
  }
},
legend: {
  layout: 'vertical',
  align: 'right',
  verticalAlign: 'middle'
},

plotOptions: {
  series: {
    label: {
      connectorAllowed: false
    },
    pointStart: 2010
  }
},

series: [{
  name: 'Installation',
  data: [43934, 52503, 57177, 69658, 97031, 119931, 137133, 154175]
}, {
  name: 'Manufacturing',
  data: [24916, 24064, 29742, 29851, 32490, 30282, 38121, 40434]
}, {
  name: 'Sales & Distribution',
  data: [11744, 17722, 16005, 19771, 20185, 24377, 32147, 39387]
}, {
  name: 'Project Development',
  data: [null, null, 7988, 12169, 15112, 22452, 34400, 34227]
}, {
  name: 'Other',
  data: [12908, 5948, 8105, 11248, 8989, 11816, 18274, 18111]
}],

responsive: {
  rules: [{
    condition: {
      maxWidth: 500
    },
    chartOptions: {
      legend: {
        layout: 'horizontal',
        align: 'center',
        verticalAlign: 'bottom'
      }
    }
  }]
}

});

Hopefully someone can help me to solve this problem. Thank you in advance!!


text: Q: Consume Test Suite Configuration by Test script - Azure DevOps In Azure-DevOps (Test-Hub) Test Plans tagged to Stages and Test Suites/Cases tagged to Configurations. Is that possible to consume/read/import Test Suite Configuration/Variables/Attributes by test script during runtime ?! Similar to Stage Variables, which can be consumed by ConfigurationBuilder() - C#. Anything like that to read Test Suite configuration ?!


text:
Q: How can I dynamically change the type of tweets that are being streamed and figure out which message to send to who? App Description
So I'm trying to create an application that does real-time sentiment analysis on tweets(as close to real time as I'm able to get it) and these tweets have to be based on user input. So in the main page of my application, I have a simple search bar where the user can enter a topic they would like to perform sentiment analysis on and when they press enter, it would take them to another page where they see a line chart displaying all the data in real time.
Problem 1
The first problem I'm facing at the moment is that I don't know how I can get tweepy to change what it is tracking when two or more people make a request. If I were to have global streaming that I simply disconnect and reconnect every time the user makes a new query, then it is also going to disconnect for other users as well which I don't want. On the other hand, if I were to allocate a streaming object for each user that connects, then this strategy should work. This still poses a problem. Twitter does not allow you to hold more than one connection at a time it seems given this StackOverflow post.
Does Tweepy support running multiple Streams to collect data?
If I still were to go along with this, I risk getting my IP banned. So both of these solutions are no good.
Problem 2
The last problem I'm having is figuring out who the message belongs to. At the moment, I'm using RabbitMQ to store all incoming messages in one single queue called twitter_topic_feed. For every tweet that I receive from tweepy, I publish it in that queue. Then RabbiMQ consumes the message and sends it to every available connection. Obviously, that behaviour is not what I'm looking for. Consider two users who search for pizza and sports. Both users will receive tweets pertaining to football and pizza when one user asked for sports tweets and the other asked for pizza tweets.
One idea is to create a queue with a unique identifier for each available connection. The identifier would have the form {Search Term}_{Hash ID}.
For generating the hash ID, I can use the UUID package that is available in python and create the ID when the connection opens and delete it when it closes. Of course, when they close the connection I also need to delete the queue. I'm not sure how well this solution would scale. If we were to have 10,000 connections, we would have 10,000 queues and each queue could potentially have a lot of messages stored in it. Seems like it would be very memory intensive.
Design

*

*tornado Framework for WebSockets,

*tweepy API for streaming tweets

*RabbitMQ For publishing messages to the queue whenever tweepy receives a new tweet. RabbitMQ will then consume that message and send it to the WebSocket.

Attempt(What I currently have so far)
TweetStreamListener uses the tweepy API to listen for tweets based on the user's input. Whatever tweet it gets, it calculates the polarity of that tweet and publishes it to rabbitMQ twitter_topic_feed queue.
import logging
from tweepy import StreamListener, OAuthHandler, Stream, API
from sentiment_analyzer import calculate_polarity_score
from constants import SETTINGS

auth = OAuthHandler(
    SETTINGS["TWITTER_CONSUMER_API_KEY"], SETTINGS["TWITTER_CONSUMER_API_SECRET_KEY"])

auth.set_access_token(
    SETTINGS["TWITTER_ACCESS_KEY"], SETTINGS["TWITTER_ACCESS_SECRET_KEY"])

api = API(auth, wait_on_rate_limit=True)

class TweetStreamListener(StreamListener):

    def __init__(self):
        self.api = api
        self.stream = Stream(auth=self.api.auth, listener=self)

    def start_listening(self):
        pass

    def on_status(self, status):
        if not hasattr(status, 'retweeted_status'):
            polarity = calculate_polarity_score(status.text)

            message = {
                'polarity': polarity,
                'timestamp': status.created_at
            }

            # TODO(Luis) Need to figure who to send this message to.
            logging.debug("Message received from Twitter: {0}".format(message))

    # limit handling
    def on_limit(self, status):
        logging.info(
            'Limit threshold exceeded. Status code: {0}'.format(status))

    def on_timeout(self, status):
        logging.error('Stream disconnected. continuing...')
        return True  # Don't kill the stream

    """
    Summary: Callback that executes for any error that may occur. Whenever we get a 420 Error code, we simply
    stop streaming tweets as we have reached our rate limit. This is due to making too many requests.

    Returns: False if we are sending too many tweets, otherwise return true to keep the stream going.
    """

    def on_error(self, status_code):
        if status_code == 420:
            logging.error(
                'Encountered error code 420. Disconnecting the stream')
            # returning False in on_data disconnects the stream
            return False
        else:
            logging.error('Encountered error with status code: {}'.format(
                status_code))
            return True  # Don't kill the stream

WS_Handler is in charge of maintaining a list of open connections and sending any message that it receives back to every client(This behaviour is something I don't want).
import logging
import json
from uuid import uuid4
from tornado.web import RequestHandler
from tornado.websocket import WebSocketHandler

class WSHandler(WebSocketHandler):

    def check_origin(self, origin):
        return True

    @property
    def sess_id(self):
        return self._sess_id

    def open(self):
        self._sess_id = uuid4().hex
        logging.debug('Connection established.')
        self.application.pc.register_websocket(self._sess_id, self)

    # When messages arrives via RabbitMQ, write it to websocket
    def on_message(self, message):
        logging.debug('Message received: {0}'.format(message))
        self.application.pc.redirect_incoming_message(
            self._sess_id, json.dumps(message))

    def on_close(self):
        logging.debug('Connection closed.')
        self.application.pc.unregister_websocket(self._sess_id)

The PikaClient module contains the PikaClient that will allows to keep track of inbound and outbound channels as well as keeping track of the websockets that currently running.
import logging
import pika
from constants import SETTINGS
from pika import PlainCredentials, ConnectionParameters
from pika.adapters.tornado_connection import TornadoConnection

pika.log = logging.getLogger(__name__)

class PikaClient(object):
    INPUT_QUEUE_NAME = 'in_queue'

    def __init__(self):
        self.connected = False
        self.connecting = False
        self.connection = None
        self.in_channel = None
        self.out_channels = {}
        self.websockets = {}

    def connect(self):
        if self.connecting:
            return

        self.connecting = True

        # Setup rabbitMQ connection
        credentials = PlainCredentials(
            SETTINGS['RABBITMQ_USERNAME'], SETTINGS['RABBITMQ_PASSWORD'])

        param = ConnectionParameters(
            host=SETTINGS['RABBITMQ_HOST'], port=SETTINGS['RABBITMQ_PORT'], virtual_host='/', credentials=credentials)

        return TornadoConnection(param, on_open_callback=self.on_connected)

    def run(self):
        self.connection = self.connect()
        self.connection.ioloop.start()

    def stop(self):
        self.connected = False
        self.connecting = False
        self.connection.ioloop.stop()

    def on_connected(self, unused_Connection):
        self.connected = True
        self.in_channel = self.connection.channel(self.on_conn_open)

    def on_conn_open(self, channel):
        self.in_channel.exchange_declare(
            exchange='tornado_input', exchange_type='topic')
        channel.queue_declare(
            callback=self.on_input_queue_declare, queue=self.INPUT_QUEUE_NAME)

    def on_input_queue_declare(self, queue):
        self.in_channel.queue_bind(
            callback=None, exchange='tornado_input', queue=self.INPUT_QUEUE_NAME, routing_key="#")

    def register_websocket(self, sess_id, ws):
        self.websockets[sess_id] = ws
        self.create_out_channel(sess_id)

    def unregister_websocket(self, sess_id):
        self.websockets.pop(sess_id)

        if sess_id in self.out_channels:
            self.out_channels[sess_id].close()

    def create_out_channel(self, sess_id):
        def on_output_channel_creation(channel):
            def on_output_queue_declaration(queue):
                channel.basic_consume(self.on_message, queue=sess_id)

            self.out_channels[sess_id] = channel
            channel.queue_declare(callback=on_output_queue_declaration,
                                  queue=sess_id, auto_delete=True, exclusive=True)

        self.connection.channel(on_output_channel_creation)

    def redirect_incoming_message(self, sess_id, message):
        self.in_channel.basic_publish(
            exchange='tornado_input', routing_key=sess_id, body=message)

    def on_message(self, channel, method, header, body):
        sess_id = method.routing_key

        if sess_id in self.websockets:
            self.websockets[sess_id].write_message(body)
            channel.basic_ack(delivery_tag=method.delivery_tag)
        else:
            channel.basic_reject(delivery_tag=method.delivery_tag)

Server.py is the main entry point of the application.
import logging
import os
from tornado import web, ioloop
from tornado.options import define, options, parse_command_line
from client import PikaClient
from handlers import WSHandler, MainHandler

define("port", default=3000, help="run on the given port.", type=int)
define("debug", default=True, help="run in debug mode.", type=bool)

def main():
    parse_command_line()

    settings = {
        "debug": options.debug,
        "static_path": os.path.join(os.path.dirname(__file__), "web/static")
    }

    app = web.Application(
        [
            (r"/", MainHandler),
            (r"/stream", WSHandler),
        ],
        **settings
    )

    # Setup PikaClient
    app.pc = PikaClient()

    app.listen(options.port)
    logging.info("Server running on http://localhost:3000")

    try:
        app.pc.run()
    except KeyboardInterrupt:
        app.pc.stop()

if __name__ == "__main__":
    main()


text:
Q: sharepoint anonymous asking to login when i clicked page in the site I enabled anonymous access to all the web pages in my sharepoint site. But in 1 page i added a tag cloud. When i am opening the page(with anonymous access), the page is asking for login. If i click cancel, then there is no error page is coming. And if the user is signed in to the site, he is able to see the flash tag cloud. how to enable the flash tag cloud to anonymous access?

A: I would guess that something on that page refers to a resource (such as a javascript, image file, or css) that requires authentication, and when you click cancel, the rest of the page loads, but that resource fails to load.
Try using firebug in firefox to monitor the files that are requested for that page and look to see which files get a 401 Unauthorized error.  You could then either make changes to ensure that those files are available to anonmyous users or change the page so that it no longer needs those files.


text:
Q: AttributeError: 'CountVectorizer' object has no attribute 'fit_transfrom' 1 from sklearn.feature_your textextraction.text import CountVectorizer
2 cv = CountVectorizer()
----> 3 X = cv.fit_transfrom(df['transformed_text']).toarray()
no error in this line


text:
Q: Fire Notification at 10 AM of morning and at every 24 hours I am using AlarmManager() to fire notification. But don't know how to set to fire at 10 AM of and at every 24 hours. Any one please help me.
My code is as below:
        Calendar Calendar_Object = Calendar.getInstance();
        Calendar_Object.set(Calendar.HOUR_OF_DAY, 10);
        Calendar_Object.set(Calendar.MINUTE, 00);
        Calendar_Object.set(Calendar.SECOND, 0);
        Intent myIntent = new Intent(Splash.this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(Splash.this, 0, myIntent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC,Calendar_Object.getTimeInMillis(),(24 * 60 * 60 * 1000),pendingIntent);

A: For every 24 hours try this code:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
long now = System.currentTimeMillis();
long diffMillis = now - pref.getLong("CurrentTimeMillis", 0);
if( diffMillis >= (3600000  * 24) ) {

 // Your code here:)
SharedPreferences.Editor editor = pref.edit();
editor.putLong("CurrentTimeMillis", System.currentTimeMillis());
editor.commit();

} else {
 // too early
}

A:  Calendar Calendar_Object = Calendar.getInstance();
        Calendar_Object.set(Calendar.HOUR_OF_DAY, 10);
        Calendar_Object.set(Calendar.MINUTE, 00);
        Calendar_Object.set(Calendar.SECOND, 0);
        Intent myIntent = new Intent(Splash.this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(Splash.this, 0, myIntent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC,Calendar_Object.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);


text:
Q: iPhone 13 pro search refreshing on input I just upgraded to the new iPhone 13 pro and after setting it up I noticed that the search keeps refreshing when I enter a specific characters… :)
Any ideas what can be wrong?
Video
iOS 15.1 (19B5052f)


text:
Q: Why does streaming Dataset fail with "Complete output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets... "? I use Spark 2.2.0 and have the following error with Spark Structured Streaming on windows:

Complete output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets without watermark.

A:
Complete output mode not supported when there are streaming aggregations on streaming DataFrames/DataSets without watermark

Streaming aggregations require that you tell the Spark Structured Streaming engine when to output the aggregation (per so-called output mode) since the data that could be part of an aggregation might be late and available only after some time.
The "some time" part is event lateness and described as the time that is watermark ago from the current time.
That's why you have to specify the watermark to let Spark drop/disregard any late events and stop accumulating state that could eventually lead to OutOfMemoryError or similar.
With that said, you should use withWatermark operator on your streaming Dataset.

withWatermark Defines an event time watermark for this Dataset. A watermark tracks a point in time before which we assume no more late data is going to arrive.

And quoting along...

Spark will use this watermark for several purposes:

*

*To know when a given time window aggregation can be finalized and thus can be emitted when using output modes that do not allow updates.

*To minimize the amount of state that we need to keep for on-going aggregations, mapGroupsWithState and dropDuplicates operators.

The current watermark is computed by looking at the MAX(eventTime) seen across all of the partitions in the query minus a user specified delayThreshold. Due to the cost of coordinating this value across partitions, the actual watermark used is only guaranteed to be at least delayThreshold behind the actual event time. In some cases we may still process records that arrive more than delayThreshold late.

Check out Spark Structured Streaming's Handling Late Data and Watermarking.


text:
Q: Screenshot/Snapshot-Button in Form in NavigationView [iOs 15 iSwiftUI Xcode 13.4.1] I have got an app with a Form in a NavigationView. In .navigationBarItems I got a Button to take a Screenshot from the whole display. The button runs a function i got from "hacking with swift" (I think this codesnippet is well known link)
The Problem: when I call the function snapshot() on self oder body nothing is happen except the qestion from ios to allow access to the imagefolder. Only when I create an extra view like the guy from "hacking with swift" it works. but then only this extra view. that is not the way I wanna go.
Question: on which object I have to call the snapshot()-function to render the whole display as it is (Navigationview with the Form NOT the textView like in the example)
I tried: self.snapshot(), body.snapshot(). How can i call the navigationbar or the form?
Thanks! :)
import SwiftUI

//FUNCTION TO TAKE A SCREENSHOT
extension View {

func snapshot() -> UIImage {
    let controller = UIHostingController(rootView: self)
    let view = controller.view

    let targetSize = controller.view.intrinsicContentSize
    view?.bounds = CGRect(origin: .zero, size: targetSize)
    view?.backgroundColor = .clear

    let renderer = UIGraphicsImageRenderer(bounds: view!.bounds)

    return renderer.image { _ in
        view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
    }
}

}

//EXAMPLE VIEW, THIS VIEW GETS SAVED IN THE EXAMPLE FROM HWS
var textView: some View {
Text("Hello, SwiftUI")
    .padding()
    .background(.blue)
    .foregroundColor(.white)
    .clipShape(Capsule())
}

//THE VIEW I WANT TO BE SAVE IN PHOTOS
var body: some View {
NavigationView {
    Form {
        Section{
            HStack{
                Text("Test")

                Text("test2")
            }

            Section{
                VStack {
                    Text("test3")

                    Text("test4")
                }
            }

        }
    }

}

.navigationBarTitle(Text("Test"))

//NAVIGATIONBAR WITH THE BUTTON FOR TAKING SCREENSHOT
.navigationBarItems(trailing:
                        Button(action: {
    let image = textView.snapshot() // WHICH OBJECT HAS TO CALL THE SNAPSHOTFUNCTION?

    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
},
                               label: {Image(systemName: "camera.fill")
    .foregroundColor(.red)}))

}


text:
Q: How to use OrderedMapIterator.previous() Using Apache Commons Collections I found the OrderedMapIterator interface to navigate back and forth in OrderedMap. Iterating to the next entry works as expected. Going to the previous element doesn't return the previous element but the current element instead.
OrderedMap<String, String> linkedMap = new LinkedMap<>();
linkedMap.put("key 1", "value 1");
linkedMap.put("key 2", "value 2");
linkedMap.put("key 3", "value 3");

OrderedMapIterator<String, String> iterator = linkedMap.mapIterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    System.out.println(key);

    if (key.endsWith("2") && iterator.hasPrevious()) {
        System.out.println("previous: " + iterator.previous());
        iterator.next(); // back to current element
    }
}

I expected the output
key 1
key 2
previous: key 1
key 3

but got
key 1
key 2
previous: key 2
key 3

Do I use OrderedMapIterator wrong or is this a bug?

A: Its because technically .previous() does  not exactly set current entry to previous, but to next.before. Look how iteration process works:
nextEntry() {
    ...
    last = next; //its current
    next = next.after;
    ...

previousEntry() {
    ...
    final LinkEntry<K, V> previous = next.before;
    ...
    next = previous;
    last = previous;

So your flow will affect the last(current)|next states as follows:
null|1 -> (next) -> 1|2 -> (next) -> 2|3 <- (previous?) <- 2|2 -> (next) -> 3|null

The reason i may think why is behaves so, because its intended to call .next(), .previous() in separate loops.
Imagine a situation where you iterate all way forward, and then need to iterate all way back.
while (it.hasNext()) {
    String key = it.next();
    list.add(key);
}
while (it.hasPrevious()) {
    String key = it.previous();
    list.remove(key);
}

With the behaviour which you want to have, you would ended up with [key 3] in list, which is not correct, but currently it works fine.


text:
Q: Makefile: building LaTeX files in subdirectories with two versions of each file I have the following folder structure
   1st-grade-math-class/
      common/
        mystyle.sty
        mysubstyle.sty
        fonts/
          font1.ttf
          font2.ttf
          font3.ttf
      week01/
        handout.tex
        image1.pdf
        image2.pdf
      week02/
        handout.tex
        image1.pdf
        image2.pdf
      ...
      week13/
        handout.tex
      output/
        [empty]

And I would like to create a Makefile - in the best way - to do the following:

*

*make sure I include the common directory properly in TEXINPUTS

*compile the handout.tex into a PDF (using either pdflatex or xelatex) and have it in the output directory as week01-handout-student.pdf

*compile the handout.tex with a line of LaTeX prepended to the beginning of the file (that sets a flag) into a PDF and have it in the output directory as week01-handout-teacher.pdf

*clean everything up (the log, aux, etc. files)
I am not sure I know how to this in any other way than manually duplicating an elementary Makefile/bash script in every subdirectory, then calling each of them one by one with a for loop.
I would appreciate help on how to build this process, ideally with a single Makefile in the root directory. Thanks.
UPDATE: I purposefully did not want to give any details about how I compile LaTeX, in case somebody has a better suggestion than my current usage. Right now I am using Latexmk (which is already a make-like wrapper of LaTeX):

*

*latexmk -pdf file.tex generates file.pdf

*to add the line of code, I do a simple echo "line of code" > temp.tex and cat handout.tex >> temp.tex, then the same latexmk command

*latexmk -c file.tex in a directory cleans all temporary files used to compile file.tex

*TEXINPUTS is the TeX path variable, to let TeX find (in its path) the style files: I do TEXINPUTS=full-path-to/common and then export TEXINPUTS before compiling anything.

If anybody has a better suggestion, I am a willing taker.

A: Something like this should do what you want I believe:
OUTDIR := output

# Tell make to export this environment variable to all recipe lines it runs.
export TEXINPUTS := $(abspath common)

# Get the list of all of our week directories.
weekdirs := $(wildcard week*)
#$(info weekdirs:$(weekdirs))

# Create student output filenames from week directory names.
STUDENT_HANDOUTS := $(patsubst %,$(OUTDIR)/%-handout-student.pdf,$(weekdirs))
#$(info STUDENT_HANDOUTS:$(STUDENT_HANDOUTS))

# Create teacher output filenames from week directory names.
TEACHER_HANDOUTS := $(patsubst %,$(OUTDIR)/%-handout-teacher.pdf,$(weekdirs))
#$(info TEACHER_HANDOUTS:$(TEACHER_HANDOUTS))

# Default target depends on all output files.
all: $(STUDENT_HANDOUTS) $(TEACHER_HANDOUTS)

# Pattern rule for building pdf files.
%.pdf:
        @echo + Making $@ from $^
        @echo cd $(@D) && echo latexmx -pdf $(abspath $<)
        @echo cd $(@D) && echo latexmk -c $(abspath $<)

# Static pattern rule mapping student output files to input files.
$(STUDENT_HANDOUTS) : $(OUTDIR)/%-handout-student.pdf : %/handout.tex

# Pattern rule to generate temporary input files from original input files.
%/handout-tmp.tex: %/handout.tex
        @echo echo 'line of code' '>' $@
        @echo cat $^ '>>' $@

# Static pattern rule mapping teacher output files to (temporary) input files.
$(TEACHER_HANDOUTS) : $(OUTDIR)/%-handout-teacher.pdf : %/handout-tmp.tex

Uncomment the $(info) lines to see a bit of how the variables are put together.
This uses latexmk -c to clean up auxiliary files after creating the output files.

A: Technique 1. The echo foo >$@; cat $< >>$@ thing is something I've done before; I think it's reasonable.
Technique 2. Another technique is to have your .tex document, or a package file it uses, include a line like:
\InputIfFileExists{lecturenotes.config}{}{}

That allows you to make certain adjustments in a makefile, as in for example:
# any bits of configuration that should be in all the .config files
SWITCHES=\makeindex

%-notes.pdf: %.tex
        printf '$(SWITCHES)\\ExecuteOptions{sidenotes}\n' >lecturenotes.config
        TEXINPUTS=styles: pdflatex $<
        mv ${<:.tex=.pdf} $@
        rm lecturenotes.config

%-single.pdf: %.tex
        printf '$(SWITCHES)\\ExecuteOptions{oneside}\n' >lecturenotes.config
        TEXINPUTS=styles: pdflatex $<
        mv ${<:.tex=.pdf} $@
        rm lecturenotes.config

Technique 3. A third technique for controlling LaTeX from outside is to include in your document (or in a package file):
\newif\ifdemonstrator
\expandafter\ifx\csname demonstrator\endcsname\relax
  \demonstratorfalse
\else
  \demonstratortrue
\fi
...
\ifdemonstrator
    \typeout{Demonstrator is TRUE}
\else
    \typeout{Demonstrator is FALSE}
\fi

Then call latex with:
%-plain.pdf: %.tex
    latex $<
    mv ${<:.tex=.pdf} $@

%-demo.pdf: %.tex
    latex --jobname ${<:.tex=} '\def\demonstrator{x}\input{$<}`
    mv ${<:.tex=.pdf} $@

Technique 1 is a bit of a blunt instrument, but if that's all that's needed, it's pretty lightweight.
Technique 2 is probably the most neatly engineered, but it is slightly more effort.
Technique 3 is probably the one I use most in this sort of circumstance.


text:
Q: manage event, with addEventListener, and select dynamic input with querySelectorAll Sorry it's look like repost but I dont saw my answer in the others topics.
I need to make dynamic website witch offer possibility to order some product by the Local Storage.
The client can select product and theses are show to my card.html, forEach product of my LS I made an article.
In this article there's a child, an input showing the quantity selected before by client. I would like link this input to my local storage. Client will change directly the quantity in this order page, and if there's change, he's report to my local Storage.
here there's my test function.
const manageQuantity = async (createArticle) => {
    await createArticle

    let itemQuantity = document.querySelector('.itemQuantity')
    console.log(itemQuantity)

    itemQuantity.addEventListener('change', () => {
        console.log("ok l'évènement est fonctionnel")
    })
}
// createArticle, make the article if I've product in LS
// itemQuantity is the class of my input

My addEventListener's not a function with quereSelectorAll, but he is with a simple querySelector. But I need to have all input created by my function.
How can I select all my input, and be sure my addEvent will running ?

A: const manageQuantity = async (createArticle) => {
    await createArticle

    let itemQuantities = document.querySelectorAll('.itemQuantity')

    itemQuantities .forEach(function(item) {
      item.addEventListener('change', () => {
        console.log("ok l'évènement est fonctionnel")
      })
    });

}

basically you should use querySelectorAll() if you are using class
it will return a node list so you can use the foreach function to loop through all of the elements with the selected class and add the event listeners


text:
Q: Criação playList com select-option e os elemento video, object e embed Para reproduzir vídeos do YouTube em uma página da Web com playlist select-option, trago um exemplo simplório:
Código

troca = function (link) {
    document.getElementById('video').innerHTML = '';
}
select {
    font-size:20px;
    width:176px;
    height:100%;
    padding:15px;
    float: right;
}

option {
    font-size: 10pt;
    padding:10 10 10 10;
    float: left;
    cursor: pointer;
}

span {
    float:left;
}

<select onChange="troca(this.options[this.selectedIndex].value);" size="4">
    <option value="https://www.youtube.com/embed/iZUojirTEgM" style="background-image: url(https://img.youtube.com/vi/iZUojirTEgM/default.jpg); background-repeat: no-repeat; padding-left: 10px; width:120px; height:90px;">stop-motion 1</option>
    <option value="https://www.youtube.com/embed/ZEOmtEyXJtU" style="background-image: url(https://img.youtube.com/vi/ZEOmtEyXJtU/default.jpg); background-repeat: no-repeat; padding-left: 10px; width:120px; height:90px;">stop-motion 2</option>
    <option value="https://www.youtube.com/embed/GSzCLf8tjP4" style="background-image: url(https://img.youtube.com/vi/GSzCLf8tjP4/default.jpg); background-repeat: no-repeat; padding-left: 10px; width:120px; height:90px;">stop-motion 3</option>
</select>

Exemplo acima se aplica usando o  (recomendado)
Antes utilizava object e embed, mas o YouTube <object> e <embed> foram suspensos a partir de janeiro de 2015. Passando a migrar seus vídeos para usar .
Bom, agora surgiu uma dúvida.
O interessante da tag <video> é que você pode definir um "fallback" caso o vídeo não consiga ser exibido.
Nesse caso seria ideal exibir até mesmo o vídeo através do Flash.
<video width="420" height="315" src="video.webm" controls>
   <object  width="420" height="315" data="flvplayer.swf" type="application/x-shockwave-flash">
    <embed src="'+link+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="420" height="315">
   <param value="'+link+'" name="movie"/>
</object>

Como poderia acrescentar os elementos video, object e embed a função junto ao select-option como playlist?

A: Esta rotina apenas verifica se o navegador dá suporte tag video, e direciona uma alternativa.

Explicando
Manipulando com JavaScript
Para criar um elemento vídeo, uso a função document.createElement.
Uso o operador "in" para checar se o atributo existe no elemento.
Se existe ou não, a condição aplicará a melhor opção ao navegador.
A variável array, define índice dos valores separado por "|" no value do option

// criar o elemento <video>
var video = document.createElement("video");

// acrescentar ao elemento
document.body.appendChild(video);

troca = function (link)
{

// criando array com índice do valores do <option>
var array = link.split("|");

if('controls' in video){

document.getElementById('video').innerHTML = [
'<video width="420" height="315" controls>',
   '<source src="'+array[0]+'.mp4" type="video/mp4">',
   '<source src="'+array[0]+'.webm" type="video/webm">',
'</video>'
]

} else {

document.getElementById('video').innerHTML = [
'<object width="420" height="315" data="'+array[1]+'">',
   '<embed width="420" height="315" src="'+array[1]+'">',
   '</embed>',
 '</object>'
]
}
}
select {
 width:300px;
 height:100%;
 padding:30px;
 float: right;
 background-color: #FCFCFC;
}

option {
 font-size: 12pt;
 color: white;
 padding: 10 10 10 10;
 margin: 0 auto;
 background-repeat: no-repeat;
 background-position: center;
 background-size: 196px; 110px;
 width: 196px;
 height: 110px;
 text-align: center;
}

option:hover {
 background-color: steelblue;
 cursor: pointer;
}

<select id="lista" onChange="troca(this.options[this.selectedIndex].value);" size="4">

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/big_buck_bunny|https://www.youtube.com/embed/yUQM7H4Swgw" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/big_buck_bunny.jpg);"></option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/madagascar_2|https://www.youtube.com/embed/y8WJG7lrHCU" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/madagascar_2.jpg);"></option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/procurando_dory|https://www.youtube.com/embed/ooSaxz-SHts" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/procurando_dory.jpg);"></option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/meu_malvado_favorito_2|https://www.youtube.com/embed/B82b77UA9qY" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/meu_malvado_favorito_2.jpg);"></option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/animais_cantando|https://www.youtube.com/embed/qiEwyK7l5uw" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/animais_cantando.jpg);"></option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/a_capela_animais|https://www.youtube.com/embed/791zd6qfqoU" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/a_capela_animais.jpg);"></option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/monstros_sa_2|https://www.youtube.com/embed/91WYf1fhB9U" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/monstros_sa_2.jpg);"></option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/peck_pocketed|https://www.youtube.com/embed/qmCWjjZketo" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/peck_pocketed.jpg);"></option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/equipment_these_days|https://www.youtube.com/embed/WxaAhc3jf5s" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/equipment_these_days.jpg);"></option>

 <option value="https://sites.google.com/site/mplayerplugin/repositorio/skate|https://www.youtube.com/embed/Zlv6eSiGl1U" style="background-image: url(https://sites.google.com/site/mplayerplugin/repositorio/skate.jpg);"></option>

</select>

Acesse - demonstração

A: Este site fala sobre uma técnica que consiste em usar a tag video normalmente com seus sources, e depois do último source tu adiciona um player em Flash para compatibilidade.

EDIT
Minha resposta inicial não responde adequadamente à pergunta, então para responder melhor a pergunta, fiz um exemplo no JSBin e no CodePen onde eu tenho um viewport para mostrar o vídeo selecionado e uma lista para que o usuário selecione o vídeo.
A ideia principal é que o código consiste em:

*

*Um container com todos os vídeos (display: none; por padrão)

*Uma lista para o usuário escolher os vídeos, onde o link dessa lista aponta para o id do vídeo correspondente. Ex.: Vídeo 1.

*Um JS escutando o evento de clique dos items da lista cujo trabalho é apenas esconder o vídeo atualmente ativo e mostrar o item selecionado pelo usuário.

Exemplo

$(document).ready(function(){
    // cache do container
    var video_container = $('.playlist-viewport');

    $('.playlist-item').on('click', function(event){
        // pega apenas a hash do link
        var video_id = "#" + this.href.split('#')[1];

        // esconde o vídel atual
        video_container.find('.video.active').removeClass('active');

        // mostra o novo video
        $(video_id).addClass('active');

        // evita que o browser siga o link
        event.preventDefault();
        return false;
    });
});
body {
    background-color: #555;
    margin-top: 30px;
}

.playlist-viewport {
    list-style: none;
}

.playlist-viewport > .video {
    display: none;
}

.playlist-viewport > .video.active {
    display: block;
}

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

                            <video class="embed-responsive-item" controls="controls"
                            poster="http://sandbox.thewikies.com/vfe-generator/images/big-buck-bunny_poster.jpg" >

                                <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" type="video/mp4" />
                                <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.webm" type="video/webm" />
                                <source src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.ogv" type="video/ogg" />

                                <object type="application/x-shockwave-flash"
                                    data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf"
                                    width="640" height="360">

                                    <param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />
                                    <param name="allowFullScreen" value="true" />
                                    <param name="wmode" value="transparent" />
                                    <param name="flashVars"
                                        value="config={'playlist':['http%3A%2F%2Fsandbox.thewikies.com%2Fvfe-generator%2Fimages%2Fbig-buck-bunny_poster.jpg',{'url':'http%3A%2F%2Fclips.vorwaerts-gmbh.de%2Fbig_buck_bunny.mp4','autoPlay':false}]}" />

                                </object>
                            </video>

                        <video class="embed-responsive-item" controls="controls" >
                            <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
                            <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
                            <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>

                            <object type="application/x-shockwave-flash"
                                data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf"
                                width="640" height="360">

                                <param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />
                                <param name="allowFullScreen" value="true" />
                                <param name="wmode" value="transparent" />
                                <param name="flashVars"
                                value="config={'playlist':[{'url ':'http%3A%2F%2Ftechslides.com%2Fdemos%2Fsample-videos%2Fsmall.mp4','autoPlay':false}]}" />
                            </object>
                        </video>

                Big Buck Bunny
                Outro vídeo


text:
Q: If $M\neq 0$ is any subset of a vector space $X$, show that span $M$ is a subspace of $X$. If $M\neq 0$ is any subset of a vector space $X$, show that span $M$ is a
subspace of $X$.

*

*$0\in \text{ span } M$ since $M\neq 0$ then $a\in M$ and since $0$ is a scalar then $(a)(0)=0\in M$.

*If $x,y \in M$ then $x+y\in M$ by definition of span $M$

*If $x\in M$ and $c$ is a scalar, then $cx\in M$ by definition of span $M$.
Is this reasoning right? Thank you very much.

A: Your reasoning is right. The only thing I would comment is that in 1 you write "vector times number", which is fairly unusual: the common way is to write "number times vector".


text:
Q: C++ SSL connect: message too long I'm developing a application where many clients should connect to a server application and transmit every minute a string with about 300 Bytes. The client's are only a gateway between RS232 and the socket server. The connection between the clients and the server is SSL encrypted with openssl. Both are developed in C++.
The transmission is running 24/7 but it's not critical if some data get lost.
First I tried it with a TCP connection, but I got trouble with it, because the connection break some times. So I decided to connect and disconnect every Minute, when I send the informations (Maybe later I will cache some data and send it not every minute). Because of that I thought it would be better to use a UDP connection with DTLS.
But I have two problems with the UDP connection.

*

*ca every 10th string has one missing character. It's not really critical, but isn't it maybe a fault in my code ?

*If I use "SSL_CTX_load_verify_locations" to verify my client, I sometimes got an error: "SSL connect: message too long".
I think it should be typically for messages over 64K? But on connect I don't send any data? How can this happen while connecting ?
You think UDP is the right protocol for me? Or should I rather use TCP?
Here are some details from my code:
Server:
server_addr.s4.sin_family = AF_INET;
server_addr.s4.sin_addr.s_addr = INADDR_ANY;
server_addr.s4.sin_port = htons(port);

THREAD_setup();
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
ctx = SSL_CTX_new(DTLSv1_server_method());
SSL_CTX_set_cipher_list(ctx, "ALL:NULL:eNULL:aNULL");
SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF);

if (!SSL_CTX_use_certificate_file(ctx, SERVERCERT, SSL_FILETYPE_PEM))
    printf("\nERROR: no certificate found!");

if (!SSL_CTX_use_PrivateKey_file(ctx, SERVERKEY, SSL_FILETYPE_PEM))
    printf("\nERROR: no private key found!");

if (!SSL_CTX_check_private_key (ctx))
    printf("\nERROR: invalid private key!");

if(!SSL_CTX_load_verify_locations(ctx, CACERT, NULL))
    cout << "\nERROR: no ca-cert found!\n";

SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, dtls_verify_callback);

SSL_CTX_set_read_ahead(ctx, 1);
SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie);
SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie);

fd = socket(server_addr.ss.ss_family, SOCK_DGRAM, 0);
if (fd < 0) {
    perror("socket");
    exit(-1);
}

setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void*) &on, (socklen_t) sizeof(on));

bind(fd, (const struct sockaddr *) &server_addr, sizeof(struct sockaddr_in));

while (1)
{
        memset(&client_addr, 0, sizeof(struct sockaddr_storage));

        bio = BIO_new_dgram(fd, BIO_NOCLOSE);

        timeout.tv_sec = 5;
        timeout.tv_usec = 0;
        BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);

        ssl = SSL_new(ctx);

        SSL_set_bio(ssl, bio, bio);
        SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);

        while (DTLSv1_listen(ssl, &client_addr) <= 0);

        info = (struct pass_info*) malloc (sizeof(struct pass_info));
        memcpy(&info->server_addr, &server_addr, sizeof(struct sockaddr_storage));
        memcpy(&info->client_addr, &client_addr, sizeof(struct sockaddr_storage));
        info->ssl = ssl;

        if (pthread_create( &tid, NULL, connection_handle, info) != 0) {
            perror("pthread_create");
            exit(-1);
        }
    }

    THREAD_cleanup();
}

Client:
OpenSSL_add_ssl_algorithms();
SSL_load_error_strings();
ctx = SSL_CTX_new(DTLSv1_client_method());
SSL_CTX_set_cipher_list(ctx, "eNULL:!MD5");

if (!SSL_CTX_use_certificate_file(ctx, CLIENTCERT, SSL_FILETYPE_PEM))
    printf("\nERROR: no certificate found!");

if (!SSL_CTX_use_PrivateKey_file(ctx, CLIENTKEY, SSL_FILETYPE_PEM))
    printf("\nERROR: no private key found!");

if (!SSL_CTX_check_private_key (ctx))
    printf("\nERROR: invalid private key!");

if(!SSL_CTX_load_verify_locations(ctx,CACERT,NULL))
    cout << "\nERROR: cannot load CA Cert file for verification!\n";

SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER,NULL);
SSL_CTX_set_read_ahead(ctx, 1);

ssl = SSL_new(ctx);

bio = BIO_new_dgram(fd, BIO_CLOSE);

connect(fd, (struct sockaddr *) &remote_addr, sizeof(struct sockaddr_in));

BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_CONNECTED, 0, &remote_addr.ss);

SSL_set_bio(ssl, bio, bio);

if (SSL_connect(ssl) < 0) {
    perror("SSL_connect");
    printf("%s\n", ERR_error_string(ERR_get_error(), buf));
    exit(-1);
}

timeout.tv_sec = 3;
timeout.tv_usec = 0;
BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout);


text:
Q: Difference between ssis upgradation and migration I am migrating ssis 2005 packages to ssis 2012.Just wondering what is the difference
1) If I manually attach the 2005 packages to ssis 2012 project and modified all
the objects according the new environment
2) Using the upgradation Wizard to upgrade all packages from 2005 to 2012

A: You can do either way. if you do it manually the wizard will pop up when you open the migrated package for the first time in SQL Server Data Tools, which is the replacement for BI Development Studio.
In any case you might need to some manual steps. One of the main things you have to decide is what kind of deployment model you want to adopt since SSIS 2012 has two: package and project deployment models. There are a few documents released by Microsoft that can help you through the process. For example, this short document covers the most important aspects to perform a safe migration:
https://msdn.microsoft.com/en-us/library/hh667275.aspx
The good thing about the wizard is that will validate the package before the upgrade and make sure that it can run in 2012; in most cases the migration is possible bar a few exceptions like packages using third party components that cannot be upgraded.


text:
Q: HTML specify print pages? I am making a table of data that needs to printed out. I want the header to be at the top of each page. SO I am thinking the best way to do this is to repeat the header maybe every 30 columns or so, and break it into sections. But theres still no way to ensure that each section gets printed on its own page that I know of. Does anyone know how to do what I am trying to do? Main concern is just making the header at the top of each page when printing out the table of data.
Thanks!

A: Make sure your table headers are in the  section of the table, then use CSS to style it:
thead { display: table-header-group; }

A: You may want to check out this article regarding paged media and css. It's a pretty good read and should get you going in the right direction.
Printing a Book with CSS: Boom!
An example using the page break css rules for a table.
@media print
{
   table {page-break-after:always}
}

Here's also the w3c references to paged media.
CSS2
CSS3

A: sigh This one brings back memories.  Over the years I have wrestled with browser printing.  I finally threw in the towel, and now just send the user a PDF.
I (and my customers) are much happier with the results.


text:
Q: Can Entity Framework map the same column to a Navigation Property and a Foreign Key I have a class Car which has a property Type that is a string. Type is a foreign key to the Car Type table but we haven't actually created that relationship in EF yet.
We have several dozen usages of Car.Type throughout our code, but now we need to access another property in the Car Type table so we need to create the relationship between the 2 objects.
So I want to go:
public class Car
{
  public string Type { get; set; }
  public CarType CarType { get; set; }
}

public class CarType
{
  public string Name { get; set; }
  public bool Display { get; set; }
}

builder.Property(e => e.Type).HasColumnName("type");
builder.HasOne(e => e.CarType).WithMany().HasForeignKey("type");

So that I can access both the navigation property and the foreign key, for example:
string typeString = myCar.Type;
bool display = myCar.CarType.Display;

But when I retrieve Cars, I get an SQLException saying Invalid column name 'Type1'.
I've tried changing this all manner of ways but I always seem to get this error. I imagine there's a way to fix it by creating a List of Cars in the CarType class, but some of the CarTypes might have tens of thousands of Cars which could make retrieving the CarTypes slow. I also don't want to eliminate the navigation property and rely solely on the foreign key property because there are dozens of things we would have to change.
Does anyone know how to do this?

A: I'm flying a little blind as I can't see everything that you've done, but this is what I would do.
In the database, in the Car table, ensure you have a column titled CarTypeId.
In the database, in the CarType table, ensure you have the columns Id, Name, and Display.
Car.CarTypeId is a foreign key to CarType.Id.
Rebuild your entity diagram (edmx) by deleteing the Car and Cartype tables on the designer surface and reloading them, and the relationships should just be there.
Type1 is likely there because you have multiple navigation properties defined (there already is a Type, so the tool calls the other one Type1. You can make this work (you could rename it), but in my experience it's a code smell and adds a manual step that you have to remember down the road. Instead of building on top of what you have, I think you should re-structure what you have correctly. After these changes, you would do this:
string typeString = myCar.Type;

would become:
string typeString = myCar.CarType.Name;

Yes, you will have to change it through your code; however, if you rebuild your entity diagram, any references to the 'old' Car.Type will now fail, and the application will not compile -- it should be easy to find all instances that need to be updated.


text:
Q: javah.exe not included in Windows JDK 8? I'm trying to learn JNI on Windows 7 64-bit, but JDK 8 does not include javah.exe. I tried both the 32-bit and 64-bit versions. The Oracle documentation shows that javah is part of JDK 8 and doesn't make any platform distinction. Is there a separate download for JNI?
Also, the tutorials that I could find on JNI on Windows are pretty old - is there a newer way to do JNI in Windows, or does anyone have any suggestions for current Windows JNI Tutorials? NetBeans is my preferred IDE, but I'm not exclusive.

A: Hej Kevin, there is no seperate download needed for JNI and javah.exe is included in your JDK, search for it in %JAVA_HOME%/bin (if you don't have set this environment variable, look into C:\Program Files\Java\jdk1.8.0_121\bin or the version you have). Make sure you have downloaded the JDK, not JRE. And, the best JNI tutorial to start with is indeed that one, at least for me it was.


text:
Q: Pi and e problem I was solving some questions on Math Stack Exchange about irrational numbers when suddenly this question struck me.
We know that $e$ is irrational and that $\pi$ is also irrational.
Then is $\pi\cdot e$ rational or irrational?

A: Quoting the List of unsolved problems in mathematics - Analysis it is yet unknown whether $\pi+e$, $\pi \cdot e$, $\frac{\pi}{e}$ and $\pi^e$ are rational, algebraic irrational, or transcendental.


text:
Q: How to get response body in middleware? I want to log every request with response information.
I tried to use middleware, and I have a problem.
res.body is undefined.
app.use((req, res, next) => {

    var time = Date.now();

    res.on('finish', function() {
        var clientIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
        var method = req.method;
        var path = req.baseUrl;
        var duration = Date.now() - time;

        console.log({
            clientIp,
            elapsedTime: `${duration}ms`,
            hostname: req.headers.host,
            level: 'INFO',
            method,
            path,
            phase: process.env.NODE_ENV,
            reqBody: req.body,
            reqHeaders: req.headers,
            resBody: res.body,
            resHeaders: res.getHeaders(),
            status: res.statusCode
        });
    });

    next();
});

Actually there is response data on client.
How can I get response body in middleware?

A: The response can be intercepted by overriding response.json function. By doing so, and adding our custom function, every time, response.json() is called, our intercepting function is triggered.
middleware/response.filter.js:
// Response Interceptor Middleware
export default (request, response, next) => {
    try {
        const oldJSON = response.json;
        response.json = (data) => {
            // For Async call, handle the promise and then set the data to `oldJson`
            if (data && data.then != undefined) {
                // Resetting json to original to avoid cyclic call.
                return data.then((responseData) => {
                    // Custom logic/code.
                    response.json = oldJSON;
                    return oldJSON.call(response, responseData);
                }).catch((error) => {
                    next(error);
                });
            } else {
                // For non-async interceptor functions
                // Resetting json to original to avoid cyclic call.
                // Custom logic/code.
                response.json = oldJSON;
                return oldJSON.call(response, finalResponse);
            }
        }
    } catch (error) {
        next(error);
    }
}

In the Server.js file, register the middleware:
// Server.js file
import externalResponseFilter from "./middleware/response.filter.js:";

// Create Express server
const app = express();

// Response interceptor - Initialization.
app.use(externalResponseFilter);

And in the controller where you are returning the response, return with response.json() function instead of response.send().
Let me know if any additional explanation is required.

A: Intercept the response body from res.json and store it in res.locals for access later.
app.express.use((req, res, next) => {
  const oldJson = res.json;
  res.json = (body) => {
    res.locals.body = body;
    return oldJson.call(res, body);
  };
  next();
});

A: The response object in Express is simply node's http.ServerResponse class. It is a writable Stream so you can interact with it as a stream. It also exposes the underlying net.Socket connection via res.socket.
This is where it gets interesting. Because net.Socket is a plain writable Stream. If you override it's .write() method you will be able to intercept all bytes going out of your socket onto the network:
function interceptorMiddleware (req, res, next) {
    const sock  = req.socket;
    const write = sock.write.bind(sock);

    sock.write = (data, encoding, callback) => {
        console.log(data);
        write(data, encoding, callback);
    }

    sock.on('close', () => console.log('DONE'));

    next();
}

You need to install this middleware very early in your application before anything gets a chance to write to the socket.
Due to the asynchronous nature of node you may get mixed packets in your log output so it may be worth adding a bit of code to identify which socket is generating an output:
console.log(sock.remoteAddress, sock.remotePort, data);

Warning!
console.log() is synchronous when outputting to the terminal or a file.
  Doing this can potentially severely degrade your server's performance.
  If you are piping stdout to another process such as pm2 then it's not so bad
  because it will be async but it may still cost you a minor performance hit.
Use this for debugging ONLY


text:
Q: What is the origin of the parmname: value syntax for passing paramters? I learned groovy last summer and discovered the syntax for constructors that you can specify the parameter name with a value and initialize that value. For instance:
Team team = new Team(name: "Bengals")

At the end of the year, I upgraded IntelliJ and this syntax started showing up in my java functions with overloaded functions with different parameter lists. (This is not implemented very well. It's confusing when I try to change the values. I've figured it out, but poorly implemented.)
team.chant = (msg: "Who dey?");

Which is interesting, because I'm learning Swift 3 and it uses the same syntax.
It seems unlikely that Swift 3 was influenced by Groovy, so I'm curious. What language is putting pressure on these languages to support the parmname: value syntax?
It seems to me that Swift is based on what little I know about Smalltalk. Does Smalltalk support this parameter syntax?

A: I don't know Swift nor Groovy, so I can only respond for the Smalltalk part.
Smalltalk does not support that syntax, but has keyword messages that read very much like that.
For instance,
team := Team new name: 'Bengals'.
team chant msg: 'who dey?'

is valid in Smalltalk.
It is not that the names of params are in the command, but the command itself is #name:, which matches the name of some instance variable but is a method to set its value... So as I said, it reads the same but the meaning is very different.


text:
Q: Are KEY_TYPED events consumed by jxbrowser? I've added a key listener to a jxbrowser 6.11 BrowserView object to log keys typed by the user.  With this listener, I can see keyPressed and keyReleased events, but no keyTyped events.  Could jxbrowser be consuming the KEY_TYPED events for some reason?  And, if so, is there anything I can do about it?  Unfortunately, because of restrictions in the external method being used to process and log the key events, it has to be a KEY_TYPED event passed to it.

A: KEY_TYPED event is processed properly in BrowserView for Browser instance that was created in LIGHTWEIGHT mode.


text:
Q: PHP cart in session show different products I stored a temporary session value and product id in orderdetails table to store different product items and how it will shows that orderdetails values in cart page. Attachement will shown at below cases:

<?php
error_reporting(0);
include("db.php");
include("header.php");
session_start();
$session_id = session_id();
?>

<form action="#" class="form1">

                Remove
                Image
                Product
                Price
                Quantity
                 Total

            <?php
                $cartid = $_GET['proid'];
                $sqlpd = mysql_query("select * from orderdetail where sessionid = '$session_id'")or die(mysql_error());
                while($getpd = mysql_fetch_array($sqlpd)){
                        $product_id = $getpd['product_id'];
                    ?>

                    <img src="admin/<?php echo $getpd['medium_image'];?>" height="50" width="50">

                <?php echo $getpd['product_id'];?>
                <?php echo number_format($getpd['actual_price'],2);?>

                    <input type="number" class="cardqty-1" min="1" value="1" style="width:50px;">

                <?php echo number_format($getpd['actual_price'],2);?>

            <?php }?>

                Sub Total
                <?php echo number_format($getpd['actual_price'],2);?>

                GST(12%)
                <?php echo number_format($getpd['actual_price'],2);?>

                Grand Total
                <?php echo number_format($getpd['actual_price'],2);?>

This code will like this...I will compare a session value from table and temp session_id. Query is working but I know the values will not correct but how can i set values from products table using product id(orderdetails-table).


text:
Q: Can't run PHP executable script. OS X 10.6 Execting php-scripts from the command line now does not work. When executing a script starting with #!/usr/bin/env php. I get this error message:

env: php: No such file or directory.

So it seems I can not run php as an executable script with /usr/bin/php.
I think what's causing my problem is that I followed these instructions for allowing MAMP's copy of PHP to run from the terminal.
sudo mv /usr/bin/php /usr/bin/php-old

appears not to be working. php is not renamed.
If I should add something to my path. What should I add? When running echo $PATH:
/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/git/bin:/usr/X11/bin

Btw (don't know if it is related): MySQL is running but I can't access http://localhost/ when running:
sudo apachectl start

A: That's why you should never mess around with /usr/bin, but keep local installations of binaries.
If you did the following
sudo mv /usr/bin/php /usr/bin/php-old

you will be able to revert by just doing
sudo mv /usr/bin/php-old /usr/bin/php

then /usr/bin/env php should work.

If you decide to continue with the MAMP installation, you can of course move your default php to php-old. But then you also need to execute the following after moving php to php-old:
sudo ln -s /Applications/MAMP/bin/php5/bin/php /usr/bin/php

in order to have the php shipped with MAMP available under /usr/bin/phpagain.
But I can't promise that will work as expected at all. Again, you shouldn't move stuff in /usr/bin.

A: You can just use the path of your PHP installation directly in the script.
#!/Applications/wherever/it/is/you/installed/php


text:
Q: In MySQL Database, which choice is better? Single huge table, or multiple smaller tables I am creating a huge database.
Currently it have more than 250mb data with 1,500,000+ row.
On next stage on those every row, i will have avg 10+ data.
So, estimates around 2.5GB data in the database.
If i create multiple tables (around 15 to 25) and save data on those tables,
I would have to write complex code (php) to get output.
But if i create single table of 2.5+ gb, most likely it will slow down the process.
Which is better way to do?
Size of data (2.5gb) is estimated/example. please let me know what you think!


text:
Q: Como puedo unir estas dos funciones en javascript para paginar tengo dos funciones la de arriba lo que hace es paginar una tabla, funciona correctamente y la de abajo igual.
pero la funcion de abajo lo que hace es un buscar en las tablas por palabras o numeros.
el problema de que funcionen por su lado cada una es que cuando borro lo que esta en buscar la funcion de paginar pierde su efecto.
alguien me puede dar una idea de por donde comenzar.
//creamos una funcion que se llamara Pager que recibira el nombre de la tabla,
//y la cantidad de registros seran presentados por paginador
//y finalmente que contendra 7 variables

function Pager(tableName, itemsPerPage) {
    this.tableName = tableName; // se asigna el nombre de la tabla al objeto
    this.itemsPerPage = itemsPerPage; // se asigna el numero de registros
    this.currentPage = 1; //indicamos cual es la pagina que presentaremos inicialmente
    this.pages = 0;//aun no sabemos cuantas paginas seran, por tanto lo declaramos a 0
    this.inited = false;//idicamos si ya inicio la tabla o no
    this.divisores = 0;//aun no sabemos la cantidad de divisores por eso la declaramos a cero
    this.cantidadDivs=5;//cantidad de divisores a mostrar por paginador

/**la variable divisores y cantidadDivs, son referencia a que mostraremos paginadores de 5 en 5,
por ejemplo si tenemos 120 registros y los mostraremos de 10 en 10, con la variable divisores indicamos que mostraremos 5 divisores,
es decir, mostraremos el paginador 1(registros 1-10), paginador 2(registros 11,20).. asi hasta el paginador 5(registros 41-50),
y cuando le demos siguiente, se mostraran los paginadores 6 al 10 ( registros 51-100,
separados en su respectivo paginador )*/

//Dentro de nuestra funcion crearemos una sub-funcion llamada init

this.init = function() {
    var rows = document.getElementById(tableName).rows;
    var records = (rows.length - 1);
    this.pages = Math.ceil(records / itemsPerPage);

    this.divisores = Math.ceil( this.pages / this.cantidadDivs );

    this.inited = true;
}
/**
obtenemos la cantidad de registos que contiene la tabla.

obtenemos la cantidad de registos, recordemos que las numeraciones empiesan en 0, para el caso de la variable rows.

obtenemos el numero de paginas que mostraremos.

obtenemos el numero de divisores que tendremos
( recordemos que es como un agrupador para los paginadores )

colocamnos la variable inicializado como cierto
*/

//Creamos nuestra funcion para poder mostrar los registros

this.showRecords = function(from, to) {
    var rows = document.getElementById(tableName).rows;
    for (var i = 1; i < rows.length; i++) {
     if (i < from || i > to)
        rows[i].style.display = 'none';
     else
        rows[i].style.display = '';
    }
}
/**
El metodo recibe el rango de registros, y lo unico que hace es colocar
o borrar el estilo, en su apartado display a "none"
*/

//Creamos nuestra funcion para poder mostrar los divisores

this.showDivs = function(pageNumber){
    var divisorMostrar = Math.ceil(pageNumber / this.cantidadDivs);
    for( var i = 1 ; i <= this.divisores ; i++ ){
     if( divisorMostrar == i ){
       document.getElementById('dv'+i).style.display = '';
     }else{
       document.getElementById('dv'+i).style.display = 'none';
        }
    }
}
/**
obtenemos el id del agrupador de divisores,
e igual agregamos o borramos el estilo display

por ahora no se preocupen por los ids, esos los veremos mas adelante
*/
//Creamos nuestra funcion para poder mostrar un paginador

this.showPage = function(pageNumber) {
    if (! this.inited) {
     alert("La tabla no se inicializo");
     return;
    }

    this.showDivs(pageNumber);

    this.currentPage = pageNumber;

    var from = (pageNumber - 1) * itemsPerPage + 1;
    var to = from + itemsPerPage - 1;
    this.showRecords(from, to);
}
/**
este metodo recibe su el id del paginador a mostrar
pero primero valida que la tabla este inicializada, para no mandar un error javascript

invocamos el metodo que mostrara los divs, y calculamos los registros que se han de mostrar
*/

//Creamos los metodos que invocaran nuestros botones

    this.prev = function() {
       if (this.currentPage > 1)
          this.showPage(this.currentPage - 1);
    }

    this.first = function() {
        if (this.currentPage > 1)
            this.showPage( 1 );
    }

    this.next = function() {
        if (this.currentPage < this.pages) {
            this.showPage(this.currentPage + 1);
        }
    }

    this.last = function() {
        if (this.currentPage < this.pages) {
            this.showPage(this.pages);
        }
    }

/**
Son los metodos de los botones primero, anterior, siguiente, ultimo
*/

//Creamos el metodo principal que asignara ids a divisores a paginadores,

this.showPageNav = function(pagerName, positionId) {
     if (! this.inited) {
      alert("La tabla no esta inicializada");
      return;
     }
     var element = document.getElementById(positionId);

     var pagerHtml = '  inicio   ';
     pagerHtml += '  anterior   ';

     var divisor = 1;
     var idDivisor = 1;
     for (var page = 1; page <= this.pages; page++) {
      if( idDivisor==1 ){
       pagerHtml += '
';
      }
      idDivisor = idDivisor+1;
         pagerHtml += '' + page + '';
         if(idDivisor==this.cantidadDivs+1){
          idDivisor=1;
          divisor=divisor+1
          pagerHtml += '
';
         }else if( page == this.pages ){
          pagerHtml += '';
         }
        }
        pagerHtml += ' siguiente   ';
        pagerHtml += ' fin ';

        element.innerHTML = pagerHtml;
    }

 }
/**
verificamos que la tabla este inicializada.

recorremos las paginas calculadas anteriormente asignandole ids, la funcion onclick

finalmente todo ese codigo lo asignamos a una variable que es la encargada de pintar el html en nuestra pagina
*/

function doSearch()
        {
            var tableReg = document.getElementById('tblResultados');
            var searchText = document.getElementById('searchTerm').value.toLowerCase();
            var cellsOfRow="";
            var found=false;
            var compareWith="";

            // Recorremos todas las filas con contenido de la tabla
            for (var i = 1; i < tableReg.rows.length; i++)
            {

                cellsOfRow = tableReg.rows[i].getElementsByTagName('td');

                found = false;
                // Recorremos todas las celdas
                for (var j = 0; j < cellsOfRow.length && !found; j++)
                {
                   console.log(compareWith);
                    compareWith = cellsOfRow[j].innerHTML.toLowerCase();
                    // Buscamos el texto en el contenido de la celda
                    if (searchText.length == 0 || (compareWith.indexOf(searchText) > -1))
                    {
                        found = true;
                    }
                }
                if(found)
                {

                    tableReg.rows[i].style.display = '';

                } else {
                    // si no ha encontrado ninguna coincidencia, esconde la
                    // fila de la tabla

                    tableReg.rows[i].style.display = 'none';

            }

            if(searchText==""){
            div = document.getElementById('limpiar');
            div.style.display = 'none';
            location.href ="Cuerpo.html";
            }

          }

        }