text:
Q: How to Highlight Words with Quotation Marks? When we highlight words with quotation marks, should the periods and commas be within or outside of them?
Examples:
Question 1
A) He is such a "good guy."
or
B) He is such a "good guy".
Question 2
A) This smartphone is the "smartest," you should get it.
or
B) This smartphone is the "smartest", you should get it.
If possible, kindly explain why are you picking those choices.
Thank you.

A: The British style puts the outside the quotes and the American style puts them inside the quotes.
Essentially, it doesn't really matter as long as you are consistent throughout your writing.
Also, why not search before posting? [1] [2]

A: Firstly, you could think of it as a question of style alone, and the answer depends on the style manual that is applicable in each case.
On the other hand, an important point in cases such as these is if what is being quoted (enclosed in quotes) is a complete sentence or a fragment. If it is complete sentence, it comes with its own terminal period, which will be part of the quotation and so will be within the pair of quote marks. If not, the overall sentence will end with period after the quotation, that is, after the closing quotation mark. This should be the principal criterion unless the applicable style overrides.
He is such a "good guy".  -- quoting a phrase
He said, "He is such a good guy."  -- quoting a sentence
He said, "He is such a good guy.".   -- quoting sentence, with normal terminal period if style requires it.


text:
Q: Invalid Argument javascript error only on certain computers Getting an error whenever we click a particular button/link on our site.  It is generating a javascript "Invalid Argument" error.  I know in the other posts it is typically because it is a syntax error in the javascript however it only just seems to have started happening and it doesn't happen on all pcs.
ie. in our client's environment if I remote onto their web server and view the uat website I get the javascript error.  If I remote onto their sql server and view the uat website I don't get the javascript error.  If it was a syntax error then I would always get the error wouldn't I?
both browsers are the same version of IE6 (yeah I know...) :)  I have tried deleting temporary internet files - including viewing the files and deleting them myself - but no joy.
client uses citrix.. and they're all getting the error :(
Any ideas would be appreciated - Thanks! :)
Update - Sorry I haven't posted specific code as there is too much to post (and I'm not sure where the error is occurring).  The "button" launches a new window which in turn opens up a couple of aspx pages and calls lots of javascript.  So the window opens ok, and there's a function that gets called to resize the window - but before it calls the resizing of the window/content it throws the invalid argument error.  Am busy trying to get alerts to trigger to see if I can see where it's falling over but so far no luck.
Again not sure why this error doesn't occur when I use a particular PC (same browser version)

A: Could you post the code for attaching your event listener to the button as well as the event listener?  This would be helpful in advising you on the best way to debug the error -- it's likely something to do with event object or the way you are referencing it.

A: It's hard to know without your code being posted, but most of the "Invalid Argument" IE issues I've encountered relate to setting a property or style on a DOM element that isn't supported by the IE6 DOM.
The error may be present on both browsers, but maybe script debugging is disabled on one and not the other, or they may have other JavaScript setting differences.  The browser that's working may just be silently stopping its script once the error occurs.

A: I'd suggest installing Internet Explorer developer toolbar. Using this tool, you can more easily pinpoint the exact problem. Just telling us "something doesn't work" won't help you or us.

A: No idea what this was - and I have since changed companies it can't be further investigated.  Thanks everyone for the comments.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Commons-Email not working with attachment in Java I am developing automated test using Selenium WebDriver in Eclipse Java code.  And able to send simple email with Commons-Email using gmail account and its working fine on both port 465, 587 (I have turned on Less Secure App). following code works perfectly.
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

public class SendEmail {

public static void main(String[] args) throws EmailException {
    System.out.println("sending email");
    Email email = new SimpleEmail();
    email.setHostName("smtp.gmail.com");
    email.setSmtpPort(587);
    email.setAuthenticator(new DefaultAuthenticator("myaccount@gmail.com",
"mypassword"));
    email.setSSLOnConnect(true);
    email.setFrom("myaccount@gmail.com");
    email.setSubject("TestNG Reports");
    email.setMsg("Attahced is the TestNG tests execution report");
    email.addTo("rec1@gmail.com","rec2@gmail.com");
    email.send();
    System.out.println("email sent");
 }
}

However when I try to send attachment then getting errors, I have tried both ports 465, 587, I have also tried to change attachment type and path. following is the code and error messages:
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;

public class SendEmail {

public static void main(String[] args) throws EmailException {
     System.out.println("sending email");
     EmailAttachment attachment = new EmailAttachment();
     attachment.setPath("D:\\failed.png");
     attachment.setDisposition(EmailAttachment.ATTACHMENT);
     attachment.setDescription("TestNG Report");
     attachment.setName("QA");

     MultiPartEmail email = new MultiPartEmail();
     email.setHostName("smtp.gmail.com");
     email.setSmtpPort(465);
     email.setAuthenticator(new DefaultAuthenticator("myaccount@gmail.com",
"mypassword"));
     email.addTo("rec1@gmail.com","rec2@gmail.com");
     email.setFrom("myaccount@gmail.com");
     email.setSubject("Test NG Execution Report");
     email.setMsg("Please find the attached Test NG test cases execution
report");
     email.attach(attachment);
     email.send();
     System.out.println("email sent");
}

}
Exception in thread "main" org.apache.commons.mail.EmailException: Sending
the email to the following server failed : smtp.gmail.com:465
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1469)
at org.apache.commons.mail.Email.send(Email.java:1496)
at setup.SendEmail.main(SendEmail.java:26)
Caused by: javax.mail.MessagingException: Could not connect to SMTP host:
smtp.gmail.com, port: 465, response: -1
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1949)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1459)
... 2 more

When port 587 used then getting following errors
Exception in thread "main" org.apache.commons.mail.EmailException: Sending
the email to the following server failed : smtp.gmail.com:587
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1469)
at org.apache.commons.mail.Email.send(Email.java:1496)
at setup.SendEmail.main(SendEmail.java:26)
Caused by: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a
STARTTLS command first. o4-v6sm35725484wra.3 - gsmtp

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at org.apache.commons.mail.Email.sendMimeMessage(Email.java:1459)
... 2 more

A: Just add :
email.setTLS(true);

in code :
package com.demo.utils;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.MultiPartEmail;

public class SendEmail {

    public static void main(String[] args) throws EmailException {
        System.out.println("sending email");
        EmailAttachment attachment = new EmailAttachment();
        attachment.setPath("C:\\Users\\12345\\Desktop\\Reebok\\BAIT-YG-Reebok-Classic-Nylon.jpg");
        attachment.setDisposition(EmailAttachment.ATTACHMENT);
        attachment.setDescription("TestNG Report");
        attachment.setName("QA");

        MultiPartEmail email = new MultiPartEmail();
        email.setHostName("smtp.gmail.com");
        email.setSmtpPort(587);
        email.setTLS(true);
        email.setAuthenticator(new DefaultAuthenticator("myaccount@gmail.com", "myPassword"));
        email.setFrom("myaccount@gmail.com");

        email.addTo("rec1@gmail.com","rec2@gmail.com");
        email.setSubject("Test NG Execution Report");
        email.attach(attachment);
        email.send();
        System.out.println("email sent");
    }
}

I am using maven dependency  :
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.2</version>
        </dependency>

Hope that helps you:)


text:
Q: Collapse Tab In React Native I'm using this package react-native-collapsible
and I wanted to behave the closing and opening of tabs like gmail.
Like when I try to open an email, when it has many threads of replies, when you click the first one, it closes the other thread. When you click its thread, it opens it and closes the other thread. I think this is just a simple react/JS issue.
import Collapsible from "react-native-collapsible";

const [collapsedIndex, setCollapsedIndex] = useState([]);

const renderEmailBody = (emailItem) => {
  return (
    <View>
      {emailItem?.body ? (
        <RenderHtml
          contentWidth={width}
          source={{
            html: emailItem?.body,
          }}
          renderersProps={{
            a: {
              onPress: (event, href) => {
                navigate("WebView", href);
              },
            },
          }}
        />
      ) : null}
    </View>
  );
};

const renderEmailData = ({ item, index }) => {
  return (
    <>
      <TouchableOpacity
        activeOpacity={1}
        onPress={() => setCollapsedIndex(index)}
      >
        <Collapsible collapsed={collapsedIndex !== index}>
          {renderEmailBody(item)}
          {item?.attachments
            ? item?.attachments?.map((innerItem, rowIndex) => {
                return <View key={rowIndex?.toString()}>...</View>;
              })
            : null}
        </Collapsible>
      </TouchableOpacity>
    </>
  );
};

const renderEmailDetailsList = () => {
  var data = emailDetailsList;

  return (
    <FlatList
      nestedScrollEnabled
      ref={flatListRef}
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
      }
      data={data}
      ItemSeparatorComponent={() => <View />}
      renderItem={renderEmailData}
      keyExtractor={(item, index) => index.toString()}
      onEndReachedThreshold={0}
    />
  );
};

A: i think initial value should be const [collapsedIndex, setCollapsedIndex] = useState(null); not a empty array, also the onpress should be
onPress={() => {
 if (index === collapsedIndex) {
    setCollapsedIndex(null)
 } else {
   setCollapsedIndex(index)
 }
}}


text:
Q: Simple Python rules matching I'm attempting to create a simple rule matching engine where if any rules match from a dictionary :
{'id': [{'status1' : 'v1'}  , {'status3' : 'v2'} , {'status1' : 'v2'}] }

and the rules are :
{'rule1': {'status1': ['v1'], 'status2': ['v2' , 'v3']},
              'rule2': {'status1': ['v2'], 'status2': ['v4']}}

The rule matching should produce the output:
[('status1', 'v1', ['v1'], 'rule1'), ('status1', 'v2', ['v2'], 'rule2')]

('status1', 'v1', ['v1'], 'rule1') corresponds to status1 matching on rule1 as rule1 contains the value v1 for status1
('status1', 'v2', ['v2'], 'rule2') corresponds to status1 matching on rule2 as rule2 contains the value v2 for status1
Here is the code I've written :
values_to_validate = {'id': [{'status1' : 'v1'}  , {'status3' : 'v2'} , {'status1' : 'v2'}] }

rule_set_1 = {'rule1': {'status1': ['v1'], 'status2': ['v2' , 'v3']},
              'rule2': {'status1': ['v2'], 'status2': ['v4']}}

class RulesConfig() :

    def __init__(self , rules):
        self.rules = rules

    def get_rule_names(self):
        return self.rules.keys()

    def get_conditions_for_rule(self, rule_name):
        return self.rules[rule_name]

    def get_matched_rules(self, values_to_validate):
        is_matched = False
        matched_rules = []
        for v in values_to_validate.values() :
            for rk,rv in self.rules.items() :
                for a in v :
                    for d,f in a.items() :
                        if d in rv :
                            matched_rules.append((d,f , rv[d] , rk))

        return matched_rules

