text:
Q: DetailsView conditionally enable edit field I have an existing asp.net detailsview and the information can be edited by a number of different roles. A new bit field has been introduced (checkbox) and the page is working correctly.
The next step is to limit the editing of this field to only one role. How can I set the edit controls as disabled?
Methods tried are

*

*Code behind - in the Detailsview's mode change event, the edit controls haven't been rendered, so can't be disabled yet

*In page code - This works enabling and disabling the control. This issue is that the field isn't saving the update. I suspect this is an issue of the code in the template. The code I'm using is:

<EditItemTemplate>
  <% If User.IsInRole("SystemAdministrator") Then%>
    <asp:CheckBox ID="BypassIpLockdownCheckBox" runat="server" Checked='<%# Bind("ByPassIPLockdown") %>' />
  <% Else%>
    <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("ByPassIPLockdown") %>' Enabled="false" />
    <% End If%>
</EditItemTemplate>

How can I conditionally enable/disable the field?

A: Try this
<asp:CheckBox ID="BypassIpLockdownCheckBox" runat="server" Checked='<%# Bind("ByPassIPLockdown") %>' Enabled='<%# User.IsInRole("SystemAdministrator") %>' />


text:
Q: Facebook.Web.Contracts - strong signature could not be verified? I've been going through the tutorial for the .NET Facebook SDK on codeplex.  I used Nuget to install the SDK, as the tutorial indicates.  However, when I try to run the application, I get the following exception:

Could not load file or assembly 'Facebook.Web.Contracts' or one of its dependencies. Strong name signature could not be verified.  The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045)

This is with version FacebookWeb 5.0.8.0.  Any ideas?

A: This problem appears to be fixed in 5.0.9

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pentaho Kettle - How to get all child nodes in XML file I have an xml file that I'm trying to insert into MongoDB using Pentaho Kettle.    This is a sample node I am processing.
<LearningStandardItem RefId="ac4fc887aeef497198822bd233989505" xml:lang="en">
  <StandardHierarchyLevel HierarchyLevelDescription="Level 1">1</StandardHierarchyLevel>
  <ParentItemRefId>ac4fc887aeef497198822bd233989505</ParentItemRefId>
  <StatementCode>LAFS.K12.L</StatementCode>
  <Statement><![CDATA[Language]]></Statement>
  <GradeLevels>
    <GradeLevel Code="KG"/>
    <GradeLevel Code="01"/>
    <GradeLevel Code="02"/>
    <GradeLevel Code="03"/>
    <GradeLevel Code="04"/>
    <GradeLevel Code="05"/>
    <GradeLevel Code="06"/>
    <GradeLevel Code="07"/>
    <GradeLevel Code="08"/>
    <GradeLevel Code="09"/>
    <GradeLevel Code="10"/>
    <GradeLevel Code="11"/>
    <GradeLevel Code="12"/>
  </GradeLevels>
  <SubjectArea Code="10">Language Arts</SubjectArea>
  <LearningStandardDocumentRefId>48c8286c12424beb950194015407afa5</LearningStandardDocumentRefId>
  <SIF_ExtendedElements>
    <SIF_ExtendedElement Name="CCRefId"><![CDATA[CED36FDE-67AD-11DF-AB5F-995D9DFF4B22]]></SIF_ExtendedElement>
  </SIF_ExtendedElements>
</LearningStandardItem>

If I set my Loop XPath to /AB_SIF/LearningStandardItem, then I get all the nodes I want except that I'm trying to get all grade levels.  When I set a field to GradeLevel/@Code, I only get the first GradeLevel node.  I need to get them all.  I am trying to insert all the grade levels into an array in MongoDB.  Is there a way to do this?

A: It returns all Code as you want.
/LearningStandardItem/GradeLevels/GradeLevel/@Code

Here is the result

A: Try the below steps in PDI (Step: Get Data from XML):

*

*Set the XPATH to /LearningStandardItem/GradeLevels//*

*In the getFields section of the step, set the XPATH as @Code and the Element type = Attribute.

this will fetch you all the attributes inside the GradeLevel node. I have attached a gist here.

Alternatively, you can also try with step "XML Input Stream (StAX)" in PDI. It uses StAX parser to read all the xml nodes and attributes. It becomes useful in case of large xml file.
Hope it helps :)


text:
Q: Select rows having equal values in one column but not those are alone This is my SQLfiddle : http://sqlfiddle.com/#!9/6a335/1/0

The result I want is the same like picture but without the 2 red rows, because for id_association_mots_idM 476 and 478, there is no traduction in english in the table.
I tried many requests and many ways.
Is it possible and if yes, how ?
Thanks for your help.

A: You're really going to have to start formatting and indenting your SQLs nicely if you want them to be maintainable in future
The following query excludes the red rows:
SELECT
  ass_m_m.id_association_mots_idM,
  ass_m_m.id_vocab_idM,
  v_a_m.categorie_v ,
  v_a_m.mot_v

FROM
`association_mots_id_mot` AS ass_m_m
INNER JOIN
`association_mots_login` AS ass_m_l
ON
  ass_m_m.id_association_mots_idM = ass_m_l.id_association_mots AND
  ass_m_l.id_login_mL = '1'

INNER JOIN
`vocabulaire_a_memoriser` AS v_a_m
ON
  ass_m_m.id_vocab_idM = v_a_m.id_vocab AND
  (v_a_m.categorie_v = 'langue_francais' OR v_a_m.categorie_v = 'langue_anglais')

INNER JOIN
(
  SELECT
    ass_m_m.id_association_mots_idM
  FROM
    `association_mots_id_mot` AS ass_m_m
    INNER JOIN
    `vocabulaire_a_memoriser` AS v_a_m
    ON
      ass_m_m.id_vocab_idM = v_a_m.id_vocab AND
      (v_a_m.categorie_v = 'langue_francais' OR v_a_m.categorie_v = 'langue_anglais')
   GROUP BY
     ass_m_m.id_association_mots_idM
   HAVING COUNT(distinct categorie_v) = 2
) wanted
ON
  ass_m_m.id_association_mots_idM = wanted.id_association_mots_idM

I've converted the query to ANSI join syntax - please avoid using the old SELECT * FROM a,b,c,d WHERE a.id=b.id ... syntax
The top part of your query is your query (converted join syntax, and laid out indented so we have a chance of seeing what's going on) unchanged
The bit that does the work is this subquery:
(
  SELECT
    ass_m_m.id_association_mots_idM
  FROM
    `association_mots_id_mot` AS ass_m_m
    INNER JOIN
    `vocabulaire_a_memoriser` AS v_a_m
    ON
      ass_m_m.id_vocab_idM = v_a_m.id_vocab AND
      (v_a_m.categorie_v = 'langue_francais' OR v_a_m.categorie_v = 'langue_anglais')
   GROUP BY
     ass_m_m.id_association_mots_idM
   HAVING COUNT(distinct categorie_v) = 2
) wanted

It reduces the ass_m_m.id_association_mots_idM list of 2,2,5,5,5,476,478 to just 2,5 because they are the only ass_m_m.id_association_mots_idM that have a COUNT(DISTINCT language) of 2 - i.e. they're the only rows where 2 distinct language values appear
Then, because the output of this query is just 2,5 when it's joined into the main, it restricts the main query to just rows where the iass_m_m.id_association_mots_idM is 2 or 5

A: Is this what you want?
select t.*
from t
where exists (select 1
              from t t2
              where t2.id_association_mots_idm = t.id_association_mots_idm and
                    t2.category_v = 'langue_anglais'
             );

A: The query below excludes the RED rows.
SELECT v_all.id_association_mots_idM,
       v_all.id_vocab_idM,
       v_all.id_vocab_idM,
       v_all.mot_v
  FROM (SELECT  ass_m_m.id_association_mots_idM,
                ass_m_m.id_vocab_idM,
                v_a_m.categorie_v ,
                v_a_m.mot_v
        FROM  `association_mots_login` AS ass_m_l,
              `association_mots_id_mot` AS ass_m_m,
              `vocabulaire_a_memoriser` AS v_a_m
        WHERE ass_m_l.id_association_mots  = ass_m_m.id_association_mots_idM
          AND ass_m_l.id_login_mL = '1'
          AND ass_m_m.id_vocab_idM = v_a_m.id_vocab
          AND v_a_m.categorie_v IN ('langue_francais', 'langue_anglais')) v_all,
        (SELECT DISTINCT ass_m_m.id_association_mots_idM
          FROM  `association_mots_login` AS ass_m_l,
                `association_mots_id_mot` AS ass_m_m,
                `vocabulaire_a_memoriser` AS v_a_m
          WHERE ass_m_l.id_association_mots  = ass_m_m.id_association_mots_idM
            AND ass_m_l.id_login_mL = '1'
            AND ass_m_m.id_vocab_idM = v_a_m.id_vocab
            AND v_a_m.categorie_v = 'langue_anglais') v_eng
WHERE v_all.id_association_mots_idM = v_eng.id_association_mots_idM        ;

Explanation:
In-line view v_all is same as what you had. Gets all the records for both langue_francais and langue_anglais. Inline view v_eng only gets the records where there is a traduction in english i.e. langue_anglais.
Inner joining the 2 views would give you just the records with english traduction.
Hope this helps!


text:
Q: Mac does not sleep automatically in Lion! My Macbook Pro will not sleep even though it is set in System Preferences → Energy Saver.

*

*I do not have any sharing options enabled (System Preferences → Sharing).

*I do not have "Wake for network access" enabled (System Preferences → Energy Saver).

*It does not matter if the Mac is connected to a power source.

*I've reset the SMC and the PRAM, but this did not help.

I'm running OS X 10.7.3.

A: Another safe boot revealed that the auto sleep mode actually is working. I believe that it would probably have worked the last time I've tried it as well  - but, since the sleep occurs several minutes later than the time defined in the Energy Saver settings, I did not notice this.
What about the 'normal' boot?
I've basically tested the auto sleep with all my menu extras enabled one by one, because the iotop command mentioned by @StuWilson didn't show anything helpful to me. As it turns out the menu extra Stack Exchange Notifier caused insomnia.

A: The biggest cause of macs not entering idle state is usually disk activity.
I'd suggest that you boot into Safe Boot mode then use Activity Monitor to see if any processes are causing IO operations.
If you do see activity then try using iotop in terminal, it will give you a breakdown of Process ID (PID) and the app or process name doing the IO operations.
sudo iotop -C 5 10

A: This might not be your problem, but I've had the same issue for a long time and couldn't find an answer for me, so I'll post what worked for me in case someone comes along later.
My MacBook Pro (and later, my iMac, since I used Migration Assistant) would not sleep when left idle for anything. It would sleep with the lid closed, or if I explicitly told it to, but would not sleep when left alone, as it should have per my preferences in Energy Saver.
I had already checked pmset -g assertions and turned off sharing and other wake-on-LAN settings, and nothing seemed to work. Monitoring pmset -g pslog, I found that the computer would go to sleep at the scheduled time, and wake back up a few seconds later, reporting as wake reason only whatever had been called last—even if it was the power button (that is, it said I had pressed the power button when I had not. That scared me). I had read this and a dozen other answers and forums and couldn't get anywhere.
I found a hint by checking pmset -g log which was a little more detailed than pslog. It turned out that every time the computer went to sleep, a process "cancelled" like so:
3/13/13 12:00:12 AM CDT  Sleep                  Software Sleep Sleep: Using AC                                              6492 secs
3/13/13 12:00:12 AM CDT  Cancelled              Kernel: Response from WDDMService is to cancel state change

Looking up WDDMService in Activity monitor, it turned out to be a background daemon that was installed by the notorious "SmartWare" that came on a Western Digital External drive. So I killed the process, and the computer went to sleep as it should! Since I don't use the software, I removed it from launchd (which I think it called the .plist? I didn't really know what I was doing there) so it wouldn't appear again. Everything works fine now!