v = RulesConfig(rule_set_1)
print(v.get_matched_rules(values_to_validate))

which returns :
[('status1', 'v1', ['v1'], 'rule1'), ('status1', 'v2', ['v1'], 'rule1'),
 ('status1', 'v1', ['v2'], 'rule2'), ('status1', 'v2', ['v2'], 'rule2')]

To return the expected output I could remove duplicated entries in the above list of tuples but I think there is a mistake in my algorithm.
The code I use to find the matched rules :
def get_matched_rules(self, values_to_validate):
    is_matched = False
    matched_rules = []
    for v in values_to_validate.values() :
        for rk,rv in self.rules.items() :
            for a in v :
                for d,f in a.items() :
                    if d in rv :
                        matched_rules.append((d,f , rv[d] , rk))

seems unnecessary complex, is there an idiomatic preferred Python method of solving this type of problem? I'm using Python 3.6 and do not want to include libraries that are not included as part of standard Python interpreter.

A: This test is insufficient:
if d in rv :
    matched_rules.append((d,f , rv[d] , rk))

This will check only if 'status1' for example is in the rule dictionary, you also need to check whether it has the right value:
if d in rv and f in rv[d]:
    matched_rules.append((d,f , rv[d] , rk))


text:
Q: Using Local Cauchy Theorem, find the integrals $\int_{|z|=1} \sqrt{9-z^2}\, dz$ and $\int_{|z|=1}(z^2+2z)^{-1}\, dz$. Using Local Cauchy Theorem, find the integrals $\int_{|z|=1} \sqrt{9-z^2}\, dz$ and $\int_{|z|=1}(z^2+2z)^{-1}\, dz$.
For the first integral, I have no idea what to do.
For the second integral partial fractions gives $$\frac{1}{(z^2+2z)}=\frac{1}{2}\left(\frac{1}{z}-\frac{1}{z+2}\right)$$
But then how do I integrate $\int_{|z|=1} \frac{1}{z+2}$?

A: If, in your first integral, $\sqrt{9-z^2}$ is a holomorphic square root of $9-z^2$ defined on $\Bbb C\setminus\bigl((-\infty,-3]\cup[3,\infty)\bigr)$, then then answer is $0$, since the while close disk centered at $0$ with radius $1$ is contained in the domain of the function.
For the same reason $\int_{|z|=1}\frac{\mathrm dz}{z+2}=0$.


text:
Q: Scrapy Spider retry request On occasion I'll have a response with unexpected html and all of the item fields will not be extracted, however, if I retry the request, it will typically return the expected html.
As a quick fix I'm catching the error in the spiders parse method:
# project/spiders/sample_spider.py

class SampleSpider(Spider):

    [...]

    def parse(self, response):
        try:
            item = SampleItem()

            item['sample_1'] = response.xpath('sample').extract()
            item['product_count_2'] = response.xpath('sample').extract()[0]

            yield item
        except IndexError:
            logger.debug('Retrying %(url)s', {'url': response.url})
            yield Request(response.url, self.parse, dont_filter=True)

I came across this post which appears to be a similar scenario, but it seems this type of error should be handled in a Item Pipeline... Any thoughts on the best way to implement this fix?


text:
Q: Changing SSL certificates on the fly in IdHTTPServer I'm developing a MITM proxy with SSL support in delphi 10.3, using indy. I use IdHttpServer component, which does work in CommandOther event. I managed to make it to decrypt and dump data on the fly, and reencrypt and send it to browser, but I need to change idhttpserver certificate for each domain. I can generate them and install my own CA, but i cant find a way to change them while my proxy is working. I will greatly appreciate if someone will show me how!
 procedure TForm3.IdHTTPServer1CommandOther(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
 var
S: string;
LClient: TIdtcpClient;
 newsize:int64;
LBuf: TIdBytes;
Len: Integer;

var response:integer;
s3: TStringDynArray;
var cmd:string;
bytes:tidbytes;

oldstr,newstr:string;
ResponseCode, ResponseText: string;
  Size: Int64;
ssl:tIdServerIOHandlerSSLopenssl;

begin
 if not TextIsSame(ARequestInfo.Command, 'CONNECT') then Exit;

 LClient := TIdtcpClient.Create(nil);
  try

S := ARequestInfo.URI;
LClient.Host := Fetch(S, ':', True);
LClient.Port := StrToIntDef(S, 443);

LClient.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(LClient);

LClient.ConnectTimeout := 5000;

// connect and activate SSL between this proxy and the target server

LClient.Connect;
try
  AResponseInfo.ResponseNo := 200;
  AResponseInfo.ResponseText := 'Connection established';
  AResponseInfo.WriteHeader;

  // activate SSL between this proxy and the client
  TIdSSLIOHandlerSocketOpenSSL(AContext.Connection.Socket).PassThrough:=false;

  // pass data between AContext.Connection.IOHandler and LClient.IOHandler
//as needed.

  // received data will be decrypted, and sent data will be encryted...
  while AContext.Connection.Connected and lclient.Connected do
  begin

    //mitm traffic modification routine

  end;

finally

 LClient.Disconnect;

end;
 finally
 LClient.Free;

end;
 end;

This is cert switching code:
procedure TForm3.IdHTTPServer1Connect(AContext: TIdContext);
var

SSL: TIdSSLIOHandlerSocketOpenSSL;
begin

if AContext.Connection.Socket.Binding.Port = 443 then
        begin

sslh:=tIdSSLIOHandlerSocketOpenSSL(AContext.Connection.IOHandler);

          sslh.SSLOptions.CertFile:='Certificate.pem';
     sslh.SSLOptions.keyfile:='PrivateKey.pem';
    sslh.SSLOptions.RootCertFile:='certificateAuthorityCertificate.pem';
     sslh.SSLOptions.SSLVersions:=[sslvSSLv23];
     sslh.ssloptions.mode:=sslmBoth;
   sslh.OnGetPassword:= IdServerIOHandlerSSLOpenSSL1GetPassword;

     sslh.PassThrough:=false;

      TIdSSLIOHandlerSocketOpenSSL(AContext.Connection).PassThrough:=false;
       //memo2.Text:=AContext.Connection.IOHandler.ReadLn();

        end;

  end;

On a form I have a tidhttpserver and TIdServerIOHandlerSSLOpenSSL as iohandler for it.

A: Assign on OnQuerySSLPort event handler that unconditionally sets the VUseSSL parameter to False regardless of the APort requested. Then, in the OnConnect event, if the AContext.Connection.Socket.Binding.Port property is 443 (or whatever port you want to use HTTPS on), you can typecast the AContext.Connection.IOHandler property to  TIdSSLIOHandlerSocketBase (or descendant, like TIdSSLIOHandlerSocketOpenSSL if using OpenSSL), configure its certificates as needed, and then set its PassThrough property to False to complete the SSL/TLS handshake.


text:
Q: Jenkins/Hudson call script on AWS EC2 Instance Today, on my work, when we need to deploy a Play! Framework (1.2.7) app in our EC2 Instance (AWS), we need to access the server and call a script that download all the source code, precompile the source code, start Play! Framework and restart nginx (everything in one script - .sh).
This process work fine today, but in emergency cases it's very slowly because we need to access de EC2 Instance (with key pair) and depending on the location the internet is slowly.
I want to know if is possible to use Hudson/Jenkins to just call this script on my EC2 Instances. I know that Hudson/Jenkins have a lot of functionality (test, build, etc.) but for now I just want to deploy my app (call the script from ec2-instance).
If anyone knows another tool that help, I will be very grateful.
Thanks.

A: You can use/build SBT plugins to run the remote command, or simply exec the local ssh with the command, but that can get quite hard to debug.
If you can build your instance to bootstrap itself from scratch, for example with a UserData script, then all you need to do is terminate your old instance and start a new one, and that is much easier to automate.


text:
Q: Sort an editable ComboBox in XAML I would like to sort an editable combobox in pure WPF, after the addition of a new record. After some research I found some tips, which used a CollectionViewSource.SortDescription, but it does not work for me correctly. What am I doing wrong? The DataContext of the item which used my DataTemplate works fine, but the binding between the DataTemplate and the resource part to sort my entry list doesn't.

My XAML Part
<DataTemplate x:Key="Document">
    <DataTemplate.Resources>
        <CollectionViewSource x:Key="SortedLabels" Source="{Binding Parent.Labels}">
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="Items"/>
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </DataTemplate.Resources>

    <Grid>
    ...
        <ComboBox Name="cbLabel"
                  ItemsSource="{Binding Source={StaticResource SortedLabels}}"
                  IsEditable="True"
                  LostFocus="cbLabel_LostFocus"
                  KeyUp="cbLabel_KeyUp"
                  Visibility="{Binding Path=IsUndiscovered, Converter={StaticResource ResourceKey=BooleanToVisibilityConverter}}"/>
    ...
    </Grid>
</DataTemplate>

EDIT
The Collection Parent.Labels are of type ObservableCollection<String>.

A: Hard to say since you didn't show what the collection is you're trying to sort, but my guess is that each object in Parent.Labels doesn't have a Items property. The PropertyName refers so a property on the individual objects in the list that it will look at and try to sort. I'd guess you want something more along the lines of "Name" or some other property.


text:
Q: Does using a constant over a standard variable use less memory? I have done some searching on the internet but fail to find an answer, so I come here hopefully to find it. So my guess would be that it would because say if i declare one final int foo = 6 it because it wouldn't change in size that it will only be set to what it needs in terms of memory. Where as a variable int bar = 8 will have to have a larger size in memory because it has a chance later in the program in change.

A: No a constant uses the exact same memory.
The only difference is that you can't change your constant after it's initialized. I'm sure you know it but you use constants for values that should not be possible to change (by accident,..)

A: The space required for a value depends on the data type, not on the exact value.  Therefore, a
final int foo = 6;

requires exactly the same space as
int bar = 8;

or
int baz = 0;

or
int shazam = Integer.MAX_VALUE;

With that in mind, it should not surprise you that whether a variable is declared final does not alter its memory requirements.

A: No.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Basically the size of the value in memory (in java) is determined by the type.  Different primitives consume different amounts of memory.  This amount is constant for the given type of primitive.


text: Q: Problem with button ESC representation on Eclipse I'm using com.ibm.eNetworlk.ECL.ECLPS to get the buttons representations, I know some of them, but now I need to represent the button "ESC", but I couldn't find it out. Does some one can help me?


text:
Q: Finding a basis of a subspace which is perpendicular Let $V = \text{span}\{(1, 1, 0, 1, 1), (1, 2, 0, 2, 1), (1, 3, 3, 3, 1)\}$ be a subspace of $\mathbb R^5$.
I found using Gram-Schmidt process that the orthonormal basis of $V$ is $\{(0.5 , 0.5 , 0 , 0.5 , 0.5), (-0.5 , 0.5 , 0 , 0.5 , -0.5), (0 , 0 , 1 , 0 , 0)\}$.
Now I am tasked to find a basis of the subspace $V^\perp = \{w ∈ \mathbb R^5\mid w \text{ is orthogonal to }V \}$.
May I ask whether the answer is linked to my orthonormal basis and if it is, what steps do I need to take to obtain the answer?
Thank you.


text:
Q: Android studio - how can I save a textView's text as a PNG image (with it's font, color, and font size)? I researched a lot on the internet but no use.
I am very new to Android programming and java.
I wrote a simple program in Android studio that lets you write a text in a cool font I set, optionally the user can chose color and font size.
I want to save this text, with its font, font size, and font color; as an image viewable with any galley application. I tried lots of things spent hours on it but universe is still against me.
I managed to create a bitmap image, and I can view it in an ImageView,but I can't save it to storage.
Can someone please explain this very simply ? Im very new to both Android and Java.

A: public boolean saveImageToInternalStorage(Bitmap image) {

    try {
        // Use the compress method on the Bitmap object to write image to
        // the OutputStream
        FileOutputStream fos = context.openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);

        // Writing the bitmap to the output stream
        image.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
        return true;
    }
    catch (Exception e) {
        Log.e("saveToInternalStorage()", e.getMessage());
        return false;
    }
}


text:
Q: Parsing the JSON iOS-Swift I have a JSON response that I am parsing with the help of codable models.
Even though my models look good, I am getting the following error:

[Result]: FAILURE: keyNotFound(CodingKeys(stringValue: "user", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"user\", intValue: nil) (\"user\").", underlyingError: nil))

The JSON response is:
{
   "status": "success",
   "message": "successfully.",
   "user": {
       "username": "admin",
       "profileImage": "/storage/default.png"
   },
   "data": {
       "cash": {
           "withdrawableCash": "$999540",
           "outstandingOrders": "$0"
       },
       "offering": [
           {
               "company": "ABCD",
               "location": "San Francisco, CA",
               "amount": 10
           }
       ],
       "history": [
           {
               "amount": 330,
               "order_id": 3,
               "order_type": "preBid",
               "status": 2,
               "message": "Placed bid with 33 notes, on Auction,
               "transaction_time": "31-07-2018 05:31"
           }
       ]
   }
}

The models are:
public struct WalletResponseModel: Codable {
    public let status: String
    public let message: String
    public let user: UserData
    public let data: WalletData
}

public struct UserData: Codable {
    public let username: String
    public let profileImage: URL

    enum CodingKeys: String, CodingKey {
        case username
        case profileImage = "profileImage"
    }
}

public struct WalletData: Codable {
    public let cash: Cash
    public let history: [HistoryItem]
    public let offerings: [Offering]

    enum CodingKeys: String, CodingKey {
        case cash
        case history
        case offerings = "offering"
    }
}

public struct Cash: Codable {
    public let withdrawableCash: String
    public let outstandingOrders: String
}

public struct HistoryItem: Codable {
    public let amount: Int
    public let status: Int
    public let orderId: Int
    public let orderType: String
    public let message: String
    public let transactionTime: String

    enum CodingKeys: String, CodingKey {
        case amount, status, message
        case transactionTime = "transaction_time"
        case orderId = "order_id"
        case orderType = "order_type"
    }
}

public struct Offering: Codable {
    public let company: String
    public let amount: Int
    public let location: String
}

A: Your json format is incorrect it contains  " " instead of " " , the valid one is
{
    "status": "success",
    "message": "successfully.",
    "user": {
        "username": "admin",
        "profileImage": "/storage/default.png"
    },
    "data": {
        "cash": {
            "withdrawableCash": "$999540",
            "outstandingOrders": "$0"
        },
        "offering": [{
            "company": "ABCD",
            "location": "San Francisco, CA",
            "amount": 10
        }],
        "history": [{
            "amount": 330,
            "order_id": 3,
            "order_type": "preBid",
            "status": 2,
            "message": "Placed bid with 33 notes, on Auction",
            "transaction_time": "31-07-2018 05:31"
        }]
    }
}


text:
Q: Defferent between constructor and form load? In Visual Studio C# Windows form application, what is the deferent between class constructor and form load?

A: Well simply put the constructor is called when the class is instantiated like all constructors, while the page load is called whenever a form is displayed for the first time.
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.load(v=vs.110).aspx

A:
a class may have multiple constructors that take different arguments, a form load, just simply loads the form on the screen and loads once the as the form is being loaded.
You can instantiate a class from your form load if you want to.

A: Question looks a bit odd for me, You can't compare apples with oranges.
Constructor is a method which will be executed when you instantiate an object where as Form.Load is an event.
btw Form.Load will only fired before the form is about to render into the screen; typically Form.Show causes Form.Load event.

A: Form.onLoad is an event, which occurs, when the form is shown on the screen. One can attach an eventhandler to this event and react inside it.
The constructor instantiates the (form)class, a public method without any return value ( even without  null ).
It MUST (MOSTLY) be called PRIOR to any "show" or "showdialog" method, so that the event "onLoad" may occurr ( in fact any "show" related methods are the reasons, why the event "onLoad" is fired).
If the constructor is not called, mostly onLoad will never occur ( because You cannot make null.showdialog for example ).
One also should keep in mind, that the Handle of the form may not yet be available in the ctor, where it surely will be already created when the event "onLoad" occurrs.

A: Constructor and formload is total different thing

*

*Constructor is function which return class return type always where
form load is event or from object.

*Constructor call internally when you create instance of class where
from load is call every time you fall into form_load signature.

*constructor can overload for taking parameter where from load cannot
be override.


text:
Q: '': cannot convert from 'initializer list' to 'Robot' I have an error in line 58 of the code : Robot robot = robot(seglist[0]...) I have tried different things but nothing works. I need to put the numbers that I have in the txt file into a vector and then assigned the values of robotNum, RobotTeam, robotPosX and robotPosY.
Hope someone can help me.
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <sstream>
#include <cstring>
#include <vector>

struct Robot {
    std::string robotNum;
    std::string robotTeam;
    std::string robotPosX;
    std::string robotPosY;
    public:
        Robot(string robotNum = "empty", string robotTeam = "empty", string robotPosX = "empty", string robotPosY = "empty") {
            this->robotNum = robotNum;
            this->robotTeam = robotTeam;
            this->robotPosX = robotPosX;
            this->robotPosY = robotPosY;
}

};

using namespace std;

string* sortArray(string* myArray) {

    //cout << "pingas";
    //cout << myArray[6];
    return myArray;
}

int main()
{

    ifstream myfile;
    myfile.open("start.txt");
    string line;
    std::vector<Robot> myArray;

    while (getline(myfile, line))
    {
        std::istringstream iss(line);
        string line;

        std::string segment;
        std::vector<std::string> seglist;

        while (std::getline(iss, segment, ','))
        {
            seglist.push_back(segment);
        }

        Robot robot = Robot(seglist[0], seglist[1], seglist[2], seglist[3]);

        myArray.push_back(robot);
        cout << "\n";
    }

    if (myfile.is_open()) {
        string myArray[2];
        for (int i = 0; i < 1; i++)
        {
            myfile >> myArray[i];
        }
        //string* arraySorted = sortArray(myArray);
        sort(myArray->begin(), myArray->end(), greater<int>());

        //for (auto& elem : myArray)
        //  cout << elem << " - " << endl;

    }
    //cout << myArray[];
    myfile.close();
    return 0;

}

A: in struct definition there should be

std:: namespace