A: I had the same problem in Mavericks with a brand new Macbook  Pro Retina (Late 2013).  When I closed the lid and left the laptop closed overnight it never went to sleep.  In the morning, the battery would be dead or very low.
As it turns out... my problem was due to a piece of software installed by my company's IT:
Symantec Encryption Desktop (SED)
As noted in this SED setup article:

Hibernation also called Safe Sleep is not supported with PGP WDE, when a Mac goes to sleep and runs out of battery power the Mac will shut down and not go into safe sleep. It's important to turn off the machine if it will run out of battery power

Here is Symantec's official reason why

PGP Whole Disk Encryption is not supported with hibernation mode in the Mac OS X. In Mac OS X, an image file is created upon hibernation of the system. Once power is restored, the state of the system is restored, including any open programs or other processes that were running. The location of this file is in /var/vm/sleepimage and is the size of RAM memory on the system.
This mode may be referred to as Safe Sleep, Deep Sleep, or Hibernation. This is not the normal Sleep mode in which the power can remain on, but the system is essentially idle. This mode does not keep an image of the processes, but rather the information is stored in the RAM memory.
The Mac OS X operating system does not support foreign file systems for hibernation. Mac OS X Hibernation mode is not supported with "boot != root". This "boot != root" is essentially the system used by Mac to boot a foreign file system. For PGP Whole Disk Encryption to boot a system, a special file system is used which is considered foreign. As PGP Whole Disk Encryption is considered a foreign file system, hibernation mode is not supported by the Mac OS X.
As a safeguard to prevent system issues and data loss, PGP Desktop disables the hibernation mode on Mac OS X. Although Sleep will still work, deep sleep does not build a sleep image.


text:
Q: $\int_E fd\mu=\lim \limits_{n\to\infty}\int_E f_nd\mu$ Let $(X,\mathcal S, \mu)$ be a measure space, $E\in \mathcal S$, $\mu(E)<\infty$ and $f_n$ be a non negative sequence, measurable  real-valued functions that converge uniformly to $f:X\rightarrow \mathbb R$.
How can I prove $\int_E f d\mu=\lim_\limits {n\to\infty}\int_E f_nd\mu?$
I tried to use Lebesgue's dominated convergence theorem but I didn't get any further here because I need a function $g$ with $|f_n|\leq g$ for all $n$


text:
Q: Sheet to CSV with custom delimiter? I need to create a CSV string with a custom delimiter from a Workbook.
I wrote this function which does the trick but problem is that looping through rows is just too slow:
Public Function CSVStringFromWB(wb As Workbook, FieldTerminator As String) As String
    Dim Line As String
    Dim r As Long
    Dim ColsCount As Long
    Dim RowsCount As Long
    ColsCount = wb.Sheets(1).UsedRange.Columns.Count
    RowsCount = wb.Sheets(1).UsedRange.Rows.Count
    With wb.Sheets(1)
        For r = 1 To RowsCount
            Line = Join(Application.Transpose(Application.Transpose(.Range(.Cells(r, 1), .Cells(r, ColsCount)).Value)), FieldTerminator)
            CSVStringFromWB = CSVStringFromWB + Line + vbNewLine
        Next r
    End With
End Function

Is there any faster alternatives to create transform a range to a CSV string with a custom delimiter?

A: This is approx 20x faster (using 6k rows x 20 cols)
Public Function FasterCSVStringFromWB(wb As Workbook, _
                                      FieldSep As String) As String
    Dim data, lines() As String, line As String, sep As String
    Dim ColsCount As Long, r As Long, c As Long
    Dim RowsCount As Long

    data = wb.Sheets(1).UsedRange.Value
    ColsCount = UBound(data, 2)
    RowsCount = UBound(data, 1)
    ReDim lines(1 To RowsCount)

    For r = 1 To RowsCount
        sep = ""
        line = ""
        For c = 1 To ColsCount
            line = line & sep & data(r, c)
            If c = 1 Then sep = FieldSep
        Next c
        lines(r) = line
    Next r

    FasterCSVStringFromWB = Join(lines, vbNewLine)
End Function

A: Reading through the entire excel sheet cell by cell is slow. If you can, save the desired excel rows/cols as a separate csv file, then write a separate small program to change the commas in the csv to something else.
If you have to go through the entire excel sheet with vba, then what you have done is probably the only way.
If you have to deal with a large amount of excel files, try to copy the rows/cols you want, then paste into a new worksheet, then save the worksheet as csv then change the delimiter afterwards.


text:
Q: Rewriting GCC inline assembly to not require volatile or a memory clobber Is it possible to rewrite or improve this function to not require volatile or a generic memory clobber in its inline assembly?
// do stuff with the input Foo structure and write the result to the
// output Bar structure.
static inline void MemFrob(const struct Foo* input, struct Bar* output) {
    register const Foo* r0 asm("r0") = input;
    register Bar* r1 asm("r1") = output;

    __asm__ __volatile__(
        "svc #0x0f0000 \n\t"
        : "+r" (r0), "+r" (r1)
        :
        : "r2", "r3", "cc", "memory"
        );
}

For this specific situation, the target platform is an ARM7 system, and the code is being compiled with GCC 5.3.0.  The system call being performed has the same calling convention as a C function call.  After some trial and error, I've arrived at the above which "works" but I am not yet confident that it is correct and will always work, subject to the whims and fancies of the optimizing compiler.
I'd like to be able to remove the "memory" clobber and tell GCC exactly which memory will be modified, but the GCC Extended Asm documentation discusses how to assign values to specific registers, and then memory constraints, but not if they both can be combined.  As of now, removing the "memory" clobber from the above example can cause GCC to not use the output in proceeding code.
I'd also like to be able to remove the volatile in the cases where the output is not used.  But as of now, removing volatile from the above example causes GCC to not emit the assembly at all.
Adding additional inline assembly to move the system call parameters into r0/r1 manually or un-inlining by moving the code to an external compilation unit are wasteful workarounds that I'd much rather avoid.

A: Long story short: this is what the "m" constraint is for.  Usually, if you are using volatile or __volatile__, with asm, it is because there is an error in your code.  One of the compiler's main jobs is flow analysis, so as long as you give it enough information to do the correct flow analysis, everything will work correctly.
Here is a fixed version:
void MemFrob(const struct Foo* input, struct Bar* output) {
    register const Foo* r0 asm("r0") = input;
    register Bar* r1 asm("r1") = output;
    __asm__ (
        "svc #0x0f0000"
        : "=m"(*r1) // writes data to *output (but does not read)
        : "m"(*r0), // reads data in *input
          "l"(r0), "l"(r1) // This is necessary to ensure correct register
        : "r2", "r3", "cc"
        );
}

You can test it on https://gcc.godbolt.org/ (-O2 compiler options recommended).  The output is as follows:
svc #0x0f0000
bx lr

Obviously, when inlined, it should reduce to just the one instruction.
Unfortunately, I couldn't figure out how to specify specific registers when using inline ARM assembly, other than the method above which is a bit clumsy.


text:
Q: Find how many seconds overlap between two different time Intervals I have two UNIX timestamps that have distance in seconds D, where D = end - start. I want to find how many of these D seconds belong to an another time window [start2, end2], i.e. how many seconds intersect. Obviously it is not time2 - time1.
For example
start timestamp 1621707530 is Saturday, May 22, 2021 6:18:50 PM (GMT)
end timestamp 1621736330 is Sunday, May 23, 2021 2:18:50 AM (GMT)
How to find (preferably in Python) how many seconds between 01:00 AM and 02:00 AM belong to my [start, end] window?
For example interval [09:00 AM, 10:00 AM] does not intersect with [01:00 AM,02:00 AM], however interval [00:55 AM,01:03 AM] intersects for 3 minutes, or 180 seconds.
My code so far:
from datetime import datetime
from collections import namedtuple
Range = namedtuple('Range', ['start', 'end'])

r1 = Range(start=datetime(2021, 5, 22, 22, 23, 00),
           end=datetime(2021, 5, 23, 2, 1, 2))
r2 = Range(start=datetime(2021, 5, 23, 1, 0, 00),
           end=datetime(2021, 5, 23, 2, 0, 00))
latest_start = max(r1.start, r2.start)
earliest_end = min(r1.end, r2.end)
delta = (earliest_end - latest_start).seconds
overlap = max(0, delta)
print(overlap)

Can it be done with a simpler method?

A: Based on the answer: https://stackoverflow.com/a/46992092/14265469
The condition if (r1.start <= r2.end) and (r2.start <= r1.end): works surprisingly well:
from datetime import datetime
from collections import namedtuple

Range = namedtuple('Range', ['start', 'end'])

r1 = Range(start=datetime(2021, 5, 22, 22, 23, 20),
             end=datetime(2021, 5, 22, 22, 23, 55))
r2 = Range(start=datetime(2021, 5, 22, 22, 23,  0),
             end=datetime(2021, 5, 22, 22, 23, 25))

delta = "No overlapping"

if (r1.start <= r2.end) and (r2.start <= r1.end):
    latest_start = max(r1.start, r2.start)
    earliest_end = min(r1.end, r2.end)
    delta = (earliest_end - latest_start).seconds

print(delta) # 5


text:
Q: Spring JPA nested Exception: detached entity passed to persist I tried almost all what I could find here in SO, and another sites tutorials about creating an One to One Relationship with Hibernate.
So, I have two models, here are the last modifications, like for example the @MapsId annotation I also removed in previous test.
Usuario:
@Entity
@Table(name="usuarios")
@JsonIdentityInfo(
          generator = ObjectIdGenerators.PropertyGenerator.class,
          property = "id")
public class Usuario {
    @Id
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="usuarios_id_seq")
    @SequenceGenerator(name="usuarios_id_seq", sequenceName="usuarios_id_seq", allocationSize=1)
    @Column(name="id")
    private Long id;

    @ManyToOne
    @JoinTable(name="roles_usuarios", joinColumns={@JoinColumn(name="usuarios_id", referencedColumnName="id")}, inverseJoinColumns={@JoinColumn(name="roles_id", referencedColumnName="id")})
    private Rol rol;

    @OneToOne(cascade = CascadeType.ALL, mappedBy="usuario")
    private Cliente cliente;