for string in Robot constructor:
public:
        Robot(std::string robotNum = "empty", std::string robotTeam = "empty", std::string robotPosX = "empty", std::string robotPosY = "empty") {

after that code works for me.


text:
Q: character '@' in comment: procedure is not compiling Can anybody explain to me, why this syntax is not working at all, when I try to compile it in a SQL Developer worksheet? It seems as the '@' char is kind of preprocessed by th SQL Developer, but I did not find any explanations, why what is happening here.
CREATE OR REPLACE PROCEDURE PROC_TEST
IS
/*
@ example
*/
BEGIN
DBMS_OUTPUT.PUT_LINE('Test @ Procedure');
END;

/

this works fine:
CREATE OR REPLACE PROCEDURE PROC_TEST
IS
/*
 -  example
*/
BEGIN
DBMS_OUTPUT.PUT_LINE('Test @ Procedure');
END;
/

SQL Developer Version 17.2.0.188
Oracle Database 12c
thanks a lot.

A: When you say it's not working, can you show the error that SQL Developer is giving you?
It could be a SQL Developer bug. If I try the same code in version 18.3, it compiles just fine.


text:
Q: Can't access nginx from worker node in docker swarm Overview
I have a docker swarm with a manager running on an EC2 instance.
My personal laptop is a worker node.
Problem
I cannot access my nginx container on the worker node (my laptop) through the browser when I navigate to http://localhost:8080. Every time I try, I get "connection refused".
However, If I use the public IP of my EC2 with port 8080, I can access it just fine.
Also, I can access the container from another container on the worker node. Meaning, I can curl my Nginx container from my django container.
Code
Here's how I start my container on the manager.
docker service create \
    --name frontend \
    --mode global \
    --network {network name}\
    --publish published=8080,target=80 \
    --with-registry-auth \
    {aws registry}/{container name}:latest

I've also tried it like this. Note the --publish arg.
docker service create \
    --name frontend \
    --mode global \
    --network {network name}\
    --publish mode=host,published=8080,target=80 \
    --with-registry-auth \
    {aws registry}/{container name}:latest

I'm also fairly certain I've opened the necessary ports on my machine and EC2.
Any help would be greatly appreciated.


text: Q: Workbenches won't appear in Main Hall- Skyrim For the Heathfire extension you can build houses, and for each section of the house is a workbench to add in furnishings. None of them are appearing for me except the entry way, how can I fix it??


text:
Q: How, on VIFM, you can map a key to call the "=" (filter) function, without an initial query? When you type "=" on VIFM, it starts with the last query as the initial query. I want it to start empty. How is that possible?

A: Put the following command into your vifmrc to achieve the desired behaviour of =:
nnoremap = =<c-u>

Some details so you know how to deal with something similar in future:

*

*The command maps = to =<c-u> sequence of keys.

*nnoremap instead of nmap is needed to prevent expansion of any keys in right-hand side (in case you map Ctrl-U in command-line mode to something else one day).

*<c-u> key (notation for Ctrl-U) in command-line mode removes all characters from current position to the beginning of the line, just as in shell.

*As cursor is positioned at the end of the line <c-u> effectively clears the line.


text:
Q: Bug with comparison I have this comparison
coordinats.start.i < 1 || coordinats.start.i > edge

Now I show outputs of this comparison.
outputs
Everytime both of them have type String.
Please, explaine me why I have this results?

A: If the type of both variables is String, you need to parse them to Integer:
coordinats.start.i < 1 || parseInt(coordinats.start.i,10) > parseInt(edge,10)


text:
Q: CreateObject("VBScript.RegExp") Run-time error '429' I've just started studying Excel VBA with Mac. When I executed the following macro, run-time error occurred. Could anyone help me out?
Here is my code:
Sub macro()
  Dim regex As Object, matchList As Object
  Dim str As String, patternStr As String
  str = "0123-4567"
  patternStr = "\d+"
  'patternStr = "¥d+"

  Set regex = CreateObject("VBScript.RegExp")
  With regex
      .Global = True
      .Pattern = patternStr
      Set matchList = .Execute(str)
  End With
End Sub

Here is the error message:
Run-time error '429':
ActiveX component can't create object

A: ActiveX is for only Windows, which means regular expressions are not officially available on Mac. It needs to download third-party libraries to enable regular expressions work on Mac.
Thank you for your help, Tim Williams.


text:
Q: Generate a customer layer for Convolutional Neural Network, but TypeError remind: float() argument must be a string or a number, not 'Dimension' The code is below (customer layer model partly omitted):
import tensorflow as tf
print(tf.__version__)
from __future__ import absolute_import, division, print_function
# TensorFlow and tf.keras
#from tensorflow.keras import datasets, layers, models

import numpy as np
import os
import pickle
import gzip
import urllib.request

from keras.optimizers import SGD
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D

from keras.layers import Layer

from keras.utils import np_utils
from keras.models import load_model

# custom layers starts from here.

class STFTLayer(Layer):
    def __init__(self, patch_size, stride, **kwargs):
        super(STFTLayer, self).__init__(**kwargs)
        self.patch_size = patch_size
        self.stride = stride
    # TensorFlow uses this function internally to get the right
    # shape for next layer in the model
    # DO NOT EDIT
    def compute_output_shape(self, input_shape):
        mock_shape = (1, input_shape[1], input_shape[2], input_shape[3])
        mock_data = tf.zeros(mock_shape)
        mock_patches = tf.image.extract_image_patches(mock_data,
        sizes=[1,self.patch_size,self.patch_size,1],strides=[1,self.stride,self.stride,1],rates=[1,1,1,1],padding='VALID')
        op_shape = mock_patches.shape
        return (input_shape[0], op_shape[1], op_shape[2], op_shape[3])
    # TensorFlow uses the this function to save the layer when
    # model.save is called
    # DO NOT EDIT
    def get_config(self):
        config = super(STFTLayer,self).get_config()
        config['patch_size'] = self.patch_size
        config['stride'] = self.stride
        return config
    # Change this function to change how the sampler vectors look
    def call(self, inputs):
        # Get patches from the input batch of images
        # code omitted here
        ###
        return op

# Main code for modeling begins here
# Load MNIST datasets

def extract_data(filename, num_images):
    with gzip.open(filename) as bytestream:
        bytestream.read(16)
        buf = bytestream.read(num_images*28*28)
        data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
        data = (data / 255) - 0.5
        data = data.reshape(num_images, 28, 28, 1)
        return data

def extract_labels(filename, num_images):
    with gzip.open(filename) as bytestream:
        bytestream.read(8)
        buf = bytestream.read(1 * num_images)
        labels = np.frombuffer(buf, dtype=np.uint8)
    return (np.arange(10) == labels[:, None]).astype(np.float32)

class MNIST:
    def __init__(self):
        if not os.path.exists("data"):
            os.mkdir("data")
            files = ["train-images-idx3-ubyte.gz",
                     "t10k-images-idx3-ubyte.gz",
                     "train-labels-idx1-ubyte.gz",
                     "t10k-labels-idx1-ubyte.gz"]
            for name in files:

                urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/' + name, "data/"+name)

        train_data = extract_data("data/train-images-idx3-ubyte.gz", 60000)
        train_labels = extract_labels("data/train-labels-idx1-ubyte.gz", 60000)
        self.test_data = extract_data("data/t10k-images-idx3-ubyte.gz", 10000)
        self.test_labels = extract_labels("data/t10k-labels-idx1-ubyte.gz", 10000)

        VALIDATION_SIZE = 5000

        self.validation_data = train_data[:VALIDATION_SIZE, :, :, :]
        self.validation_labels = train_labels[:VALIDATION_SIZE]
        self.train_data = train_data[VALIDATION_SIZE:, :, :, :]
        self.train_labels = train_labels[VALIDATION_SIZE:]

print(MNIST().train_data.shape)
print(MNIST().validation_data.shape)

train_images = MNIST().train_data
train_labels = MNIST().train_labels
test_images = MNIST().validation_data
test_labels = MNIST().validation_labels

MODEL_PATH = '/home/bo/Documents/Weibo/STFT_model/models/custom_layers'
# If saved model exists, load it
# If any changes are made to STFTLayer logic, remember
# to delete existing saved model file

if not os.path.isdir('/home/bo/Documents/Weibo/STFT_model/models/'):
    os.makedirs('/home/bo/Documents/Weibo/STFT_model/models/')

if os.path.exists(MODEL_PATH):
    model = load_model(MODEL_PATH, custom_objects={'STFTLayer': STFTLayer})
    model.summary()
# Otherwise create new model.
else:

    model = Sequential()
    # Add our STFTLayer as the first layer with patch_size 4 and stride 1
    model.add(STFTLayer(4,1,input_shape=(28,28,1),name='STFTLayer'))
    model.add(Conv2D(32, (1, 1)))
    #model.add(Conv2D(32, (1, 1), input_shape=(28,28,1)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D((2, 2)))
    model.add(Conv2D(64, (1, 1)))
    model.add(Activation('relu'))
    model.add(MaxPooling2D((2, 2)))
    model.add(Conv2D(64, (1, 1)))
    model.add(Activation('relu'))
    model.add(Flatten())
    model.add(Dense(64))
    model.add(Activation('relu'))
    #model.add(Dense(10, activation = 'softmax'))
    model.add(Dense(10))

    def fn(correct, predicted):
        return tf.nn.softmax_cross_entropy_with_logits(labels=correct,
                                                       logits=predicted/1)

    sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)

    model.compile(loss=fn,
                  optimizer='adamax',
                  metrics=['accuracy'])

    model.fit(train_images, train_labels,
              batch_size=128,
              validation_data=(test_images, test_labels),
              nb_epoch=20,
              shuffle=True)

    model.summary()
    #model.compile(optimizer='adamax',loss='sparse_categorical_crossentropy',metrics=['accuracy'])
    #model.compile(optimizer='adamax',loss='categorical_crossentropy',metrics=['accuracy'])
    # Train model
    #model.fit(train_images, train_labels, epochs=10, batch_size=128, shuffle=True)
    # Save the model
    model.save(MODEL_PATH)
test_loss, test_acc = model.evaluate(test_images, test_labels)

The code gave me the error:
TypeError                                 Traceback (most recent call last)
<ipython-input-3-44798d695c82> in <module>()
    190     # Add our STFTLayer as the first layer with patch_size 4 and stride 1
    191     model.add(STFTLayer(4,1,input_shape=(28,28,1),name='STFTLayer'))
--> 192     model.add(Conv2D(32, (1, 1)))
    193     #model.add(Conv2D(32, (1, 1), input_shape=(28,28,1)))
    194     model.add(Activation('relu'))

5 frames
/usr/local/lib/python3.6/dist-packages/keras/engine/sequential.py in add(self, layer)
    180                 self.inputs = network.get_source_inputs(self.outputs[0])
    181         elif self.outputs:
--> 182             output_tensor = layer(self.outputs[0])
    183             if isinstance(output_tensor, list):
    184                 raise TypeError('All layers in a Sequential model '

/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    423                                          'You can build it manually via: '
    424                                          '`layer.build(batch_input_shape)`')
--> 425                 self.build(unpack_singleton(input_shapes))
    426                 self.built = True
    427

/usr/local/lib/python3.6/dist-packages/keras/layers/convolutional.py in build(self, input_shape)
    139                                       name='kernel',
    140                                       regularizer=self.kernel_regularizer,
--> 141                                       constraint=self.kernel_constraint)
    142         if self.use_bias:
    143             self.bias = self.add_weight(shape=(self.filters,),

/usr/local/lib/python3.6/dist-packages/keras/legacy/interfaces.py in wrapper(*args, **kwargs)
     89                 warnings.warn('Update your `' + object_name + '` call to the ' +
     90                               'Keras 2 API: ' + signature, stacklevel=2)
---> 91             return func(*args, **kwargs)
     92         wrapper._original_function = func
     93         return wrapper

/usr/local/lib/python3.6/dist-packages/keras/engine/base_layer.py in add_weight(self, name, shape, dtype, initializer, regularizer, trainable, constraint)
    241         if dtype is None:
    242             dtype = self.dtype
--> 243         weight = K.variable(initializer(shape, dtype=dtype),
    244                             dtype=dtype,
    245                             name=name,

/usr/local/lib/python3.6/dist-packages/keras/initializers.py in __call__(self, shape, dtype)
    207             scale /= max(1., fan_out)
    208         else:
--> 209             scale /= max(1., float(fan_in + fan_out) / 2)
    210         if self.distribution == 'normal':
    211             # 0.879... = scipy.stats.truncnorm.std(a=-2, b=2, loc=0., scale=1.)

TypeError: float() argument must be a string or a number, not 'Dimension'

But the code works when I using tensorflow.keras for writing the neural networks model, here is the code below that is working well:
from __future__ import absolute_import, division, print_function
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow.keras import layers, models
import os
# Helper libraries
import numpy as np

import urllib.request
import gzip

# Custom layers starts here.

class STFTLayer(layers.Layer):
    def __init__(self, patch_size, stride, **kwargs):
        super(STFTLayer, self).__init__(**kwargs)
        self.patch_size = patch_size
        self.stride = stride
    # TensorFlow uses this function internally to get the right
    # shape for next layer in the model
    # DO NOT EDIT
    def compute_output_shape(self, input_shape):
        mock_shape = (1, input_shape[1], input_shape[2], input_shape[3])
        mock_data = tf.zeros(mock_shape)
        mock_patches = tf.image.extract_image_patches(mock_data,
        sizes=[1,self.patch_size,self.patch_size,1],strides=[1,self.stride,self.stride,1],rates=[1,1,1,1],padding='VALID')
        op_shape = mock_patches.shape
        return (input_shape[0], op_shape[1], op_shape[2], op_shape[3])
    # TensorFlow uses the this function to save the layer when
    # model.save is called
    # DO NOT EDIT
    def get_config(self):
        config = super(STFTLayer,self).get_config()
        config['patch_size'] = self.patch_size
        config['stride'] = self.stride
        return config
    # Change this function to change how the sampler vectors look
    def call(self, inputs):
        # Get patches from the input batch of images
        # code omitted here
        ###
        return op

# Main code for modeling begins here
# Load MNIST datasets

def extract_data(filename, num_images):
    with gzip.open(filename) as bytestream:
        bytestream.read(16)
        buf = bytestream.read(num_images*28*28)
        data = np.frombuffer(buf, dtype=np.uint8).astype(np.float32)
        data = (data / 255) - 0.5
        data = data.reshape(num_images, 28, 28, 1)
        return data

def extract_labels(filename, num_images):
    with gzip.open(filename) as bytestream:
        bytestream.read(8)
        buf = bytestream.read(1 * num_images)
        labels = np.frombuffer(buf, dtype=np.uint8)
    return (np.arange(10) == labels[:, None]).astype(np.float32)

class MNIST:
    def __init__(self):
        if not os.path.exists("data"):
            os.mkdir("data")
            files = ["train-images-idx3-ubyte.gz",
                     "t10k-images-idx3-ubyte.gz",
                     "train-labels-idx1-ubyte.gz",
                     "t10k-labels-idx1-ubyte.gz"]
            for name in files:

                urllib.request.urlretrieve('http://yann.lecun.com/exdb/mnist/' + name, "data/"+name)

        train_data = extract_data("data/train-images-idx3-ubyte.gz", 60000)
        train_labels = extract_labels("data/train-labels-idx1-ubyte.gz", 60000)
        self.test_data = extract_data("data/t10k-images-idx3-ubyte.gz", 10000)
        self.test_labels = extract_labels("data/t10k-labels-idx1-ubyte.gz", 10000)

        VALIDATION_SIZE = 5000

        self.validation_data = train_data[:VALIDATION_SIZE, :, :, :]
        self.validation_labels = train_labels[:VALIDATION_SIZE]
        self.train_data = train_data[VALIDATION_SIZE:, :, :, :]
        self.train_labels = train_labels[VALIDATION_SIZE:]

print(MNIST().train_data.shape)
print(MNIST().validation_data.shape)

train_images = MNIST().train_data
train_labels = MNIST().train_labels
test_images = MNIST().validation_data
test_labels = MNIST().validation_labels

MODEL_PATH = '/home/bo/Documents/Weibo/STFT_model/models/custom_layers'
# If saved model exists, load it
# If any changes are made to STFTLayer logic, remember
# to delete existing saved model file

if not os.path.isdir('/home/bo/Documents/Weibo/STFT_model/models/'):
    os.makedirs('/home/bo/Documents/Weibo/STFT_model/models/')

if os.path.exists(MODEL_PATH):
    model = keras.models.load_model(MODEL_PATH, custom_objects={'STFTLayer': STFTLayer})
    model.summary()
# Otherwise create new model.
else:
    model = models.Sequential()
    # Add our STFTLayer as the first layer with patch_size 4 and stride 1
    model.add(STFTLayer(4,1,input_shape=(28,28,1),name='STFTLayer'))
    model.add(layers.Conv2D(32, (1, 1), activation='relu'))
    model.add(layers.MaxPooling2D((2, 2)))
    model.add(layers.Conv2D(64, (1, 1), activation='relu'))
    model.add(layers.MaxPooling2D((2, 2)))
    model.add(layers.Conv2D(64, (1, 1), activation='relu'))
    model.add(layers.Flatten())
    model.add(layers.Dense(64, activation='relu'))
    #model.add(layers.Dense(10, activation='softmax'))
    model.add(layers.Dense(10))

    model.summary()

    def fn(correct, predicted):
        return tf.nn.softmax_cross_entropy_with_logits(labels=correct,
                                                       logits=predicted/1)

    sgd = tf.keras.optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)

    model.compile(loss=fn,
                  optimizer='adamax',
                  metrics=['accuracy'])

    model.fit(train_images, train_labels,
              batch_size=128,
              validation_data=(test_images, test_labels),
              nb_epoch=10,
              shuffle=True)

    #model.compile(optimizer='adamax',loss='categorical_crossentropy',metrics=['accuracy'])
    # Train model
    #model.fit(train_images, train_labels, epochs=10, batch_size=128, shuffle=True)
    # Save the model
    model.save(MODEL_PATH)
test_loss, test_acc = model.evaluate(test_images, test_labels)

In summary, the first code version by using importing keras is not working for my customer layer, but the second code version is working by using importing tensorflow.keras. I want the first code version also works for matching other people's code. Need your helps, thank you!

A: The custom layer has been solved by defining a non-training parameter function and building the sequential model layers by using keras.layers.Lambda, tensorflow version 1.x.


text:
Q: Is SATA 3 backwards compatible? I am getting a SSD but the only cheap ones are SATA 2, and my motherboard has only SATA 3 slots. Will it work with my motherboard and do I need to buy a SATA 2 or 3 cable for it?

A: Yes, it is and has always been.


text:
Q: Shortcut (.lnk) files in Visual Studio Solution Explorer If I drag in the actual Excel file, it makes a copy of it in the folder and then I can double click it open it in Excel. It shows the little Excel Logo in Visual Studio. Great!!
I am also able to add a shortcut to a file in my solution explorer in Visual Studio. It shows. Example.lnk with a white file. It would be nice if it was smart enough to show the Excel icon. But that's the least of my problems.
If I double click it, it opens the shortcut in Hex. Great if I want to actually edit the shortcut itself, however, no so great when I want to use these tables of data as references with my code. And not have to sync changes between original and the copy Visual Studio enjoys making.
Is there a way to tell Visual Studio to follow the shortcut?
Thanks!

A: I worked around this issue by creating a small .exe.
class Program
{
    static void Main(string[] args)
    {
        if(args.Count() > 1)
        {
            Process.Start(args[1]);
        }
    }
}

Then in Visual Studio, right click any .lnk file and pick Open Width. Add this .exe to the list. For arguments put in "$(ItemPath)".
Select application in the listbox and click set as default.
From this point forward any .lnk on the tree will use this program follow the .lnk.


text:
Q: RAILS: -destroy just erasing record (not deleting) bicycle.rb
  has_many :pictures, as: :imageable
  accepts_nested_attributes_for :pictures, allow_destroy: true, :reject_if => proc { |obj| obj.blank? }

picture.rb
  belongs_to :imageable, polymorphic: true
  has_attached_file :image
  validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png"]

Edit view
<% @bicycle.pictures.each do |pic| %>
              <%= bicycle_form.fields_for :pictures, pic do |frm| %>
              <div class="col-lg-2">
                  <%= image_tag pic.image.url, class: 'edit-image-thumb'%>
                  Delete: <%= frm.check_box :_destroy %>
              </div>
              <% end %>
            <% end %>

Picture attribute _destroy is whitelisted:
pictures_attributes: [:id, :image, :_destroy]

Problem:
As i understand, _destroy checkbox must delete whole record in database (picture record), but it's just erasing image_file_name image_content_type image_file_size column values, but record still exists.
Explanation:
I have bicycle which has many pirctures. So when i am creating new bicycle, i can attach many pictures. If i want to delete them, i am going to edit view and checking checkboxes for pictures i want to delete. But pictures records doesn't deleting from db, just clearing columns image_file_name image_content_type image_file_size leaving them blank but columns (in the same record) imageable_type and id still have values. So the image is showing up (it still exitst) but like missing (record exists but field with image name is nil)


text:
Q: Passing data from collection view to detail view I need some help figuring out how to pass data from my collection view to the detail view controller. I am starting by simply passing the image through. My code is below:
ViewController:
    -(MyCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

     MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];

    PFObject *imageObject = [imageFilesArray objectAtIndex:indexPath.row];
    __block UIImage *MyPicture = [[UIImage alloc]init];
    PFFile *imageFile = [imageObject objectForKey:@"test"];

    [imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
        if (!error) {
            MyPicture = [UIImage imageWithData:data];
            cell.CollectionImg.image = [UIImage imageWithData:data];
            cell.cellLabel.text = [object objectForKey:@"phone"];

        }
    }];

    return cell;
}

 - (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
        TopDetailViewController *detailVC = [[TopDetailViewController alloc] initWithNibName:@"TopDetailViewController" bundle:[NSBundle mainBundle]];
        detailVC.img= [imageFilesArray objectAtIndex: indexPath.row];
        [self.navigationController pushViewController:detailVC animated:YES];
    }

And the Detail view:
.h
@property (nonatomic, strong) IBOutlet UIImageView *imageView;
@property (nonatomic, strong) IBOutlet NSString *img;

.m
    - (void)viewDidLoad
{
    [super viewDidLoad];
    self.imageView.image = [UIImage imageNamed:self.img];
    // Do any additional setup after loading the view from its nib.
}

If someone could help me out I would greatly appreciate.

A: You can only use [UIImage imageNamed:] to retrieve images that are in your app bundle. It looks like you create these images at run-time based on the PDF file, so just passing in the string to the detail view and loading it with [UIImage imageNamed:] won't work. You should pass the reference to the image or the PFFile object so that the detail view can generate the image itself.


text:
Q: Really weird JQuery scrollTop issue break all other jquery functions I'm trying to do a simple jquery smooth scroll, but when I put the code:
$("a.fashion").click(function(){
    $("html,body").animate({scrollTop:0}, "slow");
});

All my other jquery code stops working.
Only when I add the line:
$("html,body").animate({scrollTop:0}, "slow");

I can add anything else in that function and it will work but not that line. Any idea what I'm doing wrong?

A: May be this will help you.Change the line as follow
$("a.fashion").click(function(){
 $("html, body").animate({scrollTop: $(document).height()}, 'slow');
return false;
});

or just follow this link Smooth scrolling

A: Thanks for the answer all. I just figured out the problem. It seemed to have been linked to weird spacing in the function block. I pasted it inline and it worked then made sure when I put it on the next line it was only one tab space (instead of a tabspace and a piece). Weird. Didn't think whitespace mattered... O_o


text:
Q: Did Unix have a package manager? I've looked online but couldn't get a straight answer. Plus, there are no mentions of package managers on the Unix books that I've read.
One would imagine that someone/something needed to manage the installation/update/removal of programs; like we have today.
But did the people at Bell Labs have a package manager? Did they have a centralized repository with a bunch of programs? Or was it like Slackware today where each person manages their own packages?
Thanks in advance

A: No.
The package manager requires a repository to be useful. Some storage space where packages wait to be installed.
A repository requires network. Or some other kind of external storage.
The earliest "package manager" (which was not called "package manager") was an "installation manager" which was a part of install CD. And that was 90s already... Not sure which distributive had that feature first, I met it in the middle of 90s in FreeBSD. It was a set of four CDs with an OS on the first, necessary tools on the second and last two had a lot of user-level applications (text and graphic editors, games, etc). A user could re-start the installation utility at any time (on a working OS) and install an app from these CDs, it felt very weird, but was useful.
The internet-based repository and package managers for them I first met only in this century.
Before that: get an app.tar.gz file, unpack it, run configure; make; make install - if failed, take your favorite text editor, look for a problem, try to fix, compile again.