Cliente:
@Entity
@Table(name="clientes")
@JsonIdentityInfo(
          generator = ObjectIdGenerators.PropertyGenerator.class,
          property = "id")
public class Cliente {
    @Id
    //@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="clientes_id_seq")
    //@SequenceGenerator(name="clientes_id_seq", sequenceName="clientes_id_seq", allocationSize=1)
    //@Column(name="id")
    private Long id;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="usuario_id", referencedColumnName="id")
    @MapsId
    private Usuario usuario;

Cliente Controller:
@PostMapping("/")
    public ResponseEntity<Void> postCliente(@RequestBody Cliente cliente, UriComponentsBuilder ucBuilder) {

        if( clienteService.isClienteExist(cliente) ){
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

        clienteService.save(cliente);

        HttpHeaders headers = new HttpHeaders();

        headers.setLocation( ucBuilder.path("/{id}").buildAndExpand(cliente.getId()).toUri() );

        return new ResponseEntity<Void>(headers, HttpStatus.CREATED);

    }

Cliente Service:
@Override
    public Cliente save(Cliente cliente) {

        Cliente clt = new Cliente();

        clt.setUsuario(cliente.getUsuario());
        clt.setRazonSocial(cliente.getRazonSocial());
        clt.setRfc(cliente.getRfc());
        clt.setDireccion(cliente.getDireccion());
        clt.setEmail(cliente.getEmail());
        clt.setTelefono(cliente.getTelefono());
        clt.setContacto(cliente.getContacto());
        clt.setTelContacto(cliente.getTelContacto());
        clt.setEmailContacto(cliente.getEmailContacto());

        return clienteRepository.save(clt);

    }

If you notice I also have a many to one relationship with a Rol table which works fine, but when I pass information in the OneToOne which I pass it as a JSON it produces: detached entity passed to persist: com.swargos.entities.Usuario
IDK if I'm missing some annotations, or is that the database is created when running the spring application.

A: I'm providing a somewhat qualified guess, since you didn't include code that shows how you call persist.
The error means that the Usuario instance you are passing to persist() already has a primary key, but it is not a managed entity of that persistence context, see here for Entity Object lifecycle
My guess is that the Usuario instance was loaded by another EntityManager, then json-serialized to the front-end, and then posted back to the backend, and you need to set it on a Cliente (Since you have cascade in both directions it may also be the Cliente  being set on the Usuario). Every time an entity has been loaded in one Persistence Context, and you want to save it in another you must either call em.merge() or you must call em.find() to load it into it (and then set the changes).
JPA is not magic, the life-cycle of the Entities and the Persistence Context which manage them is well defined, and unless the developer understands how these mechanisms work, a lot of time will be wasted trying to work against the framework.
Also @MapsId should only be used if Cliente used an @EmbeddedId for it primary key, which does not seem to be the case.


text:
Q: What should be a fair amount of time in an interview before rejecting a candidate? As a panelist for technical interviews, you often come across candidates who have all the requried educational qualifications, skill sets and experience level on resumes, but struggle to answer even the most basic questions.
Ideally, technical interviews should try to check different aspects of a candidate and test them on various skills. So, if the candidate falters on one aspect, one should test the other ones before coming to a conclusion. But often, if a candidates falters on the first few questions, the red flag rises up pretty quickly.
What in your opinion should be the bare minimum time spent with a candidate before making a fair accessment of his/her skills and suitability for the job?

A: Try not to make any final judgements until the end of the interview. They may start off rough but have some great answers at the end.
Obvious exceptions would be if they're stark raving mad or something like that...

Update:
I suppose if they obviously disqualify themselves by demonstrating total lack of qualifications with nothing to compensate, that could also be a good time to end the interview. Example:

    interviewer: How long have you worked with .NET?
    candidate: I've actually never worked in .NET.
    interviewer: Um, you realize this is a .NET developer position?
    candidate: Yes.
    interviewer: ...Do you have experience with anything .NET-like?
    candidate: not really, no.
    [goodbyes, etc...]

A: Short answer: 1 hour.
We have a standard 1 hour in-person technical interview (which comes after they've passed two phone screens) that we use to start off the interview day. If they don't pass that, we don't continue with the personality/culture/lunch portions of the interview - there's no point in wasting the interviewee's time or ours if they aren't a technical fit.
Technically speaking, if they can't answer the first question in the tech interview (a very, very simple programming problem on the whiteboard), then the rest of the interview is (probably) pointless. But the hour is scheduled out anyway, so I always have them go through the full set of questions. On very rare occasions, the person will end up recovering from a bad start and do really well on the later questions, and even come back and re-answer the early questions correctly. Those occasions make up for a few lost hours.

A: I know seems redundant, but, What do you mean by "Basic Questions"?
By example, "Write a recursive function example" , "Write a mutual/indirect recursive function example" may be a "Basic Programming Question".
I have been applied both, and failed the 2nd. one, the first time.
It's also happen that you may want a C# programmer, you find a Java programmer, and call him for an interview, and when you do "C# Basic Questions", the candidate may failed.
So you may take in consideration, that skilled people, may fail some "Basic Questions", so it's better to say "How many Basic Questions ?" instead of "How much time applying Basic Questions" ;-)

A: Have a telephone interview first
This would save everyone a lot of time and it is very easy to ascertain pretty much the same stuff that you'd reject them for in a face-to-face interview.
It is much easier to tell someone over the phone "thanks for your time, bye" when you realize that they're unsuitable compared to having to show them out of the building, sign them out at reception, possibly arrange a taxi and generally hang about in order to be polite.
If your recruitment process consists of shortlisting CVs/resumes and then getting the candidates in for a face-to-face interview first, then it might be time to talk to management about updating procedures.
If, while on the telephone, you need them to talk through code, then email them a code snippet and ask them to explain it or ask them to talk you through some of their own code.
After filtering out by phone, the suitability of the candidates that come in for a face-to-face interview is much higher. I've found that rejections at this stage usually comes down to a deeper issue that would only surface in a face-to-face interview rather than "they can't program".

A: Try to look at your candidates objectively until the end. What did they answer? What did they have trouble with?
Depending on the position they are applying for, try to keep the 'clever' questions to a minimum. If his job will require him to build reports from a DB (a junior position), don't throw him questions that require advanced knowledge of math.
Sometimes it's about hiring the ones who show passion and willingness to learn.

A: If they fail fast, give them long enough that you can give them honest and candid feedback on why they failed. In the first 5 minutes, you might know by induction that there is a high probability that they are going to fail all your technical questions. Ask them those questions anyway. When they have missed 2 or 3 questions, you can terminate the interview, by giving them some concrete feedback. Examples:
We are looking for someone with deeper knowledge of data structures and algorithms. It would be worthwhile for you to review [sorting algorithms|dynamic programming|trees]
We are looking for someone with deeper knowledge of [Python|Java|SQL]. The person we will hire will need to understand [List comprehensions|Generics|Different join types]
It seems like you could improve on your [topic] skills. I would recommend [relevant book] if you're interested.
The key here is not wasting their time. Dragging an interview on too long is an obvious wast of time. Cutting it to short is a less obvious waste of their time. They've made the effort of going through your preinterview process (you do phone screens, right) and taken time to meet with you, so you owe them something as a consolation prize if they don't get the job.
Finally, I'll say, be gentle but firm when delivering the bad news. And be prepared for a wide variety of responses.

A: In my experience, 20 minutes is enough for them to put their foot in their mouth.  I've been on both sides of this.
The good thing about dragging it out with a few more questions than you feel are necessary, is that they will know they aren't appropriate for the position.
For example, if you say "implement an example of polymorphism on the white board", and they say "ummm...Polly who?", they won't go away saying "I wasn't hired because I'm [insert race/age/sex/etc here]".  They will know they are unqualified.
It also helps them know what their deficiencies are, so they can further their own careers (probably not your goal, but it is a side effect I thought I should mention).

A: I think one hour is just about fair enough. Because if you make it too short it feels like a waste of time for both people, I mean sometimes people do have a rough start, but if they are going on in an hour and still doing bad......well then you know it's time.

A: I was once rejected in an interview in under 10 minutes. The interviewer was candid enough to mention that he did not find me to be a good fit.
In retrospect I thank him for that. The company ultimately hired a Physics grad for the job, I had computer science.
If you are a panelist and you know that what you are looking for isn't in this candidate, be upfront about it in a non-offending way. Dragging on a game where either parties are set to lose is a pretty bad place to be in. You don't need an hour to decide this, but don't rush into a decision either. Checking responses to a few basic questions should be good enough.
It can be much more damaging to a candidate's morale if he or she is rejected after 8 rounds, than after a single one.

A: Depends upon how the interview process has been structured.
If you are on a phone screen with someone and they are having problems, then maybe just switch over to easier questions or give them one more before wrapping things up and saying you will be in touch. These generally aren't expected to run long so you have the advantage of being able to end it gracefully without anyone feeling like they have been flatly rejected.
If you are conducting face to face interviews things get a bit trickier as you have to make sure your time isn't wasted as well as the candidates since they may report back on their impressions of the interview which might turn off another candidate that you may want. If you have a day long interview scheduled with multiple people, then at the lunch break time could be a good time as it will give some of the interviewers time to touch base and give their early impressions. If the candidate knows ahead of time that you may end things after lunch then they shouldn't take things too hard and if you pay for their lunch it will smooth things over quite a bit.
If you have less then a day worth of interviews lined up (i.e. before lunch or after lunch) then it really depends upon how they are doing during the interviewing process and what positions you have open. If someone is interviewing for a mid-level position but you have a junior position open an they seem like a good over all fit they might still accept a job offer if you tender one in which case it might make sense to continue with the interview but adjust the questions.
If they are doing poorly due to technical issues then Brandon DuRette's answer raises a good point in which you should just be honest and tell them what the short coming is. Most developers will appreciate this as they know where their weaknesses are now and can focus on improving as opposed to just an early end which leaves you wondering what you did wrong. To add to this a bit though, if you are using some sort of white board question, just show them the sort of answer you were looking for or explain it real quick before they go. This is one of those things that some developers will really appreciate so they can see how off target they were during the process.
If they are doing poorly due to personality conflicts then things are going to be a bit tougher as it can cause hard feelings depending upon how it is done and what is said. This is an area where having someone coordinating the whole interview process can help as that person could be responsible for letting the candidate know if they got the thumbs down from someone. Likewise, you might want to talk to someone in human resources for advice here because just saying you don't think the candidate would fit in with the company culture could leave the wrong impression if done the wrong way.

A: I usually start with a short hands on test (5-10 minutes) writing some simple code, and talk to the candidate a bit more in depth about the projects he was involved in, to see if he can express himself in other ways than writing code. It usually takes between 20 minutes (for unqualified candidates) and an 1-1.5 hours (for good candidates).
I found an almost 1 to 1 correlation between a candidates ability to handle the code writing test, to his ability to express himself later on, so I usually make the decision whether to continue the interview very quickly.


text:
Q: Are starters guaranteed perfect IVs? So I've been playing Pokemon Lets Go Eevee for a while now, and I unlocked the IV checker. I checked my starter Eevee's IVs and all of the stats say best on it. Am I guaranteed perfect IVs on my starter or am I just really lucky?

A: The starters in the Let's Go series are guaranteed perfect IVs. According to this guide, it's hardcoded as such in the game code, and the perfect IVs is also confirmed on Serebii.
In addition to having perfect IVs, the starters also have higher base stats compared to others in their species:

*

*Pikachu's base stats are 430 as opposed to 320

*Eevee's base stats are 435 are opposed to 325


text:
Q: Can I hide 1 column only in the dispform of a list for users which are not in the administrators group? I have a Sharepoint 2013 portal. I have a list with 10 columns in the content type. 1 of the 10 columns I would like to hide or set readonly if the user is not in the administrator group. Is this possible? If there is a Gui solution please let me know, otherwise other programmaticaly or js also welcome.

A: you could try this http://spcolumnpermission.codeplex.com/
I´ve tested it on SharePoint Foundation 2010, not on SharePoint 2013


text:
Q: Can ff object do this ff_object %in% ff_object? I have two ff objects A and B (from package ff), all integer list
   A has 1656644 rows while B hase 202897 rows
   I want to get vector C <- A %in% B

But  C = logical(0)
Is there any way do %in% operations fast with two ff objects

A: use match() , %in% is the binary version of match().


text:
Q: Check a Checkbox if it is not checked in Selenium Python I do have the Below Page Source:
1. <li_ngcontent-shv-c123 mat-menu-item role="presentation" class="mat-focus-indicator dropdown-item mat-menu-item ng-star-inserted" tabindex="0" aria-disabled="false">
2. <mat-checkbox_ngcontent-shv-c123 class= "mat-checkbox example-margin mat-accent _mat-animation-noopable" id="53oo32be-6855-4yt4-965d-y71078b642">
3.
4.
.
5. <input type="checkbox" class="mat-checkbox-input cdk-visually-hidden" id="53oo32be-6855-4yt4-965d-y71078b642-input" tabindex="0" value="53oo32be-6855-4yt4-965d-y71078b642" name="Item List" aria-checked="true">
6.

7.

8.

9.

10.

11.

12.

13. <svg version="1.1" focusable="false" viewBox="0 0 31 31" xml:space="preserve" class="mat-checkbox-checkmark">
14.  <path fill="none" stroke="white" d="M2.1,89.5 9,78.6 3.3,77.1" class="mat-checkbox-checkmark-path">
15. </Path>
16. </svg>

17.

18.

19.

20.
21.  XYZ Element
22.
23. </mat-checkbox>

24.

25.

In this Item List (Line 5) is an Drop Down List having finite number of elements with checkboxes.
What I need to check is for element XYZ Element (Line21) in the drop down list and check the checkbox with it if and only if the checkbox is unchecked.
If the checkbox is already checked leave it as such.
I tried with the below code:
test= "//span[contains(text(),'XYZ Element')]"

try:

driver.finde_element_by_xpath(test).is_selected()
pass

except:
driver.find_element_by_xpath(test).click()

The above code is not yielding the require result.
Is there any alternative way to do this?
Thanks in Advance.

A: use find_elements to see if there's anything in the list, if it is there you can click or check for click like below  :
code :
try:
    if len(driver.find_elements_by_xpath("//span[contains(text(),'XYZ Element')]/../descendant::input")) > 0 :
        print("Element is present")
        if driver.find_element_by_xpath("//span[contains(text(),'XYZ Element')]/../descendant::input").is_selected():
            print("it's already selected")
        else:
            driver.find_element_by_xpath("//span[contains(text(),'XYZ Element')]/../descendant::input").click()
    else:
        print("Element is not present at all")
except:
    print("Check out the code again")
    pass

Update 1 :
to make xyz element variable  :
some_str = "XYZ Element"
driver.find_element_by_xpath(f"//span[contains(text(),'{some_str}')]")


text:
Q: React Typescript types for monaco-editor Having the following code snippet that works fine with React + Javascript:
import React, { useRef } from "react";

import Editor from "@monaco-editor/react";

function App() {
  const editorRef = useRef(null);

  function handleEditorDidMount(editor, monaco) {
    editorRef.current = editor;
  }

  function showValue() {
    alert(editorRef.current?.getValue());
  }

  return (
    <>
      <button onClick={showValue}>Show value</button>
      <Editor
        height="90vh"
        defaultLanguage="javascript"
        defaultValue="// some comment"
        onMount={handleEditorDidMount}
      />
    </>
  );
}

export default App;

Sandbox here.
I need to use it in a React + Typescript app so I have to add types.
What type should be used for editor?
Tried like this:
  function handleEditorDidMount(editor: HTMLInputElement) {
    editorRef?.current = editor;
  }

  function showValue() {
    // eslint-disable-next-line no-alert
    alert(editorRef?.current?.getValue());
  }

For the first method, the error is:
The left-hand side of an assignment expression may not be an optional property access.ts(2779)
const editorRef: React.MutableRefObject<null>

For the second:
Property 'getValue' does not exist on type 'never'.ts(2339)

Any suggestions?

A: *

*import type onMount
import MonacoEditor, { OnMount } from "@monaco-editor/react";

if you hover on onMount:
  type OnMount = (editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => void

*

*use it on handleDidMount:
const handleEditorDidMount:OnMount=(editor) {
editorRef?.current = editor;
}
if you see the type,handleEditorDidMount takes 2 args
const handleEditorDidMount:OnMount=(editor,_monaco) {
    editorRef?.current = editor;
  }

Since you are using OnMount type, args type will be inferred by typescript:
          editor: editor.IStandaloneCodeEditor

A: The returned type of useRef(null) is React.MutableRefObject<null>. But you want typescript to know you're gonna pass an input element to the ref, so you have to explicitily set its type const editorRef = useRef(null) as React.MutableRefObject<null | HTMLInputElement>;
editorRef.current will always be defined, but the type of editorRef.current is now null | HTMLInputElement, because the type of current is the type you pass into the generic of React.MutableRefObject.
Regarding this error.
The left-hand side of an assignment expression may not be an optional property access.ts(2779)
const editorRef: React.MutableRefObject<null>

editorRef.current will always be defined. The value however can be null as you have explicitily typed. So no need for the ?
Knowing this you can adjust your last part of code to
function showValue() {
    // eslint-disable-next-line no-alert
    alert(editorRef.current?.getValue());
}


text:
Q: Migrate failing in laravel 4.2.* I'm trying to write a simple REST API for laravel 4.2. Here is my code:
This is the command to generate two tables:
php artisan migrate:make create_users_table --table=users --create
php artisan migrate:make create_urls_table --table=urls --create

Then I added this code in up section of create_users_table.php:
 $table->increments('id');
 $table->string('username')->unique();
 $table->string('password');
 $table->timestamps();

I added this code in up section of create_urls_table.php:
$table->increments('id');
$table->integer('user_id');
$table->string('url');
$table->string('description');
$table->timestamps();

My db configurations are like this:
'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'read_it_later',
            'username'  => '<username>',
            'password'  => '<password>',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

Then I added this to UserTableSeeder.php in seeds folder in database folder:
<?php

class UserTableSeeder extends Seeder {

    public function run()
    {
        DB::table('users')->delete();

        User::create(array(
            'username' => 'firstuser',
            'password' => Hash::make('first_password')
        ));

        User::create(array(
            'username' => 'seconduser',
            'password' => Hash::make('second_password')
        ));
    }

}

Then I uncommented $this->call('UserTableSeeder') in DatabaseSeeder.php file.
Then I ran this command:
php artisan migrate

And I got the following error:
**************************************
*     Application In Production!     *
**************************************

Do you really wish to run this command? y
Migration table created successfully.

  [Illuminate\Database\QueryException]
  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'read_it_later.users' doesn't exist (SQL: alter table `users` add `id` int unsigned not
  null auto_increment primary key, add `username` varchar(255) not null, add `password` varchar(255) not null, add `created_at` timestamp default 0
  not null, add `updated_at` timestamp default 0 not null)

  [PDOException]
  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'read_it_later.users' doesn't exist

migrate [--bench[="..."]] [--database[="..."]] [--force] [--path[="..."]] [--package[="..."]] [--pretend] [--seed]

How can I fix this error?

A: I just found out that I was using wrong command to generate migration tables.
I used the following commands:
php artisan migrate:make create_users_table --create=users
php artisan migrate:make create_urls_table --create=urls

Then I added my code to those files and tried these commands:
php artisan migrate
php artisan db:seed

And it worked


text:
Q: Setting location of controls in viewDidLoad I'm trying to initialize the location of a control based on portrait/landscape in viewDidLoad, as below.  It seems that the desired code is firing, but when my application starts the label appears in neither location, just the place where it was dropped in IB.
Am I forgetting a step, or does this have to happen somewhere else?
Thanks for any thoughts.
int w = self.UILabel_Label.frame.size.width;
int h = self.UILabel_Label.frame.size.height;

m_LabelFrame_Portrait = CGRectMake(10,50, w, h);
m_LabelFrame_Landscape = CGRectMake(600,50, w, h);

//self.UILabel_Label.frame = CGRectMake(200,200, w, h);

if (m_OrientationLayoutMode == OLM_Portrait)
{
    self.UILabel_Label.frame = m_LabelFrame_Portrait;
}
else
{
    self.UILabel_Label.frame = m_LabelFrame_Landscape;
}


text:
Q: What are the benefits of replacing an interface argument with a type parameter? Defining an interface type to type parameters like this:
func CallByteWriterGen[W io.ByteWriter](w W, bytes []byte) {
  _ = w.WriteByte(bytes[0])
}

...causes extra pointer dereference through dictionary (passed using AX):
MOVQ 0x10(AX), DX // <-- extra pointer dereference
MOVQ 0x18(DX), DX
MOVZX 0(CX), CX
MOVQ BX, AX
MOVL CX, BX
CALL DX

What might be the benefits that cannot be achieved by simply using an interface argument, like this:
func CallByteWriter(w io.ByteWriter, bytes []byte) {
  _ = w.WriteByte(bytes[0])
}

A: The interface version is idiomatic, not the type parameter one - use an interface where an interface is called for.
See the When to use Generics blog post for additional information and details, specifically the section Don't replace interface types with type parameters:

For example, it might be tempting to change the first function
signature here, which uses just an interface type, into the second
version, which uses a type parameter.
func ReadSome(r io.Reader) ([]byte, error)
func ReadSome[T io.Reader](r T) ([]byte, error)
Don't make that kind of change. Omitting the type parameter makes the
function easier to write, easier to read, and the execution time will
likely be the same.

A: In general don't replace interfaces with type parameters when the interface is used to abstract behavior and the dynamic types are actually irrelevant within the function body.
As for usage, it may not change much at call site. Either way you can pass into the function argument only something that implements io.ByteWriter, just like you do without type parameters.
The differences become relevant when the dynamic types of the interface are interesting. The static type of an io.ByteWriter argument is just io.ByteWriter, and to retrieve the dynamic type you have to use an assertion w.(*bytes.Buffer) which may panic, or a type switch; whereas with type parameters, the function deals directly with the concrete type W.
There's at least two use cases for this. Within the function body:

*

*you happen to declare new values of those concrete types

*you happen to do comparisons

io.ByteWriter is a bad example in either case, because you are going to use that one precisely for abstracting some behavior rather than for its dynamic type, so that's not a good candidate for type parametrization.
There may be other situations like pre-Go1.18 "generic" code based on interface{}, or perhaps protobuffers, where proto.Message is an interface, factory patterns, unit test helpers, etc. where the dynamic types are interesting.
Then, clumsy occurrences of reflect.New or reflect.Zero to create new values can be replaced by new(T) or var x T. Demo:
func newFrom(v Setter) Setter {
    return reflect.Zero(reflect.TypeOf(v)).Interface().(Setter)
}

vs.
func newFrom[T Setter](v T) T {
    return *new(T)
}

About comparisons, interfaces do support equality operators == and != natively, but the comparison may just panic if the dynamic values are not comparable. With type parameters instead the comparison between method-only interfaces simply won't compile unless you explicitly add comparable to the constraint, thus improving code safety.
// compiles, might panic
func equal(v, w Setter) bool {
    return v == w
}

vs.
// doesn't compile, must add comparable explicitly
func equal[T Setter](v, w T) bool {
    return v == w
}

This doesn't mean type parameters are always appropriate for these use cases either, but you may consider them as candidates.


text:
Q: monetdb - Row count is increasing in the target table I am loading data from SQL server DB table to MonetDB table using spark job. My source table has 100000 records. I am directly moving these records into monetdb table and no filter and joins at all. But once job completed I am seeing 279997 records in Target monetdb table. It has been observed , records are getting duplicated in the target table.
We have created simple etl to move one table to another table, not sure what went wrong. Please can someone help us on this.
Regards,
NarsimhaReddy

A: This does not ring a bell for me. Most likely would be if there is stale data in your table from an earlier attempt.
Which version of MonetDB are you using? And which library does your ETL tool use to access MonetDB (I don't know anything about Spark).
Maybe you can investigate

*

*whether the table indeed started out empty;

*whether de additional rows are duplicates of existing source rows or if they are simply garbage;

*maybe you can investigate exactly which statements your ETL tool executes, table sys.queue might be helpful there;

*and try to recreate them in a standalone sql script (to be executed through mclient) which reproduces the issue;

*whether the ETL correctly detects any errors that might be returned by the statements it executes, or that it may have swallowed a helpful error message;

*whether the ETL tool can be made to log somewhere the number of rows it believes to have created in MonetDB.

I'm sorry I cannot give you a more specific answer, this is going to require some digging.


text:
Q: Taxonomy Page in Wordpress I have created a custom taxonomy in WordPress with a custom template, below is dummy link
http://localhost/projects/countries/canada/ (For this I have used taxonomy-country.php)
This is working fine, but when someone visits the link
http://localhost/projects/countries (For this I have created category.php or archive.php, but nor is working)
Page Not found error comes, is there any way to may this work, I need a custom template for this.??
Below is my code for Custom Taxonomy
 $country_labels = array(
            'name' => __('Country', 'projects'),
            'singular_name' => __('Country', 'projects'),
            'search_items' => __('Search Country', 'projects'),
            'all_items' => __('All Country', 'projects'),
            'parent_item' => __('Parent Country', 'projects'),
            'parent_item_colon' =>__('Parent Country:', 'projects'),
            'edit_item' => __('Edit Country', 'projects'),
            'update_item' => __('Update Country', 'projects'),
            'add_new_item' => __('Add New Country', 'projects'),
            'new_item_name' => __('Country Name', 'projects'),
            'menu_name' => __('Country', 'projects')
        );

        $country_args = array(
            'hierarchical'      => true,
            'labels'            => $country_labels,
            'show_ui'           => true,
            'show_admin_column' => true,
            'query_var'         => true,
            'rewrite'           => array( 'slug' => __('countries', 'projects') ),
        );
        register_taxonomy( 'country', 'projects', $country_args );

A: I got the answer, we can create a page with category name and create a template for same.
Like, we can create a page countries, which worked for me..


text:
Q: Is it possible to place custom metadata in the offset Number in a scheduled path in a flow? I have a question about whether it is possible to place a variable in the offset number in the scheduled path? A Variable that can be modified outside the flow to avoid stopping the flow and modified it when is in production? I use this schedule path to send an email alert 31 days before the end working date. Can it be performed with apex? Or practically that requirement cannot be accomplished?

A: You're thinking about this from the wrong direction.
You can create a new Custom Field (Formula), and specify the metadata:
(Warning End Date): Returns Date
EndWorkingDate__c - $CustomMetadata.TimeDelay__mdt.DefaultValue.Offset__c

Then, in your Flow, specify (0 Days Before) (Warning_End_Date__c). A word of caution, though; records that are saved before the offset value are changed will not honor the new date unless they are edited before the scheduled path executes.


text:
Q: Nodejs https Repsponse ghost characters I'm trying to get data from an API, but it somehow gets weird data, I've tried many things and i don't know what else I could do.
const https = require("https");
https.get(`https://drednot.io/api/scoreboard?count=1000&offset_score=-1`, (resp) => {
    let data = '';
    resp.on('data', (chunk) => {
        data += chunk;
    });
    resp.on('end', async () => {
        try {
            //console.log(data)
            let result = JSON.parse(data.toString())["ships"];
            console.log(result)
        } catch (err) {
            console.log("Error: " + err.message);
        }
    });
}).on("error", async (err) => {
    console.log("Error: " + err.message);
});

both the raw data and the parsed data have some weird things inside them, for example, a substring in the raw data
{"sh         ip_name":"⚜ Full Farm Barn","hex_code":"20DE1","color":9079434,"score":2395790}

or a part in the parsed data (different because above isn't inside the parsed for some reason)
{
    ship_name: '�������� '        ,
    hex_code: '78AD5F',
    color: 815352,
    score: 25915190
}

Edit: the � characters are parsed correctly, they just cant be displayed by the terminal which isn't the problem.
Full code to see what i mean, it should sometimes print a change but it prints changes all the time which is incorrect:
const https = require("https");

function sleep(ms) {
    if (ms <= 0) {

    } else {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

var shipData = {};
class Syncer {
    finished;
    round_fetch;
    round_error;

    constructor() {
        this.finished = true;
        this.round_fetch = 0;
        this.round_error = 0;
    }

    fetch_data(offset_score, next_request, recursion_deep) {
        //console.log(offset_score)
        this.round_fetch += 1;

        https.get(`https://drednot.io/api/scoreboard?count=1000&offset_score=${offset_score.toString()}`, (resp) => {
            let chunks = [];
            resp.on('data', (chunk) => {
                chunks.push(chunk);
            });

            resp.on('end', async () => {
                let end = Date.now();
                try {
                    //console.log(data)
                    let data = Buffer.concat(chunks).toString('utf8');
                    //console.log(data)
                    console.log(`Index of hexcode: ${data.search("32FF2B")}`)
                    let result = JSON.parse(data)["ships"];
                    data = null;
                    let next_offset = result[result.length - 1].score;
                    if (next_offset === offset_score) {
                        next_offset -= 1;
                    }
                    if (next_offset < 10000000) {
                        next_offset = -1;
                    }
                    if (next_offset !== -1) {
                        if (end < next_request) {
                            await sleep(next_request - end);
                        }
                        this.fetch_data(next_offset, Date.now() + 100, recursion_deep + 1);
                    } else {
                        this.finished = true;
                    }
                    next_offset = null;
                    let rank = (recursion_deep * 1000) + 1;

                    for (let ship of result) {
                        await sleep(1);
                        ship["rank"] = rank;
                        if (ship.hex_code === "32FF2B") {
                            console.log(`Parsed ship: ${ship}`)
                        }
                        if (shipData[ship.hex_code] !== undefined) {
                            this.checkChange(shipData[ship.hex_code], ship);
                        }
                        shipData[ship.hex_code] = ship;
                    }
                    result = null;
                    offset_score = null;
                } catch (err) {
                    console.log("Error: " + err.message);
                    await sleep(1000);
                    this.round_error += 1;
                    await this.fetch_data(offset_score, Date.now() + 100, recursion_deep);
                }
            });
        }).on("error", async (err) => {
            console.log("Error: " + err.message);
            await sleep(1000);
            this.round_error += 1;
            await this.fetch_data(offset_score, Date.now() + 100, recursion_deep);
        });
    }
    checkChange(oldShip, newShip) {

        // CHECK IF OLD NAME ISNT THE SAME AS THE NEW ONE, IF SO PRINT CHANGE
        if (oldShip.ship_name !== newShip.ship_name) {
            console.log(`${oldShip.ship_name} | ${newShip.ship_name}`)
        }
    }

    async launch() {
        //this.postChanges();
        while (true) {
            try {
                if (this.finished) {
                    this.finished = false;
                    console.log(`Fetch all ships, fetch ${this.round_fetch}, error ${this.round_error}`);
                    this.round_error = 0;
                    this.round_fetch = 0;
                    await sleep(100);
                    this.fetch_data(-1, Date.now() + 100, 0);
                }
                await sleep(1000);
            } catch (e) {
                console.log(e);
            }
        }
    }
}

function launch() {
    // Start the servers
    var synchro = new Syncer();
    synchro.launch()
}

launch()

A: The problem could be that multi-byte sequences have arrived split into different chunks, and it doesn't make sense to turn any single chunk into a string by itself because some of the bytes of a character is in one chunk and the other bytes of that character are in the next chunk.
To get around this, just accumulate the incoming data chunks by keeping the the buffers they originally arrived in, and concatenate all the buffers (chunks) into a single buffer before turning them into a string.
Instead of data = '' do chunks = [], and instead of data += chunk; do chunks.push(chunk) and then in your 'end' handler, do data = Buffers.concat(chunks).toString('utf8').
    let chunks = [];
    resp.on('data', (chunk) => {
        chunks.push(chunk);
    });
    resp.on('end', async () => {
        let data = Buffer.concat(chunks).toString('utf8');
        try {
            //console.log(data)
            let result = JSON.parse(data.toString())["ships"];
            console.log(result)
        } catch (err) {
            console.log("Error: " + err.message);
        }
    });


text:
Q: How to open a port or all ports for Google Cloud Compute Engine I have an IOTA IRI instance running on a VM in GCP compute engine.
The instance is using port 14265 to communicate, and checking it locally by doing something like curl http://localhost:14265 does respond.
I want to open this port to outside of the vm, so I set up a static IP, and a firewall rule to allow tcp:14265; udp:14265 and still the port is not responding.
I even tried allowing all by doing:

But no luck. There is no port open except for 22 for ssh (looked in a port scanner)
I am aware it feels like a duplicate of How to open a specific port such as 9090 in Google Compute Engine, but I did try those answers and they didn't solve it for me.
EDIT:
Running the two commands I was asked to run in an answer:
D:\Downloads> gcloud compute networks list
NAME     MODE  IPV4_RANGE  GATEWAY_IPV4
default  auto

D:\Downloads>gcloud compute instances describe instance-1 --zone europe-west1-b
canIpForward: false
cpuPlatform: Intel Sandy Bridge
creationTimestamp: '2017-08-22T09:33:12.240-07:00'
description: ''
disks:
- autoDelete: true
  boot: true
  deviceName: instance-1
  index: 0
  interface: SCSI
  kind: compute#attachedDisk
  licenses:
  - https://www.googleapis.com/compute/v1/projects/ubuntu-os-cloud/global/licenses/ubuntu-1604-xenial
  mode: READ_WRITE
  source: https://www.googleapis.com/compute/v1/projects/iota-177616/zones/europe-west1-b/disks/instance-1
  type: PERSISTENT
id: '8895209582493819432'
kind: compute#instance
labelFingerprint: 42WmSpB8rSM=
machineType: https://www.googleapis.com/compute/v1/projects/iota-177616/zones/europe-west1-b/machineTypes/f1-micro
metadata:
  fingerprint: -pkE3KaIzLU=
  kind: compute#metadata
name: instance-1
networkInterfaces:
- accessConfigs:
  - kind: compute#accessConfig
    name: External NAT
    natIP: 35.187.9.204
    type: ONE_TO_ONE_NAT
  kind: compute#networkInterface
  name: nic0
  network: https://www.googleapis.com/compute/v1/projects/iota-177616/global/networks/default
  networkIP: 10.132.0.2
  subnetwork: https://www.googleapis.com/compute/v1/projects/iota-177616/regions/europe-west1/subnetworks/default
scheduling:
  automaticRestart: true
  onHostMaintenance: MIGRATE
  preemptible: false
selfLink: https://www.googleapis.com/compute/v1/projects/iota-177616/zones/europe-west1-b/instances/instance-1
serviceAccounts:
- email: 59105716861-compute@developer.gserviceaccount.com
  scopes:
  - https://www.googleapis.com/auth/devstorage.read_only
  - https://www.googleapis.com/auth/logging.write
  - https://www.googleapis.com/auth/monitoring.write
  - https://www.googleapis.com/auth/servicecontrol
  - https://www.googleapis.com/auth/service.management.readonly
  - https://www.googleapis.com/auth/trace.append
startRestricted: false
status: RUNNING
tags:
  fingerprint: 6smc4R4d39I=
  items:
  - http-server
  - https-server
zone: https://www.googleapis.com/compute/v1/projects/iota-177616/zones/europe-west1-b

A: It is difficult to give an exact answer without some diagnostics.
It could be that the rules are being created for a network and your instance is in a different network.
So, first of all, check the networks available in your project:
gcloud compute networks list

Secondly, check in which network your instance is located:
gcloud compute instances describe [Instance Name] --zone [Zone]

Check the firewall rules being applied to the network used by your instance:
gcloud compute firewall-rules list

Also check that the target tags are the appropriate ones.

As you can see there are not tags applied to the VM, although the rules should apply if you target it to all vm's itis a good practice to do it.

*

*Edit your VM and add a tag(Ex. frontserver)
gcloud compute instances add-tags [INSTANCE NAME] --zone [ZONE] --tags frontserver

*Now create the firewall rule and apply it to the tag created
gcloud beta compute firewall-rules create [NAME_OF_THE_RULE] --direction=INGRESS --priority=1000 --network=default --allow=all --source-ranges=0.0.0.0/0 --target-tags=frontserver
Check this it it works you can run an update to restrict it to the desired ports and protocols and your source IP
gcloud beta compute firewall-rules update [NAME_OF_THE_RULE] --direction=INGRESS --priority=1000 --network=default --allow=tcp:--source-ranges=[your_source_IP] --target-tags=frontserver

Hope this helps, further info is found here with examples


text:
Q: Applying double color transform in AS3 Simply put, I would like to set several movieclips to different specific colors and then apply a tint over them.
var color1 = new ColorTransform(); color1.color = 0x0000FF;
var color2 = new ColorTransform(); color2.color = 0x00FF00;
var color3 = new ColorTransform(); color3.color = 0xFFFF00;

thing1.transform.colorTransform = color1;
thing2.transform.colorTransform = color2;
thing3.transform.colorTransform = color3;

thing1.transform.colorTransform = new ColorTransform(1, 1, 1, 1, 0, 200, 150, 0);
thing2.transform.colorTransform = new ColorTransform(1, 1, 1, 1, 0, 200, 150, 0);
thing3.transform.colorTransform = new ColorTransform(1, 1, 1, 1, 0, 200, 150, 0);

unfortunately the colortransform resets the value. Any way to keep the value of the first color transform?

A: You should be able to do that with the ColorTransform.concat() function.
var color1 = new ColorTransform(); color1.color = 0x0000FF;
var color2 = new ColorTransform(); color2.color = 0x00FF00;
var color3 = new ColorTransform(); color3.color = 0xFFFF00;

color1.concat( new ColorTransform(1, 1, 1, 1, 0, 200, 150, 0) );
color2.concat( new ColorTransform(1, 1, 1, 1, 0, 200, 150, 0) );
color3.concat( new ColorTransform(1, 1, 1, 1, 0, 200, 150, 0) );

thing1.transform.colorTransform = color1;
thing2.transform.colorTransform = color2;
thing3.transform.colorTransform = color3;

Which essentially is the same as (clamping offset values to 255 using Math.min):
thing1.transform.colorTransform = new ColorTransform(1*1, 1*1, 1*1, 1*1, Math.min(0x00+0, 0xFF), Math.min(0x00+200, 0xFF), Math.min(0xFF+150, 0xFF), Math.min(0x00+0, 0xFF));
thing2.transform.colorTransform = new ColorTransform(1*1, 1*1, 1*1, 1*1, Math.min(0x00+0, 0xFF), Math.min(0xFF+200, 0xFF), Math.min(0x00+150, 0xFF), Math.min(0x00+0, 0xFF));
thing3.transform.colorTransform = new ColorTransform(1*1, 1*1, 1*1, 1*1, Math.min(0xFF+0, 0xFF), Math.min(0xFF+200, 0xFF), Math.min(0x00+150, 0xFF), Math.min(0x00+0, 0xFF));

Or:
thing1.transform.colorTransform = new ColorTransform(1, 1, 1, 1, 0x00, 0xC8, 0xFF, 0x00);
thing2.transform.colorTransform = new ColorTransform(1, 1, 1, 1, 0x00, 0xFF, 0x96, 0x00);
thing3.transform.colorTransform = new ColorTransform(1, 1, 1, 1, 0xFF, 0xFF, 0x96, 0x00);

A: I've found a solution to this problem.
If I set an object to a color
var color1 = new ColorTransform(); color1.color = 0x0000FF;
thing1.transform.colorTransform = color1;

I can then edit the blue and green values as so to get my desired tint
color1.blueOffset+=200;
color1.greenOffset+=150;

And then use colortransform on the object to set the new color
thing1.transform.colorTransform = color1;


text:
Q: Android, updating the recyclerview UI to reflect time in a format I prefer(Kotlin)
The image above is a New's application, to display the news I am using a recyclerview, however I can't seem to get the time format right. For example, I want the time to be shown in minutes if it is less than 60 minutes and in hours if it is more than or equal to 60 minutes.
Here is the code in my recyclerview adapter.
            val currentTimeInHours = Instant.now().atZone(ZoneId.of("Asia/Kolkata"))

        val newsTimeInHours = Instant.parse(time).atZone(ZoneId.of("Asia/Kolkata"))

        val hoursDifference = Duration.between(currentTimeInHours, newsTimeInHours)

val hoursAgos = if(hoursDifference.toMinutes() < 60){
                hoursDifference.toMinutes().toString().substring(1) + " minutes ago"
            }else{
             hoursDifference.toHours().toString().substring(1) + " hour ago"
            }

//Assigning the logic to the textview
holder.tvPublishedAt.text = hoursAgos

All of these code is located in the onbindviewholder method within the adapter.


text:
Q: How can I link PDCurses using gcc on Windows? Recently I installed PDCurses 3.6 (latest version) on my HP Pavilion laptop with Windows 7 Home Premium. Also I have installed MinGW-w64 (latest version too).
Well, I started to learn how to use the curses mode here, and downloaded their example codes (ncurses_programs.tar.gz); at this point all was OK.
After unzipping the programs, I wanted to make use of the Makefile to have all the .exes already made. Here is the problem.
I ran cmd.exe, moved to the folder where the programs are, and then typed mingw32-make -f Makefile. This is the following process:
mingw32-make[1]: Entering directory 'C:/.../ncurses_programs/JustForFun'
gcc -o hanoi.o -c hanoi.c

/* throws some warnings */

gcc -o ../demo/exe/hanoi hanoi.o -lncurses
C:/MinGW/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64w64-mingw32/bin/ld.exe: cannot find -lncurses
collect2.exe: error: ld returned 1 exit status
mingw32-make[1]: *** [Makefile:20: ../demo/exe/hanoi] Error 1
rm hanoi.o
mingw32-make[1]: Leaving directory 'C:/.../ncurses_programs/JustForFun'
mingw32-make: *** [Makefile:4: all] Error 2

Well, you surely are thinking "man, it's trying to link ncurses and you have pdcurses because you are on Windows". Yes, I know it. That's why I edited the Makefile, typing LIBS=-lpdcurses instead LIBS=-lncurses, but it doesn't find it neither.
I know where pdcurses.a is, so I tried to compile a simple program (print 'Hello World!') by console like this:
gcc -LC:\PDCurses\wincon -lpdcurses -o myprogram myprogram.c

I still getting:
C:/MinGW/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find -lpdcurses
collect2.exe: error: ld returned 1 exit status

I don't know what else can I do...
Thank you beforehand!

A: The -lname linkage of gcc is passed through to the linker, ld. It
instructs the linker to search for either of the files libname.so (a shared library)
or libname.a (a static library), first in the specified linker search directories
(-Ldir), in their specified order, and then its default search directories,
in their configured order. When either of those files is found in one of the search
directories the linker stops searching and inputs the library to the linkage. If it
finds both of them in the same directory then by default it chooses libname.so.
On Windows ports of GCC, name.lib (static library) and name.dll (dynamic library)
will probably also satisfy the -lname option.
Given that you have the PDCurses static library pdcurses.a installed in
-LC:\PDCurses\wincon, the linkage:
gcc -LC:\PDCurses\wincon -lpdcurses -o myprogram myprogram.c

fails with:
cannot find -lpdcurses

because no file called libpdcurses.a, libpdcurses.so, pdcurses.lib, or
pdcurses.dll exists in C:\PDCurses\wincon.
Renaming pdcurses.a to libpdcurses.a in that directory will remedy this failure.
If you don't want to rename it, then you can replace the linkage option -lpdcurses
with -l:pdcurses.a. The option -l:name directs the the linker to search for
a file called precisely name.
However, you will still fail link your test program with
either:
gcc -LC:\PDCurses\wincon -lpdcurses -o myprogram myprogram.c

or:
gcc -LC:\PDCurses\wincon -l:pdcurses.a -o myprogram myprogram.c

The linkage will fail with undefined reference errors to any pdcurses symbols
(functions or variables) that you refer to in myprogram.c. (If you don't actually refer to any such symbols in myprogram.c then it will not fail, but only because the library is redundant).
To correct this error (which may not effect your makefile, which we can't see),
instead run:
gcc -o myprogram myprogram.c -LC:\PDCurses\wincon -lpdcurses

or similary if you choose -l:pdcurses.a.
To understand this, see Your linkage consumes libraries before the object files that refer to them


text:
Q: Setting stylus variables programmatically I'm working on a project where one stylus file is supposed to spit out a different CSS based on a variable that is defined in a Javascript code. I found the Javascript API but can't figure out a clean and nice way to set a variable programatically.
Anyone knows how I can set a color variable in Stylus externally using Node.js and get a CSS back?

A: Something like:
var stylus = require('stylus');

stylus('body\n  color: some-color')
  .define('some-color', new stylus.nodes.RGBA(128, 128, 128, 1)) // #808080
  .render(function(err, css) {
    if (err) throw err;
    console.log(css);
  });

See lib/nodes/rgba.js and lib/nodes/hsla.js.
I guess you can also use json bif for your task.


text:
Q: ruby - possible inefficient algorithm This was my solution to a function that should return the first pair of two prime numbers spaced with a gap of g between the limits m, n if these numbers exist otherwise nil.
This is a kata from codewars.com, it passed the preliminary test. But, When I submit it I receive an error message saying that due to an inefficiency in my algorithm it takes too much time(8000ms+).
Can someone point out to me what exactly is slowing down the code, and how it should be optimized?
require 'prime'

def gap(g, m, n)
  range = (m..n).to_a
  primes = []
  range.each { |num| primes.push(num) if Prime.prime?(num)}

  primes.each_index do |count|
    prv , nxt = primes[count], primes[count+1]
    if !nxt.is_a? Integer
      return nil
    end

    if nxt - prv == g
      return [prv, nxt]
    end
  end
end

A: Try this:
require 'prime'

def gap(g, m, n)
  primes = Prime.each(n).select { |p| p >= m }
  primes[0..-2].zip(primes[1..-1]).find { |a, b| b - a == g }
end

gap(2, 1, 1000)
#=> [3, 5]

gap(6, 1, 1000)
#=> [23, 29]

Prime.each(n).select { |p| p >= m } returns you the list of all primes between m and n. This has a better performance than building an array with all numbers between m and n and the checking each number in this array if it is a prime. It is also worth noting that Prime.each uses the eratosthenes' sieve algorithm as a default.
primes[0..-2].zip(primes[1..-1]) builds an array of each pair. This is not the most efficient way to iterate over each pair in the primes array, but I think it read better than dealing with indexes.
This might be another option:
require 'prime'
require 'set'

def gap(g, m, n)
  primes = Set.new(Prime.each(n).select { |p| p>= m })
  primes.each { |prime| return [prime, prime + g] if primes.include?(prime + g) }
end

the second version doesn't build an new array with all pairs, but instead just checks for each prime if prime + g is included in the primes array too. I use a Set, because it improves include? lookups to O(1) (whereas include? on arrays would be O(n).
I am not sure which version will be faster and it might be worth it to run some benchmarks. The first versions needs more memory, but does less calculations. The performance probably depends on the size of the range.


text:
Q: jQuery iFrame Modal Return Value I applied the modal function I found in this article. It is a jQuery modal that puts the source file in an <iframe> and display as modal. Now, the problem is that I need to return to value to the background page from the modal after the user selected an item.
Here is some jQuery code: (This is were the page is loaded)
var openMyModal = function(source)
{
    modalWindow.windowId = "myModal";
    modalWindow.width = 480;
    modalWindow.height = 405;
    modalWindow.content = "<iframe width='480' height='405' frameborder='0' scrolling='no' allowtransparency='true' src='" + source + "'></iframe>";
    modalWindow.open();
};

Posible code in Modal:
<select name="selItem">
     <option value="item1">Item 1</option>
     <option value="item2">Item 2</option>
     <option value="item3">Item 3</option>
     <option value="item4">Item 4</option>
</select>

<input type="button" id="btnSel" name="btnSel" value="Select" />

There is a button in the modal display which when clicked, it will pass the value to an input text back to the background page then remove the modal.
How can I achieve this? Thank you very much!

A: Possible solution is to add click listener on the button of the model after it opens. here is some code:
modalWindow.open(function()
{
    //callback
    $('#btnSel').on('click', function()
    {
         //do what you need here.
    });
});

Note:
Make sure there is some way to run a callback function like I suggested.
from the documentation you can add your logic in the open option:
var modalWindow = {
    ....
    open:function()
    {
        //your stuff - click listener
    }
};


text:
Q: MERN deploy script bundles on render All my code compiles into dist folder. Client by CopyWebpackPlugin, server by tsc. and it looks like this. HTML sends app.get("*", (req, res) => { res.sendFile(path.join(__dirname, "client", "public", "index.html")); }); For static files i tried app.use("/static", express.static(path.join(__dirname, "client"))); app.use(express.static(path.join(__dirname, "client", "public"))); etc. Add all variants of scripts connection
<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
        <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet" />
        <title>Document</title>

And all my bundle.js files looks like this deployed app. How i suppose to add script bundles? Repo https://github.com/Dimkosyanklg/Cards-Test
Can't figure it out


text:
Q: I have a list of cost values that include "M" and "B" for million and billion. I want to create a new list that displays these values as numbers I'm attempting to convert a list of monetary values which use "B" to mean Billion and "M" to use Million
cost=["1.2M","17B","79M","44.4M"]

I want to create a new list of float values.
The solution I can think of is using a dictionary:
convert={"B":1000000000,"M":1000000}

def updated_cost(cost):

 new_costs=[]

 for c in cost:

  /* do something*/

The area i'm struggling with is trying to figure out how to multiply the dictionary value and how to remove the "B" and "M".

A: Yes, using a dictionary is a great idea!
string = "5M"
value = 0
convert={"B":1000000000,"M":1000000}

for i in convert:
    if i in string:
        value = float(string.replace(i, "")) * convert[i]

print(value)

A: You can also do it without using a dictionary:
cost=["1.2M","17B","79M","44.4M"]
new_costs = []

for elem in cost:
    if 'M' in elem:
        new_costs.append(float(elem[:-1])*1000000)
    elif 'B' in elem:
        new_costs.append(float(elem[:-1]) * 1000000000)

print(new_costs)

Output:
[1200000.0, 17000000000.0, 79000000.0, 44400000.0]

A: Shorter way using a list comprehension:
cost=["1.2M","17B","79M","44.4M"]
newlist = [eval(x.replace("M","*1000000").replace("B","*1000000000")) for x in cost]
print(newlist)


text:
Q: The sample of Google Maps Android API v2 com.example.mapdemo can not find file "R.java" Today I have read the document of Google Maps Android API v2, it said the project of android-sdk\extras\google\google_play_services\samples\maps can run,
but after I imported into eclipse and set the libraries of android-support-v4.jar and google-play-services.jar correctly, import com.example.mapdemo.R; in FeatureView.java (at line 24) can not find the file R.java.
almost all the java file in com.example.mapdemo need class "R", for example, the file BasicMapActivity.java need R in line 41 "setContentView(R.layout.basic_demo);" and line 71 mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();"
can someone tell me how to find the class "R"?
R
.java can not create automatically because the file multimap_demo.xml have some errors in

    <fragment

      android:id="@+id/map3"

      android:layout_width="match_parent"

      android:layout_height="match_parent"

      android:layout_weight="0.5"

      class="com.google.android.gms.maps.SupportMapFragment"

      map:cameraTargetLat="48.85"

      map:cameraTargetLng="2.35"

      map:cameraZoom="8"/>

eclipse said "cameraTargetLat", "cameraTargetLng" and "cameraZoom" can not recognized.
The error information:
Multiple annotations found at this line:
    - error: No resource identifier found for attribute 'cameraTargetLat' in package 'com.example.mapdemo'
    - error: No resource identifier found for attribute 'cameraTargetLng' in package 'com.example.mapdemo'
    - error: No resource identifier found for attribute 'cameraZoom' in package 'com.example.mapdemo'

I do not know why.

If I change the code like this:

    <fragment

      android:id="@+id/map3"

      android:layout_width="match_parent"

      android:layout_height="match_parent"

      android:layout_weight="0.5"

      class="com.google.android.gms.maps.SupportMapFragment"/>

the errors disappeared, but i do not know if it can run.

A: Copy the maps_attr.xml file from the library project into your project's values folder.

A: You should also import google-play-services_lib project (/extras/google/google_play_services/libproject/google-play-services_lib) - after that cameraTargetLat and other ones are recognized and R.java is generated.

A: you should import /extras/google/google_play_services/libproject/google-play-services_lib as a library in your project.

*

*Import an existing android project at /extras/google/google_play_services/libproject/google-play-services_lib, but remember COPYING IT TO WORKSPACE(important, maybe the path of its original place occurs error)

*See your project's properties->Android settings and add library "google-play-services"

*Remember to add android-support-v4.jar & google-play-services.jar to your External JARs

A: 1, include both external jar to project
2, copy \extras\google\google_play_services\libproject\google-play-services_lib\res\values\maps_attrs.xml to project value folder
3, copy google-play-services_lib to workspace looks no necessary in my test.
Update:
java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable in android

A: I solved it just adding the following meta-data to the AndroidManifest.xml
 <meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

A: may be this answer can help someone.
this is due to a silly mistake, both the projects ie. Sample project of Map and Google play service project must reside on the same directory otherwise it will not referenced properly
you need do copy projects into workplace for both the projects or if you don't want to copy, so don't do it for both this is the glitch. if you do it properly then you will find this

A: you have to include xmlns:map="http://schemas.android.com/apk/res-auto" to your layout xml for using map element.
The R file is autogenerate by Eclipse, and you can find it in gen directory. Don't edit this file ever! In some case, you will find there more than one R file, for example when you add a library to your project, like google-play-services_lib. You always can refere to this file at code like this...
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(com.your.package.R.id.map)).getMap();

If you want to configure your map, is posible to make it by XML Attributes or Programmatically.


text:
Q: Does ie10 support image pasting from clipboard? Does ie10 support the ability to support copy and pasting an image. IE has the fileReader api which is nice, but it would be cool to have ability to paste a picture.

A: A good indicator that pasting images into IE10 is not possible, is the nice site http://pasteboard.co. The site tries really hard to allow pasting of images, however it fails for IE10.
For the sake of completeness:

*

*In chrome/webkit you have to handle event paste and look into  event.clipboardData.

*In firefox you have to create a <div/> with attribute "contenteditable". See http://joelb.me/blog/2011/code-snippet-accessing-clipboard-images-with-javascript/

A: It seems that http://snag.gy/ supports copy and paste from clipboard of images in IE 10. At least it works for me. As soon as I change the mode to IE 8/9 it only works with a Java applet.


text:
Q: looping through html and deleting not found So, i'm looping through the document body searching for all "#result>tbody>tr" objects. I'm then trying to search within those elements to see if any of the names exist, if they do, I would like to delete them. I got it working if I don't loop through the names and use a single object. If I try and loop through the names, it only loops four times and then nothing else happens.
Any ideas?
Edit: Currently there are 30 objects the first loop loops through. When I add the second loop into the mix to see if the sub-objects exist, it will only loop through four and than break the loop. Hope that explains better.
Example: https://jsfiddle.net/8c9p7bp5/1/
var dlList = document.querySelectorAll("#result>tbody>tr");
for (var i = 0, len = dlList.length; i < len; i++) {

    var names = ['Test', 'Router', 'IP', 'Mod'];

    for (var j = 0, len = names.length; j < len; j++) {
        var vi = dlList[i].querySelector("td>br>img[title^='" + names[i] + "']");

        if(!dlList[i].contains(vi)) {
            //dlList[i].remove();
            console.log(dlList[i]);
        }

    }
}

A: First mistake of your code that you are using same limit for you nested loop "len", in the first iteration the value becomes 4 that's why it will break the parent loop.

A: You initialize j but never use it in the inner loop.
Try this instead:
var vi = dlList[i].querySelector("td>br>img[title^='" + names[j] + "']");
Also, you should use a different variable than len for the inner loop to avoid running into variable scope issues.


text:
Q: Biblatex not shortening authorlist I am trying to let Latex shorten the authorlist in my bibliography automatically, but it seems to ignore my settings.
This is my MWE:
\documentclass{scrreprt}
\usepackage[backend=bibtex, maxnames=2,style=numeric-comp]{biblatex}
\addbibresource{Literatur.bib}
\begin{document}

This is testing text...
\cite{Huebler2011}
\cite{Pierre2015}

\printbibliography
\end{document}

This gives me following result:

As you can see, the selected style is applied, but all authors appear in the bibliography list. I am using TeXnicCenter with MikTex 2.9.
I get one warning message after compilation, which reads Package Biblatex Warning: Using fall-back BibTeX(8) backend. I did some online search on that too, as it seems related to the problem, but haven't found anything helpful. Not specifieing a backend does not generate a bibliography at all.
I hope this doesn't turn out to be a stupid newbie mistake, but could very well be. Any help is greatly appreciated.


text:
Q: Items of ItemsPresenter in Custom-Control not shown correctly I've written a custom control that should display items in a list and provide additional commands related to scrolling events, like load more. So I decided to create a ScrollViewer and add the ItemsPresenter inside generic.xaml.
Basically this works fine when I use ItemsControl as base class. But now I need the possibility to click on a single item. The solution is to use the ListView class as base class.
Here comes the problem. As soon as I use a GridView or ListView as base class the content of the list is only shown as far as it is shown at inital offset of the list. other/new items that you can only see by scrolling down aren't shown.

I thought that the list maybe dont resize, but adding a footer and a border around the list shows the the list resizes correctly.
The collection I use is a ObservableCollection and works with the ItemsControl base class.
I think the problem is a setting or something on xaml side. But I dont know where and i have no ideas what to search next. everytime I search, all results are marked as clicked =(
Here is my xaml code of the generic.xaml:
<Style TargetType="lists:ListViewWithCommands">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="lists:ListViewWithCommands">
                <Border
                    Background="{TemplateBinding Background}"
                    BorderBrush="Red"
                    BorderThickness="1">
                    <ScrollViewer x:Name="ItemScrollViewer">
                        <Border BorderBrush="White" BorderThickness="2">
                            <StackPanel>
                                <ItemsPresenter />
                                <ContentPresenter Visibility="{TemplateBinding LoadingTemplateVisibility}" ContentTemplate="{TemplateBinding LoadingTemplate}" />
                            </StackPanel>
                        </Border>
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Here is a part of my control itselve:
[TemplatePart(Name="ItemScrollViewer", Type=typeof(ScrollViewer))]
  public sealed class ListViewWithCommands : ListView
  {
      private ScrollViewer _itemScrollViewer;

      public ListViewWithCommands()
      {
          this.DefaultStyleKey = typeof(ListViewWithCommands);
      }

      protected override void OnApplyTemplate()
      {
          base.OnApplyTemplate();
          this._itemScrollViewer = GetTemplateChild("ItemScrollViewer") as ScrollViewer;
          if (this._itemScrollViewer != null)
          {
              Debug.WriteLine(String.Format("ItemScrollViewer found! Attatching Event Handler!"), this.GetType().Name);
              this._itemScrollViewer.ViewChanged += _itemScrollViewer_ViewChanged;
          }
          else
          {
              throw new NullReferenceException("ItemScrollViewer not found!");
          }
      }
....

I hope you have any suggestions.
robert


text:
Q: Passing an array as `params` argument I have the following method:
void MyMethod(params object[] args)
{
}

which I am trying to call with a parameter of type object[]:
object[] myArgs = GetArgs();
MyMethod(myArgs);

It compiles fine, but inside MyMethod I args == { myArgs}, i.e. an array with one element that is my original arguments. Obviously I wanted to have args = myArgs, what am I doing wrong?
EDIT:
Jon Skeet was actually right, the GetArgs() did wrap the thing in an one element array, sorry for stupid question.

A: What you've described simply doesn't happen. The compiler does not create a wrapper array unless it needs to. Here's a short but complete program demonstrating this:
using System;

class Test
{
    static void MyMethod(params object[] args)
    {
        Console.WriteLine(args.Length);
    }

    static void Main()
    {
        object[] args = { "foo", "bar", "baz" };
        MyMethod(args);
    }
}

According to your question, this would print 1 - but it doesn't, it prints 3. The value of args is passed directly to MyMethod, with no further expansion.
Either your code isn't as you've posted it, or the "wrapping" occurs within GetArgs.
You can force it to wrap by casting args to object. For example, if I change the last line of Main to:
MyMethod((object) args);

... then it prints 1, because it's effectively calling MyMethod(new object[] { args }).


text:
Q: C# Roslyn compiler: Dynamic variables causes weird failure (.NET Core 2.2 console app) I am trying to use Rosyln to dynamically compile some code into an assembly. I have it all working with one exception: when I try to declare a type as dynamic, I get a compiler error (from the runtime compile) saying:
error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'

Some research—such as the Stack Overflow thread Using System.Dynamic in Roslyn—suggests including a reference to the Microsoft.CSharp.dll and to the dynamic attribute, which I did.
Again, if I switch the type in the code text to int, it works just fine. It requires the Microsoft.CodeAnalysis.Compilers NuGet package. If it matters, I am using a console application with .NET Core 2.2 on Windows.

For reference, this code is based on the useful Compiling and Running C# Code in Runtime.

Any suggestions?

using System;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;

namespace RoslynTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var assemblyName = "TestLibrary";
            var code = @"
    namespace TestNamespace
    {
        public class TestClass
        {
            public static int Add(dynamic a, int b)  // Works if a is declared as int
            {
                return a+b;
            }
        }
    }";

            SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
            CSharpCompilation compilation = CSharpCompilation.Create(
                assemblyName,
                new[] { syntaxTree },
                new MetadataReference[]
                {
                    MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(DynamicAttribute).Assembly.Location),
                    MetadataReference.CreateFromFile(typeof(Microsoft.CSharp.RuntimeBinder.Binder).Assembly.Location)
                },
                new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using (var memoryStream = new MemoryStream())
            {
                EmitResult result = compilation.Emit(memoryStream);

                if (result.Success)
                {
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    Assembly assembly = Assembly.Load(memoryStream.ToArray());

                    Type testClassType = assembly.GetType("TestNamespace.TestClass");
                    var addResult = (int)testClassType.GetMethod("Add").Invoke(null, new object[] { 3, 4 });
                    Console.WriteLine($"Result is {addResult}");
                }
                else
                {
                    foreach(var error in result.Diagnostics)
                        Console.WriteLine(error.ToString());
                }

                Console.ReadLine();
            }
        }
    }
}


text:
Q: defining an Enum instance in scalaz How would one do the analogue of the following in scalaz?
ghci> data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Eq, Show, Enum)
ghci> [Monday .. Wednesday]
[Monday,Tuesday,Wednesday]

For instance I should be able to do (Monday |-> Wednesday) and get List(Monday,Tuesday,Wednesday) once an Enum instance has been defined.
The Enum instances in AnyVal.scala seem pretty complicated. Is there a simpler way?


text:
Q: Getting "Not Applicable" compile error with generic type I have the following classes:
public interface IEntity<T extends IEntity<T>>
{
   T createNewEntity(IEntityCreator creator);
}

public interface IEntityCreator
{
   <T extends IEntity<T>> T createNewEntity(T source);
}

public abstract class EntityBase<T extends EntityBase<T>> implements IEntity<T>
{
   @Override
   public T createNewEntity(IEntityCreator creator)
   {
      return creator.createNewEntity(this); //Error here
   }
}

I get the following error:
"Bound mismatch: The generic method createNewEntity(T) of type IEntityCreator is not applicable for the arguments (EntityBase). The inferred type EntityBase is not a valid substitute for the bounded parameter >"
I tried a different approach with the following code with no success:
public interface IEntity<T extends IEntity<T>>
{
   T createNewEntity(IEntityCreator<T> creator);
}

public interface IEntityCreator<T extends IEntity<T>>
{
   T createNewEntity(T source);
}

public abstract class EntityBase<T extends EntityBase<T>> implements IEntity<T>
{
   @Override
   public T createNewEntity(IEntityCreator<T> creator)
   {
      return creator.createNewEntity(this); //Error here
   }
}

This time the compiler says:
"The method createNewEntity(T) in the type IEntityCreator is not applicable for the arguments (EntityBase)"
What is the cause for this error? How can I correct it?
Thanks

A: Pretty extrange pattern here, but this compiles...
public interface IEntity<T extends EntityBase<T>>
{
   T createNewEntity(IEntityCreator<T> creator);
}

public interface IEntityCreator<T extends EntityBase<T>>
{
   T createNewEntity(EntityBase<T> entityBase);
}

public abstract class EntityBase<T extends EntityBase<T>> implements IEntity<T>
{
   @Override
   public T createNewEntity(IEntityCreator<T> creator)
   {
      return creator.createNewEntity(this);
   }
}

A: The cause for error is that IEntityCreator.createNewEntity() needs a T which implements IEntity<T>, and you are passing EntityBase<T>, so it should implement IEntity<EntityBase<T>>, which it doesn't do.
You need to explicitly cast this to T (a derived class from EntityBase<T> which actually implements IEntity<T>), like Wundwin Born suggested in comments:
public T createNewEntity(IEntityCreator creator) {
    return creator.createNewEntity((T)this);
}