A: Early unix did not have a package manager, but some of the commercial distributions added package managers.  All of them were proprietary and non-standard.
For example, SunOS (aka Solaris), HPUX, and IRIX all had package managers.  Early versions of these were designed to install packages from distribution media or pre-downloaded packages given on the command line.  Most of these predated internet, so did not have support for downloading.  (Instead, you would feed them packages likely pulled from magnetic tape, and later cdrom or dvd.)  Later, some versions were able to download from internet or they were wrapped in meta package managers that could.


text:
Q: C change words beginning with lowercase to capital in text file Well I try to read a file and change every word that's beginning with a lowercase to the same word beginning with an uppercase.
This is what i got:
#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *fp;
int zeichen;

fp = fopen("test.txt", "r+");

if(fp == NULL){
    printf("Die Datei konnte nicht geoeffnet werden.\n");
}
else{
    fseek(fp, 0L, SEEK_SET);
    zeichen = fgetc(fp);
    while(zeichen != EOF){
        if(zeichen == ' '){
            fseek(fp, 1L, SEEK_CUR);
            if(('a' <= zeichen) && (zeichen <= 'z')){
                zeichen = fgetc(fp);
                fputc(toupper(zeichen), fp);
            }
        }
        zeichen = fgetc(fp);
    }
    zeichen = fgetc(fp);
    fclose(fp);
}
return 0;
}

My test.txt file does not change at all.
Any suggestions what i am doing wrong?
EDIT:
Thank you for the different ways to achieve my task.
Most of them where using stuff i didn't learn yet, so i tried it by copying the characters from one file to another + making the first letter of each word an uppercase by toupper() cause it's indeed easy to use. Then deleting the old file + rename the new one.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    FILE *fp, *neu;
    int zeichen;

    fp = fopen("test.txt", "r");
    neu = fopen("new.txt", "w");

    if(fp == NULL) {
        printf("Die Datei konnte nicht geoeffnet werden.\n");
        exit(EXIT_FAILURE);
    }

    while((zeichen = fgetc(fp)) != EOF) {
        if(zeichen == ' ') {
            fputc(zeichen, neu);
            zeichen = fgetc(fp);
            zeichen = toupper(zeichen);
            fputc(zeichen, neu);
        }
        else{
            fputc(zeichen, neu);
        }
    }
    fclose(fp);
    fclose(neu);
    remove("test.txt");
    rename("new.txt", "test.txt");
    printf("File has been changed.\n");
    return 0;
}

A: Let us say a word begins with a letter after a space (or white-space) or at file beginning.
Look for the pattern <space><lowercase>
Seeking relative to SEEK_CUR should be avoided for text files.
bool previous_space = true;
long offset = ftell(fp);  // remember where we are
while(offset != -1 && (zeichen = fgetc(fp)) != EOF) {
  if (previous_space && islower(zeichen)) {
    fseek(fp, offset, SEEK_SET);
    fputc(toupper(zeichen), fp);
  }
  previous_space = isspace(zeichen);
  offset = ftell(fp);
}

OP's code had trouble as fseek() was not needed and ('a' <= zeichen) && (zeichen <= 'z') is always false (in ASCII) as ' ' is not between 'a' and 'z'.
    if(zeichen == ' '){
        fseek(fp, 1L, SEEK_CUR);
        if(('a' <= zeichen) && (zeichen <= 'z')){
            zeichen = fgetc(fp);
            fputc(toupper(zeichen), fp);
        }
    }

A: Apart from that focusing on words you can achieve more secure results, if your file contains only space separated words, you can rely on first letter after space character.
You tried to use the fseek which is not not bad at all but I would use it differently:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main() {
    FILE* fp;
    int zeichen;

    fp = fopen("test.txt", "r+");
    if(fp == NULL) {
        printf("Die Datei konnte nicht geoeffnet werden.\n");
        exit(EXIT_FAILURE);
    }

    while((zeichen = fgetc(fp)) != EOF) {
        if(zeichen == ' ') {
            zeichen = fgetc(fp);
            fseek(fp, -1, SEEK_CUR);
            fputc(toupper(zeichen), fp);
        }
    }

    fclose(fp);
    return 0;
}

Stepping back after reading the first letter next to a space is important, because fgetc (and fputc too) autmatically step the cursor forward after reading. So, to rewrite the current letter to its upper case counterpart, you have to step back the cursor.
The shortcomings of my example are that it won't change the first letter of the first word in a file and it's important to the file should not end with a space but with a word.

A: Your code is a bit of an overkill, let alone some things I am not that smart to understand (for example why you are checking for the space character, why the condition of checking for a lowercase is ('a' <= zeichen) && (zeichen <= 'z') and not 'a' >= ...). Moreover the non-universal language makes it tough for me. Some of them are already explained in the comments, so I will try to explain what I would do.
I wouldn't try to fseek() all the time, I would read the file once and then write the data once again. Here is my algorithm:

*

*Read file line by line.

*Store every word in a 2D array.

*Check if a word starts with a lowercase, and if so swap that
lowercase letter with an uppercase one.

*Now the array holds all the data I need to write to the file.

*Set the file pointer to the start of the file.

*Iterate over the stored words in the array and write them to file.

Here is my implementation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX 5   // max number of words to be read
#define LEN 10  // max lenght of a word allowed

int main(void)
{
    FILE* fp = fopen("test.txt", "r+");
    char buffer[MAX][LEN]; // read up to 5 words, of at most 10 characters
    if (fp == NULL)
        exit(EXIT_FAILURE);
    int count = 0;
    while(count < MAX && fgets(buffer[count], LEN, fp)) {
        if(buffer[count][strlen(buffer[count]) - 1] == '\n') buffer[count][strl$
        //printf("%s\n", buffer[count]);
        if(islower(buffer[count][0]))
            buffer[count][0] = (char)toupper(buffer[count][0]);
        //printf("%s\n", buffer[count]);
        count++;
    }

    fseek(fp, 0, SEEK_SET);
    for(int i = 0; i < count; ++i)
        fprintf(fp, "%s\n", buffer[i]);

    fclose(fp);
    return 0;
}

which will overwrite the contents of this file:
Manu
Samaras
small

to this:
Manu
Samaras
Small

A: FILE *fp;
int zeichen;

fp = fopen("test.txt", "r+");

if (fp == NULL) {
    printf("Die Datei konnte nicht geoeffnet werden.\n");
    exit(EXIT_FAILURE);
}

// upper first charcter
zeichen = getc(fp);
if (zeichen != EOF) putchar(toupper(zeichen));

// scan rest of chars
while ((zeichen = getc(fp)) != EOF) {
    putchar(zeichen);
    if (zeichen == ' ' && zeichen != EOF) {
        char c_upper = getc(fp);
        putchar(toupper(c_upper));
    }
}
fclose(fp);
return 0;

you can use std out redirection ./main > output.txt


text:
Q: Modifying interface with key interactions in javafx I'm trying to code a 2048 game using JavaFX and I'm facing a problem.
@Override
public void start(Stage primaryStage){
    primaryStage.setResizable(false);
    Scene scene = new Scene(firstContent());
    primaryStage.setScene(scene);
    primaryStage.show();
    scene.setOnKeyPressed(new EventHandler<KeyEvent>(){
        @Override
        public void handle(KeyEvent e){
            KeyCode key = e.getCode();
            if((key.equals(KeyCode.UP))){
                System.out.println("recieved UP");
                Scene scene = new Scene(createContent());
                primaryStage.setScene(scene);
                primaryStage.show();
            } else if(key.equals(KeyCode.DOWN)){
                System.out.println("recieved DOWN");
            }
        }
    });
}

So here I open my window initialised with firstContent (basically it creates an array of empty tiles, and fills two of them with 2 or 4 randomly), display it and start listening for key presses. The idea is to have a behavior for each arrow key (UP DOWN LEFT RIGHT) which will move the tiles accordingly. This is done by the following createContent() method :
    public Parent createContent(){
    String c  = "";
    List<Integer> known = new ArrayList<Integer>();
    Pane root = new Pane();
    root.setPrefSize(740, 700);
    Random rand = new Random();
    int pos1 = rand.nextInt(15);
    if(tiles.get(pos1) != new Tile("")){
        known.add(pos1);
        pos1 = rand.nextInt(15);
        if(known.contains(pos1)){
            known.add(pos1);
            pos1 = rand.nextInt(15);
        }
    }
    for(int i = 0; i < NB_TILES; i++){
        tiles.add(new Tile(c));
    }
    tiles.set(pos1, new Tile("2048"));

    for(int i = 0; i < tiles.size(); i++){
        // boring stuff to set the tile display to the right size
    }
    return root;
}

Now for the problem : when the application is running, if I press the down arrow, I do get on my terminal the "recieved DOWN" text as many times as I press the key as expected. But if I press the up arrow, the application will only recieve it once and the application seems to be frozen (meaning if I press down again, nothing happens).
As you could guess, I want to be able to call my method for each key press to be able to move my tiles around and utltimately combine them to get a playable version of 2048... Anyone know why my app gets frozen ?
If needed, I can provide other bits of code but I think I provided the essential. Just know that firstContent() works basically the same as createContent for now except it genereates two random numbers to get the first tiles of the game.
Thanks in advance for your help.


text:
Q: C++ polymorphism: going from base class to derived class class A{};

class B : A{};

void func(A* p)
{

      B* p2 = p; // Error

}

A: Your code has several oddities.

*

*You use private inheritance. In private inheritance you will not be able to convert to a derived class ever when you are not inside the class scope itself.

*Even if you would inherit publicly, you will need at least one virtual function (and that should be the destructor) in the base class to use dynamic_cast.

*Chances are you are doing something wrong when you need a lot of down-casts. You should probably rethink your design or usage of the provided API.

Typically, things would look like this:
class A {
public:
  virtual ~A() {}
};

class Derived : public A {

};

void func(A* a) {
  if(Derived* d = dynamic_cast<Derived*>(a)) {
    // yeah, a is of type derived
  } else {
    // a is not of type Derived
  }
}

A: is-a relationship is implemented by public inheritance. as you are inheriting it privately this is association relationship which is not is-a. so B is not an A. So you cannot store A in B or A cannot become an B
and dynamic_cast will not work as source type is not polymorphic
neither would static_cast work as 'A' is an inaccessible base of 'B'
To make an is-a relationship you need to do class B: public A{}

A: For classes private inheritance is used by default.


text:
Q: Flutter : How to parse JSON Array of Array of objects Can anyone tell me how to parse arrays of arrays of object in flutter. When I am parsing the json I am getting error as
List<dynamic> is not a subtype of type Map<String, dynamic>.
I have used quicktype to write the model class and I am trying to print the worksheetData in the Future but I am getting error. Below is my json file which needs to be parsed. Please help me to fix this issue. Stuck since two days.
[
    {
        "_id": "5ebae61440315c41995eccc7",
        "projectName": "NSM",
        "sheetName": "Priliminaries - A1",
        "worksheetData": [
            [
                {
                    "serial": "Sl.No",
                    "description": "ITEM DESCRIPTION",
                    "quantity": "QTY.",
                    "unit": "UNIT",
                    "unitrate": "UNIT PRICE",
                }
            ],
            null,
            [
                {
                    "serial": "1.1",
                    "description": "Allowance for CAR policy, Mobilization, demobilization after works, Firstaid boxes, Fire extinguishers etc.",
                    "quantity": 1,
                    "unit": "Lot",
                    "unitrate": 12500,
                }
            ],
            [
                {
                    "serial": "1.2",
                    "description": "Demolition of existing gypsum partitions, ceilings, necessary floor tiles etc and cart away debris if any",
                    "quantity": 0,
                    "unit": "Lot",
                    "unitrate": 5000,
                }
            ]
        ],
        "__v": "0"
    },
    {
        "_id": "5ebae61440315c41995eccc8",
        "projectName": "NSM",
        "sheetName": "General works -A2",
        "worksheetData": [
            [
                {
                    "serial": "Sl.No",
                    "description": "ITEM DESCRIPTION",
                    "quantity": "QTY.",
                    "unit": "UNIT",
                    "unitrate": "UNIT PRICE",
                }
            ],
            null,
            [
                {
                    "serial": "1.1",
                    "description": "Allowance for CAR policy, Mobilization, demobilization after works, Firstaid boxes, Fire extinguishers etc.",
                    "quantity": 1,
                    "unit": "Lot",
                    "unitrate": 12500,
                }
            ],
            [
                {
                    "serial": "1.2",
                    "description": "Demolition of existing gypsum partitions, ceilings, necessary floor tiles etc and cart away debris if any",
                    "quantity": 0,
                    "unit": "Lot",
                    "unitrate": 5000,
                }
            ]
        ],
        "__v": "0"
    }
]

Main.dart
class WorkSheet extends StatefulWidget {
  const WorkSheet({Key key}) : super(key: key);
  @override
  _WorkSheetState createState() => new _WorkSheetState();
}

class _WorkSheetState extends State<WorkSheet> {
  // List<ArticleslistData> articleslist = [];
  // List<ArticleslistData> list;

  @override
  void initState() {
    setState(() {
      loadSheetDataFromAssets();
    });
    super.initState();
  }

  Future loadSheetDataFromAssets() async {
    var jsonData = await rootBundle.loadString('assets/Vibyor.json');
    var data = json.decode(jsonData);
    ArticleslistData articleslistData = new ArticleslistData.fromJson(data);
     print('data : ${articleslistData.worksheetData[0]}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Work sheet data'),
      ),
      body: FutureBuilder(
          future: loadSheetDataFromAssets(),
          builder: (context, snapshot) {
            return snapshot.data != null
                ? Text(snapshot.data)
                : Center(child: CircularProgressIndicator());
          }),
    );
  }
}

A: I've refactored Your classes:
class ArticleslistData {
  String sId;
  String projectName;
  String sheetName;
  List<WorksheetData> worksheetData = [];
  String sV;

  ArticleslistData(this.sId, this.projectName, this.sheetName, this.worksheetData, this.sV);

  static ArticleslistData fromMap(Map<String, dynamic> map) {
    List<WorksheetData> worksheetData = [];
    if (map['worksheetData'] != null) {
      for (Iterable row in map['worksheetData']) {
        if (row == null) continue;
        for (Map map in row) {
          worksheetData.add(WorksheetData.fromMap(map));
        }
      }
    }

    return ArticleslistData(
      map['_id'],
      map['projectName'],
      map['sheetName'],
      worksheetData,
      map['__v']
    );
  }

  Map<String, dynamic> toMap() {
    return {
      "_id":            this.sId,
      "projectName":    this.projectName,
      "sheetName":      this.sheetName,
      "worksheetData":  this.worksheetData,
      "__v":            this.sV
    };
  }
}

class WorksheetData {
  String serial;
  String description;
  String quantity;
  String unit;
  String unitrate;

  WorksheetData(this.serial, this.description, this.quantity, this.unit, this.unitrate);

  static WorksheetData fromMap(Map map) {
    return WorksheetData(
        map['serial'].toString(),
        map['description'].toString(),
        map['quantity'].toString(),
        map['unit'].toString(),
        map['unitrate'].toString()
    );
  }

  Map<String, dynamic> toMap() {
    return {
      "serial":       this.serial,
      "description":  this.description,
      "quantity":     this.quantity,
      "unit":         this.unit,
      "unitrate":     this.unitrate
    };
  }
}

Usage:
Future loadSheetDataFromAssets() async {
  var jsonData = await rootBundle.loadString('assets/Vibyor.json');
  var data = json.decode(jsonData);

  this.articleslist = [];
  List<ArticleslistData> items = [];
  data.forEach((item) {
    items.add(ArticleslistData.fromMap(element));
  });
  this.articleslist = items;

  print('data : ${this.articleslist[0].worksheetData[0]}');
  return this.articleslist;
}

Don't forget to uncomment following from Your _WorkSheetState widget:
List<ArticleslistData> articleslist = [];

P.S. fromJson and toJson method names are not valid, so I renamed them to fromMap, toMap since You were working maps.
JSON is string that You decoded, after decode it becomes Iterable and Map.
Small hint: if You want to easily solve Your issues - use IntelliJ Idea Community Edition and do debug by setting breakpoints.


text:
Q: Extract number and following text and create multiple new columns in R I have free-text data with numerous references to specific questions, and I'd like to organize it as shown below.
I'm able to create columns that note mentions of a certain topic (if the respondent references it by number), but I'd like a way to extract all of the text following the number, until another number is encountered.
Thanks in advance for any help!
library(tidyverse, warn.conflicts = F)

# Data
df <- data.frame(comment = c("topic 1: this is fine. 4 this is fine too. #9 not so good", "1 ok this is fine. 17 i do not like this idea. 25 great idea 43 cool idea"))

# I can identify the mentions if a respondent specifies the number they are responding to
df <- df %>%
  mutate(mention = map(str_extract_all(comment, "[0-9]+"), as.numeric)) %>%
  unnest_wider(col = mention, names_sep = "_")

# Ideal output
df_ideal <- structure(list(comment = c("topic 1: this is fine. 4 this is fine too. #9 not so good",
"1 ok this is fine. 17 i do not like this idea. 25 great idea 43 cool idea"
), mention_1 = c(1, 1), mention_2 = c(4, 17), mention_3 = c(9,
25), mention_4 = c(NA, 43), comment_1 = c("1: this is fine.",
"1 ok this is fine."), comment_2 = c("4 this is fine too.", "17 i do not like this idea."
), comment_3 = c("9 not so good", "25 great idea"), comment_4 = c(NA,
"42 nice idea")), row.names = c(NA, -2L), class = c("tbl_df",
"tbl", "data.frame"))

Created on 2021-04-18 by the reprex package (v2.0.0)

A: An option with strsplit to split at one or more space (\\s+) that follows a dot (\\. - . - metacharacters are escaped), and precedes a digit or # (regex lookaround), then we loop over the output list with lapply, remove any characters that are not digits  (\\D+) from the start (^) of each of the string with sub, rbind the list elements and assign the 'comment_' columns  into the original dataset 'df'
df[paste0('comment_', 1:3)] <- do.call(rbind, lapply(strsplit(df$comment,
      "(?<=\\.)\\s+(?=[0-9#])", perl = TRUE), function(x) sub("^\\D+", "", x)))

-output
df
# A tibble: 2 x 7
  comment                                                      mention_1 mention_2 mention_3 comment_1          comment_2                   comment_3
  <chr>                                                            <dbl>     <dbl>     <dbl> <chr>              <chr>                       <chr>
1 topic 1: this is fine. 4 this is fine too. #9 not so good            1         4         9 1: this is fine.   4 this is fine too.         9 not so good
2 1 ok this is fine. 17 i do not like this idea. 25 great idea         1        17        25 1 ok this is fine. 17 i do not like this idea. 25 great idea

Update
If the length differ (as in the updated example), we can pad NA at the end based on the max lengths from the list to make the list elements equal in length before doing the rbind
lst1 <- lapply(strsplit(df$comment,
   "(topic \\d+)(*SKIP)(*F)|\\s+(?=[0-9#])", perl = TRUE),
         function(x) sub("^\\D+", "", x))
mx <- max(lengths(lst1))
df[paste0('comment_', seq_len(mx))] <- do.call(rbind,
           lapply(lst1, `length<-`, mx))

-output
df
# A tibble: 2 x 9
  comment                                                             mention_1 mention_2 mention_3 mention_4 comment_1          comment_2                 comment_3    comment_4
  <chr>                                                                   <dbl>     <dbl>     <dbl>     <dbl> <chr>              <chr>                     <chr>        <chr>
1 topic 1: this is fine. 4 this is fine too. #9 not so good                   1         4         9        NA 1: this is fine.   4 this is fine too.       9 not so go… <NA>
2 1 ok this is fine. 17 i do not like this idea. 25 great idea 43 co…         1        17        25        43 1 ok this is fine. 17 i do not like this id… 25 great id… 43 cool id…
>

A: A base R approach is just to read the data in again:
read.table(text = gsub("(\\d+)","&\\1",df$comment), sep = "&", fill = TRUE,
           comment.char = "", header = FALSE, strip.white = TRUE, na.strings = "")[,-1]
                  V2                          V3            V4           V5
1   1: this is fine.       4 this is fine too. # 9 not so good         <NA>
2 1 ok this is fine. 17 i do not like this idea. 25 great idea 43 cool idea

A: You can continue without your extract and unnest_wider approach.
library(tidyverse)

df %>%
  mutate(mention = map(str_extract_all(comment, "[0-9]+"), as.numeric),
         new_comment = str_extract_all(comment, '\\d+.*?(?=\\d|$)')) %>%
  unnest_wider(col = new_comment, names_sep = "_") %>%
  unnest_wider(col = mention, names_sep = "_")

#                                                                    comment
#1                 topic 1: this is fine. 4 this is fine too. #9 not so good
#2 1 ok this is fine. 17 i do not like this idea. 25 great idea 43 cool idea

#  mention_1 mention_2 mention_3 mention_4       new_comment_1
#1         1         4         9        NA   1: this is fine.
#2         1        17        25        43 1 ok this is fine.

#                 new_comment_2  new_comment_3 new_comment_4
#1        4 this is fine too. #  9 not so good          <NA>
#2 17 i do not like this idea.  25 great idea   43 cool idea


text:
Q: Python check matching digit I'm trying check whether the short int have digits that contains in long int.  Instead this came out:
long int: 198381998
short int: 19
Found a match at   0
Found a match at   1
Found a match at   2
Found a match at   3
Found a match at   4
Found a match at   5
Found a match at   6
Found a match at   7

It's suppose to look like this: (Correct one)
long int: 198381998
short int: 19
Found a match at   0
Found a match at   5

Code:
longInt = ( input ("long int: "))
floatLong = float (longInt)
shortInt =  ( input ("short int: "))
floatShort = float (shortInt)

max_digit =  int (math.log10(floatLong)) #Count the no. of long int

i = int(math.log10(floatShort)) # Count the no. shortInt that is being input

for string in range (max_digit):

    if ( shortInt in longInt): # Check whether there is any digit in shortInt
                               # that contains anything inside longInt
        print ( "Found a match at  ", string)

Without using any built-in function of python, no list or string.etc method.

A: shortInt in longInt yield always True ('19' in 198381998' is always True).
Use slice:
>>> '198381998'[4:6]
'81'
>>> '198381998'[5:7]
'19'

long_int = input("long int: ")
short_int =  input("short int: ")

short_len = len(short_int) # You don't need `math.log10`

for i in range(len(long_int)):
    if long_int[i:i+short_len] == short_int:
        print("Found a match at", i)

A: Inside your loop for digit positions make "integer slicing" function by using integer % (remainder of division aka modulo), // (integer division) and ** (raising to power) operations. Here is the idea:
>>> l = 1932319
>>> l // (10**3) % (10**2)
32

Then you can compare it to your small integer (using the usual ==). The rest is your homework, I guess.
NB. The 'in' operation is string operation, so you can't use it.


text:
Q: Workaround for rounded corners of grouped UITableView, iOS7 Since the introduction of iOS7, rounded corners for the cells of UITableView with grouped style is removed by Apple (confirmed here). Still, I am sure there are smart people out there who have built workarounds for this.
Please, to help me and a lot of other fellow iOS programmers, post your workarounds to get rounded corners for the cells in a UITableViewStyleGrouped in iOS7 in this thread. It will be much appreciated!

A: Here is a slightly improved answer to that of Roberto Ferraz.
It figures out the top and bottom cell for you (assuming there is no gap between the cells).
It also uses has trick from remove borders from group that works in iOS7
@interface CustomTableViewCell : UITableViewCell

Override messages:
#define radius 10

- (void)layoutSubviews {
    [super layoutSubviews];

    CGRect frame = self.frame;
    CGFloat top = frame.origin.y;
    CGFloat bottom = top + frame.size.height;
    UIRectCorner corners = UIRectCornerAllCorners;
    CAShapeLayer* mask = [CAShapeLayer layer];

    for (UIView* view in self.superview.subviews) {
        if (view.frame.origin.y + view.frame.size.height == top) {
            corners = corners & ~(UIRectCornerTopLeft|UIRectCornerTopRight);
        } else if (view.frame.origin.y == bottom) {
            corners = corners & ~(UIRectCornerBottomLeft|UIRectCornerBottomRight);
        }
    }

    mask.path = [UIBezierPath bezierPathWithRoundedRect:
                 CGRectMake(0, 0, frame.size.width, frame.size.height)
                                      byRoundingCorners:corners
                            cornerRadii:CGSizeMake(radius, radius)].CGPath;

    self.layer.mask = mask;
    self.layer.masksToBounds = YES;
}

/*
 iOS 7 workaround to get rid of top and bottom separators
*/
- (void) addSubview:(UIView*)view {
    if (view.frame.origin.x > 0 || view.frame.size.width < self.frame.size.width) {
        [super addSubview:view];
    }
}

A: Just add following UITableView delegate method in your code. It's really helped me to same issue like you for Table view in iOS7. Try following code taken from this answer by jvanmetre, may be it's also solved your problem:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(tintColor)]) {
        if (tableView == tblProfileDetails) {    // self.tableview
            CGFloat cornerRadius = 5.f;
            cell.backgroundColor = UIColor.clearColor;
            CAShapeLayer *layer = [[CAShapeLayer alloc] init];
            CGMutablePathRef pathRef = CGPathCreateMutable();
            CGRect bounds = CGRectInset(cell.bounds, 5, 0);
            BOOL addLine = NO;
            if (indexPath.row == 0 && indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
                CGPathAddRoundedRect(pathRef, nil, bounds, cornerRadius, cornerRadius);
            } else if (indexPath.row == 0) {
                CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds));
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds), CGRectGetMidX(bounds), CGRectGetMinY(bounds), cornerRadius);
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
                CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds));
                    addLine = YES;
            } else if (indexPath.row == [tableView numberOfRowsInSection:indexPath.section]-1) {
                CGPathMoveToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMinY(bounds));
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMinX(bounds), CGRectGetMaxY(bounds), CGRectGetMidX(bounds), CGRectGetMaxY(bounds), cornerRadius);
                CGPathAddArcToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMaxY(bounds), CGRectGetMaxX(bounds), CGRectGetMidY(bounds), cornerRadius);
                CGPathAddLineToPoint(pathRef, nil, CGRectGetMaxX(bounds), CGRectGetMinY(bounds));
            } else {
                CGPathAddRect(pathRef, nil, bounds);
                addLine = YES;
            }
            layer.path = pathRef;
            CFRelease(pathRef);
            layer.fillColor = [UIColor colorWithWhite:1.f alpha:0.8f].CGColor;

            if (addLine == YES) {
                CALayer *lineLayer = [[CALayer alloc] init];
                CGFloat lineHeight = (1.f / [UIScreen mainScreen].scale);
                lineLayer.frame = CGRectMake(CGRectGetMinX(bounds)+5, bounds.size.height-lineHeight, bounds.size.width-5, lineHeight);
                lineLayer.backgroundColor = tableView.separatorColor.CGColor;
                [layer addSublayer:lineLayer];
            }
            UIView *testView = [[UIView alloc] initWithFrame:bounds];
            [testView.layer insertSublayer:layer atIndex:0];
            testView.backgroundColor = UIColor.clearColor;
            cell.backgroundView = testView;
        }
    }
}

A: Considering you can have multiple groups in your table, some cells are rounding in just in the top corners, other just in the bottom, and others are not rounded. So I created here really fast a subclass (that can be really shortened) of UITableViewCell with the following methods:
A property that you can call anything you want, I called top and bottom:
@property(nonatomic,assign) BOOL top,bottom;

The implementation:
- (void)layoutSubviews
{
    [super layoutSubviews];

    if(self.top && self.bottom)
    {
        self.layer.cornerRadius = 10;
        self.layer.masksToBounds = YES;
        return;
    }

    if (self.top)
    {
        CAShapeLayer *shape = [[CAShapeLayer alloc] init];
        shape.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)].CGPath;
        self.layer.mask = shape;
        self.layer.masksToBounds = YES;
        return;
    }

    if (self.bottom)
    {
        CAShapeLayer *shape = [[CAShapeLayer alloc] init];
        shape.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)].CGPath;
        self.layer.mask = shape;
        self.layer.masksToBounds = YES;
    }
}

In Swift 4.2:
class MyCell: UITableViewCell {

var top = false
var bottom = false

override func layoutSubviews() {
    super.layoutSubviews()

    if top && bottom {
        layer.cornerRadius = 10
        layer.masksToBounds = true
        return
    }

    let shape = CAShapeLayer()
    let rect = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.size.height)
    let corners: UIRectCorner = self.top ? [.topLeft, .topRight] : [.bottomRight, .bottomLeft]

    shape.path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: 10, height: 10)).cgPath
    layer.mask = shape
    layer.masksToBounds = true
  }
}

To use is simple, if your cell is the first of a group, set top = True, if it is the last cell, bottom = true, if the cell is the only on the group set both to true.
If you want more or less rounded, just change the radios from 10 to another value.

A: You can use UIImageView and set the corner radius like so:
CALayer * l = [self.cellBackgroundImage layer];
[l setMasksToBounds:YES];
[l setCornerRadius:5.0];

To use this you should import quarts core:
#import <QuartzCore/QuartzCore.h>


text:
Q: Database update needs FROM clause, but FROM clause causes error I've been trying to figure out how to update the ID of the newest person in my database for 36 hours. It moans about the clients in the FROM clause, but when I remove that clause, the update affects every ID in the whole database.
UPDATE clients SET ID = $id WHERE timestamp = (SELECT MAX(timestamp) FROM clients)

What am I doing wrong?

A: Replace it with
UPDATE clients SET ID = $id ORDER BY `timestamp` DESC LIMIT 1

PS: this query solves the original task specified in the question "to update the id of the newest person in my database"

A: You can't update a table using a WHERE condition aggregated from the exact same table.
perhaps you want this:
UPDATE
    client
SET
    client.[id] = $id
ORDER BY
    client.[timestamp] DESC
LIMIT 1


text:
Q: Rewrite adminhtml template not working, only if I refresh the page I want to modify the backend template design/adminhtml/default/default/template/sales/order/create/totals.phtml
Its gonna be part of a module so I've implement the rewrite in the modules layout update file (app/design/adminhtml/default/default/layout/xentas_sales.xml)
<?xml version="1.0"?>
<layout version="0.1.0">

    <!-- Backend create order -->
    <adminhtml_sales_order_create_index>
        <!-- Overwrite totals template -->
        <reference name="data">
                <block type="adminhtml/sales_order_create_totals" name="totals">
                    <action method="unsetChild"><name>totals</name></action>
                    <action method="setTemplate">
                        <template>xentas_sales/sales/order/create/totals.phtml</template>
                    </action>
                </block>
        </reference>
    </adminhtml_sales_order_create_index>
</layout>

But the new template only shows up if I refresh the "create new order" page in backend. It does not show up when I load the page in the first place.
I experience the same issue if I overwrite app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Totals.php
and add to its _construct method setTemplate('...');
So it looks like there is some kind of sort order issue? How can I override an adminhtml template without creating my own admin theme and make sure its get overwritten by page load and not only by page refresh?
Thanks!

A: If you want to change only template. There are no need to change rewrite block class.
As per as,magento by reference <reference name=""> name you can change template file.So no need to rewrite block class.
<adminhtml_sales_order_create_index>
        <!-- Overwrite totals template -->
        <reference name="totals">
                    <action method="setTemplate">
                        <template>xentas_sales/sales/order/create/totals.phtml</template>
                    </action>
        </reference>
</adminhtml_sales_order_create_index>

Also there are two handlers,this phtml are called ,so you should need  to changes also there .
<adminhtml_sales_order_create_load_block_totals>
        <reference name="totals">
                    <action method="setTemplate">
                        <template>xentas_sales/sales/order/create/totals.phtml</template>
                    </action>
        </reference>
</adminhtml_sales_order_create_load_block_totals>
<adminhtml_sales_order_create_load_block_data>
        <reference name="totals">
                    <action method="setTemplate">
                        <template>xentas_sales/sales/order/create/totals.phtml</template>
                    </action>
        </reference>
</adminhtml_sales_order_create_load_block_data>

Most Important thing
You need to  define xentas_sales.xml file at config.xml